-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgcp.go
86 lines (75 loc) · 2.47 KB
/
gcp.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
package cloudinfo
import (
"encoding/json"
"path"
"strconv"
"strings"
)
type gcpProvider struct {
cache *cachedHttp
info *Info
}
type gcpMetadata struct {
// attributes: physical_host, ssh-keys, stop-state
CPUPlatform string `json:"cpuPlatform"` // Intel Broadwell
Description string `json:"description"` // ?
Hostname string `json:"hostname"` // instance-name.asia-northeast1-b.c.project-name.internal
ID int64 `json:"id"` // 123456...
Image string `json:"image"` // projects/debian-cloud/global/images/debian-12-bookworm-v20240515
MachineType string `json:"machineType"` // projects/<id>/machineTypes/e2-standard-4
Name string `json:"name"` // name of machine
// "licenses": [{"id": "123456..."}]
NetworkInterfaces []struct {
AccessConfigs []struct {
ExternalIP string `json:"externalIp"`
Type string `json:"type"` // ONE_TO_ONE_NAT
} `json:"accessConfigs"`
// "dnsServers": ["169.254.169.254"]
// "forwardedIps": [],
Gateway string `json:"gateway"`
IP string `json:"ip"` // local ip (private)
// "ipAliases": [],
// "mac": "42:01:0a:92:00:02",
// "mtu": 1460,
// "network": "projects/<id>/networks/default",
// "subnetmask": "255.255.240.0",
// "targetInstanceIps": []
} `json:"networkInterfaces"`
//Tags []string `json:"tags"`
Zone string `json:"zone"` // projects/<id>/zones/asia-northeast1-b
}
func (g *gcpProvider) Name() string {
return "gcp"
}
func (g *gcpProvider) Fetch() (*Info, error) {
res, _, err := g.cache.GetWithHeaders("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true&timeout_sec=1", map[string]string{"Metadata-Flavor": "Google"})
if err != nil {
return g.info, err
}
var info *gcpMetadata
err = json.Unmarshal(res, &info)
if err != nil {
return g.info, err
}
g.info.Hostname = info.Hostname
g.info.ID = strconv.FormatInt(info.ID, 10)
g.info.Image = info.Image
g.info.Type = path.Base(info.MachineType)
if a := strings.Split(info.Zone, "/"); len(a) >= 2 && a[0] == "projects" {
g.info.AccountId = a[1]
}
for _, intf := range info.NetworkInterfaces {
g.info.PrivateIP.addString(intf.IP)
for _, ac := range intf.AccessConfigs {
g.info.PublicIP.addString(ac.ExternalIP)
}
}
zone := path.Base(info.Zone)
region := zone
if pos := strings.LastIndexByte(region, '-'); pos > 0 {
region = region[:pos]
}
g.info.Location = makeLocation("cloud", "gcp", "region", region, "zone", zone)
g.info.fix()
return g.info, nil
}