sigs.k8s.io/cluster-api-provider-azure@v1.14.3/azure/regional_baseuri.go (about)

     1  /*
     2  Copyright 2021 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package azure
    18  
    19  import (
    20  	"fmt"
    21  	"net/url"
    22  	"path"
    23  
    24  	"github.com/pkg/errors"
    25  )
    26  
    27  // aliasAuth helps to embed the interface Authorize since the Authorizer interface also defines an Authorizer method and
    28  // the compiler gets confused without a type alias (or renaming the method Authorizer).
    29  type aliasAuth Authorizer
    30  
    31  // baseURIAdapter wraps an azure.Authorizer and adds a region to the BaseURI. This is useful if you need to make direct
    32  // calls to a specific Azure region. One possible case is to avoid replication delay when listing resources within a
    33  // resource group. For example, listing the VMSSes within a resource group.
    34  type baseURIAdapter struct {
    35  	aliasAuth
    36  	Region    string
    37  	parsedURL *url.URL
    38  }
    39  
    40  // WithRegionalBaseURI returns an authorizer that has a regional base URI, like `https://{region}.management.azure.com`.
    41  func WithRegionalBaseURI(authorizer Authorizer, region string) (Authorizer, error) {
    42  	parsedURI, err := url.Parse(authorizer.BaseURI())
    43  	if err != nil {
    44  		return nil, errors.Wrap(err, "failed to parse the base URI of client")
    45  	}
    46  
    47  	return &baseURIAdapter{
    48  		aliasAuth: authorizer,
    49  		Region:    region,
    50  		parsedURL: parsedURI,
    51  	}, nil
    52  }
    53  
    54  // BaseURI return a regional base URI, like `https://{region}.management.azure.com`.
    55  func (a *baseURIAdapter) BaseURI() string {
    56  	if a == nil || a.parsedURL == nil || a.Region == "" {
    57  		return a.aliasAuth.BaseURI()
    58  	}
    59  
    60  	sansScheme := path.Join(fmt.Sprintf("%s.%s", a.Region, a.parsedURL.Host), a.parsedURL.Path)
    61  	return fmt.Sprintf("%s://%s", a.parsedURL.Scheme, sansScheme)
    62  }