Debian Codegraph @

modules/caddyhttp/reverseproxy/upstreams.go

raw symbols SCIP
1 package reverseproxy
2
3 import (
4 "context"
5 "encoding/json"
6 "fmt"
7 weakrand "math/rand/v2"
8 "net"
9 "net/http"
10 "strconv"
11 "sync"
12 "time"
13
14 "go.uber.org/zap"
15 "go.uber.org/zap/zapcore"
16
17 "github.com/caddyserver/caddy/v2"
18 )
19
20 func init() {
21 caddy.RegisterModule(SRVUpstreams{})
22 caddy.RegisterModule(AUpstreams{})
23 caddy.RegisterModule(MultiUpstreams{})
24 }
25
26 // SRVUpstreams provides upstreams from SRV lookups.
27 // The lookup DNS name can be configured either by
28 // its individual parts (that is, specifying the
29 // service, protocol, and name separately) to form
30 // the standard "_service._proto.name" domain, or
31 // the domain can be specified directly in name by
32 // leaving service and proto empty. See RFC 2782.
33 //
34 // Lookups are cached and refreshed at the configured
35 // refresh interval.
36 //
37 // Returned upstreams are sorted by priority and weight.
38 type SRVUpstreams struct {
39 // The service label.
40 Service string `json:"service,omitempty"`
41
42 // The protocol label; either tcp or udp.
43 Proto string `json:"proto,omitempty"`
44
45 // The name label; or, if service and proto are
46 // empty, the entire domain name to look up.
47 Name string `json:"name,omitempty"`
48
49 // The interval at which to refresh the SRV lookup.
50 // Results are cached between lookups. Default: 1m
51 Refresh caddy.Duration `json:"refresh,omitempty"`
52
53 // If > 0 and there is an error with the lookup,
54 // continue to use the cached results for up to
55 // this long before trying again, (even though they
56 // are stale) instead of returning an error to the
57 // client. Default: 0s.
58 GracePeriod caddy.Duration `json:"grace_period,omitempty"`
59
60 // Configures the DNS resolver used to resolve the
61 // SRV address to SRV records.
62 Resolver *UpstreamResolver `json:"resolver,omitempty"`
63
64 // If Resolver is configured, how long to wait before
65 // timing out trying to connect to the DNS server.
66 DialTimeout caddy.Duration `json:"dial_timeout,omitempty"`
67
68 // If Resolver is configured, how long to wait before
69 // spawning an RFC 6555 Fast Fallback connection.
70 // A negative value disables this.
71 FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"`
72
73 // Specific network to dial when connecting to the upstream(s)
74 // provided by SRV records upstream. See Go's net package for
75 // accepted values. For example, to restrict to IPv4, use "tcp4".
76 DialNetwork string `json:"dial_network,omitempty"`
77
78 resolver *net.Resolver
79
80 logger *zap.Logger
81 }
82
83 // CaddyModule returns the Caddy module information.
84 func (SRVUpstreams) CaddyModule() caddy.ModuleInfo {
85 return caddy.ModuleInfo{
86 ID: "http.reverse_proxy.upstreams.srv",
87 New: func() caddy.Module { return new(SRVUpstreams) },
88 }
89 }
90
91 func (su *SRVUpstreams) Provision(ctx caddy.Context) error {
92 su.logger = ctx.Logger()
93 if su.Refresh == 0 {
94 su.Refresh = caddy.Duration(time.Minute)
95 }
96
97 if su.Resolver != nil {
98 err := su.Resolver.ParseAddresses()
99 if err != nil {
100 return err
101 }
102 d := &net.Dialer{
103 Timeout: time.Duration(su.DialTimeout),
104 FallbackDelay: time.Duration(su.FallbackDelay),
105 }
106 su.resolver = &net.Resolver{
107 PreferGo: true,
108 Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
109 //nolint:gosec
110 addr := su.Resolver.netAddrs[weakrand.IntN(len(su.Resolver.netAddrs))]
111 return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0))
112 },
113 }
114 }
115 if su.resolver == nil {
116 su.resolver = net.DefaultResolver
117 }
118
119 return nil
120 }
121
122 func (su *SRVUpstreams) ResetCache(r *http.Request) error {
123 srvsMu.Lock()
124 if r == nil {
125 srvs = make(map[string]srvLookup)
126 } else {
127 suAddr, _, _, _ := su.expandedAddr(r)
128 delete(srvs, suAddr)
129 }
130 srvsMu.Unlock()
131 return nil
132 }
133
134 func (su SRVUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) {
135 suAddr, service, proto, name := su.expandedAddr(r)
136
137 // first, use a cheap read-lock to return a cached result quickly
138 srvsMu.RLock()
139 cached := srvs[suAddr]
140 srvsMu.RUnlock()
141 if cached.isFresh() {
142 return allNew(cached.upstreams), nil
143 }
144
145 // otherwise, obtain a write-lock to update the cached value
146 srvsMu.Lock()
147 defer srvsMu.Unlock()
148
149 // check to see if it's still stale, since we're now in a different
150 // lock from when we first checked freshness; another goroutine might
151 // have refreshed it in the meantime before we re-obtained our lock
152 cached = srvs[suAddr]
153 if cached.isFresh() {
154 return allNew(cached.upstreams), nil
155 }
156
157 if c := su.logger.Check(zapcore.DebugLevel, "refreshing SRV upstreams"); c != nil {
158 c.Write(
159 zap.String("service", service),
160 zap.String("proto", proto),
161 zap.String("name", name),
162 )
163 }
164
165 _, records, err := su.resolver.LookupSRV(r.Context(), service, proto, name)
166 if err != nil {
167 // From LookupSRV docs: "If the response contains invalid names, those records are filtered
168 // out and an error will be returned alongside the remaining results, if any." Thus, we
169 // only return an error if no records were also returned.
170 if len(records) == 0 {
171 if su.GracePeriod > 0 {
172 if c := su.logger.Check(zapcore.ErrorLevel, "SRV lookup failed; using previously cached"); c != nil {
173 c.Write(zap.Error(err))
174 }
175 cached.freshness = time.Now().Add(time.Duration(su.GracePeriod) - time.Duration(su.Refresh))
176 srvs[suAddr] = cached
177 return allNew(cached.upstreams), nil
178 }
179 return nil, err
180 }
181 if c := su.logger.Check(zapcore.WarnLevel, "SRV records filtered"); c != nil {
182 c.Write(zap.Error(err))
183 }
184 }
185
186 upstreams := make([]Upstream, len(records))
187 for i, rec := range records {
188 if c := su.logger.Check(zapcore.DebugLevel, "discovered SRV record"); c != nil {
189 c.Write(
190 zap.String("target", rec.Target),
191 zap.Uint16("port", rec.Port),
192 zap.Uint16("priority", rec.Priority),
193 zap.Uint16("weight", rec.Weight),
194 )
195 }
196 addr := net.JoinHostPort(rec.Target, strconv.Itoa(int(rec.Port)))
197 if su.DialNetwork != "" {
198 addr = su.DialNetwork + "/" + addr
199 }
200 upstreams[i] = Upstream{Dial: addr}
201 }
202
203 // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full
204 if cached.freshness.IsZero() && len(srvs) >= 100 {
205 for randomKey := range srvs {
206 delete(srvs, randomKey)
207 break
208 }
209 }
210
211 srvs[suAddr] = srvLookup{
212 srvUpstreams: su,
213 freshness: time.Now(),
214 upstreams: upstreams,
215 }
216
217 return allNew(upstreams), nil
218 }
219
220 func (su SRVUpstreams) String() string {
221 if su.Service == "" && su.Proto == "" {
222 return su.Name
223 }
224 return su.formattedAddr(su.Service, su.Proto, su.Name)
225 }
226
227 // expandedAddr expands placeholders in the configured SRV domain labels.
228 // The return values are: addr, the RFC 2782 representation of the SRV domain;
229 // service, the service; proto, the protocol; and name, the name.
230 // If su.Service and su.Proto are empty, name will be returned as addr instead.
231 func (su SRVUpstreams) expandedAddr(r *http.Request) (addr, service, proto, name string) {
232 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
233 name = repl.ReplaceAll(su.Name, "")
234 if su.Service == "" && su.Proto == "" {
235 addr = name
236 return addr, service, proto, name
237 }
238 service = repl.ReplaceAll(su.Service, "")
239 proto = repl.ReplaceAll(su.Proto, "")
240 addr = su.formattedAddr(service, proto, name)
241 return addr, service, proto, name
242 }
243
244 // formattedAddr the RFC 2782 representation of the SRV domain, in
245 // the form "_service._proto.name".
246 func (SRVUpstreams) formattedAddr(service, proto, name string) string {
247 return fmt.Sprintf("_%s._%s.%s", service, proto, name)
248 }
249
250 type srvLookup struct {
251 srvUpstreams SRVUpstreams
252 freshness time.Time
253 upstreams []Upstream
254 }
255
256 func (sl srvLookup) isFresh() bool {
257 return time.Since(sl.freshness) < time.Duration(sl.srvUpstreams.Refresh)
258 }
259
260 type IPVersions struct {
261 IPv4 *bool `json:"ipv4,omitempty"`
262 IPv6 *bool `json:"ipv6,omitempty"`
263 }
264
265 func resolveIpVersion(versions *IPVersions) string {
266 resolveIpv4 := versions == nil || (versions.IPv4 == nil && versions.IPv6 == nil) || (versions.IPv4 != nil && *versions.IPv4)
267 resolveIpv6 := versions == nil || (versions.IPv6 == nil && versions.IPv4 == nil) || (versions.IPv6 != nil && *versions.IPv6)
268 switch {
269 case resolveIpv4 && !resolveIpv6:
270 return "ip4"
271 case !resolveIpv4 && resolveIpv6:
272 return "ip6"
273 default:
274 return "ip"
275 }
276 }
277
278 // AUpstreams provides upstreams from A/AAAA lookups.
279 // Results are cached and refreshed at the configured
280 // refresh interval.
281 type AUpstreams struct {
282 // The domain name to look up.
283 Name string `json:"name,omitempty"`
284
285 // The port to use with the upstreams. Default: 80
286 Port string `json:"port,omitempty"`
287
288 // The interval at which to refresh the A lookup.
289 // Results are cached between lookups. Default: 1m
290 Refresh caddy.Duration `json:"refresh,omitempty"`
291
292 // Configures the DNS resolver used to resolve the
293 // domain name to A records.
294 Resolver *UpstreamResolver `json:"resolver,omitempty"`
295
296 // If Resolver is configured, how long to wait before
297 // timing out trying to connect to the DNS server.
298 DialTimeout caddy.Duration `json:"dial_timeout,omitempty"`
299
300 // If Resolver is configured, how long to wait before
301 // spawning an RFC 6555 Fast Fallback connection.
302 // A negative value disables this.
303 FallbackDelay caddy.Duration `json:"dial_fallback_delay,omitempty"`
304
305 // The IP versions to resolve for. By default, both
306 // "ipv4" and "ipv6" will be enabled, which
307 // correspond to A and AAAA records respectively.
308 Versions *IPVersions `json:"versions,omitempty"`
309
310 resolver *net.Resolver
311
312 logger *zap.Logger
313 }
314
315 // CaddyModule returns the Caddy module information.
316 func (AUpstreams) CaddyModule() caddy.ModuleInfo {
317 return caddy.ModuleInfo{
318 ID: "http.reverse_proxy.upstreams.a",
319 New: func() caddy.Module { return new(AUpstreams) },
320 }
321 }
322
323 func (au *AUpstreams) Provision(ctx caddy.Context) error {
324 au.logger = ctx.Logger()
325 if au.Refresh == 0 {
326 au.Refresh = caddy.Duration(time.Minute)
327 }
328 if au.Port == "" {
329 au.Port = "80"
330 }
331
332 if au.Resolver != nil {
333 err := au.Resolver.ParseAddresses()
334 if err != nil {
335 return err
336 }
337 d := &net.Dialer{
338 Timeout: time.Duration(au.DialTimeout),
339 FallbackDelay: time.Duration(au.FallbackDelay),
340 }
341 au.resolver = &net.Resolver{
342 PreferGo: true,
343 Dial: func(ctx context.Context, _, _ string) (net.Conn, error) {
344 //nolint:gosec
345 addr := au.Resolver.netAddrs[weakrand.IntN(len(au.Resolver.netAddrs))]
346 return d.DialContext(ctx, addr.Network, addr.JoinHostPort(0))
347 },
348 }
349 }
350 if au.resolver == nil {
351 au.resolver = net.DefaultResolver
352 }
353
354 return nil
355 }
356
357 func (au AUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) {
358 repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
359
360 // Map ipVersion early, so we can use it as part of the cache-key.
361 // This should be fairly inexpensive and comes and the upside of
362 // allowing the same dynamic upstream (name + port combination)
363 // to be used multiple times with different ip versions.
364 //
365 // It also forced a cache-miss if a previously cached dynamic
366 // upstream changes its ip version, e.g. after a config reload,
367 // while keeping the cache-invalidation as simple as it currently is.
368 ipVersion := resolveIpVersion(au.Versions)
369
370 auStr := repl.ReplaceAll(au.String()+ipVersion, "")
371
372 // first, use a cheap read-lock to return a cached result quickly
373 aAaaaMu.RLock()
374 cached := aAaaa[auStr]
375 aAaaaMu.RUnlock()
376 if cached.isFresh() {
377 return allNew(cached.upstreams), nil
378 }
379
380 // otherwise, obtain a write-lock to update the cached value
381 aAaaaMu.Lock()
382 defer aAaaaMu.Unlock()
383
384 // check to see if it's still stale, since we're now in a different
385 // lock from when we first checked freshness; another goroutine might
386 // have refreshed it in the meantime before we re-obtained our lock
387 cached = aAaaa[auStr]
388 if cached.isFresh() {
389 return allNew(cached.upstreams), nil
390 }
391
392 name := repl.ReplaceAll(au.Name, "")
393 port := repl.ReplaceAll(au.Port, "")
394
395 if c := au.logger.Check(zapcore.DebugLevel, "refreshing A upstreams"); c != nil {
396 c.Write(
397 zap.String("version", ipVersion),
398 zap.String("name", name),
399 zap.String("port", port),
400 )
401 }
402
403 ips, err := au.resolver.LookupIP(r.Context(), ipVersion, name)
404 if err != nil {
405 return nil, err
406 }
407
408 upstreams := make([]Upstream, len(ips))
409 for i, ip := range ips {
410 if c := au.logger.Check(zapcore.DebugLevel, "discovered A record"); c != nil {
411 c.Write(zap.String("ip", ip.String()))
412 }
413 upstreams[i] = Upstream{
414 Dial: net.JoinHostPort(ip.String(), port),
415 }
416 }
417
418 // before adding a new one to the cache (as opposed to replacing stale one), make room if cache is full
419 if cached.freshness.IsZero() && len(aAaaa) >= 100 {
420 for randomKey := range aAaaa {
421 delete(aAaaa, randomKey)
422 break
423 }
424 }
425
426 aAaaa[auStr] = aLookup{
427 aUpstreams: au,
428 freshness: time.Now(),
429 upstreams: upstreams,
430 }
431
432 return allNew(upstreams), nil
433 }
434
435 func (au AUpstreams) String() string { return net.JoinHostPort(au.Name, au.Port) }
436
437 type aLookup struct {
438 aUpstreams AUpstreams
439 freshness time.Time
440 upstreams []Upstream
441 }
442
443 func (al aLookup) isFresh() bool {
444 return time.Since(al.freshness) < time.Duration(al.aUpstreams.Refresh)
445 }
446
447 // MultiUpstreams is a single dynamic upstream source that
448 // aggregates the results of multiple dynamic upstream sources.
449 // All configured sources will be queried in order, with their
450 // results appended to the end of the list. Errors returned
451 // from individual sources will be logged and the next source
452 // will continue to be invoked.
453 //
454 // This module makes it easy to implement redundant cluster
455 // failovers, especially in conjunction with the `first` load
456 // balancing policy: if the first source returns an error or
457 // no upstreams, the second source's upstreams will be used
458 // naturally.
459 type MultiUpstreams struct {
460 // The list of upstream source modules to get upstreams from.
461 // They will be queried in order, with their results appended
462 // in the order they are returned.
463 SourcesRaw []json.RawMessage `json:"sources,omitempty" caddy:"namespace=http.reverse_proxy.upstreams inline_key=source"`
464 sources []UpstreamSource
465
466 logger *zap.Logger
467 }
468
469 // CaddyModule returns the Caddy module information.
470 func (MultiUpstreams) CaddyModule() caddy.ModuleInfo {
471 return caddy.ModuleInfo{
472 ID: "http.reverse_proxy.upstreams.multi",
473 New: func() caddy.Module { return new(MultiUpstreams) },
474 }
475 }
476
477 func (mu *MultiUpstreams) Provision(ctx caddy.Context) error {
478 mu.logger = ctx.Logger()
479
480 if mu.SourcesRaw != nil {
481 mod, err := ctx.LoadModule(mu, "SourcesRaw")
482 if err != nil {
483 return fmt.Errorf("loading upstream source modules: %v", err)
484 }
485 for _, src := range mod.([]any) {
486 mu.sources = append(mu.sources, src.(UpstreamSource))
487 }
488 }
489
490 return nil
491 }
492
493 func (mu MultiUpstreams) GetUpstreams(r *http.Request) ([]*Upstream, error) {
494 var upstreams []*Upstream
495
496 for i, src := range mu.sources {
497 select {
498 case <-r.Context().Done():
499 return upstreams, context.Canceled
500 default:
501 }
502
503 up, err := src.GetUpstreams(r)
504 if err != nil {
505 if c := mu.logger.Check(zapcore.ErrorLevel, "upstream source returned error"); c != nil {
506 c.Write(
507 zap.Int("source_idx", i),
508 zap.Error(err),
509 )
510 }
511 } else if len(up) == 0 {
512 if c := mu.logger.Check(zapcore.WarnLevel, "upstream source returned 0 upstreams"); c != nil {
513 c.Write(zap.Int("source_idx", i))
514 }
515 } else {
516 upstreams = append(upstreams, up...)
517 }
518 }
519
520 return upstreams, nil
521 }
522
523 // UpstreamResolver holds the set of addresses of DNS resolvers of
524 // upstream addresses
525 type UpstreamResolver struct {
526 // The addresses of DNS resolvers to use when looking up the addresses of proxy upstreams.
527 // It accepts [network addresses](/docs/conventions#network-addresses)
528 // with port range of only 1. If the host is an IP address, it will be dialed directly to resolve the upstream server.
529 // If the host is not an IP address, the addresses are resolved using the [name resolution convention](https://golang.org/pkg/net/#hdr-Name_Resolution) of the Go standard library.
530 // If the array contains more than 1 resolver address, one is chosen at random.
531 Addresses []string `json:"addresses,omitempty"`
532 netAddrs []caddy.NetworkAddress
533 }
534
535 // ParseAddresses parses all the configured network addresses
536 // and ensures they're ready to be used.
537 func (u *UpstreamResolver) ParseAddresses() error {
538 for _, v := range u.Addresses {
539 addr, err := caddy.ParseNetworkAddressWithDefaults(v, "udp", 53)
540 if err != nil {
541 return err
542 }
543 if addr.PortRangeSize() != 1 {
544 return fmt.Errorf("resolver address must have exactly one address; cannot call %v", addr)
545 }
546 u.netAddrs = append(u.netAddrs, addr)
547 }
548 return nil
549 }
550
551 func allNew(upstreams []Upstream) []*Upstream {
552 results := make([]*Upstream, len(upstreams))
553 for i := range upstreams {
554 results[i] = &Upstream{Dial: upstreams[i].Dial}
555 }
556 return results
557 }
558
559 var (
560 srvs = make(map[string]srvLookup)
561 srvsMu sync.RWMutex
562
563 aAaaa = make(map[string]aLookup)
564 aAaaaMu sync.RWMutex
565 )
566
567 // Interface guards
568 var (
569 _ caddy.Provisioner = (*SRVUpstreams)(nil)
570 _ UpstreamSource = (*SRVUpstreams)(nil)
571 _ CachingUpstreamSource = (*SRVUpstreams)(nil)
572 _ caddy.Provisioner = (*AUpstreams)(nil)
573 _ UpstreamSource = (*AUpstreams)(nil)
574 )