Skip to content

Commit

Permalink
fix header comparison causing spurious http checks
Browse files Browse the repository at this point in the history
Consul modifies (adds headers) the header map on the cached version
which makes it always fail the comparison (DeepEqual) test. This fixes
the comparison to ignore the fields Consul adds.
  • Loading branch information
eikenb committed Oct 12, 2022
1 parent f49b952 commit e603bf4
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 1 deletion.
18 changes: 17 additions & 1 deletion check.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ func (c *CheckRunner) updateCheckHTTP(
httpCheck, httpCheckExists := c.checksHTTP.Load(checkHash)
if httpCheckExists &&
httpCheck.HTTP == http.HTTP &&
reflect.DeepEqual(httpCheck.Header, http.Header) &&
headersAlmostEqual(httpCheck.Header, http.Header) &&
httpCheck.Method == http.Method &&
httpCheck.TLSClientConfig.InsecureSkipVerify == http.TLSClientConfig.InsecureSkipVerify &&
httpCheck.TLSClientConfig.ServerName == http.TLSClientConfig.ServerName &&
Expand Down Expand Up @@ -172,6 +172,22 @@ func (c *CheckRunner) updateCheckHTTP(
return true
}

// Compares headers, skipping ones automatically added by Consul
// in consul/agent/checks/check.go
func headersAlmostEqual(h1, h2 map[string][]string) bool {
skip := map[string]bool{"User-Agent": true, "Accept": true}
for k1, v1 := range h1 {
if skip[k1] {
continue
}
v2 := h2[k1]
if !reflect.DeepEqual(v1, v2) {
return false
}
}
return true
}

func (c *CheckRunner) updateCheckTCP(
latestCheck *api.HealthCheck, checkHash types.CheckID,
definition *api.HealthCheckDefinition, updated, added checkIDSet,
Expand Down
47 changes: 47 additions & 0 deletions check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -423,3 +423,50 @@ func TestCheck_NoFlapping(t *testing.T) {
assert.Equal(t, 1, currentCheck.successCounter)
assert.Equal(t, api.HealthCritical, currentCheck.Status)
}

func TestHeadersAlmostEqual(t *testing.T) {
type headers map[string][]string
type testCase struct {
h1, h2 headers
equal bool
}
testCases := []testCase{
{
h1: headers{},
h2: headers{},
equal: true,
},
{
h1: headers{"foo": {"foo"}},
h2: headers{"bar": {"bar"}},
equal: false,
},
{
h1: headers{"User-Agent": {"foo"}},
h2: headers{"Accept": {"bar"}},
equal: true,
},
{
h1: headers{"foo": {"foo"}, "User-Agent": {"foo"}},
h2: headers{"Accept": {"bar"}},
equal: false,
},
{
h1: headers{"foo": {"foo"}, "User-Agent": {"foo"}},
h2: headers{"foo": {"foo"}, "Accept": {"bar"}},
equal: true,
},
}
for _, tc := range testCases {
switch eq := headersAlmostEqual(tc.h1, tc.h2); tc.equal {
case true:
if !eq {
t.Error("headers should be equal", tc.h1, tc.h2)
}
case false:
if eq {
t.Error("headers should NOT be equal", tc.h1, tc.h2)
}
}
}
}

0 comments on commit e603bf4

Please sign in to comment.