| 1 | // Copyright 2015 Matthew Holt and The Caddy Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package reverseproxy |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "github.com/caddyserver/caddy/v2" |
| 23 | ) |
| 24 | |
| 25 | // newPassiveHandler builds a minimal Handler with passive health checks |
| 26 | // configured and a live caddy.Context so the fail-forgetter goroutine can |
| 27 | // be cancelled cleanly. The caller must call cancel() when done. |
| 28 | func newPassiveHandler(t *testing.T, maxFails int, failDuration time.Duration) (*Handler, context.CancelFunc) { |
| 29 | t.Helper() |
| 30 | caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) |
| 31 | h := &Handler{ |
| 32 | ctx: caddyCtx, |
| 33 | HealthChecks: &HealthChecks{ |
| 34 | Passive: &PassiveHealthChecks{ |
| 35 | MaxFails: maxFails, |
| 36 | FailDuration: caddy.Duration(failDuration), |
| 37 | }, |
| 38 | }, |
| 39 | } |
| 40 | return h, cancel |
| 41 | } |
| 42 | |
| 43 | // provisionedStaticUpstream creates a static upstream, registers it in the |
| 44 | // UsagePool, and returns a cleanup func that removes it from the pool. |
| 45 | func provisionedStaticUpstream(t *testing.T, h *Handler, addr string) (*Upstream, func()) { |
| 46 | t.Helper() |
| 47 | u := &Upstream{Dial: addr} |
| 48 | h.provisionUpstream(u, false) |
| 49 | return u, func() { _, _ = hosts.Delete(addr) } |
| 50 | } |
| 51 | |
| 52 | // provisionedDynamicUpstream creates a dynamic upstream, registers it in |
| 53 | // dynamicHosts, and returns a cleanup func that removes it. |
| 54 | func provisionedDynamicUpstream(t *testing.T, h *Handler, addr string) (*Upstream, func()) { |
| 55 | t.Helper() |
| 56 | u := &Upstream{Dial: addr} |
| 57 | h.provisionUpstream(u, true) |
| 58 | return u, func() { |
| 59 | dynamicHostsMu.Lock() |
| 60 | delete(dynamicHosts, addr) |
| 61 | dynamicHostsMu.Unlock() |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | // --- countFailure behaviour --- |
| 66 | |
| 67 | // TestCountFailureNoopWhenNoHealthChecks verifies that countFailure is a no-op |
| 68 | // when HealthChecks is nil. |
| 69 | func TestCountFailureNoopWhenNoHealthChecks(t *testing.T) { |
| 70 | resetDynamicHosts() |
| 71 | h := &Handler{} |
| 72 | u := &Upstream{Dial: "10.1.0.1:80", Host: new(Host)} |
| 73 | |
| 74 | h.countFailure(u) |
| 75 | |
| 76 | if u.Host.Fails() != 0 { |
| 77 | t.Errorf("expected 0 fails with no HealthChecks config, got %d", u.Host.Fails()) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | // TestCountFailureNoopWhenZeroDuration verifies that countFailure is a no-op |
| 82 | // when FailDuration is 0 (the zero value disables passive checks). |
| 83 | func TestCountFailureNoopWhenZeroDuration(t *testing.T) { |
| 84 | resetDynamicHosts() |
| 85 | caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) |
| 86 | defer cancel() |
| 87 | h := &Handler{ |
| 88 | ctx: caddyCtx, |
| 89 | HealthChecks: &HealthChecks{ |
| 90 | Passive: &PassiveHealthChecks{MaxFails: 1, FailDuration: 0}, |
| 91 | }, |
| 92 | } |
| 93 | u := &Upstream{Dial: "10.1.0.2:80", Host: new(Host)} |
| 94 | |
| 95 | h.countFailure(u) |
| 96 | |
| 97 | if u.Host.Fails() != 0 { |
| 98 | t.Errorf("expected 0 fails with zero FailDuration, got %d", u.Host.Fails()) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | // TestCountFailureIncrementsCount verifies that countFailure increments the |
| 103 | // fail count on the upstream's Host. |
| 104 | func TestCountFailureIncrementsCount(t *testing.T) { |
| 105 | resetDynamicHosts() |
| 106 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 107 | defer cancel() |
| 108 | u := &Upstream{Dial: "10.1.0.3:80", Host: new(Host)} |
| 109 | |
| 110 | h.countFailure(u) |
| 111 | |
| 112 | if u.Host.Fails() != 1 { |
| 113 | t.Errorf("expected 1 fail after countFailure, got %d", u.Host.Fails()) |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | // TestCountFailureDecrementsAfterDuration verifies that the fail count is |
| 118 | // decremented back after FailDuration elapses. |
| 119 | func TestCountFailureDecrementsAfterDuration(t *testing.T) { |
| 120 | resetDynamicHosts() |
| 121 | const failDuration = 50 * time.Millisecond |
| 122 | h, cancel := newPassiveHandler(t, 2, failDuration) |
| 123 | defer cancel() |
| 124 | u := &Upstream{Dial: "10.1.0.4:80", Host: new(Host)} |
| 125 | |
| 126 | h.countFailure(u) |
| 127 | if u.Host.Fails() != 1 { |
| 128 | t.Fatalf("expected 1 fail immediately after countFailure, got %d", u.Host.Fails()) |
| 129 | } |
| 130 | |
| 131 | // Wait long enough for the forgetter goroutine to fire. |
| 132 | time.Sleep(3 * failDuration) |
| 133 | |
| 134 | if u.Host.Fails() != 0 { |
| 135 | t.Errorf("expected fail count to return to 0 after FailDuration, got %d", u.Host.Fails()) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | // TestCountFailureCancelledContextForgets verifies that cancelling the handler |
| 140 | // context (simulating a config unload) also triggers the forgetter to run, |
| 141 | // decrementing the fail count. |
| 142 | func TestCountFailureCancelledContextForgets(t *testing.T) { |
| 143 | resetDynamicHosts() |
| 144 | h, cancel := newPassiveHandler(t, 2, time.Hour) // very long duration |
| 145 | u := &Upstream{Dial: "10.1.0.5:80", Host: new(Host)} |
| 146 | |
| 147 | h.countFailure(u) |
| 148 | if u.Host.Fails() != 1 { |
| 149 | t.Fatalf("expected 1 fail immediately after countFailure, got %d", u.Host.Fails()) |
| 150 | } |
| 151 | |
| 152 | // Cancelling the context should cause the forgetter goroutine to exit and |
| 153 | // decrement the count. |
| 154 | cancel() |
| 155 | time.Sleep(50 * time.Millisecond) |
| 156 | |
| 157 | if u.Host.Fails() != 0 { |
| 158 | t.Errorf("expected fail count to be decremented after context cancel, got %d", u.Host.Fails()) |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | // --- static upstream passive health check --- |
| 163 | |
| 164 | // TestStaticUpstreamHealthyWithNoFailures verifies that a static upstream with |
| 165 | // no recorded failures is considered healthy. |
| 166 | func TestStaticUpstreamHealthyWithNoFailures(t *testing.T) { |
| 167 | resetDynamicHosts() |
| 168 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 169 | defer cancel() |
| 170 | |
| 171 | u, cleanup := provisionedStaticUpstream(t, h, "10.2.0.1:80") |
| 172 | defer cleanup() |
| 173 | |
| 174 | if !u.Healthy() { |
| 175 | t.Error("upstream with no failures should be healthy") |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // TestStaticUpstreamUnhealthyAtMaxFails verifies that a static upstream is |
| 180 | // marked unhealthy once its fail count reaches MaxFails. |
| 181 | func TestStaticUpstreamUnhealthyAtMaxFails(t *testing.T) { |
| 182 | resetDynamicHosts() |
| 183 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 184 | defer cancel() |
| 185 | |
| 186 | u, cleanup := provisionedStaticUpstream(t, h, "10.2.0.2:80") |
| 187 | defer cleanup() |
| 188 | |
| 189 | h.countFailure(u) |
| 190 | if !u.Healthy() { |
| 191 | t.Error("upstream should still be healthy after 1 of 2 allowed failures") |
| 192 | } |
| 193 | |
| 194 | h.countFailure(u) |
| 195 | if u.Healthy() { |
| 196 | t.Error("upstream should be unhealthy after reaching MaxFails=2") |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | // TestStaticUpstreamRecoversAfterFailDuration verifies that a static upstream |
| 201 | // returns to healthy once its failures expire. |
| 202 | func TestStaticUpstreamRecoversAfterFailDuration(t *testing.T) { |
| 203 | resetDynamicHosts() |
| 204 | const failDuration = 50 * time.Millisecond |
| 205 | h, cancel := newPassiveHandler(t, 1, failDuration) |
| 206 | defer cancel() |
| 207 | |
| 208 | u, cleanup := provisionedStaticUpstream(t, h, "10.2.0.3:80") |
| 209 | defer cleanup() |
| 210 | |
| 211 | h.countFailure(u) |
| 212 | if u.Healthy() { |
| 213 | t.Fatal("upstream should be unhealthy immediately after MaxFails failure") |
| 214 | } |
| 215 | |
| 216 | time.Sleep(3 * failDuration) |
| 217 | |
| 218 | if !u.Healthy() { |
| 219 | t.Errorf("upstream should recover to healthy after FailDuration, Fails=%d", u.Host.Fails()) |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // TestStaticUpstreamHealthPersistedAcrossReprovisioning verifies that static |
| 224 | // upstreams share a Host via the UsagePool, so a second call to provisionUpstream |
| 225 | // for the same address (as happens on config reload) sees the accumulated state. |
| 226 | func TestStaticUpstreamHealthPersistedAcrossReprovisioning(t *testing.T) { |
| 227 | resetDynamicHosts() |
| 228 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 229 | defer cancel() |
| 230 | |
| 231 | u1, cleanup1 := provisionedStaticUpstream(t, h, "10.2.0.4:80") |
| 232 | defer cleanup1() |
| 233 | |
| 234 | h.countFailure(u1) |
| 235 | h.countFailure(u1) |
| 236 | |
| 237 | // Simulate a second handler instance referencing the same upstream |
| 238 | // (e.g. after a config reload that keeps the same backend address). |
| 239 | u2, cleanup2 := provisionedStaticUpstream(t, h, "10.2.0.4:80") |
| 240 | defer cleanup2() |
| 241 | |
| 242 | if u1.Host != u2.Host { |
| 243 | t.Fatal("expected both Upstream structs to share the same *Host via UsagePool") |
| 244 | } |
| 245 | if u2.Healthy() { |
| 246 | t.Error("re-provisioned upstream should still see the prior fail count and be unhealthy") |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | // --- dynamic upstream passive health check --- |
| 251 | |
| 252 | // TestDynamicUpstreamHealthyWithNoFailures verifies that a freshly provisioned |
| 253 | // dynamic upstream is healthy. |
| 254 | func TestDynamicUpstreamHealthyWithNoFailures(t *testing.T) { |
| 255 | resetDynamicHosts() |
| 256 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 257 | defer cancel() |
| 258 | |
| 259 | u, cleanup := provisionedDynamicUpstream(t, h, "10.3.0.1:80") |
| 260 | defer cleanup() |
| 261 | |
| 262 | if !u.Healthy() { |
| 263 | t.Error("dynamic upstream with no failures should be healthy") |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | // TestDynamicUpstreamUnhealthyAtMaxFails verifies that a dynamic upstream is |
| 268 | // marked unhealthy once its fail count reaches MaxFails. |
| 269 | func TestDynamicUpstreamUnhealthyAtMaxFails(t *testing.T) { |
| 270 | resetDynamicHosts() |
| 271 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 272 | defer cancel() |
| 273 | |
| 274 | u, cleanup := provisionedDynamicUpstream(t, h, "10.3.0.2:80") |
| 275 | defer cleanup() |
| 276 | |
| 277 | h.countFailure(u) |
| 278 | if !u.Healthy() { |
| 279 | t.Error("dynamic upstream should still be healthy after 1 of 2 allowed failures") |
| 280 | } |
| 281 | |
| 282 | h.countFailure(u) |
| 283 | if u.Healthy() { |
| 284 | t.Error("dynamic upstream should be unhealthy after reaching MaxFails=2") |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | // TestDynamicUpstreamFailCountPersistedBetweenRequests is the core regression |
| 289 | // test: it simulates two sequential (non-concurrent) requests to the same |
| 290 | // dynamic upstream. Before the fix, the UsagePool entry would be deleted |
| 291 | // between requests, wiping the fail count. Now it should survive. |
| 292 | func TestDynamicUpstreamFailCountPersistedBetweenRequests(t *testing.T) { |
| 293 | resetDynamicHosts() |
| 294 | h, cancel := newPassiveHandler(t, 2, time.Minute) |
| 295 | defer cancel() |
| 296 | |
| 297 | // --- first request --- |
| 298 | u1 := &Upstream{Dial: "10.3.0.3:80"} |
| 299 | h.provisionUpstream(u1, true) |
| 300 | h.countFailure(u1) |
| 301 | |
| 302 | if u1.Host.Fails() != 1 { |
| 303 | t.Fatalf("expected 1 fail after first request, got %d", u1.Host.Fails()) |
| 304 | } |
| 305 | |
| 306 | // Simulate end of first request: no delete from any pool (key difference |
| 307 | // vs. the old behaviour where hosts.Delete was deferred). |
| 308 | |
| 309 | // --- second request: brand-new *Upstream struct, same dial address --- |
| 310 | u2 := &Upstream{Dial: "10.3.0.3:80"} |
| 311 | h.provisionUpstream(u2, true) |
| 312 | |
| 313 | if u1.Host != u2.Host { |
| 314 | t.Fatal("expected both requests to share the same *Host pointer from dynamicHosts") |
| 315 | } |
| 316 | if u2.Host.Fails() != 1 { |
| 317 | t.Errorf("expected fail count to persist across requests, got %d", u2.Host.Fails()) |
| 318 | } |
| 319 | |
| 320 | // A second failure now tips it over MaxFails=2. |
| 321 | h.countFailure(u2) |
| 322 | if u2.Healthy() { |
| 323 | t.Error("upstream should be unhealthy after accumulated failures across requests") |
| 324 | } |
| 325 | |
| 326 | // Cleanup. |
| 327 | dynamicHostsMu.Lock() |
| 328 | delete(dynamicHosts, "10.3.0.3:80") |
| 329 | dynamicHostsMu.Unlock() |
| 330 | } |
| 331 | |
| 332 | // TestDynamicUpstreamRecoveryAfterFailDuration verifies that a dynamic |
| 333 | // upstream's fail count expires and it returns to healthy. |
| 334 | func TestDynamicUpstreamRecoveryAfterFailDuration(t *testing.T) { |
| 335 | resetDynamicHosts() |
| 336 | const failDuration = 50 * time.Millisecond |
| 337 | h, cancel := newPassiveHandler(t, 1, failDuration) |
| 338 | defer cancel() |
| 339 | |
| 340 | u, cleanup := provisionedDynamicUpstream(t, h, "10.3.0.4:80") |
| 341 | defer cleanup() |
| 342 | |
| 343 | h.countFailure(u) |
| 344 | if u.Healthy() { |
| 345 | t.Fatal("upstream should be unhealthy immediately after MaxFails failure") |
| 346 | } |
| 347 | |
| 348 | time.Sleep(3 * failDuration) |
| 349 | |
| 350 | // Re-provision (as a new request would) to get fresh *Upstream with policy set. |
| 351 | u2 := &Upstream{Dial: "10.3.0.4:80"} |
| 352 | h.provisionUpstream(u2, true) |
| 353 | |
| 354 | if !u2.Healthy() { |
| 355 | t.Errorf("dynamic upstream should recover to healthy after FailDuration, Fails=%d", u2.Host.Fails()) |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | // TestDynamicUpstreamMaxRequestsFromUnhealthyRequestCount verifies that |
| 360 | // UnhealthyRequestCount is copied into MaxRequests so Full() works correctly. |
| 361 | func TestDynamicUpstreamMaxRequestsFromUnhealthyRequestCount(t *testing.T) { |
| 362 | resetDynamicHosts() |
| 363 | caddyCtx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) |
| 364 | defer cancel() |
| 365 | h := &Handler{ |
| 366 | ctx: caddyCtx, |
| 367 | HealthChecks: &HealthChecks{ |
| 368 | Passive: &PassiveHealthChecks{ |
| 369 | UnhealthyRequestCount: 3, |
| 370 | }, |
| 371 | }, |
| 372 | } |
| 373 | |
| 374 | u, cleanup := provisionedDynamicUpstream(t, h, "10.3.0.5:80") |
| 375 | defer cleanup() |
| 376 | |
| 377 | if u.MaxRequests != 3 { |
| 378 | t.Errorf("expected MaxRequests=3 from UnhealthyRequestCount, got %d", u.MaxRequests) |
| 379 | } |
| 380 | |
| 381 | // Should not be full with fewer requests than the limit. |
| 382 | _ = u.Host.countRequest(2) |
| 383 | if u.Full() { |
| 384 | t.Error("upstream should not be full with 2 of 3 allowed requests") |
| 385 | } |
| 386 | |
| 387 | _ = u.Host.countRequest(1) |
| 388 | if !u.Full() { |
| 389 | t.Error("upstream should be full at UnhealthyRequestCount concurrent requests") |
| 390 | } |
| 391 | } |