1 // Copyright 2014 Google Inc. All Rights Reserved.
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
7 // http://www.apache.org/licenses/LICENSE-2.0
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.
15 // Package metadata provides access to Google Compute Engine (GCE)
16 // metadata and API service accounts.
18 // This package is a wrapper around the GCE metadata service,
19 // as documented at https://developers.google.com/compute/docs/metadata.
20 package metadata // import "cloud.google.com/go/compute/metadata"
35 "golang.org/x/net/context"
36 "golang.org/x/net/context/ctxhttp"
38 "cloud.google.com/go/internal"
42 // metadataIP is the documented metadata server IP address.
43 metadataIP = "169.254.169.254"
45 // metadataHostEnv is the environment variable specifying the
46 // GCE metadata hostname. If empty, the default value of
47 // metadataIP ("169.254.169.254") is used instead.
48 // This is variable name is not defined by any spec, as far as
49 // I know; it was made up for the Go package.
50 metadataHostEnv = "GCE_METADATA_HOST"
53 type cachedValue struct {
61 projID = &cachedValue{k: "project/project-id", trim: true}
62 projNum = &cachedValue{k: "project/numeric-project-id", trim: true}
63 instID = &cachedValue{k: "instance/id", trim: true}
67 metaClient = &http.Client{
68 Transport: &internal.Transport{
69 Base: &http.Transport{
71 Timeout: 2 * time.Second,
72 KeepAlive: 30 * time.Second,
74 ResponseHeaderTimeout: 2 * time.Second,
78 subscribeClient = &http.Client{
79 Transport: &internal.Transport{
80 Base: &http.Transport{
82 Timeout: 2 * time.Second,
83 KeepAlive: 30 * time.Second,
90 // NotDefinedError is returned when requested metadata is not defined.
92 // The underlying string is the suffix after "/computeMetadata/v1/".
94 // This error is not returned if the value is defined to be the empty
96 type NotDefinedError string
98 func (suffix NotDefinedError) Error() string {
99 return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
102 // Get returns a value from the metadata service.
103 // The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
105 // If the GCE_METADATA_HOST environment variable is not defined, a default of
106 // 169.254.169.254 will be used instead.
108 // If the requested metadata is not defined, the returned error will
109 // be of type NotDefinedError.
110 func Get(suffix string) (string, error) {
111 val, _, err := getETag(metaClient, suffix)
115 // getETag returns a value from the metadata service as well as the associated
116 // ETag using the provided client. This func is otherwise equivalent to Get.
117 func getETag(client *http.Client, suffix string) (value, etag string, err error) {
118 // Using a fixed IP makes it very difficult to spoof the metadata service in
119 // a container, which is an important use-case for local testing of cloud
120 // deployments. To enable spoofing of the metadata service, the environment
121 // variable GCE_METADATA_HOST is first inspected to decide where metadata
122 // requests shall go.
123 host := os.Getenv(metadataHostEnv)
125 // Using 169.254.169.254 instead of "metadata" here because Go
126 // binaries built with the "netgo" tag and without cgo won't
127 // know the search suffix for "metadata" is
128 // ".google.internal", and this IP address is documented as
129 // being stable anyway.
132 url := "http://" + host + "/computeMetadata/v1/" + suffix
133 req, _ := http.NewRequest("GET", url, nil)
134 req.Header.Set("Metadata-Flavor", "Google")
135 res, err := client.Do(req)
139 defer res.Body.Close()
140 if res.StatusCode == http.StatusNotFound {
141 return "", "", NotDefinedError(suffix)
143 if res.StatusCode != 200 {
144 return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
146 all, err := ioutil.ReadAll(res.Body)
150 return string(all), res.Header.Get("Etag"), nil
153 func getTrimmed(suffix string) (s string, err error) {
155 s = strings.TrimSpace(s)
159 func (c *cachedValue) get() (v string, err error) {
166 v, err = getTrimmed(c.k)
181 // OnGCE reports whether this process is running on Google Compute Engine.
183 onGCEOnce.Do(initOnGCE)
191 func testOnGCE() bool {
192 // The user explicitly said they're on GCE, so trust them.
193 if os.Getenv(metadataHostEnv) != "" {
197 ctx, cancel := context.WithCancel(context.Background())
200 resc := make(chan bool, 2)
202 // Try two strategies in parallel.
203 // See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/194
205 res, err := ctxhttp.Get(ctx, metaClient, "http://"+metadataIP)
210 defer res.Body.Close()
211 resc <- res.Header.Get("Metadata-Flavor") == "Google"
215 addrs, err := net.LookupHost("metadata.google.internal")
216 if err != nil || len(addrs) == 0 {
220 resc <- strsContains(addrs, metadataIP)
223 tryHarder := systemInfoSuggestsGCE()
227 // The first strategy succeeded, so let's use it.
230 // Wait for either the DNS or metadata server probe to
231 // contradict the other one and say we are running on
232 // GCE. Give it a lot of time to do so, since the system
233 // info already suggests we're running on a GCE BIOS.
234 timer := time.NewTimer(5 * time.Second)
240 // Too slow. Who knows what this system is.
245 // There's no hint from the system info that we're running on
246 // GCE, so use the first probe's result as truth, whether it's
247 // true or false. The goal here is to optimize for speed for
248 // users who are NOT running on GCE. We can't assume that
249 // either a DNS lookup or an HTTP request to a blackholed IP
250 // address is fast. Worst case this should return when the
251 // metaClient's Transport.ResponseHeaderTimeout or
252 // Transport.Dial.Timeout fires (in two seconds).
256 // systemInfoSuggestsGCE reports whether the local system (without
257 // doing network requests) suggests that we're running on GCE. If this
258 // returns true, testOnGCE tries a bit harder to reach its metadata
260 func systemInfoSuggestsGCE() bool {
261 if runtime.GOOS != "linux" {
262 // We don't have any non-Linux clues available, at least yet.
265 slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name")
266 name := strings.TrimSpace(string(slurp))
267 return name == "Google" || name == "Google Compute Engine"
270 // Subscribe subscribes to a value from the metadata service.
271 // The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/".
272 // The suffix may contain query parameters.
274 // Subscribe calls fn with the latest metadata value indicated by the provided
275 // suffix. If the metadata value is deleted, fn is called with the empty string
276 // and ok false. Subscribe blocks until fn returns a non-nil error or the value
277 // is deleted. Subscribe returns the error value returned from the last call to
278 // fn, which may be nil when ok == false.
279 func Subscribe(suffix string, fn func(v string, ok bool) error) error {
280 const failedSubscribeSleep = time.Second * 5
282 // First check to see if the metadata value exists at all.
283 val, lastETag, err := getETag(subscribeClient, suffix)
288 if err := fn(val, true); err != nil {
293 if strings.ContainsRune(suffix, '?') {
294 suffix += "&wait_for_change=true&last_etag="
296 suffix += "?wait_for_change=true&last_etag="
299 val, etag, err := getETag(subscribeClient, suffix+url.QueryEscape(lastETag))
301 if _, deleted := err.(NotDefinedError); !deleted {
302 time.Sleep(failedSubscribeSleep)
303 continue // Retry on other errors.
309 if err := fn(val, ok); err != nil || !ok {
315 // ProjectID returns the current instance's project ID string.
316 func ProjectID() (string, error) { return projID.get() }
318 // NumericProjectID returns the current instance's numeric project ID.
319 func NumericProjectID() (string, error) { return projNum.get() }
321 // InternalIP returns the instance's primary internal IP address.
322 func InternalIP() (string, error) {
323 return getTrimmed("instance/network-interfaces/0/ip")
326 // ExternalIP returns the instance's primary external (public) IP address.
327 func ExternalIP() (string, error) {
328 return getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip")
331 // Hostname returns the instance's hostname. This will be of the form
332 // "<instanceID>.c.<projID>.internal".
333 func Hostname() (string, error) {
334 return getTrimmed("instance/hostname")
337 // InstanceTags returns the list of user-defined instance tags,
338 // assigned when initially creating a GCE instance.
339 func InstanceTags() ([]string, error) {
341 j, err := Get("instance/tags")
345 if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil {
351 // InstanceID returns the current VM's numeric instance ID.
352 func InstanceID() (string, error) {
356 // InstanceName returns the current VM's instance ID string.
357 func InstanceName() (string, error) {
358 host, err := Hostname()
362 return strings.Split(host, ".")[0], nil
365 // Zone returns the current VM's zone, such as "us-central1-b".
366 func Zone() (string, error) {
367 zone, err := getTrimmed("instance/zone")
368 // zone is of the form "projects/<projNum>/zones/<zoneName>".
372 return zone[strings.LastIndex(zone, "/")+1:], nil
375 // InstanceAttributes returns the list of user-defined attributes,
376 // assigned when initially creating a GCE VM instance. The value of an
377 // attribute can be obtained with InstanceAttributeValue.
378 func InstanceAttributes() ([]string, error) { return lines("instance/attributes/") }
380 // ProjectAttributes returns the list of user-defined attributes
381 // applying to the project as a whole, not just this VM. The value of
382 // an attribute can be obtained with ProjectAttributeValue.
383 func ProjectAttributes() ([]string, error) { return lines("project/attributes/") }
385 func lines(suffix string) ([]string, error) {
386 j, err := Get(suffix)
390 s := strings.Split(strings.TrimSpace(j), "\n")
392 s[i] = strings.TrimSpace(s[i])
397 // InstanceAttributeValue returns the value of the provided VM
398 // instance attribute.
400 // If the requested attribute is not defined, the returned error will
401 // be of type NotDefinedError.
403 // InstanceAttributeValue may return ("", nil) if the attribute was
404 // defined to be the empty string.
405 func InstanceAttributeValue(attr string) (string, error) {
406 return Get("instance/attributes/" + attr)
409 // ProjectAttributeValue returns the value of the provided
410 // project attribute.
412 // If the requested attribute is not defined, the returned error will
413 // be of type NotDefinedError.
415 // ProjectAttributeValue may return ("", nil) if the attribute was
416 // defined to be the empty string.
417 func ProjectAttributeValue(attr string) (string, error) {
418 return Get("project/attributes/" + attr)
421 // Scopes returns the service account scopes for the given account.
422 // The account may be empty or the string "default" to use the instance's
424 func Scopes(serviceAccount string) ([]string, error) {
425 if serviceAccount == "" {
426 serviceAccount = "default"
428 return lines("instance/service-accounts/" + serviceAccount + "/scopes")
431 func strsContains(ss []string, s string) bool {
432 for _, v := range ss {