Skip to content

Commit

Permalink
compute/metadata: add an error type for undefined metadata
Browse files Browse the repository at this point in the history
Change-Id: I215d03cd6443903fd642c8558c1ecb8a32a369ca
  • Loading branch information
bradfitz authored and Gerrit Code Review committed Jan 14, 2015
1 parent a5869dd commit 2e43671
Showing 1 changed file with 30 additions and 0 deletions.
30 changes: 30 additions & 0 deletions compute/metadata/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,8 +73,23 @@ func dialer() *net.Dialer {
}
}

// NotDefinedError is returned when requested metadata is not defined.
//
// The underlying string is the suffix after "/computeMetadata/v1/".
//
// This error is not returned if the value is defined to be the empty
// string.
type NotDefinedError string

func (suffix NotDefinedError) Error() string {
return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix))
}

// Get returns a value from the metadata service.
// The suffix is appended to "http://metadata/computeMetadata/v1/".
//
// If the requested metadata is not defined, the returned error will
// be of type NotDefinedError.
func Get(suffix string) (string, error) {
// Using 169.254.169.254 instead of "metadata" here because Go
// binaries built with the "netgo" tag and without cgo won't
Expand All @@ -89,6 +104,9 @@ func Get(suffix string) (string, error) {
return "", err
}
defer res.Body.Close()
if res.StatusCode == http.StatusNotFound {
return "", NotDefinedError(suffix)
}
if res.StatusCode != 200 {
return "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url)
}
Expand Down Expand Up @@ -216,12 +234,24 @@ func lines(suffix string) ([]string, error) {

// InstanceAttributeValue returns the value of the provided VM
// instance attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// InstanceAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func InstanceAttributeValue(attr string) (string, error) {
return Get("instance/attributes/" + attr)
}

// ProjectAttributeValue returns the value of the provided
// project attribute.
//
// If the requested attribute is not defined, the returned error will
// be of type NotDefinedError.
//
// ProjectAttributeValue may return ("", nil) if the attribute was
// defined to be the empty string.
func ProjectAttributeValue(attr string) (string, error) {
return Get("project/attributes/" + attr)
}
Expand Down

0 comments on commit 2e43671

Please sign in to comment.