Skip to content

Commit

Permalink
fix: build imds compute url correctly and give a default retryAttempts (
Browse files Browse the repository at this point in the history
#2566)

* fix: build imds compute url correctly

* fix: remove httputil debug stuff
  • Loading branch information
thatmattlong authored Feb 8, 2024
1 parent 1d36cfc commit f97eb96
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
19 changes: 11 additions & 8 deletions cns/imds/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,14 @@ func RetryAttempts(attempts uint) ClientOption {
}

const (
vmUniqueIDProperty = "vmId"
imdsComputePath = "/metadata/instance/compute?api-version=2021-01-01&format=json"
metadataHeaderKey = "Metadata"
metadataHeaderValue = "true"
defaultRetryAttempts = 10
defaultIMDSEndpoint = "http://169.254.169.254"
vmUniqueIDProperty = "vmId"
imdsComputePath = "/metadata/instance/compute"
imdsComputeAPIVersion = "api-version=2021-01-01"
imdsFormatJSON = "format=json"
metadataHeaderKey = "Metadata"
metadataHeaderValue = "true"
defaultRetryAttempts = 3
defaultIMDSEndpoint = "http://169.254.169.254"
)

var (
Expand All @@ -60,7 +62,8 @@ var (
// NewClient creates a new imds client
func NewClient(opts ...ClientOption) *Client {
config := clientConfig{
endpoint: defaultIMDSEndpoint,
endpoint: defaultIMDSEndpoint,
retryAttempts: defaultRetryAttempts,
}

for _, o := range opts {
Expand Down Expand Up @@ -104,6 +107,7 @@ func (c *Client) getInstanceComputeMetadata(ctx context.Context) (map[string]any
if err != nil {
return nil, errors.Wrap(err, "unable to build path to IMDS compute metadata")
}
imdsComputeURL = imdsComputeURL + "?" + imdsComputeAPIVersion + "&" + imdsFormatJSON

req, err := http.NewRequestWithContext(ctx, http.MethodGet, imdsComputeURL, http.NoBody)
if err != nil {
Expand All @@ -112,7 +116,6 @@ func (c *Client) getInstanceComputeMetadata(ctx context.Context) (map[string]any

// IMDS requires the "Metadata: true" header
req.Header.Add(metadataHeaderKey, metadataHeaderValue)

resp, err := c.cli.Do(req)
if err != nil {
return nil, errors.Wrap(err, "error querying IMDS")
Expand Down
6 changes: 6 additions & 0 deletions cns/imds/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ func TestGetVMUniqueID(t *testing.T) {
// request header "Metadata: true" must be present
metadataHeader := r.Header.Get("Metadata")
assert.Equal(t, "true", metadataHeader)

// query params should include apiversion and json format
apiVersion := r.URL.Query().Get("api-version")
assert.Equal(t, "2021-01-01", apiVersion)
format := r.URL.Query().Get("format")
assert.Equal(t, "json", format)
w.WriteHeader(http.StatusOK)
_, writeErr := w.Write(computeMetadata)
require.NoError(t, writeErr, "error writing response")
Expand Down

0 comments on commit f97eb96

Please sign in to comment.