github.com/m-lab/locate@v0.17.6/cmd/heartbeat/metadata/gcp.go (about) 1 package metadata 2 3 import ( 4 "fmt" 5 "strings" 6 7 "github.com/m-lab/go/host" 8 ) 9 10 const groupTemplate = "https://www.googleapis.com/compute/v1/projects/%s/regions/%s/instanceGroups/%s" 11 12 // GCPMetadata contains metadata about a GCP VM. 13 type GCPMetadata struct { 14 project string 15 backend string 16 region string 17 group string 18 } 19 20 // Client uses HTTP requests to query the metadata service. 21 type Client interface { 22 ProjectID() (string, error) 23 Zone() (string, error) 24 } 25 26 // NewGCPMetadata returns a new instance of GCPMetadata. 27 func NewGCPMetadata(c Client, hostname string) (*GCPMetadata, error) { 28 h, err := host.Parse(hostname) 29 if err != nil { 30 return nil, err 31 } 32 // Backend refers to the GCP load balancer. 33 // Resources for a GCP load balancer all have the same name. That is, 34 // the VM hostname with dots turned to dashes (since GCP does not allow 35 // dots in names). 36 backend := strings.ReplaceAll(h.String(), ".", "-") 37 38 project, err := c.ProjectID() 39 if err != nil { 40 return nil, err 41 } 42 43 zone, err := c.Zone() 44 if err != nil { 45 return nil, err 46 } 47 region := zone[:len(zone)-2] 48 49 return &GCPMetadata{ 50 project: project, 51 backend: backend, 52 region: region, 53 group: fmt.Sprintf(groupTemplate, project, region, backend), 54 }, nil 55 } 56 57 // Project ID (e.g., mlab-sandbox). 58 func (m *GCPMetadata) Project() string { 59 return m.project 60 } 61 62 // Backend in GCE. 63 func (m *GCPMetadata) Backend() string { 64 return m.backend 65 } 66 67 // Region derived from zone (e.g., us-west1). 68 func (m *GCPMetadata) Region() string { 69 return m.region 70 } 71 72 // Group is the the URI referencing the instance group. 73 func (m *GCPMetadata) Group() string { 74 return m.group 75 }