| 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 | "fmt" |
| 20 | "net/netip" |
| 21 | "strconv" |
| 22 | "sync" |
| 23 | "sync/atomic" |
| 24 | "time" |
| 25 | |
| 26 | "github.com/caddyserver/caddy/v2" |
| 27 | "github.com/caddyserver/caddy/v2/modules/caddyhttp" |
| 28 | ) |
| 29 | |
| 30 | // UpstreamPool is a collection of upstreams. |
| 31 | type UpstreamPool []*Upstream |
| 32 | |
| 33 | // Upstream bridges this proxy's configuration to the |
| 34 | // state of the backend host it is correlated with. |
| 35 | // Upstream values must not be copied. |
| 36 | type Upstream struct { |
| 37 | *Host `json:"-"` |
| 38 | |
| 39 | // The [network address](/docs/conventions#network-addresses) |
| 40 | // to dial to connect to the upstream. Must represent precisely |
| 41 | // one socket (i.e. no port ranges). A valid network address |
| 42 | // either has a host and port or is a unix socket address. |
| 43 | // |
| 44 | // Placeholders may be used to make the upstream dynamic, but be |
| 45 | // aware of the health check implications of this: a single |
| 46 | // upstream that represents numerous (perhaps arbitrary) backends |
| 47 | // can be considered down if one or enough of the arbitrary |
| 48 | // backends is down. Also be aware of open proxy vulnerabilities. |
| 49 | Dial string `json:"dial,omitempty"` |
| 50 | |
| 51 | // The maximum number of simultaneous requests to allow to |
| 52 | // this upstream. If set, overrides the global passive health |
| 53 | // check UnhealthyRequestCount value. |
| 54 | MaxRequests int `json:"max_requests,omitempty"` |
| 55 | |
| 56 | // TODO: This could be really useful, to bind requests |
| 57 | // with certain properties to specific backends |
| 58 | // HeaderAffinity string |
| 59 | // IPAffinity string |
| 60 | |
| 61 | activeHealthCheckPort int |
| 62 | activeHealthCheckUpstream string |
| 63 | healthCheckPolicy *PassiveHealthChecks |
| 64 | cb CircuitBreaker |
| 65 | unhealthy atomic.Int32 // status from active health checker |
| 66 | } |
| 67 | |
| 68 | // (pointer receiver necessary to avoid a race condition, since |
| 69 | // copying the Upstream reads the 'unhealthy' field which is |
| 70 | // accessed atomically) |
| 71 | func (u *Upstream) String() string { return u.Dial } |
| 72 | |
| 73 | // Available returns true if the remote host |
| 74 | // is available to receive requests. This is |
| 75 | // the method that should be used by selection |
| 76 | // policies, etc. to determine if a backend |
| 77 | // should be able to be sent a request. |
| 78 | func (u *Upstream) Available() bool { |
| 79 | return u.Healthy() && !u.Full() |
| 80 | } |
| 81 | |
| 82 | // Healthy returns true if the remote host |
| 83 | // is currently known to be healthy or "up". |
| 84 | // It consults the circuit breaker, if any. |
| 85 | func (u *Upstream) Healthy() bool { |
| 86 | healthy := u.healthy() |
| 87 | if healthy && u.healthCheckPolicy != nil { |
| 88 | healthy = u.Host.Fails() < u.healthCheckPolicy.MaxFails |
| 89 | } |
| 90 | if healthy && u.cb != nil { |
| 91 | healthy = u.cb.OK() |
| 92 | } |
| 93 | return healthy |
| 94 | } |
| 95 | |
| 96 | // Full returns true if the remote host |
| 97 | // cannot receive more requests at this time. |
| 98 | func (u *Upstream) Full() bool { |
| 99 | return u.MaxRequests > 0 && u.Host.NumRequests() >= u.MaxRequests |
| 100 | } |
| 101 | |
| 102 | // fillDialInfo returns a filled DialInfo for upstream u, using the request |
| 103 | // context. Note that the returned value is not a pointer. |
| 104 | func (u *Upstream) fillDialInfo(repl *caddy.Replacer) (DialInfo, error) { |
| 105 | var addr caddy.NetworkAddress |
| 106 | |
| 107 | // use provided dial address |
| 108 | var err error |
| 109 | dial := repl.ReplaceAll(u.Dial, "") |
| 110 | addr, err = caddy.ParseNetworkAddress(dial) |
| 111 | if err != nil { |
| 112 | return DialInfo{}, fmt.Errorf("upstream %s: invalid dial address %s: %v", u.Dial, dial, err) |
| 113 | } |
| 114 | if numPorts := addr.PortRangeSize(); numPorts != 1 { |
| 115 | return DialInfo{}, fmt.Errorf("upstream %s: dial address must represent precisely one socket: %s represents %d", |
| 116 | u.Dial, dial, numPorts) |
| 117 | } |
| 118 | |
| 119 | return DialInfo{ |
| 120 | Upstream: u, |
| 121 | Network: addr.Network, |
| 122 | Address: addr.JoinHostPort(0), |
| 123 | Host: addr.Host, |
| 124 | Port: strconv.Itoa(int(addr.StartPort)), |
| 125 | }, nil |
| 126 | } |
| 127 | |
| 128 | func (u *Upstream) fillHost() { |
| 129 | host := new(Host) |
| 130 | existingHost, loaded := hosts.LoadOrStore(u.String(), host) |
| 131 | if loaded { |
| 132 | host = existingHost.(*Host) |
| 133 | } |
| 134 | u.Host = host |
| 135 | } |
| 136 | |
| 137 | // fillDynamicHost is like fillHost, but stores the host in the separate |
| 138 | // dynamicHosts map rather than the reference-counted UsagePool. Dynamic |
| 139 | // hosts are not reference-counted; instead, they are retained as long as |
| 140 | // they are actively seen and are evicted by a background cleanup goroutine |
| 141 | // after dynamicHostIdleExpiry of inactivity. This preserves health state |
| 142 | // (e.g. passive fail counts) across sequential requests. |
| 143 | func (u *Upstream) fillDynamicHost() { |
| 144 | dynamicHostsMu.Lock() |
| 145 | entry, ok := dynamicHosts[u.String()] |
| 146 | if ok { |
| 147 | entry.lastSeen = time.Now() |
| 148 | dynamicHosts[u.String()] = entry |
| 149 | u.Host = entry.host |
| 150 | } else { |
| 151 | h := new(Host) |
| 152 | dynamicHosts[u.String()] = dynamicHostEntry{host: h, lastSeen: time.Now()} |
| 153 | u.Host = h |
| 154 | } |
| 155 | dynamicHostsMu.Unlock() |
| 156 | |
| 157 | // ensure the cleanup goroutine is running |
| 158 | dynamicHostsCleanerOnce.Do(func() { |
| 159 | go func() { |
| 160 | for { |
| 161 | time.Sleep(dynamicHostCleanupInterval) |
| 162 | dynamicHostsMu.Lock() |
| 163 | for addr, entry := range dynamicHosts { |
| 164 | if time.Since(entry.lastSeen) > dynamicHostIdleExpiry { |
| 165 | delete(dynamicHosts, addr) |
| 166 | } |
| 167 | } |
| 168 | dynamicHostsMu.Unlock() |
| 169 | } |
| 170 | }() |
| 171 | }) |
| 172 | } |
| 173 | |
| 174 | // Host is the basic, in-memory representation of the state of a remote host. |
| 175 | // Its fields are accessed atomically and Host values must not be copied. |
| 176 | type Host struct { |
| 177 | numRequests atomic.Int64 |
| 178 | fails atomic.Int64 |
| 179 | activePasses atomic.Int64 |
| 180 | activeFails atomic.Int64 |
| 181 | } |
| 182 | |
| 183 | // NumRequests returns the number of active requests to the upstream. |
| 184 | func (h *Host) NumRequests() int { |
| 185 | return int(h.numRequests.Load()) |
| 186 | } |
| 187 | |
| 188 | // Fails returns the number of recent failures with the upstream. |
| 189 | func (h *Host) Fails() int { |
| 190 | return int(h.fails.Load()) |
| 191 | } |
| 192 | |
| 193 | // activeHealthPasses returns the number of consecutive active health check passes with the upstream. |
| 194 | func (h *Host) activeHealthPasses() int { |
| 195 | return int(h.activePasses.Load()) |
| 196 | } |
| 197 | |
| 198 | // activeHealthFails returns the number of consecutive active health check failures with the upstream. |
| 199 | func (h *Host) activeHealthFails() int { |
| 200 | return int(h.activeFails.Load()) |
| 201 | } |
| 202 | |
| 203 | // countRequest mutates the active request count by |
| 204 | // delta. It returns an error if the adjustment fails. |
| 205 | func (h *Host) countRequest(delta int) error { |
| 206 | result := h.numRequests.Add(int64(delta)) |
| 207 | if result < 0 { |
| 208 | return fmt.Errorf("count below 0: %d", result) |
| 209 | } |
| 210 | return nil |
| 211 | } |
| 212 | |
| 213 | // countFail mutates the recent failures count by |
| 214 | // delta. It returns an error if the adjustment fails. |
| 215 | func (h *Host) countFail(delta int) error { |
| 216 | result := h.fails.Add(int64(delta)) |
| 217 | if result < 0 { |
| 218 | return fmt.Errorf("count below 0: %d", result) |
| 219 | } |
| 220 | return nil |
| 221 | } |
| 222 | |
| 223 | // countHealthPass mutates the recent passes count by |
| 224 | // delta. It returns an error if the adjustment fails. |
| 225 | func (h *Host) countHealthPass(delta int) error { |
| 226 | result := h.activePasses.Add(int64(delta)) |
| 227 | if result < 0 { |
| 228 | return fmt.Errorf("count below 0: %d", result) |
| 229 | } |
| 230 | return nil |
| 231 | } |
| 232 | |
| 233 | // countHealthFail mutates the recent failures count by |
| 234 | // delta. It returns an error if the adjustment fails. |
| 235 | func (h *Host) countHealthFail(delta int) error { |
| 236 | result := h.activeFails.Add(int64(delta)) |
| 237 | if result < 0 { |
| 238 | return fmt.Errorf("count below 0: %d", result) |
| 239 | } |
| 240 | return nil |
| 241 | } |
| 242 | |
| 243 | // resetHealth resets the health check counters. |
| 244 | func (h *Host) resetHealth() { |
| 245 | h.activePasses.Store(0) |
| 246 | h.activeFails.Store(0) |
| 247 | } |
| 248 | |
| 249 | // healthy returns true if the upstream is not actively marked as unhealthy. |
| 250 | // (This returns the status only from the "active" health checks.) |
| 251 | func (u *Upstream) healthy() bool { |
| 252 | return u.unhealthy.Load() == 0 |
| 253 | } |
| 254 | |
| 255 | // SetHealthy sets the upstream has healthy or unhealthy |
| 256 | // and returns true if the new value is different. This |
| 257 | // sets the status only for the "active" health checks. |
| 258 | func (u *Upstream) setHealthy(healthy bool) bool { |
| 259 | var unhealthy, compare int32 = 1, 0 |
| 260 | if healthy { |
| 261 | unhealthy, compare = 0, 1 |
| 262 | } |
| 263 | return u.unhealthy.CompareAndSwap(compare, unhealthy) |
| 264 | } |
| 265 | |
| 266 | // DialInfo contains information needed to dial a |
| 267 | // connection to an upstream host. This information |
| 268 | // may be different than that which is represented |
| 269 | // in a URL (for example, unix sockets don't have |
| 270 | // a host that can be represented in a URL, but |
| 271 | // they certainly have a network name and address). |
| 272 | type DialInfo struct { |
| 273 | // Upstream is the Upstream associated with |
| 274 | // this DialInfo. It may be nil. |
| 275 | Upstream *Upstream |
| 276 | |
| 277 | // The network to use. This should be one of |
| 278 | // the values that is accepted by net.Dial: |
| 279 | // https://golang.org/pkg/net/#Dial |
| 280 | Network string |
| 281 | |
| 282 | // The address to dial. Follows the same |
| 283 | // semantics and rules as net.Dial. |
| 284 | Address string |
| 285 | |
| 286 | // Host and Port are components of Address. |
| 287 | Host, Port string |
| 288 | } |
| 289 | |
| 290 | // String returns the Caddy network address form |
| 291 | // by joining the network and address with a |
| 292 | // forward slash. |
| 293 | func (di DialInfo) String() string { |
| 294 | return caddy.JoinNetworkAddress(di.Network, di.Host, di.Port) |
| 295 | } |
| 296 | |
| 297 | // GetDialInfo gets the upstream dialing info out of the context, |
| 298 | // and returns true if there was a valid value; false otherwise. |
| 299 | func GetDialInfo(ctx context.Context) (DialInfo, bool) { |
| 300 | dialInfo, ok := caddyhttp.GetVar(ctx, dialInfoVarKey).(DialInfo) |
| 301 | return dialInfo, ok |
| 302 | } |
| 303 | |
| 304 | // hosts is the global repository for hosts that are |
| 305 | // currently in use by active configuration(s). This |
| 306 | // allows the state of remote hosts to be preserved |
| 307 | // through config reloads. |
| 308 | var hosts = caddy.NewUsagePool() |
| 309 | |
| 310 | // dynamicHosts tracks hosts that were provisioned from dynamic upstream |
| 311 | // sources. Unlike static upstreams which are reference-counted via the |
| 312 | // UsagePool, dynamic upstream hosts are not reference-counted. Instead, |
| 313 | // their last-seen time is updated on each request, and a background |
| 314 | // goroutine evicts entries that have been idle for dynamicHostIdleExpiry. |
| 315 | // This preserves health state (e.g. passive fail counts) across requests |
| 316 | // to the same dynamic backend. |
| 317 | var ( |
| 318 | dynamicHosts = make(map[string]dynamicHostEntry) |
| 319 | dynamicHostsMu sync.RWMutex |
| 320 | dynamicHostsCleanerOnce sync.Once |
| 321 | dynamicHostCleanupInterval = 5 * time.Minute |
| 322 | dynamicHostIdleExpiry = time.Hour |
| 323 | ) |
| 324 | |
| 325 | // dynamicHostEntry holds a Host and the last time it was seen |
| 326 | // in a set of dynamic upstreams returned for a request. |
| 327 | type dynamicHostEntry struct { |
| 328 | host *Host |
| 329 | lastSeen time.Time |
| 330 | } |
| 331 | |
| 332 | // dialInfoVarKey is the key used for the variable that holds |
| 333 | // the dial info for the upstream connection. |
| 334 | const dialInfoVarKey = "reverse_proxy.dial_info" |
| 335 | |
| 336 | // proxyProtocolInfoVarKey is the key used for the variable that holds |
| 337 | // the proxy protocol info for the upstream connection. |
| 338 | const proxyProtocolInfoVarKey = "reverse_proxy.proxy_protocol_info" |
| 339 | |
| 340 | // ProxyProtocolInfo contains information needed to write proxy protocol to a |
| 341 | // connection to an upstream host. |
| 342 | type ProxyProtocolInfo struct { |
| 343 | AddrPort netip.AddrPort |
| 344 | } |
| 345 | |
| 346 | // tlsH1OnlyVarKey is the key used that indicates the connection will use h1 only for TLS. |
| 347 | // https://github.com/caddyserver/caddy/issues/7292 |
| 348 | const tlsH1OnlyVarKey = "reverse_proxy.tls_h1_only" |
| 349 | |
| 350 | // proxyVarKey is the key used that indicates the proxy server used for a request. |
| 351 | const proxyVarKey = "reverse_proxy.proxy" |