Debian Codegraph @

modules/caddyhttp/reverseproxy/selectionpolicies.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 "crypto/hmac"
19 "crypto/sha256"
20 "encoding/hex"
21 "encoding/json"
22 "fmt"
23 weakrand "math/rand/v2"
24 "net"
25 "net/http"
26 "strconv"
27 "strings"
28 "sync/atomic"
29 "time"
30
31 "github.com/cespare/xxhash/v2"
32
33 "github.com/caddyserver/caddy/v2"
34 "github.com/caddyserver/caddy/v2/caddyconfig"
35 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
36 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
37 )
38
39 func init() {
40 caddy.RegisterModule(RandomSelection{})
41 caddy.RegisterModule(RandomChoiceSelection{})
42 caddy.RegisterModule(LeastConnSelection{})
43 caddy.RegisterModule(new(RoundRobinSelection))
44 caddy.RegisterModule(new(WeightedRoundRobinSelection))
45 caddy.RegisterModule(FirstSelection{})
46 caddy.RegisterModule(IPHashSelection{})
47 caddy.RegisterModule(ClientIPHashSelection{})
48 caddy.RegisterModule(URIHashSelection{})
49 caddy.RegisterModule(QueryHashSelection{})
50 caddy.RegisterModule(HeaderHashSelection{})
51 caddy.RegisterModule(CookieHashSelection{})
52 }
53
54 // RandomSelection is a policy that selects
55 // an available host at random.
56 type RandomSelection struct{}
57
58 // CaddyModule returns the Caddy module information.
59 func (RandomSelection) CaddyModule() caddy.ModuleInfo {
60 return caddy.ModuleInfo{
61 ID: "http.reverse_proxy.selection_policies.random",
62 New: func() caddy.Module { return new(RandomSelection) },
63 }
64 }
65
66 // Select returns an available host, if any.
67 func (r RandomSelection) Select(pool UpstreamPool, request *http.Request, _ http.ResponseWriter) *Upstream {
68 return selectRandomHost(pool)
69 }
70
71 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
72 func (r *RandomSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
73 d.Next() // consume policy name
74 if d.NextArg() {
75 return d.ArgErr()
76 }
77 return nil
78 }
79
80 // WeightedRoundRobinSelection is a policy that selects
81 // a host based on weighted round-robin ordering.
82 type WeightedRoundRobinSelection struct {
83 // The weight of each upstream in order,
84 // corresponding with the list of upstreams configured.
85 Weights []int `json:"weights,omitempty"`
86 index atomic.Uint32
87 totalWeight int
88 }
89
90 // CaddyModule returns the Caddy module information.
91 func (*WeightedRoundRobinSelection) CaddyModule() caddy.ModuleInfo {
92 return caddy.ModuleInfo{
93 ID: "http.reverse_proxy.selection_policies.weighted_round_robin",
94 New: func() caddy.Module {
95 return new(WeightedRoundRobinSelection)
96 },
97 }
98 }
99
100 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
101 func (r *WeightedRoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
102 d.Next() // consume policy name
103
104 args := d.RemainingArgs()
105 if len(args) == 0 {
106 return d.ArgErr()
107 }
108
109 for _, weight := range args {
110 weightInt, err := strconv.Atoi(weight)
111 if err != nil {
112 return d.Errf("invalid weight value '%s': %v", weight, err)
113 }
114 if weightInt < 0 {
115 return d.Errf("invalid weight value '%s': weight should be non-negative", weight)
116 }
117 r.Weights = append(r.Weights, weightInt)
118 }
119 return nil
120 }
121
122 // Provision sets up r.
123 func (r *WeightedRoundRobinSelection) Provision(ctx caddy.Context) error {
124 for _, weight := range r.Weights {
125 r.totalWeight += weight
126 }
127 return nil
128 }
129
130 // Select returns an available host, if any.
131 func (r *WeightedRoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
132 if len(pool) == 0 {
133 return nil
134 }
135 if len(r.Weights) < 2 {
136 return pool[0]
137 }
138 var index, totalWeight int
139 var weights []int
140
141 for _, w := range r.Weights {
142 if w > 0 {
143 weights = append(weights, w)
144 }
145 }
146 currentWeight := int(r.index.Add(1)) % r.totalWeight
147 for i, weight := range weights {
148 totalWeight += weight
149 if currentWeight < totalWeight {
150 index = i
151 break
152 }
153 }
154
155 upstreams := make([]*Upstream, 0, len(weights))
156 for i, upstream := range pool {
157 if !upstream.Available() || r.Weights[i] == 0 {
158 continue
159 }
160 upstreams = append(upstreams, upstream)
161 if len(upstreams) == cap(upstreams) {
162 break
163 }
164 }
165 if len(upstreams) == 0 {
166 return nil
167 }
168 return upstreams[index%len(upstreams)]
169 }
170
171 // RandomChoiceSelection is a policy that selects
172 // two or more available hosts at random, then
173 // chooses the one with the least load.
174 type RandomChoiceSelection struct {
175 // The size of the sub-pool created from the larger upstream pool. The default value
176 // is 2 and the maximum at selection time is the size of the upstream pool.
177 Choose int `json:"choose,omitempty"`
178 }
179
180 // CaddyModule returns the Caddy module information.
181 func (RandomChoiceSelection) CaddyModule() caddy.ModuleInfo {
182 return caddy.ModuleInfo{
183 ID: "http.reverse_proxy.selection_policies.random_choose",
184 New: func() caddy.Module { return new(RandomChoiceSelection) },
185 }
186 }
187
188 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
189 func (r *RandomChoiceSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
190 d.Next() // consume policy name
191
192 if !d.NextArg() {
193 return d.ArgErr()
194 }
195 chooseStr := d.Val()
196 choose, err := strconv.Atoi(chooseStr)
197 if err != nil {
198 return d.Errf("invalid choice value '%s': %v", chooseStr, err)
199 }
200 r.Choose = choose
201 return nil
202 }
203
204 // Provision sets up r.
205 func (r *RandomChoiceSelection) Provision(ctx caddy.Context) error {
206 if r.Choose == 0 {
207 r.Choose = 2
208 }
209 return nil
210 }
211
212 // Validate ensures that r's configuration is valid.
213 func (r RandomChoiceSelection) Validate() error {
214 if r.Choose < 2 {
215 return fmt.Errorf("choose must be at least 2")
216 }
217 return nil
218 }
219
220 // Select returns an available host, if any.
221 func (r RandomChoiceSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
222 k := min(r.Choose, len(pool))
223 choices := make([]*Upstream, k)
224 for i, upstream := range pool {
225 if !upstream.Available() {
226 continue
227 }
228 j := weakrand.IntN(i + 1) //nolint:gosec
229 if j < k {
230 choices[j] = upstream
231 }
232 }
233 return leastRequests(choices)
234 }
235
236 // LeastConnSelection is a policy that selects the
237 // host with the least active requests. If multiple
238 // hosts have the same fewest number, one is chosen
239 // randomly. The term "conn" or "connection" is used
240 // in this policy name due to its similar meaning in
241 // other software, but our load balancer actually
242 // counts active requests rather than connections,
243 // since these days requests are multiplexed onto
244 // shared connections.
245 type LeastConnSelection struct{}
246
247 // CaddyModule returns the Caddy module information.
248 func (LeastConnSelection) CaddyModule() caddy.ModuleInfo {
249 return caddy.ModuleInfo{
250 ID: "http.reverse_proxy.selection_policies.least_conn",
251 New: func() caddy.Module { return new(LeastConnSelection) },
252 }
253 }
254
255 // Select selects the up host with the least number of connections in the
256 // pool. If more than one host has the same least number of connections,
257 // one of the hosts is chosen at random.
258 func (LeastConnSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
259 var bestHost *Upstream
260 var count int
261 leastReqs := -1
262
263 for _, host := range pool {
264 if !host.Available() {
265 continue
266 }
267 numReqs := host.NumRequests()
268 if leastReqs == -1 || numReqs < leastReqs {
269 leastReqs = numReqs
270 count = 0
271 }
272
273 // among hosts with same least connections, perform a reservoir
274 // sample: https://en.wikipedia.org/wiki/Reservoir_sampling
275 if numReqs == leastReqs {
276 count++
277 if count == 1 || weakrand.IntN(count) == 0 { //nolint:gosec
278 bestHost = host
279 }
280 }
281 }
282
283 return bestHost
284 }
285
286 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
287 func (r *LeastConnSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
288 d.Next() // consume policy name
289 if d.NextArg() {
290 return d.ArgErr()
291 }
292 return nil
293 }
294
295 // RoundRobinSelection is a policy that selects
296 // a host based on round-robin ordering.
297 type RoundRobinSelection struct {
298 robin atomic.Uint32
299 }
300
301 // CaddyModule returns the Caddy module information.
302 func (*RoundRobinSelection) CaddyModule() caddy.ModuleInfo {
303 return caddy.ModuleInfo{
304 ID: "http.reverse_proxy.selection_policies.round_robin",
305 New: func() caddy.Module { return new(RoundRobinSelection) },
306 }
307 }
308
309 // Select returns an available host, if any.
310 func (r *RoundRobinSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
311 n := uint32(len(pool))
312 if n == 0 {
313 return nil
314 }
315 for range n {
316 robin := r.robin.Add(1)
317 host := pool[robin%n]
318 if host.Available() {
319 return host
320 }
321 }
322 return nil
323 }
324
325 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
326 func (r *RoundRobinSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
327 d.Next() // consume policy name
328 if d.NextArg() {
329 return d.ArgErr()
330 }
331 return nil
332 }
333
334 // FirstSelection is a policy that selects
335 // the first available host.
336 type FirstSelection struct{}
337
338 // CaddyModule returns the Caddy module information.
339 func (FirstSelection) CaddyModule() caddy.ModuleInfo {
340 return caddy.ModuleInfo{
341 ID: "http.reverse_proxy.selection_policies.first",
342 New: func() caddy.Module { return new(FirstSelection) },
343 }
344 }
345
346 // Select returns an available host, if any.
347 func (FirstSelection) Select(pool UpstreamPool, _ *http.Request, _ http.ResponseWriter) *Upstream {
348 for _, host := range pool {
349 if host.Available() {
350 return host
351 }
352 }
353 return nil
354 }
355
356 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
357 func (r *FirstSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
358 d.Next() // consume policy name
359 if d.NextArg() {
360 return d.ArgErr()
361 }
362 return nil
363 }
364
365 // IPHashSelection is a policy that selects a host
366 // based on hashing the remote IP of the request.
367 type IPHashSelection struct{}
368
369 // CaddyModule returns the Caddy module information.
370 func (IPHashSelection) CaddyModule() caddy.ModuleInfo {
371 return caddy.ModuleInfo{
372 ID: "http.reverse_proxy.selection_policies.ip_hash",
373 New: func() caddy.Module { return new(IPHashSelection) },
374 }
375 }
376
377 // Select returns an available host, if any.
378 func (IPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream {
379 clientIP, _, err := net.SplitHostPort(req.RemoteAddr)
380 if err != nil {
381 clientIP = req.RemoteAddr
382 }
383 return hostByHashing(pool, clientIP)
384 }
385
386 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
387 func (r *IPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
388 d.Next() // consume policy name
389 if d.NextArg() {
390 return d.ArgErr()
391 }
392 return nil
393 }
394
395 // ClientIPHashSelection is a policy that selects a host
396 // based on hashing the client IP of the request, as determined
397 // by the HTTP app's trusted proxies settings.
398 type ClientIPHashSelection struct{}
399
400 // CaddyModule returns the Caddy module information.
401 func (ClientIPHashSelection) CaddyModule() caddy.ModuleInfo {
402 return caddy.ModuleInfo{
403 ID: "http.reverse_proxy.selection_policies.client_ip_hash",
404 New: func() caddy.Module { return new(ClientIPHashSelection) },
405 }
406 }
407
408 // Select returns an available host, if any.
409 func (ClientIPHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream {
410 address := caddyhttp.GetVar(req.Context(), caddyhttp.ClientIPVarKey).(string)
411 clientIP, _, err := net.SplitHostPort(address)
412 if err != nil {
413 clientIP = address // no port
414 }
415 return hostByHashing(pool, clientIP)
416 }
417
418 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
419 func (r *ClientIPHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
420 d.Next() // consume policy name
421 if d.NextArg() {
422 return d.ArgErr()
423 }
424 return nil
425 }
426
427 // URIHashSelection is a policy that selects a
428 // host by hashing the request URI.
429 type URIHashSelection struct{}
430
431 // CaddyModule returns the Caddy module information.
432 func (URIHashSelection) CaddyModule() caddy.ModuleInfo {
433 return caddy.ModuleInfo{
434 ID: "http.reverse_proxy.selection_policies.uri_hash",
435 New: func() caddy.Module { return new(URIHashSelection) },
436 }
437 }
438
439 // Select returns an available host, if any.
440 func (URIHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream {
441 return hostByHashing(pool, req.RequestURI)
442 }
443
444 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
445 func (r *URIHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
446 d.Next() // consume policy name
447 if d.NextArg() {
448 return d.ArgErr()
449 }
450 return nil
451 }
452
453 // QueryHashSelection is a policy that selects
454 // a host based on a given request query parameter.
455 type QueryHashSelection struct {
456 // The query key whose value is to be hashed and used for upstream selection.
457 Key string `json:"key,omitempty"`
458
459 // The fallback policy to use if the query key is not present. Defaults to `random`.
460 FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
461 fallback Selector
462 }
463
464 // CaddyModule returns the Caddy module information.
465 func (QueryHashSelection) CaddyModule() caddy.ModuleInfo {
466 return caddy.ModuleInfo{
467 ID: "http.reverse_proxy.selection_policies.query",
468 New: func() caddy.Module { return new(QueryHashSelection) },
469 }
470 }
471
472 // Provision sets up the module.
473 func (s *QueryHashSelection) Provision(ctx caddy.Context) error {
474 if s.Key == "" {
475 return fmt.Errorf("query key is required")
476 }
477 if s.FallbackRaw == nil {
478 s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil)
479 }
480 mod, err := ctx.LoadModule(s, "FallbackRaw")
481 if err != nil {
482 return fmt.Errorf("loading fallback selection policy: %s", err)
483 }
484 s.fallback = mod.(Selector)
485 return nil
486 }
487
488 // Select returns an available host, if any.
489 func (s QueryHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream {
490 // Since the query may have multiple values for the same key,
491 // we'll join them to avoid a problem where the user can control
492 // the upstream that the request goes to by sending multiple values
493 // for the same key, when the upstream only considers the first value.
494 // Keep in mind that a client changing the order of the values may
495 // affect which upstream is selected, but this is a semantically
496 // different request, because the order of the values is significant.
497 vals := strings.Join(req.URL.Query()[s.Key], ",")
498 if vals == "" {
499 return s.fallback.Select(pool, req, nil)
500 }
501 return hostByHashing(pool, vals)
502 }
503
504 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
505 func (s *QueryHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
506 d.Next() // consume policy name
507
508 if !d.NextArg() {
509 return d.ArgErr()
510 }
511 s.Key = d.Val()
512
513 for d.NextBlock(0) {
514 switch d.Val() {
515 case "fallback":
516 if !d.NextArg() {
517 return d.ArgErr()
518 }
519 if s.FallbackRaw != nil {
520 return d.Err("fallback selection policy already specified")
521 }
522 mod, err := loadFallbackPolicy(d)
523 if err != nil {
524 return err
525 }
526 s.FallbackRaw = mod
527 default:
528 return d.Errf("unrecognized option '%s'", d.Val())
529 }
530 }
531 return nil
532 }
533
534 // HeaderHashSelection is a policy that selects
535 // a host based on a given request header.
536 type HeaderHashSelection struct {
537 // The HTTP header field whose value is to be hashed and used for upstream selection.
538 Field string `json:"field,omitempty"`
539
540 // The fallback policy to use if the header is not present. Defaults to `random`.
541 FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
542 fallback Selector
543 }
544
545 // CaddyModule returns the Caddy module information.
546 func (HeaderHashSelection) CaddyModule() caddy.ModuleInfo {
547 return caddy.ModuleInfo{
548 ID: "http.reverse_proxy.selection_policies.header",
549 New: func() caddy.Module { return new(HeaderHashSelection) },
550 }
551 }
552
553 // Provision sets up the module.
554 func (s *HeaderHashSelection) Provision(ctx caddy.Context) error {
555 if s.Field == "" {
556 return fmt.Errorf("header field is required")
557 }
558 if s.FallbackRaw == nil {
559 s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil)
560 }
561 mod, err := ctx.LoadModule(s, "FallbackRaw")
562 if err != nil {
563 return fmt.Errorf("loading fallback selection policy: %s", err)
564 }
565 s.fallback = mod.(Selector)
566 return nil
567 }
568
569 // Select returns an available host, if any.
570 func (s HeaderHashSelection) Select(pool UpstreamPool, req *http.Request, _ http.ResponseWriter) *Upstream {
571 // The Host header should be obtained from the req.Host field
572 // since net/http removes it from the header map.
573 if s.Field == "Host" && req.Host != "" {
574 return hostByHashing(pool, req.Host)
575 }
576
577 val := req.Header.Get(s.Field)
578 if val == "" {
579 return s.fallback.Select(pool, req, nil)
580 }
581 return hostByHashing(pool, val)
582 }
583
584 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
585 func (s *HeaderHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
586 d.Next() // consume policy name
587
588 if !d.NextArg() {
589 return d.ArgErr()
590 }
591 s.Field = d.Val()
592
593 for d.NextBlock(0) {
594 switch d.Val() {
595 case "fallback":
596 if !d.NextArg() {
597 return d.ArgErr()
598 }
599 if s.FallbackRaw != nil {
600 return d.Err("fallback selection policy already specified")
601 }
602 mod, err := loadFallbackPolicy(d)
603 if err != nil {
604 return err
605 }
606 s.FallbackRaw = mod
607 default:
608 return d.Errf("unrecognized option '%s'", d.Val())
609 }
610 }
611 return nil
612 }
613
614 // CookieHashSelection is a policy that selects
615 // a host based on a given cookie name.
616 type CookieHashSelection struct {
617 // The HTTP cookie name whose value is to be hashed and used for upstream selection.
618 Name string `json:"name,omitempty"`
619 // Secret to hash (Hmac256) chosen upstream in cookie
620 Secret string `json:"secret,omitempty"` //nolint:gosec // yes it's exported because it needs to encode to JSON
621 // The cookie's Max-Age before it expires. Default is no expiry.
622 MaxAge caddy.Duration `json:"max_age,omitempty"`
623
624 // The fallback policy to use if the cookie is not present. Defaults to `random`.
625 FallbackRaw json.RawMessage `json:"fallback,omitempty" caddy:"namespace=http.reverse_proxy.selection_policies inline_key=policy"`
626 fallback Selector
627 }
628
629 // CaddyModule returns the Caddy module information.
630 func (CookieHashSelection) CaddyModule() caddy.ModuleInfo {
631 return caddy.ModuleInfo{
632 ID: "http.reverse_proxy.selection_policies.cookie",
633 New: func() caddy.Module { return new(CookieHashSelection) },
634 }
635 }
636
637 // Provision sets up the module.
638 func (s *CookieHashSelection) Provision(ctx caddy.Context) error {
639 if s.Name == "" {
640 s.Name = "lb"
641 }
642 if s.FallbackRaw == nil {
643 s.FallbackRaw = caddyconfig.JSONModuleObject(RandomSelection{}, "policy", "random", nil)
644 }
645 mod, err := ctx.LoadModule(s, "FallbackRaw")
646 if err != nil {
647 return fmt.Errorf("loading fallback selection policy: %s", err)
648 }
649 s.fallback = mod.(Selector)
650 return nil
651 }
652
653 // Select returns an available host, if any.
654 func (s CookieHashSelection) Select(pool UpstreamPool, req *http.Request, w http.ResponseWriter) *Upstream {
655 // selects a new Host using the fallback policy (typically random)
656 // and write a sticky session cookie to the response.
657 selectNewHost := func() *Upstream {
658 upstream := s.fallback.Select(pool, req, w)
659 if upstream == nil {
660 return nil
661 }
662 sha, err := hashCookie(s.Secret, upstream.Dial)
663 if err != nil {
664 return upstream
665 }
666 cookie := &http.Cookie{
667 Name: s.Name,
668 Value: sha,
669 Path: "/",
670 Secure: false,
671 HttpOnly: true,
672 SameSite: http.SameSiteLaxMode,
673 }
674 isProxyHttps := false
675 if trusted, ok := caddyhttp.GetVar(req.Context(), caddyhttp.TrustedProxyVarKey).(bool); ok && trusted {
676 xfp, xfpOk, _ := lastHeaderValue(req.Header, "X-Forwarded-Proto")
677 isProxyHttps = xfpOk && xfp == "https"
678 }
679 if req.TLS != nil || isProxyHttps {
680 cookie.Secure = true
681 cookie.SameSite = http.SameSiteNoneMode
682 }
683 if s.MaxAge > 0 {
684 cookie.MaxAge = int(time.Duration(s.MaxAge).Seconds())
685 }
686 http.SetCookie(w, cookie)
687 return upstream
688 }
689
690 cookie, err := req.Cookie(s.Name)
691 // If there's no cookie, select a host using the fallback policy
692 if err != nil || cookie == nil {
693 return selectNewHost()
694 }
695 // If the cookie is present, loop over the available upstreams until we find a match
696 cookieValue := cookie.Value
697 for _, upstream := range pool {
698 if !upstream.Available() {
699 continue
700 }
701 sha, err := hashCookie(s.Secret, upstream.Dial)
702 if err == nil && sha == cookieValue {
703 return upstream
704 }
705 }
706 // If there is no matching host, select a host using the fallback policy
707 return selectNewHost()
708 }
709
710 // UnmarshalCaddyfile sets up the module from Caddyfile tokens. Syntax:
711 //
712 // lb_policy cookie [<name> [<secret>]] {
713 // fallback <policy>
714 // max_age <duration>
715 // }
716 //
717 // By default name is `lb`
718 func (s *CookieHashSelection) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
719 args := d.RemainingArgs()
720 switch len(args) {
721 case 1:
722 case 2:
723 s.Name = args[1]
724 case 3:
725 s.Name = args[1]
726 s.Secret = args[2]
727 default:
728 return d.ArgErr()
729 }
730 for d.NextBlock(0) {
731 switch d.Val() {
732 case "fallback":
733 if !d.NextArg() {
734 return d.ArgErr()
735 }
736 if s.FallbackRaw != nil {
737 return d.Err("fallback selection policy already specified")
738 }
739 mod, err := loadFallbackPolicy(d)
740 if err != nil {
741 return err
742 }
743 s.FallbackRaw = mod
744 case "max_age":
745 if !d.NextArg() {
746 return d.ArgErr()
747 }
748 if s.MaxAge != 0 {
749 return d.Err("cookie max_age already specified")
750 }
751 maxAge, err := caddy.ParseDuration(d.Val())
752 if err != nil {
753 return d.Errf("invalid duration: %s", d.Val())
754 }
755 if maxAge <= 0 {
756 return d.Errf("invalid duration: %s, max_age should be non-zero and positive", d.Val())
757 }
758 if d.NextArg() {
759 return d.ArgErr()
760 }
761 s.MaxAge = caddy.Duration(maxAge)
762 default:
763 return d.Errf("unrecognized option '%s'", d.Val())
764 }
765 }
766 return nil
767 }
768
769 // hashCookie hashes (HMAC 256) some data with the secret
770 func hashCookie(secret string, data string) (string, error) {
771 h := hmac.New(sha256.New, []byte(secret))
772 _, err := h.Write([]byte(data))
773 if err != nil {
774 return "", err
775 }
776 return hex.EncodeToString(h.Sum(nil)), nil
777 }
778
779 // selectRandomHost returns a random available host
780 func selectRandomHost(pool []*Upstream) *Upstream {
781 // use reservoir sampling because the number of available
782 // hosts isn't known: https://en.wikipedia.org/wiki/Reservoir_sampling
783 var randomHost *Upstream
784 var count int
785 for _, upstream := range pool {
786 if !upstream.Available() {
787 continue
788 }
789 // (n % 1 == 0) holds for all n, therefore a
790 // upstream will always be chosen if there is at
791 // least one available
792 count++
793 if weakrand.IntN(count) == 0 { //nolint:gosec
794 randomHost = upstream
795 }
796 }
797 return randomHost
798 }
799
800 // leastRequests returns the host with the
801 // least number of active requests to it.
802 // If more than one host has the same
803 // least number of active requests, then
804 // one of those is chosen at random.
805 func leastRequests(upstreams []*Upstream) *Upstream {
806 if len(upstreams) == 0 {
807 return nil
808 }
809 var best []*Upstream
810 bestReqs := -1
811 for _, upstream := range upstreams {
812 if upstream == nil {
813 continue
814 }
815 reqs := upstream.NumRequests()
816 if reqs == 0 {
817 return upstream
818 }
819 // If bestReqs was just initialized to -1
820 // we need to append upstream also
821 if reqs <= bestReqs || bestReqs == -1 {
822 bestReqs = reqs
823 best = append(best, upstream)
824 }
825 }
826 if len(best) == 0 {
827 return nil
828 }
829 if len(best) == 1 {
830 return best[0]
831 }
832 return best[weakrand.IntN(len(best))] //nolint:gosec
833 }
834
835 // hostByHashing returns an available host from pool based on a hashable string s.
836 func hostByHashing(pool []*Upstream, s string) *Upstream {
837 // Highest Random Weight (HRW, or "Rendezvous") hashing,
838 // guarantees stability when the list of upstreams changes;
839 // see https://medium.com/i0exception/rendezvous-hashing-8c00e2fb58b0,
840 // https://randorithms.com/2020/12/26/rendezvous-hashing.html,
841 // and https://en.wikipedia.org/wiki/Rendezvous_hashing.
842 var highestHash uint64
843 var upstream *Upstream
844 for _, up := range pool {
845 if !up.Available() {
846 continue
847 }
848 h := hash(up.String() + s) // important to hash key and server together
849 if h > highestHash {
850 highestHash = h
851 upstream = up
852 }
853 }
854 return upstream
855 }
856
857 // hash calculates a fast hash based on s.
858 func hash(s string) uint64 {
859 h := xxhash.New()
860 _, _ = h.Write([]byte(s))
861 return h.Sum64()
862 }
863
864 func loadFallbackPolicy(d *caddyfile.Dispenser) (json.RawMessage, error) {
865 name := d.Val()
866 modID := "http.reverse_proxy.selection_policies." + name
867 unm, err := caddyfile.UnmarshalModule(d, modID)
868 if err != nil {
869 return nil, err
870 }
871 sel, ok := unm.(Selector)
872 if !ok {
873 return nil, d.Errf("module %s (%T) is not a reverseproxy.Selector", modID, unm)
874 }
875 return caddyconfig.JSONModuleObject(sel, "policy", name, nil), nil
876 }
877
878 // Interface guards
879 var (
880 _ Selector = (*RandomSelection)(nil)
881 _ Selector = (*RandomChoiceSelection)(nil)
882 _ Selector = (*LeastConnSelection)(nil)
883 _ Selector = (*RoundRobinSelection)(nil)
884 _ Selector = (*WeightedRoundRobinSelection)(nil)
885 _ Selector = (*FirstSelection)(nil)
886 _ Selector = (*IPHashSelection)(nil)
887 _ Selector = (*ClientIPHashSelection)(nil)
888 _ Selector = (*URIHashSelection)(nil)
889 _ Selector = (*QueryHashSelection)(nil)
890 _ Selector = (*HeaderHashSelection)(nil)
891 _ Selector = (*CookieHashSelection)(nil)
892
893 _ caddy.Validator = (*RandomChoiceSelection)(nil)
894
895 _ caddy.Provisioner = (*RandomChoiceSelection)(nil)
896 _ caddy.Provisioner = (*WeightedRoundRobinSelection)(nil)
897
898 _ caddyfile.Unmarshaler = (*RandomChoiceSelection)(nil)
899 _ caddyfile.Unmarshaler = (*WeightedRoundRobinSelection)(nil)
900 )