-
Notifications
You must be signed in to change notification settings - Fork 0
/
gce_metadata.go
108 lines (92 loc) · 2.09 KB
/
gce_metadata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"time"
"github.com/jpillora/backoff"
)
type GetOptions struct {
WaitForChange bool
LastETag string
Recursive bool
}
type GetResult struct {
ETag string
}
type GCEMetadataClient struct {
http *http.Client
}
func NewGCEMetadataClient() *GCEMetadataClient {
return &GCEMetadataClient{
http: &http.Client{},
}
}
func (c *GCEMetadataClient) Get(
key string,
data interface{},
opts GetOptions) (*GetResult, error) {
boff := &backoff.Backoff{
Jitter: true,
}
for {
url := fmt.Sprintf("http://metadata.google.internal/computeMetadata/v1/%s", key)
resp, err := c.doGET(url, opts)
if err != nil {
log.Print(err)
time.Sleep(boff.Duration())
continue
}
switch resp.StatusCode {
case http.StatusOK:
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading body from response: %s", err)
time.Sleep(boff.Duration())
continue
}
err = json.Unmarshal(b, data)
if err != nil {
log.Printf("Error parsing body from response: %s. Body was: %s", err, string(b))
time.Sleep(boff.Duration())
continue
}
return &GetResult{
ETag: resp.Header.Get("ETag"),
}, nil
case http.StatusBadGateway, http.StatusServiceUnavailable,
http.StatusGatewayTimeout:
log.Printf("Status %d from %s: %s", resp.StatusCode, url, resp.Status)
time.Sleep(boff.Duration())
continue
default:
return nil, fmt.Errorf("GET %s failed with status %d: %s",
url, resp.StatusCode, resp.Status)
}
}
}
func (c *GCEMetadataClient) doGET(endpointURL string, opts GetOptions) (*http.Response, error) {
u, err := url.Parse(endpointURL)
if err != nil {
return nil, err
}
q := u.Query()
q.Set("alt", "json")
if opts.WaitForChange {
q.Set("wait_for_change", "true")
}
if opts.LastETag != "" {
q.Set("last_etag", opts.LastETag)
}
u.RawQuery = q.Encode()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
panic(err)
}
req.Header.Add("Metadata-Flavor", "Google")
log.Printf("GET %s", u)
return c.http.Do(req)
}