Fast and extensible multi-platform HTTP/1-2-3 web server with automatic HTTPS
Mirrored from https://github.com/Slazee/caddy.git
Synced Nov 14, 05:15 UTC
reverse_proxy: Fix random_choose selection policy (#3811)
Dimitri Masson committed
Nov 16, 2020 at 20:47 UTC
99b8f44486b766f220a33906d84ac05af942f260
2 files changed
+58
-2
modules/caddyhttp/reverseproxy/selectionpolicies.go
+7
-2
@@ -397,13 +397,18 @@ func leastRequests(upstreams []*Upstream) *Upstream {
397
return nil
398
}
399
var best []*Upstream
400
- var bestReqs int
400
+ var bestReqs int = -1
401
for _, upstream := range upstreams {
402
+ if upstream == nil {
403
+ continue
404
+ }
405
reqs := upstream.NumRequests()
406
if reqs == 0 {
407
return upstream
408
}
406
- if reqs <= bestReqs {
409
+ // If bestReqs was just initialized to -1
410
+ // we need to append upstream also
411
+ if reqs <= bestReqs || bestReqs == -1 {
412
bestReqs = reqs
413
best = append(best, upstream)
414
}
modules/caddyhttp/reverseproxy/selectionpolicies_test.go
+51
@@ -271,3 +271,54 @@ func TestURIHashPolicy(t *testing.T) {
271
t.Error("Expected uri policy policy host to be nil.")
272
}
273
}
274
+
275
+func TestLeastRequests(t *testing.T) {
276
+ pool := testPool()
277
+ pool[0].Dial = "localhost:8080"
278
+ pool[1].Dial = "localhost:8081"
279
+ pool[2].Dial = "localhost:8082"
280
+ pool[0].SetHealthy(true)
281
+ pool[1].SetHealthy(true)
282
+ pool[2].SetHealthy(true)
283
+ pool[0].CountRequest(10)
284
+ pool[1].CountRequest(20)
285
+ pool[2].CountRequest(30)
286
+
287
+ result := leastRequests(pool)
288
+
289
+ if result == nil {
290
+ t.Error("Least request should not return nil")
291
+ }
292
+
293
+ if result != pool[0] {
294
+ t.Error("Least request should return pool[0]")
295
+ }
296
+}
297
+
298
+func TestRandomChoicePolicy(t *testing.T) {
299
+ pool := testPool()
300
+ pool[0].Dial = "localhost:8080"
301
+ pool[1].Dial = "localhost:8081"
302
+ pool[2].Dial = "localhost:8082"
303
+ pool[0].SetHealthy(false)
304
+ pool[1].SetHealthy(true)
305
+ pool[2].SetHealthy(true)
306
+ pool[0].CountRequest(10)
307
+ pool[1].CountRequest(20)
308
+ pool[2].CountRequest(30)
309
+
310
+ request := httptest.NewRequest(http.MethodGet, "/test", nil)
311
+ randomChoicePolicy := new(RandomChoiceSelection)
312
+ randomChoicePolicy.Choose = 2
313
+
314
+ h := randomChoicePolicy.Select(pool, request)
315
+
316
+ if h == nil {
317
+ t.Error("RandomChoicePolicy should not return nil")
318
+ }
319
+
320
+ if h == pool[0] {
321
+ t.Error("RandomChoicePolicy should not choose pool[0]")
322
+ }
323
+
324
+}