github.com/stevenmatthewt/agent@v3.5.4+incompatible/agent/gcp_meta_data.go (about)

     1  package agent
     2  
     3  import (
     4  	"errors"
     5  	"strings"
     6  
     7  	"cloud.google.com/go/compute/metadata"
     8  )
     9  
    10  type GCPMetaData struct {
    11  }
    12  
    13  func (e GCPMetaData) Get() (map[string]string, error) {
    14  	result := make(map[string]string)
    15  
    16  	instanceId, err := metadata.Get("instance/id")
    17  	if err != nil {
    18  		return result, err
    19  	}
    20  	result["gcp:instance-id"] = instanceId
    21  
    22  	machineType, err := machineType()
    23  	if err != nil {
    24  		return result, err
    25  	}
    26  	result["gcp:machine-type"] = machineType
    27  
    28  	preemptible, err := metadata.Get("instance/scheduling/preemptible")
    29  	if err != nil {
    30  		return result, err
    31  	}
    32  	result["gcp:preemptible"] = strings.ToLower(preemptible)
    33  
    34  	projectId, err := metadata.ProjectID()
    35  	if err != nil {
    36  		return result, err
    37  	}
    38  	result["gcp:project-id"] = projectId
    39  
    40  	zone, err := metadata.Zone()
    41  	if err != nil {
    42  		return result, err
    43  	}
    44  	result["gcp:zone"] = zone
    45  
    46  	region, err := parseRegionFromZone(zone)
    47  	if err != nil {
    48  		return result, err
    49  	}
    50  	result["gcp:region"] = region
    51  
    52  	return result, nil
    53  }
    54  
    55  func machineType() (string, error) {
    56  	machType, err := metadata.Get("instance/machine-type")
    57  	// machType is of the form "projects/<projNum>/machineTypes/<machType>".
    58  	if err != nil {
    59  		return "", err
    60  	}
    61  	index := strings.LastIndex(machType, "/")
    62  	if index == -1 {
    63  		return "", errors.New("cannot parse machine-type: " + machType)
    64  	}
    65  	return machType[index+1:], nil
    66  }
    67  
    68  func parseRegionFromZone(zone string) (string, error) {
    69  	// zone is of the form "<region>-<letter>".
    70  	index := strings.LastIndex(zone, "-")
    71  	if index == -1 {
    72  		return "", errors.New("cannot parse zone: " + zone)
    73  	}
    74  	return zone[:index], nil
    75  }