-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmetadata.go
86 lines (77 loc) · 2.16 KB
/
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
package gke
import (
"context"
"encoding/json"
"os"
"strings"
"cloud.google.com/go/compute/metadata"
)
type GKEMetaData struct {
ClusterLocation string
ClusterName string
ContainerName string
Namespace string
InstanceName string
InstanceID int64
NumericProjectID int64
PodName string
ProjectID string
Zone string
}
type instance struct {
Instance struct {
Attributes struct {
ClusterLocation string `json:"cluster-location"`
ClusterName string `json:"cluster-name"`
ClusterUID string `json:"cluster-uid"`
} `json:"attributes"`
Hostname string `json:"hostname"`
ID int64 `json:"id"`
Name string `json:"name"`
NetworkInterfaces map[string]struct {
Ipv6s string `json:"ipv6s"`
} `json:"networkInterfaces"`
ServiceAccounts map[string]struct {
Aliases []string `json:"aliases"`
Email string `json:"email"`
Scopes []string `json:"scopes"`
} `json:"serviceAccounts"`
Zone string `json:"zone"`
} `json:"instance"`
Project struct {
NumericProjectID int64 `json:"numericProjectId"`
ProjectID string `json:"projectId"`
} `json:"project"`
}
func parseInstanceJSON(jsonData []byte) (*instance, error) {
var instance instance
err := json.Unmarshal(jsonData, &instance)
if err != nil {
return nil, err
}
return &instance, nil
}
func GetMetaData(ctx context.Context) (*GKEMetaData, error) {
s, err := metadata.GetWithContext(ctx, "/?recursive=true")
if err != nil {
return &GKEMetaData{}, err
}
i, err := parseInstanceJSON([]byte(s))
if err != nil {
return &GKEMetaData{}, err
}
zp := strings.Split(i.Instance.Zone, "/")
zoneName := zp[len(zp)-1]
return &GKEMetaData{
ClusterLocation: i.Instance.Attributes.ClusterLocation,
ClusterName: i.Instance.Attributes.ClusterName,
ContainerName: os.Getenv("CONTAINER_NAME"),
Namespace: os.Getenv("POD_NAMESPACE"),
InstanceName: i.Instance.Name,
InstanceID: i.Instance.ID,
NumericProjectID: i.Project.NumericProjectID,
PodName: os.Getenv("POD_NAME"),
ProjectID: i.Project.ProjectID,
Zone: zoneName,
}, nil
}