services: Set Nomad's User-Agent by default on HTTP checks for nomad services (#16248)

This commit is contained in:
Seth Hoenig 2023-02-23 08:10:42 -06:00 committed by GitHub
parent ddb2c309e8
commit 61404b2551
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 26 additions and 4 deletions

3
.changelog/16248.txt Normal file
View File

@ -0,0 +1,3 @@
```release-note:improvement
services: Set Nomad's User-Agent by default on HTTP checks in Nomad services
```

View File

@ -15,6 +15,7 @@ import (
"github.com/hashicorp/go-cleanhttp"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/nomad/client/serviceregistration"
"github.com/hashicorp/nomad/helper/useragent"
"github.com/hashicorp/nomad/nomad/structs"
"oss.indeed.com/go/libtime"
)
@ -163,14 +164,18 @@ func (c *checker) checkHTTP(ctx context.Context, qc *QueryContext, q *Query) *st
qr.Status = structs.CheckFailure
return qr
}
for header, values := range q.Headers {
for _, value := range values {
request.Header.Add(header, value)
}
}
request.Host = request.Header.Get("Host")
if len(request.Header.Get(useragent.Header)) == 0 {
request.Header.Set(useragent.Header, useragent.String())
}
request.Host = request.Header.Get("Host")
request.Body = io.NopCloser(strings.NewReader(q.Body))
request = request.WithContext(ctx)

View File

@ -13,6 +13,7 @@ import (
"github.com/hashicorp/nomad/ci"
"github.com/hashicorp/nomad/helper/testlog"
"github.com/hashicorp/nomad/helper/useragent"
"github.com/hashicorp/nomad/nomad/mock"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/shoenig/test/must"
@ -239,7 +240,7 @@ func TestChecker_Do_HTTP_extras(t *testing.T) {
}
encoding := [2]string{"Accept-Encoding", "gzip"}
agent := [2]string{"User-Agent", "Go-http-client/1.1"}
agent := [2]string{useragent.Header, useragent.String()}
cases := []struct {
name string
@ -270,6 +271,13 @@ func TestChecker_Do_HTTP_extras(t *testing.T) {
[2]string{"Authorization", "Basic ZWxhc3RpYzpjaGFuZ2VtZQ=="},
),
},
{
name: "user agent header",
method: "GET",
headers: makeHeaders(encoding,
[2]string{"User-Agent", "my-custom-agent"},
),
},
{
name: "host header",
method: "GET",
@ -348,7 +356,7 @@ func TestChecker_Do_HTTP_extras(t *testing.T) {
}
}
if !hostSent {
must.Eq(t, nil, tc.headers["Host"])
must.Nil(t, tc.headers["Host"])
}
must.Eq(t, tc.headers, headers)

View File

@ -8,6 +8,12 @@ import (
"github.com/hashicorp/nomad/version"
)
const (
// Header is the User-Agent header key
// https://www.rfc-editor.org/rfc/rfc7231#section-5.5.3
Header = `User-Agent`
)
var (
// projectURL is the project URL.
projectURL = "https://www.nomadproject.io/"
@ -37,6 +43,6 @@ type HeaderSetter interface {
// SetHeaders configures the User-Agent http.Header for the client.
func SetHeaders(client HeaderSetter) {
client.SetHeaders(http.Header{
"User-Agent": []string{String()},
Header: []string{String()},
})
}