Debian Codegraph @

modules/caddyhttp/reverseproxy/selectionpolicies_test.go

raw symbols SCIP
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 "net/http"
20 "net/http/httptest"
21 "testing"
22
23 "github.com/caddyserver/caddy/v2"
24 "github.com/caddyserver/caddy/v2/caddyconfig"
25 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
26 )
27
28 func testPool() UpstreamPool {
29 return UpstreamPool{
30 {Host: new(Host), Dial: "0.0.0.1"},
31 {Host: new(Host), Dial: "0.0.0.2"},
32 {Host: new(Host), Dial: "0.0.0.3"},
33 }
34 }
35
36 func TestRoundRobinPolicy(t *testing.T) {
37 pool := testPool()
38 rrPolicy := RoundRobinSelection{}
39 req, _ := http.NewRequest("GET", "/", nil)
40
41 h := rrPolicy.Select(pool, req, nil)
42 // First selected host is 1, because counter starts at 0
43 // and increments before host is selected
44 if h != pool[1] {
45 t.Error("Expected first round robin host to be second host in the pool.")
46 }
47 h = rrPolicy.Select(pool, req, nil)
48 if h != pool[2] {
49 t.Error("Expected second round robin host to be third host in the pool.")
50 }
51 h = rrPolicy.Select(pool, req, nil)
52 if h != pool[0] {
53 t.Error("Expected third round robin host to be first host in the pool.")
54 }
55 // mark host as down
56 pool[1].setHealthy(false)
57 h = rrPolicy.Select(pool, req, nil)
58 if h != pool[2] {
59 t.Error("Expected to skip down host.")
60 }
61 // mark host as up
62 pool[1].setHealthy(true)
63
64 h = rrPolicy.Select(pool, req, nil)
65 if h == pool[2] {
66 t.Error("Expected to balance evenly among healthy hosts")
67 }
68 // mark host as full
69 pool[1].countRequest(1)
70 pool[1].MaxRequests = 1
71 h = rrPolicy.Select(pool, req, nil)
72 if h != pool[2] {
73 t.Error("Expected to skip full host.")
74 }
75 }
76
77 func TestWeightedRoundRobinPolicy(t *testing.T) {
78 pool := testPool()
79 wrrPolicy := WeightedRoundRobinSelection{
80 Weights: []int{3, 2, 1},
81 totalWeight: 6,
82 }
83 req, _ := http.NewRequest("GET", "/", nil)
84
85 h := wrrPolicy.Select(pool, req, nil)
86 if h != pool[0] {
87 t.Error("Expected first weighted round robin host to be first host in the pool.")
88 }
89 h = wrrPolicy.Select(pool, req, nil)
90 if h != pool[0] {
91 t.Error("Expected second weighted round robin host to be first host in the pool.")
92 }
93 // Third selected host is 1, because counter starts at 0
94 // and increments before host is selected
95 h = wrrPolicy.Select(pool, req, nil)
96 if h != pool[1] {
97 t.Error("Expected third weighted round robin host to be second host in the pool.")
98 }
99 h = wrrPolicy.Select(pool, req, nil)
100 if h != pool[1] {
101 t.Error("Expected fourth weighted round robin host to be second host in the pool.")
102 }
103 h = wrrPolicy.Select(pool, req, nil)
104 if h != pool[2] {
105 t.Error("Expected fifth weighted round robin host to be third host in the pool.")
106 }
107 h = wrrPolicy.Select(pool, req, nil)
108 if h != pool[0] {
109 t.Error("Expected sixth weighted round robin host to be first host in the pool.")
110 }
111
112 // mark host as down
113 pool[0].setHealthy(false)
114 h = wrrPolicy.Select(pool, req, nil)
115 if h != pool[1] {
116 t.Error("Expected to skip down host.")
117 }
118 // mark host as up
119 pool[0].setHealthy(true)
120
121 h = wrrPolicy.Select(pool, req, nil)
122 if h != pool[0] {
123 t.Error("Expected to select first host on availability.")
124 }
125 // mark host as full
126 pool[1].countRequest(1)
127 pool[1].MaxRequests = 1
128 h = wrrPolicy.Select(pool, req, nil)
129 if h != pool[2] {
130 t.Error("Expected to skip full host.")
131 }
132 }
133
134 func TestWeightedRoundRobinPolicyWithZeroWeight(t *testing.T) {
135 pool := testPool()
136 wrrPolicy := WeightedRoundRobinSelection{
137 Weights: []int{0, 2, 1},
138 totalWeight: 3,
139 }
140 req, _ := http.NewRequest("GET", "/", nil)
141
142 h := wrrPolicy.Select(pool, req, nil)
143 if h != pool[1] {
144 t.Error("Expected first weighted round robin host to be second host in the pool.")
145 }
146
147 h = wrrPolicy.Select(pool, req, nil)
148 if h != pool[2] {
149 t.Error("Expected second weighted round robin host to be third host in the pool.")
150 }
151
152 h = wrrPolicy.Select(pool, req, nil)
153 if h != pool[1] {
154 t.Error("Expected third weighted round robin host to be second host in the pool.")
155 }
156
157 // mark second host as down
158 pool[1].setHealthy(false)
159 h = wrrPolicy.Select(pool, req, nil)
160 if h != pool[2] {
161 t.Error("Expect select next available host.")
162 }
163
164 h = wrrPolicy.Select(pool, req, nil)
165 if h != pool[2] {
166 t.Error("Expect select only available host.")
167 }
168 // mark second host as up
169 pool[1].setHealthy(true)
170
171 h = wrrPolicy.Select(pool, req, nil)
172 if h != pool[1] {
173 t.Error("Expect select first host on availability.")
174 }
175
176 // test next select in full cycle
177 expected := []*Upstream{pool[1], pool[2], pool[1], pool[1], pool[2], pool[1]}
178 for i, want := range expected {
179 got := wrrPolicy.Select(pool, req, nil)
180 if want != got {
181 t.Errorf("Selection %d: got host[%s], want host[%s]", i+1, got, want)
182 }
183 }
184 }
185
186 func TestLeastConnPolicy(t *testing.T) {
187 pool := testPool()
188 lcPolicy := LeastConnSelection{}
189 req, _ := http.NewRequest("GET", "/", nil)
190
191 pool[0].countRequest(10)
192 pool[1].countRequest(10)
193 h := lcPolicy.Select(pool, req, nil)
194 if h != pool[2] {
195 t.Error("Expected least connection host to be third host.")
196 }
197 pool[2].countRequest(100)
198 h = lcPolicy.Select(pool, req, nil)
199 if h != pool[0] && h != pool[1] {
200 t.Error("Expected least connection host to be first or second host.")
201 }
202 }
203
204 func TestIPHashPolicy(t *testing.T) {
205 pool := testPool()
206 ipHash := IPHashSelection{}
207 req, _ := http.NewRequest("GET", "/", nil)
208
209 // We should be able to predict where every request is routed.
210 req.RemoteAddr = "172.0.0.1:80"
211 h := ipHash.Select(pool, req, nil)
212 if h != pool[0] {
213 t.Error("Expected ip hash policy host to be the first host.")
214 }
215 req.RemoteAddr = "172.0.0.2:80"
216 h = ipHash.Select(pool, req, nil)
217 if h != pool[1] {
218 t.Error("Expected ip hash policy host to be the second host.")
219 }
220 req.RemoteAddr = "172.0.0.3:80"
221 h = ipHash.Select(pool, req, nil)
222 if h != pool[0] {
223 t.Error("Expected ip hash policy host to be the first host.")
224 }
225 req.RemoteAddr = "172.0.0.4:80"
226 h = ipHash.Select(pool, req, nil)
227 if h != pool[1] {
228 t.Error("Expected ip hash policy host to be the second host.")
229 }
230
231 // we should get the same results without a port
232 req.RemoteAddr = "172.0.0.1"
233 h = ipHash.Select(pool, req, nil)
234 if h != pool[0] {
235 t.Error("Expected ip hash policy host to be the first host.")
236 }
237 req.RemoteAddr = "172.0.0.2"
238 h = ipHash.Select(pool, req, nil)
239 if h != pool[1] {
240 t.Error("Expected ip hash policy host to be the second host.")
241 }
242 req.RemoteAddr = "172.0.0.3"
243 h = ipHash.Select(pool, req, nil)
244 if h != pool[0] {
245 t.Error("Expected ip hash policy host to be the first host.")
246 }
247 req.RemoteAddr = "172.0.0.4"
248 h = ipHash.Select(pool, req, nil)
249 if h != pool[1] {
250 t.Error("Expected ip hash policy host to be the second host.")
251 }
252
253 // we should get a healthy host if the original host is unhealthy and a
254 // healthy host is available
255 req.RemoteAddr = "172.0.0.4"
256 pool[1].setHealthy(false)
257 h = ipHash.Select(pool, req, nil)
258 if h != pool[2] {
259 t.Error("Expected ip hash policy host to be the third host.")
260 }
261
262 req.RemoteAddr = "172.0.0.2"
263 h = ipHash.Select(pool, req, nil)
264 if h != pool[0] {
265 t.Error("Expected ip hash policy host to be the first host.")
266 }
267 pool[1].setHealthy(true)
268
269 req.RemoteAddr = "172.0.0.3"
270 pool[2].setHealthy(false)
271 h = ipHash.Select(pool, req, nil)
272 if h != pool[0] {
273 t.Error("Expected ip hash policy host to be the first host.")
274 }
275 req.RemoteAddr = "172.0.0.4"
276 h = ipHash.Select(pool, req, nil)
277 if h != pool[1] {
278 t.Error("Expected ip hash policy host to be the second host.")
279 }
280
281 // We should be able to resize the host pool and still be able to predict
282 // where a req will be routed with the same IP's used above
283 pool = UpstreamPool{
284 {Host: new(Host), Dial: "0.0.0.2"},
285 {Host: new(Host), Dial: "0.0.0.3"},
286 }
287 req.RemoteAddr = "172.0.0.1:80"
288 h = ipHash.Select(pool, req, nil)
289 if h != pool[0] {
290 t.Error("Expected ip hash policy host to be the first host.")
291 }
292 req.RemoteAddr = "172.0.0.2:80"
293 h = ipHash.Select(pool, req, nil)
294 if h != pool[0] {
295 t.Error("Expected ip hash policy host to be the first host.")
296 }
297 req.RemoteAddr = "172.0.0.3:80"
298 h = ipHash.Select(pool, req, nil)
299 if h != pool[0] {
300 t.Error("Expected ip hash policy host to be the first host.")
301 }
302 req.RemoteAddr = "172.0.0.4:80"
303 h = ipHash.Select(pool, req, nil)
304 if h != pool[0] {
305 t.Error("Expected ip hash policy host to be the first host.")
306 }
307
308 // We should get nil when there are no healthy hosts
309 pool[0].setHealthy(false)
310 pool[1].setHealthy(false)
311 h = ipHash.Select(pool, req, nil)
312 if h != nil {
313 t.Error("Expected ip hash policy host to be nil.")
314 }
315
316 // Reproduce #4135
317 pool = UpstreamPool{
318 {Host: new(Host)},
319 {Host: new(Host)},
320 {Host: new(Host)},
321 {Host: new(Host)},
322 {Host: new(Host)},
323 {Host: new(Host)},
324 {Host: new(Host)},
325 {Host: new(Host)},
326 {Host: new(Host)},
327 }
328 pool[0].setHealthy(false)
329 pool[1].setHealthy(false)
330 pool[2].setHealthy(false)
331 pool[3].setHealthy(false)
332 pool[4].setHealthy(false)
333 pool[5].setHealthy(false)
334 pool[6].setHealthy(false)
335 pool[7].setHealthy(false)
336 pool[8].setHealthy(true)
337
338 // We should get a result back when there is one healthy host left.
339 h = ipHash.Select(pool, req, nil)
340 if h == nil {
341 // If it is nil, it means we missed a host even though one is available
342 t.Error("Expected ip hash policy host to not be nil, but it is nil.")
343 }
344 }
345
346 func TestClientIPHashPolicy(t *testing.T) {
347 pool := testPool()
348 ipHash := ClientIPHashSelection{}
349 req, _ := http.NewRequest("GET", "/", nil)
350 req = req.WithContext(context.WithValue(req.Context(), caddyhttp.VarsCtxKey, make(map[string]any)))
351
352 // We should be able to predict where every request is routed.
353 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80")
354 h := ipHash.Select(pool, req, nil)
355 if h != pool[0] {
356 t.Error("Expected ip hash policy host to be the first host.")
357 }
358 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80")
359 h = ipHash.Select(pool, req, nil)
360 if h != pool[1] {
361 t.Error("Expected ip hash policy host to be the second host.")
362 }
363 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80")
364 h = ipHash.Select(pool, req, nil)
365 if h != pool[0] {
366 t.Error("Expected ip hash policy host to be the first host.")
367 }
368 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80")
369 h = ipHash.Select(pool, req, nil)
370 if h != pool[1] {
371 t.Error("Expected ip hash policy host to be the second host.")
372 }
373
374 // we should get the same results without a port
375 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1")
376 h = ipHash.Select(pool, req, nil)
377 if h != pool[0] {
378 t.Error("Expected ip hash policy host to be the first host.")
379 }
380 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2")
381 h = ipHash.Select(pool, req, nil)
382 if h != pool[1] {
383 t.Error("Expected ip hash policy host to be the second host.")
384 }
385 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3")
386 h = ipHash.Select(pool, req, nil)
387 if h != pool[0] {
388 t.Error("Expected ip hash policy host to be the first host.")
389 }
390 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4")
391 h = ipHash.Select(pool, req, nil)
392 if h != pool[1] {
393 t.Error("Expected ip hash policy host to be the second host.")
394 }
395
396 // we should get a healthy host if the original host is unhealthy and a
397 // healthy host is available
398 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4")
399 pool[1].setHealthy(false)
400 h = ipHash.Select(pool, req, nil)
401 if h != pool[2] {
402 t.Error("Expected ip hash policy host to be the third host.")
403 }
404
405 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2")
406 h = ipHash.Select(pool, req, nil)
407 if h != pool[0] {
408 t.Error("Expected ip hash policy host to be the first host.")
409 }
410 pool[1].setHealthy(true)
411
412 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3")
413 pool[2].setHealthy(false)
414 h = ipHash.Select(pool, req, nil)
415 if h != pool[0] {
416 t.Error("Expected ip hash policy host to be the first host.")
417 }
418 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4")
419 h = ipHash.Select(pool, req, nil)
420 if h != pool[1] {
421 t.Error("Expected ip hash policy host to be the second host.")
422 }
423
424 // We should be able to resize the host pool and still be able to predict
425 // where a req will be routed with the same IP's used above
426 pool = UpstreamPool{
427 {Host: new(Host), Dial: "0.0.0.2"},
428 {Host: new(Host), Dial: "0.0.0.3"},
429 }
430 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.1:80")
431 h = ipHash.Select(pool, req, nil)
432 if h != pool[0] {
433 t.Error("Expected ip hash policy host to be the first host.")
434 }
435 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.2:80")
436 h = ipHash.Select(pool, req, nil)
437 if h != pool[0] {
438 t.Error("Expected ip hash policy host to be the first host.")
439 }
440 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.3:80")
441 h = ipHash.Select(pool, req, nil)
442 if h != pool[0] {
443 t.Error("Expected ip hash policy host to be the first host.")
444 }
445 caddyhttp.SetVar(req.Context(), caddyhttp.ClientIPVarKey, "172.0.0.4:80")
446 h = ipHash.Select(pool, req, nil)
447 if h != pool[0] {
448 t.Error("Expected ip hash policy host to be the first host.")
449 }
450
451 // We should get nil when there are no healthy hosts
452 pool[0].setHealthy(false)
453 pool[1].setHealthy(false)
454 h = ipHash.Select(pool, req, nil)
455 if h != nil {
456 t.Error("Expected ip hash policy host to be nil.")
457 }
458
459 // Reproduce #4135
460 pool = UpstreamPool{
461 {Host: new(Host)},
462 {Host: new(Host)},
463 {Host: new(Host)},
464 {Host: new(Host)},
465 {Host: new(Host)},
466 {Host: new(Host)},
467 {Host: new(Host)},
468 {Host: new(Host)},
469 {Host: new(Host)},
470 }
471 pool[0].setHealthy(false)
472 pool[1].setHealthy(false)
473 pool[2].setHealthy(false)
474 pool[3].setHealthy(false)
475 pool[4].setHealthy(false)
476 pool[5].setHealthy(false)
477 pool[6].setHealthy(false)
478 pool[7].setHealthy(false)
479 pool[8].setHealthy(true)
480
481 // We should get a result back when there is one healthy host left.
482 h = ipHash.Select(pool, req, nil)
483 if h == nil {
484 // If it is nil, it means we missed a host even though one is available
485 t.Error("Expected ip hash policy host to not be nil, but it is nil.")
486 }
487 }
488
489 func TestFirstPolicy(t *testing.T) {
490 pool := testPool()
491 firstPolicy := FirstSelection{}
492 req := httptest.NewRequest(http.MethodGet, "/", nil)
493
494 h := firstPolicy.Select(pool, req, nil)
495 if h != pool[0] {
496 t.Error("Expected first policy host to be the first host.")
497 }
498
499 pool[0].setHealthy(false)
500 h = firstPolicy.Select(pool, req, nil)
501 if h != pool[1] {
502 t.Error("Expected first policy host to be the second host.")
503 }
504 }
505
506 func TestQueryHashPolicy(t *testing.T) {
507 ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
508 defer cancel()
509 queryPolicy := QueryHashSelection{Key: "foo"}
510 if err := queryPolicy.Provision(ctx); err != nil {
511 t.Errorf("Provision error: %v", err)
512 t.FailNow()
513 }
514
515 pool := testPool()
516
517 request := httptest.NewRequest(http.MethodGet, "/?foo=1", nil)
518 h := queryPolicy.Select(pool, request, nil)
519 if h != pool[0] {
520 t.Error("Expected query policy host to be the first host.")
521 }
522
523 request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil)
524 h = queryPolicy.Select(pool, request, nil)
525 if h != pool[1] {
526 t.Error("Expected query policy host to be the second host.")
527 }
528
529 request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil)
530 pool[0].setHealthy(false)
531 h = queryPolicy.Select(pool, request, nil)
532 if h != pool[2] {
533 t.Error("Expected query policy host to be the third host.")
534 }
535
536 request = httptest.NewRequest(http.MethodGet, "/?foo=100000", nil)
537 h = queryPolicy.Select(pool, request, nil)
538 if h != pool[1] {
539 t.Error("Expected query policy host to be the second host.")
540 }
541
542 // We should be able to resize the host pool and still be able to predict
543 // where a request will be routed with the same query used above
544 pool = UpstreamPool{
545 {Host: new(Host)},
546 {Host: new(Host)},
547 }
548
549 request = httptest.NewRequest(http.MethodGet, "/?foo=1", nil)
550 h = queryPolicy.Select(pool, request, nil)
551 if h != pool[0] {
552 t.Error("Expected query policy host to be the first host.")
553 }
554
555 pool[0].setHealthy(false)
556 h = queryPolicy.Select(pool, request, nil)
557 if h != pool[1] {
558 t.Error("Expected query policy host to be the second host.")
559 }
560
561 request = httptest.NewRequest(http.MethodGet, "/?foo=4", nil)
562 h = queryPolicy.Select(pool, request, nil)
563 if h != pool[1] {
564 t.Error("Expected query policy host to be the second host.")
565 }
566
567 pool[0].setHealthy(false)
568 pool[1].setHealthy(false)
569 h = queryPolicy.Select(pool, request, nil)
570 if h != nil {
571 t.Error("Expected query policy host to be nil.")
572 }
573
574 request = httptest.NewRequest(http.MethodGet, "/?foo=aa11&foo=bb22", nil)
575 pool = testPool()
576 h = queryPolicy.Select(pool, request, nil)
577 if h != pool[0] {
578 t.Error("Expected query policy host to be the first host.")
579 }
580 }
581
582 func TestURIHashPolicy(t *testing.T) {
583 pool := testPool()
584 uriPolicy := URIHashSelection{}
585
586 request := httptest.NewRequest(http.MethodGet, "/test", nil)
587 h := uriPolicy.Select(pool, request, nil)
588 if h != pool[2] {
589 t.Error("Expected uri policy host to be the third host.")
590 }
591
592 pool[2].setHealthy(false)
593 h = uriPolicy.Select(pool, request, nil)
594 if h != pool[0] {
595 t.Error("Expected uri policy host to be the first host.")
596 }
597
598 request = httptest.NewRequest(http.MethodGet, "/test_2", nil)
599 h = uriPolicy.Select(pool, request, nil)
600 if h != pool[0] {
601 t.Error("Expected uri policy host to be the first host.")
602 }
603
604 // We should be able to resize the host pool and still be able to predict
605 // where a request will be routed with the same URI's used above
606 pool = UpstreamPool{
607 {Host: new(Host)},
608 {Host: new(Host)},
609 }
610
611 request = httptest.NewRequest(http.MethodGet, "/test", nil)
612 h = uriPolicy.Select(pool, request, nil)
613 if h != pool[0] {
614 t.Error("Expected uri policy host to be the first host.")
615 }
616
617 pool[0].setHealthy(false)
618 h = uriPolicy.Select(pool, request, nil)
619 if h != pool[1] {
620 t.Error("Expected uri policy host to be the first host.")
621 }
622
623 request = httptest.NewRequest(http.MethodGet, "/test_2", nil)
624 h = uriPolicy.Select(pool, request, nil)
625 if h != pool[1] {
626 t.Error("Expected uri policy host to be the second host.")
627 }
628
629 pool[0].setHealthy(false)
630 pool[1].setHealthy(false)
631 h = uriPolicy.Select(pool, request, nil)
632 if h != nil {
633 t.Error("Expected uri policy host to be nil.")
634 }
635 }
636
637 func TestLeastRequests(t *testing.T) {
638 pool := testPool()
639 pool[0].Dial = "localhost:8080"
640 pool[1].Dial = "localhost:8081"
641 pool[2].Dial = "localhost:8082"
642 pool[0].setHealthy(true)
643 pool[1].setHealthy(true)
644 pool[2].setHealthy(true)
645 pool[0].countRequest(10)
646 pool[1].countRequest(20)
647 pool[2].countRequest(30)
648
649 result := leastRequests(pool)
650
651 if result == nil {
652 t.Error("Least request should not return nil")
653 }
654
655 if result != pool[0] {
656 t.Error("Least request should return pool[0]")
657 }
658 }
659
660 func TestRandomChoicePolicy(t *testing.T) {
661 pool := testPool()
662 pool[0].Dial = "localhost:8080"
663 pool[1].Dial = "localhost:8081"
664 pool[2].Dial = "localhost:8082"
665 pool[0].setHealthy(false)
666 pool[1].setHealthy(true)
667 pool[2].setHealthy(true)
668 pool[0].countRequest(10)
669 pool[1].countRequest(20)
670 pool[2].countRequest(30)
671
672 request := httptest.NewRequest(http.MethodGet, "/test", nil)
673 randomChoicePolicy := RandomChoiceSelection{Choose: 2}
674
675 h := randomChoicePolicy.Select(pool, request, nil)
676
677 if h == nil {
678 t.Error("RandomChoicePolicy should not return nil")
679 }
680
681 if h == pool[0] {
682 t.Error("RandomChoicePolicy should not choose pool[0]")
683 }
684 }
685
686 func TestCookieHashPolicy(t *testing.T) {
687 ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
688 defer cancel()
689 cookieHashPolicy := CookieHashSelection{}
690 if err := cookieHashPolicy.Provision(ctx); err != nil {
691 t.Errorf("Provision error: %v", err)
692 t.FailNow()
693 }
694
695 pool := testPool()
696 pool[0].Dial = "localhost:8080"
697 pool[1].Dial = "localhost:8081"
698 pool[2].Dial = "localhost:8082"
699 pool[0].setHealthy(true)
700 pool[1].setHealthy(false)
701 pool[2].setHealthy(false)
702 request := httptest.NewRequest(http.MethodGet, "/test", nil)
703 w := httptest.NewRecorder()
704
705 h := cookieHashPolicy.Select(pool, request, w)
706 cookieServer1 := w.Result().Cookies()[0]
707 if cookieServer1 == nil {
708 t.Fatal("cookieHashPolicy should set a cookie")
709 }
710 if cookieServer1.Name != "lb" {
711 t.Error("cookieHashPolicy should set a cookie with name lb")
712 }
713 if cookieServer1.Secure {
714 t.Error("cookieHashPolicy should set cookie Secure attribute to false when request is not secure")
715 }
716 if h != pool[0] {
717 t.Error("Expected cookieHashPolicy host to be the first only available host.")
718 }
719 pool[1].setHealthy(true)
720 pool[2].setHealthy(true)
721 request = httptest.NewRequest(http.MethodGet, "/test", nil)
722 w = httptest.NewRecorder()
723 request.AddCookie(cookieServer1)
724 h = cookieHashPolicy.Select(pool, request, w)
725 if h != pool[0] {
726 t.Error("Expected cookieHashPolicy host to stick to the first host (matching cookie).")
727 }
728 s := w.Result().Cookies()
729 if len(s) != 0 {
730 t.Error("Expected cookieHashPolicy to not set a new cookie.")
731 }
732 pool[0].setHealthy(false)
733 request = httptest.NewRequest(http.MethodGet, "/test", nil)
734 w = httptest.NewRecorder()
735 request.AddCookie(cookieServer1)
736 h = cookieHashPolicy.Select(pool, request, w)
737 if h == pool[0] {
738 t.Error("Expected cookieHashPolicy to select a new host.")
739 }
740 if w.Result().Cookies() == nil {
741 t.Error("Expected cookieHashPolicy to set a new cookie.")
742 }
743 }
744
745 func TestCookieHashPolicyWithSecureRequest(t *testing.T) {
746 ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
747 defer cancel()
748 cookieHashPolicy := CookieHashSelection{}
749 if err := cookieHashPolicy.Provision(ctx); err != nil {
750 t.Errorf("Provision error: %v", err)
751 t.FailNow()
752 }
753
754 pool := testPool()
755 pool[0].Dial = "localhost:8080"
756 pool[1].Dial = "localhost:8081"
757 pool[2].Dial = "localhost:8082"
758 pool[0].setHealthy(true)
759 pool[1].setHealthy(false)
760 pool[2].setHealthy(false)
761
762 // Create a test server that serves HTTPS requests
763 ts := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
764 h := cookieHashPolicy.Select(pool, r, w)
765 if h != pool[0] {
766 t.Error("Expected cookieHashPolicy host to be the first only available host.")
767 }
768 }))
769 defer ts.Close()
770
771 // Make a new HTTPS request to the test server
772 client := ts.Client()
773 request, err := http.NewRequest(http.MethodGet, ts.URL+"/test", nil)
774 if err != nil {
775 t.Fatal(err)
776 }
777 response, err := client.Do(request)
778 if err != nil {
779 t.Fatal(err)
780 }
781
782 // Check if the cookie set is Secure and has SameSiteNone mode
783 cookies := response.Cookies()
784 if len(cookies) == 0 {
785 t.Fatal("Expected a cookie to be set")
786 }
787 cookie := cookies[0]
788 if !cookie.Secure {
789 t.Error("Expected cookie Secure attribute to be true when request is secure")
790 }
791 if cookie.SameSite != http.SameSiteNoneMode {
792 t.Error("Expected cookie SameSite attribute to be None when request is secure")
793 }
794 }
795
796 func TestCookieHashPolicyWithFirstFallback(t *testing.T) {
797 ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()})
798 defer cancel()
799 cookieHashPolicy := CookieHashSelection{
800 FallbackRaw: caddyconfig.JSONModuleObject(FirstSelection{}, "policy", "first", nil),
801 }
802 if err := cookieHashPolicy.Provision(ctx); err != nil {
803 t.Errorf("Provision error: %v", err)
804 t.FailNow()
805 }
806
807 pool := testPool()
808 pool[0].Dial = "localhost:8080"
809 pool[1].Dial = "localhost:8081"
810 pool[2].Dial = "localhost:8082"
811 pool[0].setHealthy(true)
812 pool[1].setHealthy(true)
813 pool[2].setHealthy(true)
814 request := httptest.NewRequest(http.MethodGet, "/test", nil)
815 w := httptest.NewRecorder()
816
817 h := cookieHashPolicy.Select(pool, request, w)
818 cookieServer1 := w.Result().Cookies()[0]
819 if cookieServer1 == nil {
820 t.Fatal("cookieHashPolicy should set a cookie")
821 }
822 if cookieServer1.Name != "lb" {
823 t.Error("cookieHashPolicy should set a cookie with name lb")
824 }
825 if h != pool[0] {
826 t.Errorf("Expected cookieHashPolicy host to be the first only available host, got %s", h)
827 }
828 request = httptest.NewRequest(http.MethodGet, "/test", nil)
829 w = httptest.NewRecorder()
830 request.AddCookie(cookieServer1)
831 h = cookieHashPolicy.Select(pool, request, w)
832 if h != pool[0] {
833 t.Errorf("Expected cookieHashPolicy host to stick to the first host (matching cookie), got %s", h)
834 }
835 s := w.Result().Cookies()
836 if len(s) != 0 {
837 t.Error("Expected cookieHashPolicy to not set a new cookie.")
838 }
839 pool[0].setHealthy(false)
840 request = httptest.NewRequest(http.MethodGet, "/test", nil)
841 w = httptest.NewRecorder()
842 request.AddCookie(cookieServer1)
843 h = cookieHashPolicy.Select(pool, request, w)
844 if h != pool[1] {
845 t.Errorf("Expected cookieHashPolicy to select the next first available host, got %s", h)
846 }
847 if w.Result().Cookies() == nil {
848 t.Error("Expected cookieHashPolicy to set a new cookie.")
849 }
850 }