agent: LastContact cannot be negative (#3067)

The X-Consul-LastContact header cannot be negative.

Fixes #3067
This commit is contained in:
Frank Schroeder 2017-06-01 13:53:27 +02:00 committed by Frank Schröder
parent b66eb6b6ac
commit 7f18fe1a5b
2 changed files with 22 additions and 5 deletions

View File

@ -311,6 +311,9 @@ func setKnownLeader(resp http.ResponseWriter, known bool) {
// setLastContact is used to set the last contact header // setLastContact is used to set the last contact header
func setLastContact(resp http.ResponseWriter, last time.Duration) { func setLastContact(resp http.ResponseWriter, last time.Duration) {
if last < 0 {
last = 0
}
lastMsec := uint64(last / time.Millisecond) lastMsec := uint64(last / time.Millisecond)
resp.Header().Set("X-Consul-LastContact", strconv.FormatUint(lastMsec, 10)) resp.Header().Set("X-Consul-LastContact", strconv.FormatUint(lastMsec, 10))
} }

View File

@ -150,11 +150,25 @@ func TestSetKnownLeader(t *testing.T) {
func TestSetLastContact(t *testing.T) { func TestSetLastContact(t *testing.T) {
t.Parallel() t.Parallel()
resp := httptest.NewRecorder() tests := []struct {
setLastContact(resp, 123456*time.Microsecond) desc string
header := resp.Header().Get("X-Consul-LastContact") d time.Duration
if header != "123" { h string
t.Fatalf("Bad: %v", header) }{
{"neg", -1, "0"},
{"zero", 0, "0"},
{"pos", 123 * time.Millisecond, "123"},
{"pos ms only", 123456 * time.Microsecond, "123"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
resp := httptest.NewRecorder()
setLastContact(resp, tt.d)
header := resp.Header().Get("X-Consul-LastContact")
if got, want := header, tt.h; got != want {
t.Fatalf("got X-Consul-LastContact header %q want %q", got, want)
}
})
} }
} }