Debian Codegraph @

provider/gce/gce_discover.go

raw symbols SCIP
1 // Package gce provides node discovery for Google Cloud.
2 package gce
3
4 import (
5 "fmt"
6 "io/ioutil"
7 "log"
8 "net/http"
9
10 "golang.org/x/oauth2"
11 "golang.org/x/oauth2/google"
12 compute "google.golang.org/api/compute/v1"
13 )
14
15 type Provider struct {
16 userAgent string
17 }
18
19 func (p *Provider) SetUserAgent(s string) {
20 p.userAgent = s
21 }
22
23 func (p *Provider) Help() string {
24 return `Google Cloud:
25
26 provider: "gce"
27 project_name: The name of the project. discovered if not set
28 tag_value: The tag value for filtering instances
29 zone_pattern: A RE2 regular expression for filtering zones, e.g. us-west1-.*, or us-(?west|east).*
30 credentials_file: The path to the credentials file. See below for more details
31
32 The credentials for a GCE Service Account are required and are searched in
33 the following locations:
34
35 1. Use credentials from "credentials_file", if provided.
36 2. Use JSON file from GOOGLE_APPLICATION_CREDENTIALS environment variable.
37 3. Use JSON file in a location known to the gcloud command-line tool.
38 On Windows, this is %APPDATA%/gcloud/application_default_credentials.json.
39 On other systems, $HOME/.config/gcloud/application_default_credentials.json.
40 4. On Google Compute Engine, use credentials from the metadata
41 server. In this final case any provided scopes are ignored.
42 `
43 }
44
45 func (p *Provider) Addrs(args map[string]string, l *log.Logger) ([]string, error) {
46 if args["provider"] != "gce" {
47 return nil, fmt.Errorf("discover-gce: invalid provider " + args["provider"])
48 }
49
50 if l == nil {
51 l = log.New(ioutil.Discard, "", 0)
52 }
53
54 project := args["project_name"]
55 zone := args["zone_pattern"]
56 creds := args["credentials_file"]
57 tagValue := args["tag_value"]
58
59 // determine the project name
60 if project == "" {
61 l.Println("[INFO] discover-gce: Looking up project name")
62 p, err := lookupProject()
63 if err != nil {
64 return nil, fmt.Errorf("discover-gce: %s", err)
65 }
66 project = p
67 }
68 l.Printf("[INFO] discover-gce: Project name is %q", project)
69
70 // create an authenticated client
71 if creds != "" {
72 l.Printf("[INFO] discover-gce: Loading credentials from %s", creds)
73 }
74 client, err := client(creds)
75 if err != nil {
76 return nil, fmt.Errorf("discover-gce: %s", err)
77 }
78 svc, err := compute.New(client)
79 if err != nil {
80 return nil, fmt.Errorf("discover-gce: %s", err)
81 }
82 if p.userAgent != "" {
83 svc.UserAgent = p.userAgent
84 }
85
86 // lookup the project zones to look in
87 if zone != "" {
88 l.Printf("[INFO] discover-gce: Looking up zones matching %s", zone)
89 } else {
90 l.Printf("[INFO] discover-gce: Looking up all zones")
91 }
92 zones, err := lookupZones(svc, project, zone)
93 if err != nil {
94 return nil, fmt.Errorf("discover-gce: %s", err)
95 }
96 l.Printf("[INFO] discover-gce: Found zones %v", zones)
97
98 // lookup the instance addresses
99 var addrs []string
100 for _, zone := range zones {
101 a, err := lookupAddrs(svc, project, zone, tagValue)
102 if err != nil {
103 return nil, fmt.Errorf("discover-gce: %s", err)
104 }
105 l.Printf("[INFO] discover-gce: Zone %q has %v", zone, a)
106 addrs = append(addrs, a...)
107 }
108 return addrs, nil
109 }
110
111 // client returns an authenticated HTTP client for use with GCE.
112 func client(path string) (*http.Client, error) {
113 if path == "" {
114 return google.DefaultClient(oauth2.NoContext, compute.ComputeScope)
115 }
116
117 key, err := ioutil.ReadFile(path)
118 if err != nil {
119 return nil, err
120 }
121
122 jwtConfig, err := google.JWTConfigFromJSON(key, compute.ComputeScope)
123 if err != nil {
124 return nil, err
125 }
126
127 return jwtConfig.Client(oauth2.NoContext), nil
128 }
129
130 // lookupProject retrieves the project name from the metadata of the current node.
131 func lookupProject() (string, error) {
132 req, err := http.NewRequest("GET", "http://metadata.google.internal/computeMetadata/v1/project/project-id", nil)
133 if err != nil {
134 return "", err
135 }
136 req.Header.Add("Metadata-Flavor", "Google")
137
138 resp, err := http.DefaultClient.Do(req)
139 if err != nil {
140 return "", err
141 }
142 defer resp.Body.Close()
143
144 if resp.StatusCode != 200 {
145 return "", fmt.Errorf("discover-gce: invalid status code %d when fetching project id", resp.StatusCode)
146 }
147
148 project, err := ioutil.ReadAll(resp.Body)
149 if err != nil {
150 return "", err
151 }
152 return string(project), nil
153 }
154
155 // lookupZones retrieves the zones of the project and filters them by pattern.
156 func lookupZones(svc *compute.Service, project, pattern string) ([]string, error) {
157 call := svc.Zones.List(project)
158 if pattern != "" {
159 call = call.Filter("name eq " + pattern)
160 }
161
162 var zones []string
163 f := func(page *compute.ZoneList) error {
164 for _, v := range page.Items {
165 zones = append(zones, v.Name)
166 }
167 return nil
168 }
169
170 if err := call.Pages(oauth2.NoContext, f); err != nil {
171 return nil, err
172 }
173 return zones, nil
174 }
175
176 // lookupAddrs retrieves the private ip addresses of all instances in a given
177 // project and zone which have a matching tag value.
178 func lookupAddrs(svc *compute.Service, project, zone, tag string) ([]string, error) {
179 var addrs []string
180 f := func(page *compute.InstanceList) error {
181 for _, v := range page.Items {
182 if len(v.NetworkInterfaces) == 0 || v.NetworkInterfaces[0].NetworkIP == "" {
183 continue
184 }
185 for _, t := range v.Tags.Items {
186 if t == tag {
187 addrs = append(addrs, v.NetworkInterfaces[0].NetworkIP)
188 break
189 }
190 }
191 }
192 return nil
193 }
194
195 call := svc.Instances.List(project, zone)
196 if err := call.Pages(oauth2.NoContext, f); err != nil {
197 return nil, err
198 }
199 return addrs, nil
200 }