googlecloud.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. // Package googlecloud contains internal helpful functions for google cloud.
  19. package googlecloud
  20. import (
  21. "runtime"
  22. "strings"
  23. "sync"
  24. "google.golang.org/grpc/grpclog"
  25. internalgrpclog "google.golang.org/grpc/internal/grpclog"
  26. )
  27. const logPrefix = "[googlecloud]"
  28. var (
  29. vmOnGCEOnce sync.Once
  30. vmOnGCE bool
  31. logger = internalgrpclog.NewPrefixLogger(grpclog.Component("googlecloud"), logPrefix)
  32. )
  33. // OnGCE returns whether the client is running on GCE.
  34. //
  35. // It provides similar functionality as metadata.OnGCE from the cloud library
  36. // package. We keep this to avoid depending on the cloud library module.
  37. func OnGCE() bool {
  38. vmOnGCEOnce.Do(func() {
  39. mf, err := manufacturer()
  40. if err != nil {
  41. logger.Infof("failed to read manufacturer, setting onGCE=false: %v")
  42. return
  43. }
  44. vmOnGCE = isRunningOnGCE(mf, runtime.GOOS)
  45. })
  46. return vmOnGCE
  47. }
  48. // isRunningOnGCE checks whether the local system, without doing a network request, is
  49. // running on GCP.
  50. func isRunningOnGCE(manufacturer []byte, goos string) bool {
  51. name := string(manufacturer)
  52. switch goos {
  53. case "linux":
  54. name = strings.TrimSpace(name)
  55. return name == "Google" || name == "Google Compute Engine"
  56. case "windows":
  57. name = strings.Replace(name, " ", "", -1)
  58. name = strings.Replace(name, "\n", "", -1)
  59. name = strings.Replace(name, "\r", "", -1)
  60. return name == "Google"
  61. default:
  62. return false
  63. }
  64. }