...

Source file src/google.golang.org/grpc/internal/googlecloud/googlecloud.go

Documentation: google.golang.org/grpc/internal/googlecloud

     1  /*
     2   *
     3   * Copyright 2021 gRPC authors.
     4   *
     5   * Licensed under the Apache License, Version 2.0 (the "License");
     6   * you may not use this file except in compliance with the License.
     7   * You may obtain a copy of the License at
     8   *
     9   *     http://www.apache.org/licenses/LICENSE-2.0
    10   *
    11   * Unless required by applicable law or agreed to in writing, software
    12   * distributed under the License is distributed on an "AS IS" BASIS,
    13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14   * See the License for the specific language governing permissions and
    15   * limitations under the License.
    16   *
    17   */
    18  
    19  // Package googlecloud contains internal helpful functions for google cloud.
    20  package googlecloud
    21  
    22  import (
    23  	"runtime"
    24  	"strings"
    25  	"sync"
    26  
    27  	"google.golang.org/grpc/grpclog"
    28  	internalgrpclog "google.golang.org/grpc/internal/grpclog"
    29  )
    30  
    31  const logPrefix = "[googlecloud]"
    32  
    33  var (
    34  	vmOnGCEOnce sync.Once
    35  	vmOnGCE     bool
    36  
    37  	logger = internalgrpclog.NewPrefixLogger(grpclog.Component("googlecloud"), logPrefix)
    38  )
    39  
    40  // OnGCE returns whether the client is running on GCE.
    41  //
    42  // It provides similar functionality as metadata.OnGCE from the cloud library
    43  // package. We keep this to avoid depending on the cloud library module.
    44  func OnGCE() bool {
    45  	vmOnGCEOnce.Do(func() {
    46  		mf, err := manufacturer()
    47  		if err != nil {
    48  			logger.Infof("failed to read manufacturer, setting onGCE=false: %v")
    49  			return
    50  		}
    51  		vmOnGCE = isRunningOnGCE(mf, runtime.GOOS)
    52  	})
    53  	return vmOnGCE
    54  }
    55  
    56  // isRunningOnGCE checks whether the local system, without doing a network request, is
    57  // running on GCP.
    58  func isRunningOnGCE(manufacturer []byte, goos string) bool {
    59  	name := string(manufacturer)
    60  	switch goos {
    61  	case "linux":
    62  		name = strings.TrimSpace(name)
    63  		return name == "Google" || name == "Google Compute Engine"
    64  	case "windows":
    65  		name = strings.Replace(name, " ", "", -1)
    66  		name = strings.Replace(name, "\n", "", -1)
    67  		name = strings.Replace(name, "\r", "", -1)
    68  		return name == "Google"
    69  	default:
    70  		return false
    71  	}
    72  }
    73  

View as plain text