Set user-agent when talking to GCE metadata

This commit is contained in:
Seth Vargo
2018-04-10 10:36:46 -04:00
parent c8a76a1ac7
commit ba6111e2a4
4 changed files with 58 additions and 0 deletions

View File

@@ -15,6 +15,7 @@ import (
"github.com/hashicorp/go-cleanhttp"
cstructs "github.com/hashicorp/nomad/client/structs"
"github.com/hashicorp/nomad/helper/useragent"
"github.com/hashicorp/nomad/nomad/structs"
)
@@ -97,6 +98,7 @@ func (f *EnvGCEFingerprint) Get(attribute string, recursive bool) (string, error
URL: parsedUrl,
Header: http.Header{
"Metadata-Flavor": []string{"Google"},
"User-Agent": []string{useragent.String()},
},
}

View File

@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/hashicorp/nomad/client/config"
@@ -66,6 +67,14 @@ func testFingerprint_GCE(t *testing.T, withExternalIp bool) {
t.Fatalf("Expected Metadata-Flavor Google, saw %s", value[0])
}
uavalue, ok := r.Header["User-Agent"]
if !ok {
t.Fatal("User-Agent not present in HTTP request header")
}
if !strings.Contains(uavalue[0], "Nomad/") {
t.Fatalf("Expected User-Agent to contain Nomad/, got %s", uavalue[0])
}
found := false
for _, e := range routes.Endpoints {
if r.RequestURI == e.Uri {

View File

@@ -0,0 +1,29 @@
package useragent
import (
"fmt"
"runtime"
"github.com/hashicorp/nomad/version"
)
var (
// projectURL is the project URL.
projectURL = "https://www.nomadproject.io/"
// rt is the runtime - variable for tests.
rt = runtime.Version()
// versionFunc is the func that returns the current version. This is a
// function to take into account the different build processes and distinguish
// between enterprise and oss builds.
versionFunc = func() string {
return version.GetVersion().VersionNumber()
}
)
// String returns the consistent user-agent string for Nomad.
func String() string {
return fmt.Sprintf("Nomad/%s (+%s; %s)",
versionFunc(), projectURL, rt)
}

View File

@@ -0,0 +1,18 @@
package useragent
import (
"testing"
)
func TestUserAgent(t *testing.T) {
projectURL = "https://nomad-test.com"
rt = "go5.0"
versionFunc = func() string { return "1.2.3" }
act := String()
exp := "Nomad/1.2.3 (+https://nomad-test.com; go5.0)"
if exp != act {
t.Errorf("expected %q to be %q", act, exp)
}
}