| 1 |
/* |
| 2 |
Copyright 2014 The Kubernetes Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package healthz |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"errors" |
| 22 |
"fmt" |
| 23 |
"net/http" |
| 24 |
"net/http/httptest" |
| 25 |
"net/url" |
| 26 |
"reflect" |
| 27 |
"strings" |
| 28 |
"testing" |
| 29 |
|
| 30 |
corev1 "k8s.io/api/core/v1" |
| 31 |
"k8s.io/apimachinery/pkg/util/sets" |
| 32 |
"k8s.io/apiserver/pkg/endpoints/metrics" |
| 33 |
"k8s.io/component-base/metrics/legacyregistry" |
| 34 |
"k8s.io/component-base/metrics/testutil" |
| 35 |
) |
| 36 |
|
| 37 |
func TestInstallHandler(t *testing.T) { |
| 38 |
mux := http.NewServeMux() |
| 39 |
InstallHandler(mux) |
| 40 |
req, err := http.NewRequest("GET", "http://example.com/healthz", nil) |
| 41 |
if err != nil { |
| 42 |
t.Fatalf("unexpected error: %v", err) |
| 43 |
} |
| 44 |
w := httptest.NewRecorder() |
| 45 |
mux.ServeHTTP(w, req) |
| 46 |
if w.Code != http.StatusOK { |
| 47 |
t.Errorf("expected %v, got %v", http.StatusOK, w.Code) |
| 48 |
} |
| 49 |
c := w.Header().Get("Content-Type") |
| 50 |
if c != "text/plain; charset=utf-8" { |
| 51 |
t.Errorf("expected %v, got %v", "text/plain", c) |
| 52 |
} |
| 53 |
if w.Body.String() != "ok" { |
| 54 |
t.Errorf("expected %v, got %v", "ok", w.Body.String()) |
| 55 |
} |
| 56 |
} |
| 57 |
|
| 58 |
func TestInstallPathHandler(t *testing.T) { |
| 59 |
mux := http.NewServeMux() |
| 60 |
InstallPathHandler(mux, "/healthz/test") |
| 61 |
InstallPathHandler(mux, "/healthz/ready") |
| 62 |
req, err := http.NewRequest("GET", "http://example.com/healthz/test", nil) |
| 63 |
if err != nil { |
| 64 |
t.Fatalf("unexpected error: %v", err) |
| 65 |
} |
| 66 |
w := httptest.NewRecorder() |
| 67 |
mux.ServeHTTP(w, req) |
| 68 |
if w.Code != http.StatusOK { |
| 69 |
t.Errorf("expected %v, got %v", http.StatusOK, w.Code) |
| 70 |
} |
| 71 |
c := w.Header().Get("Content-Type") |
| 72 |
if c != "text/plain; charset=utf-8" { |
| 73 |
t.Errorf("expected %v, got %v", "text/plain", c) |
| 74 |
} |
| 75 |
if w.Body.String() != "ok" { |
| 76 |
t.Errorf("expected %v, got %v", "ok", w.Body.String()) |
| 77 |
} |
| 78 |
|
| 79 |
req, err = http.NewRequest("GET", "http://example.com/healthz/ready", nil) |
| 80 |
if err != nil { |
| 81 |
t.Fatalf("unexpected error: %v", err) |
| 82 |
} |
| 83 |
w = httptest.NewRecorder() |
| 84 |
mux.ServeHTTP(w, req) |
| 85 |
if w.Code != http.StatusOK { |
| 86 |
t.Errorf("expected %v, got %v", http.StatusOK, w.Code) |
| 87 |
} |
| 88 |
c = w.Header().Get("Content-Type") |
| 89 |
if c != "text/plain; charset=utf-8" { |
| 90 |
t.Errorf("expected %v, got %v", "text/plain", c) |
| 91 |
} |
| 92 |
if w.Body.String() != "ok" { |
| 93 |
t.Errorf("expected %v, got %v", "ok", w.Body.String()) |
| 94 |
} |
| 95 |
|
| 96 |
} |
| 97 |
|
| 98 |
func testMultipleChecks(path, name string, t *testing.T) { |
| 99 |
tests := []struct { |
| 100 |
path string |
| 101 |
expectedResponse string |
| 102 |
expectedStatus int |
| 103 |
addBadCheck bool |
| 104 |
}{ |
| 105 |
{"?verbose", fmt.Sprintf("[+]ping ok\n%s check passed\n", name), http.StatusOK, false}, |
| 106 |
{"?exclude=dontexist", "ok", http.StatusOK, false}, |
| 107 |
{"?exclude=bad", "ok", http.StatusOK, true}, |
| 108 |
{"?verbose=true&exclude=bad", fmt.Sprintf("[+]ping ok\n[+]bad excluded: ok\n%s check passed\n", name), http.StatusOK, true}, |
| 109 |
{"?verbose=true&exclude=dontexist", fmt.Sprintf("[+]ping ok\nwarn: some health checks cannot be excluded: no matches for \"dontexist\"\n%s check passed\n", name), http.StatusOK, false}, |
| 110 |
{"/ping", "ok", http.StatusOK, false}, |
| 111 |
{"", "ok", http.StatusOK, false}, |
| 112 |
{"?verbose", fmt.Sprintf("[+]ping ok\n[-]bad failed: reason withheld\n%s check failed\n", name), http.StatusInternalServerError, true}, |
| 113 |
{"/ping", "ok", http.StatusOK, true}, |
| 114 |
{"/bad", "internal server error: this will fail\n", http.StatusInternalServerError, true}, |
| 115 |
{"", fmt.Sprintf("[+]ping ok\n[-]bad failed: reason withheld\n%s check failed\n", name), http.StatusInternalServerError, true}, |
| 116 |
} |
| 117 |
|
| 118 |
for i, test := range tests { |
| 119 |
mux := http.NewServeMux() |
| 120 |
checks := []HealthChecker{PingHealthz} |
| 121 |
if test.addBadCheck { |
| 122 |
checks = append(checks, NamedCheck("bad", func(_ *http.Request) error { |
| 123 |
return errors.New("this will fail") |
| 124 |
})) |
| 125 |
} |
| 126 |
if path == "" { |
| 127 |
InstallHandler(mux, checks...) |
| 128 |
path = "/healthz" |
| 129 |
} else { |
| 130 |
InstallPathHandler(mux, path, checks...) |
| 131 |
} |
| 132 |
req, err := http.NewRequest("GET", fmt.Sprintf("http://example.com%s%v", path, test.path), nil) |
| 133 |
if err != nil { |
| 134 |
t.Fatalf("case[%d] Unexpected error: %v", i, err) |
| 135 |
} |
| 136 |
w := httptest.NewRecorder() |
| 137 |
mux.ServeHTTP(w, req) |
| 138 |
if w.Code != test.expectedStatus { |
| 139 |
t.Errorf("case[%d] Expected: %v, got: %v", i, test.expectedStatus, w.Code) |
| 140 |
} |
| 141 |
c := w.Header().Get("Content-Type") |
| 142 |
if c != "text/plain; charset=utf-8" { |
| 143 |
t.Errorf("case[%d] Expected: %v, got: %v", i, "text/plain", c) |
| 144 |
} |
| 145 |
if w.Body.String() != test.expectedResponse { |
| 146 |
t.Errorf("case[%d] Expected:\n%v\ngot:\n%v\n", i, test.expectedResponse, w.Body.String()) |
| 147 |
} |
| 148 |
} |
| 149 |
} |
| 150 |
|
| 151 |
func TestMultipleChecks(t *testing.T) { |
| 152 |
testMultipleChecks("", "healthz", t) |
| 153 |
} |
| 154 |
|
| 155 |
func TestMultiplePathChecks(t *testing.T) { |
| 156 |
testMultipleChecks("/ready", "ready", t) |
| 157 |
} |
| 158 |
|
| 159 |
func TestCheckerNames(t *testing.T) { |
| 160 |
n1 := "n1" |
| 161 |
n2 := "n2" |
| 162 |
c1 := &healthzCheck{name: n1} |
| 163 |
c2 := &healthzCheck{name: n2} |
| 164 |
|
| 165 |
testCases := []struct { |
| 166 |
desc string |
| 167 |
have []HealthChecker |
| 168 |
want []string |
| 169 |
}{ |
| 170 |
{"no checker", []HealthChecker{}, []string{}}, |
| 171 |
{"one checker", []HealthChecker{c1}, []string{n1}}, |
| 172 |
{"other checker", []HealthChecker{c2}, []string{n2}}, |
| 173 |
{"checker order", []HealthChecker{c1, c2}, []string{n1, n2}}, |
| 174 |
{"different checker order", []HealthChecker{c2, c1}, []string{n2, n1}}, |
| 175 |
} |
| 176 |
|
| 177 |
for _, tc := range testCases { |
| 178 |
result := checkerNames(tc.have...) |
| 179 |
t.Run(tc.desc, func(t *testing.T) { |
| 180 |
if !reflect.DeepEqual(tc.want, result) { |
| 181 |
t.Errorf("want %#v, got %#v", tc.want, result) |
| 182 |
} |
| 183 |
}) |
| 184 |
} |
| 185 |
} |
| 186 |
|
| 187 |
func TestFormatQuoted(t *testing.T) { |
| 188 |
n1 := "n1" |
| 189 |
n2 := "n2" |
| 190 |
testCases := []struct { |
| 191 |
desc string |
| 192 |
names []string |
| 193 |
expected string |
| 194 |
}{ |
| 195 |
{"empty", []string{}, ""}, |
| 196 |
{"single name", []string{n1}, "\"n1\""}, |
| 197 |
{"two names", []string{n1, n2}, "\"n1\",\"n2\""}, |
| 198 |
{"two names, reverse order", []string{n2, n1}, "\"n2\",\"n1\""}, |
| 199 |
} |
| 200 |
for _, tc := range testCases { |
| 201 |
result := formatQuoted(tc.names...) |
| 202 |
t.Run(tc.desc, func(t *testing.T) { |
| 203 |
if result != tc.expected { |
| 204 |
t.Errorf("expected %#v, got %#v", tc.expected, result) |
| 205 |
} |
| 206 |
}) |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
func TestGetExcludedChecks(t *testing.T) { |
| 211 |
tests := []struct { |
| 212 |
name string |
| 213 |
r *http.Request |
| 214 |
want sets.String |
| 215 |
}{ |
| 216 |
{"Should have no excluded health checks", |
| 217 |
createGetRequestWithUrl("/healthz?verbose=true"), |
| 218 |
sets.NewString(), |
| 219 |
}, |
| 220 |
{"Should extract out the ping health check", |
| 221 |
createGetRequestWithUrl("/healthz?exclude=ping"), |
| 222 |
sets.NewString("ping"), |
| 223 |
}, |
| 224 |
{"Should extract out ping and log health check", |
| 225 |
createGetRequestWithUrl("/healthz?exclude=ping&exclude=log"), |
| 226 |
sets.NewString("ping", "log"), |
| 227 |
}, |
| 228 |
} |
| 229 |
for _, tt := range tests { |
| 230 |
t.Run(tt.name, func(t *testing.T) { |
| 231 |
if got := getExcludedChecks(tt.r); !reflect.DeepEqual(got, tt.want) { |
| 232 |
t.Errorf("getExcludedChecks() = %v, want %v", got, tt.want) |
| 233 |
} |
| 234 |
}) |
| 235 |
} |
| 236 |
} |
| 237 |
|
| 238 |
func TestMetrics(t *testing.T) { |
| 239 |
mux := http.NewServeMux() |
| 240 |
InstallHandler(mux) |
| 241 |
InstallLivezHandler(mux) |
| 242 |
InstallReadyzHandler(mux) |
| 243 |
metrics.Register() |
| 244 |
metrics.Reset() |
| 245 |
|
| 246 |
paths := []string{"/healthz", "/livez", "/readyz"} |
| 247 |
for _, path := range paths { |
| 248 |
req, err := http.NewRequest("GET", fmt.Sprintf("http://example.com%s", path), nil) |
| 249 |
if err != nil { |
| 250 |
t.Errorf("%v", err) |
| 251 |
} |
| 252 |
mux.ServeHTTP(httptest.NewRecorder(), req) |
| 253 |
} |
| 254 |
|
| 255 |
expected := strings.NewReader(` |
| 256 |
# HELP apiserver_request_total [STABLE] Counter of apiserver requests broken out for each verb, dry run value, group, version, resource, scope, component, and HTTP response code. |
| 257 |
# TYPE apiserver_request_total counter |
| 258 |
apiserver_request_total{code="200",component="",dry_run="",group="",resource="",scope="",subresource="/healthz",verb="GET",version=""} 1 |
| 259 |
apiserver_request_total{code="200",component="",dry_run="",group="",resource="",scope="",subresource="/livez",verb="GET",version=""} 1 |
| 260 |
apiserver_request_total{code="200",component="",dry_run="",group="",resource="",scope="",subresource="/readyz",verb="GET",version=""} 1 |
| 261 |
`) |
| 262 |
if err := testutil.GatherAndCompare(legacyregistry.DefaultGatherer, expected, "apiserver_request_total"); err != nil { |
| 263 |
t.Error(err) |
| 264 |
} |
| 265 |
} |
| 266 |
|
| 267 |
func createGetRequestWithUrl(rawUrlString string) *http.Request { |
| 268 |
url, _ := url.Parse(rawUrlString) |
| 269 |
return &http.Request{ |
| 270 |
Method: http.MethodGet, |
| 271 |
Proto: "HTTP/1.1", |
| 272 |
URL: url, |
| 273 |
} |
| 274 |
} |
| 275 |
|
| 276 |
func TestInformerSyncHealthChecker(t *testing.T) { |
| 277 |
t.Run("test that check returns nil when all informers are started", func(t *testing.T) { |
| 278 |
healthChecker := NewInformerSyncHealthz(cacheSyncWaiterStub{ |
| 279 |
startedByInformerType: map[reflect.Type]bool{ |
| 280 |
reflect.TypeOf(corev1.Pod{}): true, |
| 281 |
}, |
| 282 |
}) |
| 283 |
|
| 284 |
err := healthChecker.Check(nil) |
| 285 |
if err != nil { |
| 286 |
t.Errorf("Got %v, expected no error", err) |
| 287 |
} |
| 288 |
}) |
| 289 |
|
| 290 |
t.Run("test that check returns err when there is not started informer", func(t *testing.T) { |
| 291 |
healthChecker := NewInformerSyncHealthz(cacheSyncWaiterStub{ |
| 292 |
startedByInformerType: map[reflect.Type]bool{ |
| 293 |
reflect.TypeOf(corev1.Pod{}): true, |
| 294 |
reflect.TypeOf(corev1.Service{}): false, |
| 295 |
reflect.TypeOf(corev1.Node{}): true, |
| 296 |
}, |
| 297 |
}) |
| 298 |
|
| 299 |
err := healthChecker.Check(nil) |
| 300 |
if err == nil { |
| 301 |
t.Errorf("expected error, got: %v", err) |
| 302 |
} |
| 303 |
}) |
| 304 |
} |
| 305 |
|
| 306 |
type cacheSyncWaiterStub struct { |
| 307 |
startedByInformerType map[reflect.Type]bool |
| 308 |
} |
| 309 |
|
| 310 |
// WaitForCacheSync is a stub implementation of the corresponding func |
| 311 |
// that simply returns the value passed during stub initialization. |
| 312 |
func (s cacheSyncWaiterStub) WaitForCacheSync(_ <-chan struct{}) map[reflect.Type]bool { |
| 313 |
return s.startedByInformerType |
| 314 |
} |
| 315 |
|
| 316 |
func TestInstallPathHandlerWithHealthyFunc(t *testing.T) { |
| 317 |
mux := http.NewServeMux() |
| 318 |
readyzCh := make(chan struct{}) |
| 319 |
|
| 320 |
hasBeenReadyCounter := 0 |
| 321 |
hasBeenReadyFn := func() { |
| 322 |
hasBeenReadyCounter++ |
| 323 |
} |
| 324 |
InstallPathHandlerWithHealthyFunc(mux, "/readyz", hasBeenReadyFn, readyOnChanClose{readyzCh}) |
| 325 |
|
| 326 |
// scenario 1: expect the check to fail since the channel hasn't been closed |
| 327 |
req, err := http.NewRequest("GET", fmt.Sprintf("http://example.com%s", "/readyz"), nil) |
| 328 |
if err != nil { |
| 329 |
t.Errorf("%v", err) |
| 330 |
} |
| 331 |
rr := httptest.NewRecorder() |
| 332 |
mux.ServeHTTP(rr, req) |
| 333 |
if rr.Code != http.StatusInternalServerError { |
| 334 |
t.Errorf("scenario 1: unexpected status code returned, expected %d, got %d", http.StatusInternalServerError, rr.Code) |
| 335 |
} |
| 336 |
|
| 337 |
// scenario 2: close the channel that will cause the readyz checker to report success, |
| 338 |
// verify that hasBeenReadyFn was called |
| 339 |
close(readyzCh) |
| 340 |
rr = httptest.NewRecorder() |
| 341 |
req = req.Clone(context.TODO()) |
| 342 |
mux.ServeHTTP(rr, req) |
| 343 |
if rr.Code != http.StatusOK { |
| 344 |
t.Errorf("scenario 2: unexpected status code returned, expected %d, got %d", http.StatusOK, rr.Code) |
| 345 |
} |
| 346 |
if hasBeenReadyCounter != 1 { |
| 347 |
t.Errorf("scenario 2: unexpected value of hasBeenReadyCounter, expected 1, got %d", hasBeenReadyCounter) |
| 348 |
} |
| 349 |
|
| 350 |
// scenario 3: checks if hasBeenReadyFn hasn't been called again. |
| 351 |
rr = httptest.NewRecorder() |
| 352 |
req = req.Clone(context.TODO()) |
| 353 |
mux.ServeHTTP(rr, req) |
| 354 |
if rr.Code != http.StatusOK { |
| 355 |
t.Errorf("scenario 3: unexpected status code returned, expected %d, got %d", http.StatusOK, rr.Code) |
| 356 |
} |
| 357 |
if hasBeenReadyCounter != 1 { |
| 358 |
t.Errorf("scenario 3: unexpected value of hasBeenReadyCounter, expected 1, got %d", hasBeenReadyCounter) |
| 359 |
} |
| 360 |
} |
| 361 |
|
| 362 |
type readyOnChanClose struct { |
| 363 |
ch <-chan struct{} |
| 364 |
} |
| 365 |
|
| 366 |
func (readyOnChanClose) Name() string { |
| 367 |
return "readyOnChanClose" |
| 368 |
} |
| 369 |
|
| 370 |
func (c readyOnChanClose) Check(_ *http.Request) error { |
| 371 |
select { |
| 372 |
case <-c.ch: |
| 373 |
return nil |
| 374 |
default: |
| 375 |
} |
| 376 |
return fmt.Errorf("the provided channel hasn't been closed") |
| 377 |
} |