forked from DataDog/dd-trace-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
internal/hostname: Add tracer side hostname detection (DataDog#1712)
- Loading branch information
1 parent
0ef937c
commit 3ccf65d
Showing
23 changed files
with
1,382 additions
and
7 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
// Unless explicitly stated otherwise all files in this repository are licensed | ||
// under the Apache License Version 2.0. | ||
// This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
// Copyright 2016-present Datadog, Inc. | ||
|
||
package azure | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"time" | ||
|
||
"gopkg.in/DataDog/dd-trace-go.v1/internal/hostname/cachedfetch" | ||
"gopkg.in/DataDog/dd-trace-go.v1/internal/hostname/httputils" | ||
"gopkg.in/DataDog/dd-trace-go.v1/internal/hostname/validate" | ||
) | ||
|
||
// declare these as vars not const to ease testing | ||
var ( | ||
metadataURL = "http://169.254.169.254" | ||
timeout = 300 * time.Millisecond | ||
|
||
// CloudProviderName contains the inventory name of for Azure | ||
CloudProviderName = "Azure" | ||
) | ||
|
||
func getResponse(ctx context.Context, url string) (string, error) { | ||
return httputils.Get(ctx, url, map[string]string{"Metadata": "true"}, timeout) | ||
} | ||
|
||
// GetHostname returns hostname based on Azure instance metadata. | ||
func GetHostname(ctx context.Context) (string, error) { | ||
metadataJSON, err := instanceMetaFetcher.Fetch(ctx) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
var metadata struct { | ||
VMID string | ||
} | ||
if err := json.Unmarshal([]byte(metadataJSON), &metadata); err != nil { | ||
return "", fmt.Errorf("failed to parse Azure instance metadata: %s", err) | ||
} | ||
|
||
if err := validate.ValidHostname(metadata.VMID); err != nil { | ||
return "", err | ||
} | ||
|
||
return metadata.VMID, nil | ||
} | ||
|
||
var instanceMetaFetcher = cachedfetch.Fetcher{ | ||
Name: "Azure Instance Metadata", | ||
Attempt: func(ctx context.Context) (string, error) { | ||
metadataJSON, err := getResponse(ctx, | ||
metadataURL+"/metadata/instance/compute?api-version=2017-08-01") | ||
if err != nil { | ||
return "", fmt.Errorf("failed to get Azure instance metadata: %s", err) | ||
} | ||
return metadataJSON, nil | ||
}, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
// Unless explicitly stated otherwise all files in this repository are licensed | ||
// under the Apache License Version 2.0. | ||
// This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
// Copyright 2016-present Datadog, Inc. | ||
|
||
package azure | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestGetHostname(t *testing.T) { | ||
ctx := context.Background() | ||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
w.Header().Set("Content-Type", "application/json") | ||
io.WriteString(w, `{ | ||
"name": "vm-name", | ||
"resourceGroupName": "my-resource-group", | ||
"subscriptionId": "2370ac56-5683-45f8-a2d4-d1054292facb", | ||
"vmId": "b33fa46-6aff-4dfa-be0a-9e922ca3ac6d" | ||
}`) | ||
})) | ||
defer ts.Close() | ||
metadataURL = ts.URL | ||
|
||
cases := []struct { | ||
value string | ||
err bool | ||
}{ | ||
{"b33fa46-6aff-4dfa-be0a-9e922ca3ac6d", false}, | ||
} | ||
|
||
for _, tt := range cases { | ||
hostname, err := GetHostname(ctx) | ||
assert.Equal(t, tt.value, hostname) | ||
assert.Equal(t, tt.err, err != nil) | ||
} | ||
} | ||
|
||
func TestGetHostnameWithInvalidMetadata(t *testing.T) { | ||
ctx := context.Background() | ||
|
||
for _, response := range []string{"", "!"} { | ||
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
w.Header().Set("Content-Type", "application/json") | ||
io.WriteString(w, fmt.Sprintf(`{ | ||
"name": "%s", | ||
"resourceGroupName": "%s", | ||
"subscriptionId": "%s", | ||
"vmId": "%s" | ||
}`, response, response, response, response)) | ||
})) | ||
metadataURL = ts.URL | ||
|
||
t.Run(fmt.Sprintf("with response '%s'", response), func(t *testing.T) { | ||
hostname, err := GetHostname(ctx) | ||
assert.Empty(t, hostname) | ||
assert.NotNil(t, err) | ||
}) | ||
|
||
ts.Close() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,86 @@ | ||
// Unless explicitly stated otherwise all files in this repository are licensed | ||
// under the Apache License Version 2.0. | ||
// This product includes software developed at Datadog (https://www.datadoghq.com/). | ||
// Copyright 2016-present Datadog, Inc. | ||
|
||
// This file is pulled from datadog-agent/pkg/util/cachedfetch changing the logger and using strings only | ||
|
||
// Package cachedfetch provides a read-through cache for fetched values. | ||
package cachedfetch | ||
|
||
import ( | ||
"context" | ||
"sync" | ||
|
||
"gopkg.in/DataDog/dd-trace-go.v1/internal/log" | ||
) | ||
|
||
// Fetcher supports fetching a value, such as from a cloud service API. An | ||
// attempt is made to fetch the value on each call to Fetch, but if that | ||
// attempt fails then a cached value from the last successful attempt is | ||
// returned, if such a value exists. This helps the agent to "ride out" | ||
// temporary failures in cloud APIs while still fetching fresh data when those | ||
// APIs are functioning properly. Cached values do not expire. | ||
// | ||
// Callers should instantiate one fetcher per piece of data required. | ||
type Fetcher struct { | ||
// function that attempts to fetch the value | ||
Attempt func(context.Context) (string, error) | ||
|
||
// the name of the thing being fetched, used in the default log message. At | ||
// least one of Name and LogFailure must be non-nil. | ||
Name string | ||
|
||
// function to log a fetch failure, given the error and the last successful | ||
// value. This function is not called if there is no last successful value. | ||
// If left at its zero state, a default log message will be generated, using | ||
// Name. | ||
LogFailure func(error, interface{}) | ||
|
||
// previous successfully fetched value | ||
lastValue interface{} | ||
|
||
// mutex to protect access to lastValue | ||
sync.Mutex | ||
} | ||
|
||
// Fetch attempts to fetch the value, returning the result or the last successful | ||
// value, or an error if no attempt has ever been successful. No special handling | ||
// is included for the Context: both context.Cancelled and context.DeadlineExceeded | ||
// are handled like any other error by returning the cached value. | ||
// | ||
// This can be called from multiple goroutines, in which case it will call Attempt | ||
// concurrently. | ||
func (f *Fetcher) Fetch(ctx context.Context) (string, error) { | ||
value, err := f.Attempt(ctx) | ||
if err == nil { | ||
f.Lock() | ||
f.lastValue = value | ||
f.Unlock() | ||
return value, nil | ||
} | ||
|
||
f.Lock() | ||
lastValue := f.lastValue | ||
f.Unlock() | ||
|
||
if lastValue == nil { | ||
// attempt was never successful | ||
return value, err | ||
} | ||
|
||
if f.LogFailure == nil { | ||
log.Debug("Unable to get %s; returning cached value instead", f.Name) | ||
} else { | ||
f.LogFailure(err, lastValue) | ||
} | ||
|
||
return lastValue.(string), nil | ||
} | ||
|
||
// Reset resets the cached value (used for testing) | ||
func (f *Fetcher) Reset() { | ||
f.Lock() | ||
f.lastValue = nil | ||
f.Unlock() | ||
} |
Oops, something went wrong.