metadata.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. // Copyright 2014 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. // http://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. // Package metadata provides access to Google Compute Engine (GCE)
  15. // metadata and API service accounts.
  16. //
  17. // This package is a wrapper around the GCE metadata service,
  18. // as documented at https://cloud.google.com/compute/docs/metadata/overview.
  19. package metadata // import "cloud.google.com/go/compute/metadata"
  20. import (
  21. "context"
  22. "encoding/json"
  23. "fmt"
  24. "io/ioutil"
  25. "net"
  26. "net/http"
  27. "net/url"
  28. "os"
  29. "runtime"
  30. "strings"
  31. "sync"
  32. "time"
  33. )
  34. const (
  35. // metadataIP is the documented metadata server IP address.
  36. metadataIP = "169.254.169.254"
  37. // metadataHostEnv is the environment variable specifying the
  38. // GCE metadata hostname. If empty, the default value of
  39. // metadataIP ("169.254.169.254") is used instead.
  40. // This is variable name is not defined by any spec, as far as
  41. // I know; it was made up for the Go package.
  42. metadataHostEnv = "GCE_METADATA_HOST"
  43. userAgent = "gcloud-golang/0.1"
  44. )
  45. type cachedValue struct {
  46. k string
  47. trim bool
  48. mu sync.Mutex
  49. v string
  50. }
  51. var (
  52. projID = &cachedValue{k: "project/project-id", trim: true}
  53. projNum = &cachedValue{k: "project/numeric-project-id", trim: true}
  54. instID = &cachedValue{k: "instance/id", trim: true}
  55. )
  56. var defaultClient = &Client{hc: newDefaultHTTPClient()}
  57. func newDefaultHTTPClient() *http.Client {
  58. return &http.Client{
  59. Transport: &http.Transport{
  60. Dial: (&net.Dialer{
  61. Timeout: 2 * time.Second,
  62. KeepAlive: 30 * time.Second,
  63. }).Dial,
  64. IdleConnTimeout: 60 * time.Second,
  65. },
  66. Timeout: 5 * time.Second,
  67. }
  68. }
  69. // NotDefinedError is returned when requested metadata is not defined.
  70. //
  71. // The underlying string is the suffix after "/computeMetadata/v1/".
  72. //
  73. // This error is not returned if the value is defined to be the empty
  74. // string.
  75. type NotDefinedError string
  76. func (suffix NotDefinedError) Error() string {
  77. return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
  78. }
  79. func (c *cachedValue) get(cl *Client) (v string, err error) {
  80. defer c.mu.Unlock()
  81. c.mu.Lock()
  82. if c.v != "" {
  83. return c.v, nil
  84. }
  85. if c.trim {
  86. v, err = cl.getTrimmed(c.k)
  87. } else {
  88. v, err = cl.Get(c.k)
  89. }
  90. if err == nil {
  91. c.v = v
  92. }
  93. return
  94. }
  95. var (
  96. onGCEOnce sync.Once
  97. onGCE bool
  98. )
  99. // OnGCE reports whether this process is running on Google Compute Engine.
  100. func OnGCE() bool {
  101. onGCEOnce.Do(initOnGCE)
  102. return onGCE
  103. }
  104. func initOnGCE() {
  105. onGCE = testOnGCE()
  106. }
  107. func testOnGCE() bool {
  108. // The user explicitly said they're on GCE, so trust them.
  109. if os.Getenv(metadataHostEnv) != "" {
  110. return true
  111. }
  112. ctx, cancel := context.WithCancel(context.Background())
  113. defer cancel()
  114. resc := make(chan bool, 2)
  115. // Try two strategies in parallel.
  116. // See https://github.com/googleapis/google-cloud-go/issues/194
  117. go func() {
  118. req, _ := http.NewRequest("GET", "http://"+metadataIP, nil)
  119. req.Header.Set("User-Agent", userAgent)
  120. res, err := newDefaultHTTPClient().Do(req.WithContext(ctx))
  121. if err != nil {
  122. resc <- false
  123. return
  124. }
  125. defer res.Body.Close()
  126. resc <- res.Header.Get("Metadata-Flavor") == "Google"
  127. }()
  128. go func() {
  129. resolver := &net.Resolver{}
  130. addrs, err := resolver.LookupHost(ctx, "metadata.google.internal.")
  131. if err != nil || len(addrs) == 0 {
  132. resc <- false
  133. return
  134. }
  135. resc <- strsContains(addrs, metadataIP)
  136. }()
  137. tryHarder := systemInfoSuggestsGCE()
  138. if tryHarder {
  139. res := <-resc
  140. if res {
  141. // The first strategy succeeded, so let's use it.
  142. return true
  143. }
  144. // Wait for either the DNS or metadata server probe to
  145. // contradict the other one and say we are running on
  146. // GCE. Give it a lot of time to do so, since the system
  147. // info already suggests we're running on a GCE BIOS.
  148. timer := time.NewTimer(5 * time.Second)
  149. defer timer.Stop()
  150. select {
  151. case res = <-resc:
  152. return res
  153. case <-timer.C:
  154. // Too slow. Who knows what this system is.
  155. return false
  156. }
  157. }
  158. // There's no hint from the system info that we're running on
  159. // GCE, so use the first probe's result as truth, whether it's
  160. // true or false. The goal here is to optimize for speed for
  161. // users who are NOT running on GCE. We can't assume that
  162. // either a DNS lookup or an HTTP request to a blackholed IP
  163. // address is fast. Worst case this should return when the
  164. // metaClient's Transport.ResponseHeaderTimeout or
  165. // Transport.Dial.Timeout fires (in two seconds).
  166. return <-resc
  167. }
  168. // systemInfoSuggestsGCE reports whether the local system (without
  169. // doing network requests) suggests that we're running on GCE. If this
  170. // returns true, testOnGCE tries a bit harder to reach its metadata
  171. // server.
  172. func systemInfoSuggestsGCE() bool {
  173. if runtime.GOOS != "linux" {
  174. // We don't have any non-Linux clues available, at least yet.
  175. return false
  176. }
  177. slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name")
  178. name := strings.TrimSpace(string(slurp))
  179. return name == "Google" || name == "Google Compute Engine"
  180. }
  181. // Subscribe calls Client.Subscribe on the default client.
  182. func Subscribe(suffix string, fn func(v string, ok bool) error) error {
  183. return defaultClient.Subscribe(suffix, fn)
  184. }
  185. // Get calls Client.Get on the default client.
  186. func Get(suffix string) (string, error) { return defaultClient.Get(suffix) }
  187. // ProjectID returns the current instance's project ID string.
  188. func ProjectID() (string, error) { return defaultClient.ProjectID() }
  189. // NumericProjectID returns the current instance's numeric project ID.
  190. func NumericProjectID() (string, error) { return defaultClient.NumericProjectID() }
  191. // InternalIP returns the instance's primary internal IP address.
  192. func InternalIP() (string, error) { return defaultClient.InternalIP() }
  193. // ExternalIP returns the instance's primary external (public) IP address.
  194. func ExternalIP() (string, error) { return defaultClient.ExternalIP() }
  195. // Email calls Client.Email on the default client.
  196. func Email(serviceAccount string) (string, error) { return defaultClient.Email(serviceAccount) }
  197. // Hostname returns the instance's hostname. This will be of the form
  198. // "<instanceID>.c.<projID>.internal".
  199. func Hostname() (string, error) { return defaultClient.Hostname() }
  200. // InstanceTags returns the list of user-defined instance tags,
  201. // assigned when initially creating a GCE instance.
  202. func InstanceTags() ([]string, error) { return defaultClient.InstanceTags() }
  203. // InstanceID returns the current VM's numeric instance ID.
  204. func InstanceID() (string, error) { return defaultClient.InstanceID() }
  205. // InstanceName returns the current VM's instance ID string.
  206. func InstanceName() (string, error) { return defaultClient.InstanceName() }
  207. // Zone returns the current VM's zone, such as "us-central1-b".
  208. func Zone() (string, error) { return defaultClient.Zone() }
  209. // InstanceAttributes calls Client.InstanceAttributes on the default client.
  210. func InstanceAttributes() ([]string, error) { return defaultClient.InstanceAttributes() }
  211. // ProjectAttributes calls Client.ProjectAttributes on the default client.
  212. func ProjectAttributes() ([]string, error) { return defaultClient.ProjectAttributes() }
  213. // InstanceAttributeValue calls Client.InstanceAttributeValue on the default client.
  214. func InstanceAttributeValue(attr string) (string, error) {
  215. return defaultClient.InstanceAttributeValue(attr)
  216. }
  217. // ProjectAttributeValue calls Client.ProjectAttributeValue on the default client.
  218. func ProjectAttributeValue(attr string) (string, error) {
  219. return defaultClient.ProjectAttributeValue(attr)
  220. }
  221. // Scopes calls Client.Scopes on the default client.
  222. func Scopes(serviceAccount string) ([]string, error) { return defaultClient.Scopes(serviceAccount) }
  223. func strsContains(ss []string, s string) bool {
  224. for _, v := range ss {
  225. if v == s {
  226. return true
  227. }
  228. }
  229. return false
  230. }
  231. // A Client provides metadata.
  232. type Client struct {
  233. hc *http.Client
  234. }
  235. // NewClient returns a Client that can be used to fetch metadata.
  236. // Returns the client that uses the specified http.Client for HTTP requests.
  237. // If nil is specified, returns the default client.
  238. func NewClient(c *http.Client) *Client {
  239. if c == nil {
  240. return defaultClient
  241. }
  242. return &Client{hc: c}
  243. }
  244. // getETag returns a value from the metadata service as well as the associated ETag.
  245. // This func is otherwise equivalent to Get.
  246. func (c *Client) getETag(suffix string) (value, etag string, err error) {
  247. ctx := context.TODO()
  248. // Using a fixed IP makes it very difficult to spoof the metadata service in
  249. // a container, which is an important use-case for local testing of cloud
  250. // deployments. To enable spoofing of the metadata service, the environment
  251. // variable GCE_METADATA_HOST is first inspected to decide where metadata
  252. // requests shall go.
  253. host := os.Getenv(metadataHostEnv)
  254. if host == "" {
  255. // Using 169.254.169.254 instead of "metadata" here because Go
  256. // binaries built with the "netgo" tag and without cgo won't
  257. // know the search suffix for "metadata" is
  258. // ".google.internal", and this IP address is documented as
  259. // being stable anyway.
  260. host = metadataIP
  261. }
  262. suffix = strings.TrimLeft(suffix, "/")
  263. u := "http://" + host + "/computeMetadata/v1/" + suffix
  264. req, err := http.NewRequest("GET", u, nil)
  265. if err != nil {
  266. return "", "", err
  267. }
  268. req.Header.Set("Metadata-Flavor", "Google")
  269. req.Header.Set("User-Agent", userAgent)
  270. var res *http.Response
  271. var reqErr error
  272. retryer := newRetryer()
  273. for {
  274. res, reqErr = c.hc.Do(req)
  275. var code int
  276. if res != nil {
  277. code = res.StatusCode
  278. }
  279. if delay, shouldRetry := retryer.Retry(code, reqErr); shouldRetry {
  280. if err := sleep(ctx, delay); err != nil {
  281. return "", "", err
  282. }
  283. continue
  284. }
  285. break
  286. }
  287. if reqErr != nil {
  288. return "", "", reqErr
  289. }
  290. defer res.Body.Close()
  291. if res.StatusCode == http.StatusNotFound {
  292. return "", "", NotDefinedError(suffix)
  293. }
  294. all, err := ioutil.ReadAll(res.Body)
  295. if err != nil {
  296. return "", "", err
  297. }
  298. if res.StatusCode != 200 {
  299. return "", "", &Error{Code: res.StatusCode, Message: string(all)}
  300. }
  301. return string(all), res.Header.Get("Etag"), nil
  302. }
  303. // Get returns a value from the metadata service.
  304. // The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
  305. //
  306. // If the GCE_METADATA_HOST environment variable is not defined, a default of
  307. // 169.254.169.254 will be used instead.
  308. //
  309. // If the requested metadata is not defined, the returned error will
  310. // be of type NotDefinedError.
  311. func (c *Client) Get(suffix string) (string, error) {
  312. val, _, err := c.getETag(suffix)
  313. return val, err
  314. }
  315. func (c *Client) getTrimmed(suffix string) (s string, err error) {
  316. s, err = c.Get(suffix)
  317. s = strings.TrimSpace(s)
  318. return
  319. }
  320. func (c *Client) lines(suffix string) ([]string, error) {
  321. j, err := c.Get(suffix)
  322. if err != nil {
  323. return nil, err
  324. }
  325. s := strings.Split(strings.TrimSpace(j), "\n")
  326. for i := range s {
  327. s[i] = strings.TrimSpace(s[i])
  328. }
  329. return s, nil
  330. }
  331. // ProjectID returns the current instance's project ID string.
  332. func (c *Client) ProjectID() (string, error) { return projID.get(c) }
  333. // NumericProjectID returns the current instance's numeric project ID.
  334. func (c *Client) NumericProjectID() (string, error) { return projNum.get(c) }
  335. // InstanceID returns the current VM's numeric instance ID.
  336. func (c *Client) InstanceID() (string, error) { return instID.get(c) }
  337. // InternalIP returns the instance's primary internal IP address.
  338. func (c *Client) InternalIP() (string, error) {
  339. return c.getTrimmed("instance/network-interfaces/0/ip")
  340. }
  341. // Email returns the email address associated with the service account.
  342. // The account may be empty or the string "default" to use the instance's
  343. // main account.
  344. func (c *Client) Email(serviceAccount string) (string, error) {
  345. if serviceAccount == "" {
  346. serviceAccount = "default"
  347. }
  348. return c.getTrimmed("instance/service-accounts/" + serviceAccount + "/email")
  349. }
  350. // ExternalIP returns the instance's primary external (public) IP address.
  351. func (c *Client) ExternalIP() (string, error) {
  352. return c.getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip")
  353. }
  354. // Hostname returns the instance's hostname. This will be of the form
  355. // "<instanceID>.c.<projID>.internal".
  356. func (c *Client) Hostname() (string, error) {
  357. return c.getTrimmed("instance/hostname")
  358. }
  359. // InstanceTags returns the list of user-defined instance tags,
  360. // assigned when initially creating a GCE instance.
  361. func (c *Client) InstanceTags() ([]string, error) {
  362. var s []string
  363. j, err := c.Get("instance/tags")
  364. if err != nil {
  365. return nil, err
  366. }
  367. if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil {
  368. return nil, err
  369. }
  370. return s, nil
  371. }
  372. // InstanceName returns the current VM's instance ID string.
  373. func (c *Client) InstanceName() (string, error) {
  374. return c.getTrimmed("instance/name")
  375. }
  376. // Zone returns the current VM's zone, such as "us-central1-b".
  377. func (c *Client) Zone() (string, error) {
  378. zone, err := c.getTrimmed("instance/zone")
  379. // zone is of the form "projects/<projNum>/zones/<zoneName>".
  380. if err != nil {
  381. return "", err
  382. }
  383. return zone[strings.LastIndex(zone, "/")+1:], nil
  384. }
  385. // InstanceAttributes returns the list of user-defined attributes,
  386. // assigned when initially creating a GCE VM instance. The value of an
  387. // attribute can be obtained with InstanceAttributeValue.
  388. func (c *Client) InstanceAttributes() ([]string, error) { return c.lines("instance/attributes/") }
  389. // ProjectAttributes returns the list of user-defined attributes
  390. // applying to the project as a whole, not just this VM. The value of
  391. // an attribute can be obtained with ProjectAttributeValue.
  392. func (c *Client) ProjectAttributes() ([]string, error) { return c.lines("project/attributes/") }
  393. // InstanceAttributeValue returns the value of the provided VM
  394. // instance attribute.
  395. //
  396. // If the requested attribute is not defined, the returned error will
  397. // be of type NotDefinedError.
  398. //
  399. // InstanceAttributeValue may return ("", nil) if the attribute was
  400. // defined to be the empty string.
  401. func (c *Client) InstanceAttributeValue(attr string) (string, error) {
  402. return c.Get("instance/attributes/" + attr)
  403. }
  404. // ProjectAttributeValue returns the value of the provided
  405. // project attribute.
  406. //
  407. // If the requested attribute is not defined, the returned error will
  408. // be of type NotDefinedError.
  409. //
  410. // ProjectAttributeValue may return ("", nil) if the attribute was
  411. // defined to be the empty string.
  412. func (c *Client) ProjectAttributeValue(attr string) (string, error) {
  413. return c.Get("project/attributes/" + attr)
  414. }
  415. // Scopes returns the service account scopes for the given account.
  416. // The account may be empty or the string "default" to use the instance's
  417. // main account.
  418. func (c *Client) Scopes(serviceAccount string) ([]string, error) {
  419. if serviceAccount == "" {
  420. serviceAccount = "default"
  421. }
  422. return c.lines("instance/service-accounts/" + serviceAccount + "/scopes")
  423. }
  424. // Subscribe subscribes to a value from the metadata service.
  425. // The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
  426. // The suffix may contain query parameters.
  427. //
  428. // Subscribe calls fn with the latest metadata value indicated by the provided
  429. // suffix. If the metadata value is deleted, fn is called with the empty string
  430. // and ok false. Subscribe blocks until fn returns a non-nil error or the value
  431. // is deleted. Subscribe returns the error value returned from the last call to
  432. // fn, which may be nil when ok == false.
  433. func (c *Client) Subscribe(suffix string, fn func(v string, ok bool) error) error {
  434. const failedSubscribeSleep = time.Second * 5
  435. // First check to see if the metadata value exists at all.
  436. val, lastETag, err := c.getETag(suffix)
  437. if err != nil {
  438. return err
  439. }
  440. if err := fn(val, true); err != nil {
  441. return err
  442. }
  443. ok := true
  444. if strings.ContainsRune(suffix, '?') {
  445. suffix += "&wait_for_change=true&last_etag="
  446. } else {
  447. suffix += "?wait_for_change=true&last_etag="
  448. }
  449. for {
  450. val, etag, err := c.getETag(suffix + url.QueryEscape(lastETag))
  451. if err != nil {
  452. if _, deleted := err.(NotDefinedError); !deleted {
  453. time.Sleep(failedSubscribeSleep)
  454. continue // Retry on other errors.
  455. }
  456. ok = false
  457. }
  458. lastETag = etag
  459. if err := fn(val, ok); err != nil || !ok {
  460. return err
  461. }
  462. }
  463. }
  464. // Error contains an error response from the server.
  465. type Error struct {
  466. // Code is the HTTP response status code.
  467. Code int
  468. // Message is the server response message.
  469. Message string
  470. }
  471. func (e *Error) Error() string {
  472. return fmt.Sprintf("compute: Received %d `%s`", e.Code, e.Message)
  473. }