...

Source file src/cloud.google.com/go/internal/detect/detect.go

Documentation: cloud.google.com/go/internal/detect

     1  // Copyright 2021 Google LLC
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     https://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package detect is used find information from the environment.
    16  package detect
    17  
    18  import (
    19  	"context"
    20  	"errors"
    21  	"fmt"
    22  	"os"
    23  
    24  	"golang.org/x/oauth2/google"
    25  	"google.golang.org/api/option"
    26  	"google.golang.org/api/transport"
    27  )
    28  
    29  const (
    30  	projectIDSentinel = "*detect-project-id*"
    31  	envProjectID      = "GOOGLE_CLOUD_PROJECT"
    32  )
    33  
    34  var (
    35  	adcLookupFunc func(context.Context, ...option.ClientOption) (*google.Credentials, error) = transport.Creds
    36  	envLookupFunc func(string) string                                                        = os.Getenv
    37  )
    38  
    39  // ProjectID tries to detect the project ID from the environment if the sentinel
    40  // value, "*detect-project-id*", is sent. It looks in the following order:
    41  //  1. GOOGLE_CLOUD_PROJECT envvar
    42  //  2. ADC creds.ProjectID
    43  //  3. A static value if the environment is emulated.
    44  func ProjectID(ctx context.Context, projectID string, emulatorEnvVar string, opts ...option.ClientOption) (string, error) {
    45  	if projectID != projectIDSentinel {
    46  		return projectID, nil
    47  	}
    48  	// 1. Try a well known environment variable
    49  	if id := envLookupFunc(envProjectID); id != "" {
    50  		return id, nil
    51  	}
    52  	// 2. Try ADC
    53  	creds, err := adcLookupFunc(ctx, opts...)
    54  	if err != nil {
    55  		return "", fmt.Errorf("fetching creds: %v", err)
    56  	}
    57  	// 3. If ADC does not work, and the environment is emulated, return a const value.
    58  	if creds.ProjectID == "" && emulatorEnvVar != "" && envLookupFunc(emulatorEnvVar) != "" {
    59  		return "emulated-project", nil
    60  	}
    61  	// 4. If 1-3 don't work, error out
    62  	if creds.ProjectID == "" {
    63  		return "", errors.New("unable to detect projectID, please refer to docs for DetectProjectID")
    64  	}
    65  	// Success from ADC
    66  	return creds.ProjectID, nil
    67  }
    68  

View as plain text