2019-09-04 02:10:11 +08:00
|
|
|
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
|
|
|
package reverseproxy
|
|
|
|
|
|
|
|
import (
|
2019-09-06 03:14:39 +08:00
|
|
|
"context"
|
2019-09-04 02:10:11 +08:00
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
"net/http"
|
|
|
|
"net/url"
|
|
|
|
"regexp"
|
2020-05-13 01:36:20 +08:00
|
|
|
"runtime/debug"
|
2019-09-04 02:10:11 +08:00
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
|
2023-08-14 23:41:15 +08:00
|
|
|
"go.uber.org/zap"
|
|
|
|
|
2019-09-04 02:10:11 +08:00
|
|
|
"github.com/caddyserver/caddy/v2"
|
|
|
|
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
|
|
|
|
)
|
|
|
|
|
2019-12-24 03:45:35 +08:00
|
|
|
// HealthChecks configures active and passive health checks.
|
2019-09-04 02:10:11 +08:00
|
|
|
type HealthChecks struct {
|
2019-12-24 03:45:35 +08:00
|
|
|
// Active health checks run in the background on a timer. To
|
|
|
|
// minimally enable active health checks, set either path or
|
2022-03-07 08:43:39 +08:00
|
|
|
// port (or both). Note that active health check status
|
|
|
|
// (healthy/unhealthy) is stored per-proxy-handler, not
|
|
|
|
// globally; this allows different handlers to use different
|
|
|
|
// criteria to decide what defines a healthy backend.
|
|
|
|
//
|
|
|
|
// Active health checks do not run for dynamic upstreams.
|
2019-12-24 03:45:35 +08:00
|
|
|
Active *ActiveHealthChecks `json:"active,omitempty"`
|
|
|
|
|
|
|
|
// Passive health checks monitor proxied requests for errors or timeouts.
|
|
|
|
// To minimally enable passive health checks, specify at least an empty
|
2022-12-01 07:03:31 +08:00
|
|
|
// config object with fail_duration > 0. Passive health check state is
|
|
|
|
// shared (stored globally), so a failure from one handler will be counted
|
|
|
|
// by all handlers; but the tolerances or standards for what defines
|
|
|
|
// healthy/unhealthy backends is configured per-proxy-handler.
|
2022-03-07 08:43:39 +08:00
|
|
|
//
|
|
|
|
// Passive health checks technically do operate on dynamic upstreams,
|
|
|
|
// but are only effective for very busy proxies where the list of
|
|
|
|
// upstreams is mostly stable. This is because the shared/global
|
|
|
|
// state of upstreams is cleaned up when the upstreams are no longer
|
|
|
|
// used. Since dynamic upstreams are allocated dynamically at each
|
|
|
|
// request (specifically, each iteration of the proxy loop per request),
|
|
|
|
// they are also cleaned up after every request. Thus, if there is a
|
|
|
|
// moment when no requests are actively referring to a particular
|
|
|
|
// upstream host, the passive health check state will be reset because
|
|
|
|
// it will be garbage-collected. It is usually better for the dynamic
|
|
|
|
// upstream module to only return healthy, available backends instead.
|
2019-09-04 02:10:11 +08:00
|
|
|
Passive *PassiveHealthChecks `json:"passive,omitempty"`
|
|
|
|
}
|
|
|
|
|
2019-09-04 06:56:09 +08:00
|
|
|
// ActiveHealthChecks holds configuration related to active
|
|
|
|
// health checks (that is, health checks which occur in a
|
|
|
|
// background goroutine independently).
|
2019-09-04 02:10:11 +08:00
|
|
|
type ActiveHealthChecks struct {
|
2022-03-07 08:43:39 +08:00
|
|
|
// DEPRECATED: Use 'uri' instead. This field will be removed. TODO: remove this field
|
2019-12-24 03:45:35 +08:00
|
|
|
Path string `json:"path,omitempty"`
|
|
|
|
|
2021-03-30 08:36:40 +08:00
|
|
|
// The URI (path and query) to use for health checks
|
|
|
|
URI string `json:"uri,omitempty"`
|
|
|
|
|
2019-12-24 03:45:35 +08:00
|
|
|
// The port to use (if different from the upstream's dial
|
|
|
|
// address) for health checks.
|
|
|
|
Port int `json:"port,omitempty"`
|
|
|
|
|
|
|
|
// HTTP headers to set on health check requests.
|
|
|
|
Headers http.Header `json:"headers,omitempty"`
|
|
|
|
|
|
|
|
// How frequently to perform active health checks (default 30s).
|
|
|
|
Interval caddy.Duration `json:"interval,omitempty"`
|
|
|
|
|
|
|
|
// How long to wait for a response from a backend before
|
|
|
|
// considering it unhealthy (default 5s).
|
|
|
|
Timeout caddy.Duration `json:"timeout,omitempty"`
|
|
|
|
|
|
|
|
// The maximum response body to download from the backend
|
|
|
|
// during a health check.
|
|
|
|
MaxSize int64 `json:"max_size,omitempty"`
|
|
|
|
|
|
|
|
// The HTTP status code to expect from a healthy backend.
|
|
|
|
ExpectStatus int `json:"expect_status,omitempty"`
|
|
|
|
|
|
|
|
// A regular expression against which to match the response
|
|
|
|
// body of a healthy backend.
|
|
|
|
ExpectBody string `json:"expect_body,omitempty"`
|
2019-09-04 02:10:11 +08:00
|
|
|
|
2021-03-30 08:36:40 +08:00
|
|
|
uri *url.URL
|
2019-09-04 02:10:11 +08:00
|
|
|
httpClient *http.Client
|
|
|
|
bodyRegexp *regexp.Regexp
|
2019-10-30 06:02:40 +08:00
|
|
|
logger *zap.Logger
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
|
2023-05-06 05:19:22 +08:00
|
|
|
// Provision ensures that a is set up properly before use.
|
|
|
|
func (a *ActiveHealthChecks) Provision(ctx caddy.Context, h *Handler) error {
|
|
|
|
if !a.IsEnabled() {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Canonicalize the header keys ahead of time, since
|
|
|
|
// JSON unmarshaled headers may be incorrect
|
|
|
|
cleaned := http.Header{}
|
|
|
|
for key, hdrs := range a.Headers {
|
|
|
|
for _, val := range hdrs {
|
|
|
|
cleaned.Add(key, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
a.Headers = cleaned
|
|
|
|
|
|
|
|
h.HealthChecks.Active.logger = h.logger.Named("health_checker.active")
|
|
|
|
|
|
|
|
timeout := time.Duration(a.Timeout)
|
|
|
|
if timeout == 0 {
|
|
|
|
timeout = 5 * time.Second
|
|
|
|
}
|
|
|
|
|
|
|
|
if a.Path != "" {
|
|
|
|
a.logger.Warn("the 'path' option is deprecated, please use 'uri' instead!")
|
|
|
|
}
|
|
|
|
|
|
|
|
// parse the URI string (supports path and query)
|
|
|
|
if a.URI != "" {
|
|
|
|
parsedURI, err := url.Parse(a.URI)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
a.uri = parsedURI
|
|
|
|
}
|
|
|
|
|
|
|
|
a.httpClient = &http.Client{
|
|
|
|
Timeout: timeout,
|
|
|
|
Transport: h.Transport,
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, upstream := range h.Upstreams {
|
|
|
|
// if there's an alternative port for health-check provided in the config,
|
|
|
|
// then use it, otherwise use the port of upstream.
|
|
|
|
if a.Port != 0 {
|
|
|
|
upstream.activeHealthCheckPort = a.Port
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if a.Interval == 0 {
|
|
|
|
a.Interval = caddy.Duration(30 * time.Second)
|
|
|
|
}
|
|
|
|
|
|
|
|
if a.ExpectBody != "" {
|
|
|
|
var err error
|
|
|
|
a.bodyRegexp, err = regexp.Compile(a.ExpectBody)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("expect_body: compiling regular expression: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsEnabled checks if the active health checks have
|
|
|
|
// the minimum config necessary to be enabled.
|
|
|
|
func (a *ActiveHealthChecks) IsEnabled() bool {
|
|
|
|
return a.Path != "" || a.URI != "" || a.Port != 0
|
|
|
|
}
|
|
|
|
|
2019-09-04 06:56:09 +08:00
|
|
|
// PassiveHealthChecks holds configuration related to passive
|
|
|
|
// health checks (that is, health checks which occur during
|
|
|
|
// the normal flow of request proxying).
|
2019-09-04 02:10:11 +08:00
|
|
|
type PassiveHealthChecks struct {
|
2019-12-24 03:45:35 +08:00
|
|
|
// How long to remember a failed request to a backend. A duration > 0
|
|
|
|
// enables passive health checking. Default is 0.
|
|
|
|
FailDuration caddy.Duration `json:"fail_duration,omitempty"`
|
|
|
|
|
|
|
|
// The number of failed requests within the FailDuration window to
|
|
|
|
// consider a backend as "down". Must be >= 1; default is 1. Requires
|
|
|
|
// that FailDuration be > 0.
|
|
|
|
MaxFails int `json:"max_fails,omitempty"`
|
|
|
|
|
|
|
|
// Limits the number of simultaneous requests to a backend by
|
|
|
|
// marking the backend as "down" if it has this many concurrent
|
|
|
|
// requests or more.
|
|
|
|
UnhealthyRequestCount int `json:"unhealthy_request_count,omitempty"`
|
|
|
|
|
|
|
|
// Count the request as failed if the response comes back with
|
|
|
|
// one of these status codes.
|
|
|
|
UnhealthyStatus []int `json:"unhealthy_status,omitempty"`
|
|
|
|
|
|
|
|
// Count the request as failed if the response takes at least this
|
|
|
|
// long to receive.
|
|
|
|
UnhealthyLatency caddy.Duration `json:"unhealthy_latency,omitempty"`
|
2019-10-30 06:02:40 +08:00
|
|
|
|
|
|
|
logger *zap.Logger
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
|
2019-09-04 09:06:54 +08:00
|
|
|
// CircuitBreaker is a type that can act as an early-warning
|
|
|
|
// system for the health checker when backends are getting
|
2020-05-02 09:47:41 +08:00
|
|
|
// overloaded. This interface is still experimental and is
|
|
|
|
// subject to change.
|
2019-09-04 09:06:54 +08:00
|
|
|
type CircuitBreaker interface {
|
|
|
|
OK() bool
|
|
|
|
RecordMetric(statusCode int, latency time.Duration)
|
|
|
|
}
|
|
|
|
|
2019-09-04 06:56:09 +08:00
|
|
|
// activeHealthChecker runs active health checks on a
|
|
|
|
// regular basis and blocks until
|
|
|
|
// h.HealthChecks.Active.stopChan is closed.
|
2019-09-04 02:10:11 +08:00
|
|
|
func (h *Handler) activeHealthChecker() {
|
2020-05-13 01:36:20 +08:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
2022-03-07 08:43:39 +08:00
|
|
|
h.HealthChecks.Active.logger.Error("active health checker panicked",
|
|
|
|
zap.Any("error", err),
|
|
|
|
zap.ByteString("stack", debug.Stack()))
|
2020-05-13 01:36:20 +08:00
|
|
|
}
|
|
|
|
}()
|
2019-09-04 02:10:11 +08:00
|
|
|
ticker := time.NewTicker(time.Duration(h.HealthChecks.Active.Interval))
|
2020-02-24 05:30:52 +08:00
|
|
|
h.doActiveHealthCheckForAllHosts()
|
2019-09-04 02:10:11 +08:00
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2020-02-24 05:30:52 +08:00
|
|
|
h.doActiveHealthCheckForAllHosts()
|
2020-08-08 08:02:24 +08:00
|
|
|
case <-h.ctx.Done():
|
2019-09-04 02:10:11 +08:00
|
|
|
ticker.Stop()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-24 05:30:52 +08:00
|
|
|
// doActiveHealthCheckForAllHosts immediately performs a
|
|
|
|
// health checks for all upstream hosts configured by h.
|
|
|
|
func (h *Handler) doActiveHealthCheckForAllHosts() {
|
|
|
|
for _, upstream := range h.Upstreams {
|
|
|
|
go func(upstream *Upstream) {
|
2020-05-13 01:36:20 +08:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
2022-03-07 08:43:39 +08:00
|
|
|
h.HealthChecks.Active.logger.Error("active health check panicked",
|
|
|
|
zap.Any("error", err),
|
|
|
|
zap.ByteString("stack", debug.Stack()))
|
2020-05-13 01:36:20 +08:00
|
|
|
}
|
|
|
|
}()
|
2020-09-18 00:25:34 +08:00
|
|
|
|
2020-10-14 00:35:20 +08:00
|
|
|
networkAddr, err := caddy.NewReplacer().ReplaceOrErr(upstream.Dial, true, true)
|
|
|
|
if err != nil {
|
|
|
|
h.HealthChecks.Active.logger.Error("invalid use of placeholders in dial address for active health checks",
|
|
|
|
zap.String("address", networkAddr),
|
|
|
|
zap.Error(err),
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
addr, err := caddy.ParseNetworkAddress(networkAddr)
|
|
|
|
if err != nil {
|
|
|
|
h.HealthChecks.Active.logger.Error("bad network address",
|
|
|
|
zap.String("address", networkAddr),
|
|
|
|
zap.Error(err),
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if hcp := uint(upstream.activeHealthCheckPort); hcp != 0 {
|
|
|
|
if addr.IsUnixNetwork() {
|
|
|
|
addr.Network = "tcp" // I guess we just assume TCP since we are using a port??
|
|
|
|
}
|
|
|
|
addr.StartPort, addr.EndPort = hcp, hcp
|
|
|
|
}
|
2023-04-11 04:08:40 +08:00
|
|
|
if addr.PortRangeSize() != 1 {
|
2020-10-14 00:35:20 +08:00
|
|
|
h.HealthChecks.Active.logger.Error("multiple addresses (upstream must map to only one address)",
|
|
|
|
zap.String("address", networkAddr),
|
|
|
|
)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
hostAddr := addr.JoinHostPort(0)
|
2021-07-07 11:43:45 +08:00
|
|
|
dialAddr := hostAddr
|
2020-10-14 00:35:20 +08:00
|
|
|
if addr.IsUnixNetwork() {
|
2019-09-06 03:14:39 +08:00
|
|
|
// this will be used as the Host portion of a http.Request URL, and
|
|
|
|
// paths to socket files would produce an error when creating URL,
|
2019-09-15 03:25:26 +08:00
|
|
|
// so use a fake Host value instead; unix sockets are usually local
|
|
|
|
hostAddr = "localhost"
|
2019-09-06 03:14:39 +08:00
|
|
|
}
|
2022-03-07 08:43:39 +08:00
|
|
|
err = h.doActiveHealthCheck(DialInfo{Network: addr.Network, Address: dialAddr}, hostAddr, upstream)
|
2019-09-06 03:14:39 +08:00
|
|
|
if err != nil {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Error("active health check failed",
|
2020-09-18 00:25:34 +08:00
|
|
|
zap.String("address", hostAddr),
|
2019-10-30 06:02:40 +08:00
|
|
|
zap.Error(err),
|
|
|
|
)
|
2019-09-06 03:14:39 +08:00
|
|
|
}
|
2020-02-24 05:30:52 +08:00
|
|
|
}(upstream)
|
|
|
|
}
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
|
2022-03-07 08:43:39 +08:00
|
|
|
// doActiveHealthCheck performs a health check to upstream which
|
2019-09-04 02:10:11 +08:00
|
|
|
// can be reached at address hostAddr. The actual address for
|
|
|
|
// the request will be built according to active health checker
|
|
|
|
// config. The health status of the host will be updated
|
|
|
|
// according to whether it passes the health check. An error is
|
|
|
|
// returned only if the health check fails to occur or if marking
|
|
|
|
// the host's health status fails.
|
2022-03-07 08:43:39 +08:00
|
|
|
func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, upstream *Upstream) error {
|
2019-09-06 03:14:39 +08:00
|
|
|
// create the URL for the request that acts as a health check
|
|
|
|
u := &url.URL{
|
2023-06-23 06:20:30 +08:00
|
|
|
Scheme: "http",
|
2019-09-06 03:14:39 +08:00
|
|
|
Host: hostAddr,
|
2021-03-30 08:36:40 +08:00
|
|
|
}
|
|
|
|
|
2023-06-23 06:20:30 +08:00
|
|
|
// split the host and port if possible, override the port if configured
|
|
|
|
host, port, err := net.SplitHostPort(hostAddr)
|
|
|
|
if err != nil {
|
|
|
|
host = hostAddr
|
|
|
|
}
|
|
|
|
if h.HealthChecks.Active.Port != 0 {
|
|
|
|
port := strconv.Itoa(h.HealthChecks.Active.Port)
|
|
|
|
u.Host = net.JoinHostPort(host, port)
|
|
|
|
}
|
|
|
|
|
|
|
|
// this is kind of a hacky way to know if we should use HTTPS, but whatever
|
|
|
|
if tt, ok := h.Transport.(TLSTransport); ok && tt.TLSEnabled() {
|
|
|
|
u.Scheme = "https"
|
|
|
|
|
|
|
|
// if the port is in the except list, flip back to HTTP
|
|
|
|
if ht, ok := h.Transport.(*HTTPTransport); ok {
|
|
|
|
for _, exceptPort := range ht.TLS.ExceptPorts {
|
|
|
|
if exceptPort == port {
|
|
|
|
u.Scheme = "http"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-30 08:36:40 +08:00
|
|
|
// if we have a provisioned uri, use that, otherwise use
|
|
|
|
// the deprecated Path option
|
|
|
|
if h.HealthChecks.Active.uri != nil {
|
|
|
|
u.Path = h.HealthChecks.Active.uri.Path
|
|
|
|
u.RawQuery = h.HealthChecks.Active.uri.RawQuery
|
|
|
|
} else {
|
|
|
|
u.Path = h.HealthChecks.Active.Path
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
2019-09-06 03:14:39 +08:00
|
|
|
|
2023-01-07 04:06:38 +08:00
|
|
|
// attach dialing information to this request, as well as context values that
|
|
|
|
// may be expected by handlers of this request
|
2020-09-01 03:22:34 +08:00
|
|
|
ctx := h.ctx.Context
|
2019-09-06 03:14:39 +08:00
|
|
|
ctx = context.WithValue(ctx, caddy.ReplacerCtxKey, caddy.NewReplacer())
|
2022-08-03 04:39:09 +08:00
|
|
|
ctx = context.WithValue(ctx, caddyhttp.VarsCtxKey, map[string]any{
|
http: Change routes to sequential matcher evaluation (#2967)
Previously, all matchers in a route would be evaluated before any
handlers were executed, and a composite route of the matching routes
would be created. This made rewrites especially tricky, since the only
way to defer later matchers' evaluation was to wrap them in a subroute,
or to invoke a "rehandle" which often caused bugs.
Instead, this new sequential design evaluates each route's matchers then
its handlers in lock-step; matcher-handlers-matcher-handlers...
If the first matching route consists of a rewrite, then the second route
will be evaluated against the rewritten request, rather than the original
one, and so on.
This should do away with any need for rehandling.
I've also taken this opportunity to avoid adding new values to the
request context in the handler chain, as this creates a copy of the
Request struct, which may possibly lead to bugs like it has in the past
(see PR #1542, PR #1481, and maybe issue #2463). We now add all the
expected context values in the top-level handler at the server, then
any new values can be added to the variable table via the VarsCtxKey
context key, or just the GetVar/SetVar functions. In particular, we are
using this facility to convey dial information in the reverse proxy.
Had to be careful in one place as the middleware compilation logic has
changed, and moved a bit. We no longer compile a middleware chain per-
request; instead, we can compile it at provision-time, and defer only the
evaluation of matchers to request-time, which should slightly improve
performance. Doing this, however, we take advantage of multiple function
closures, and we also changed the use of HandlerFunc (function pointer)
to Handler (interface)... this led to a situation where, if we aren't
careful, allows one request routed a certain way to permanently change
the "next" handler for all/most other requests! We avoid this by making
a copy of the interface value (which is a lightweight pointer copy) and
using exclusively that within our wrapped handlers. This way, the
original stack frame is preserved in a "read-only" fashion. The comments
in the code describe this phenomenon.
This may very well be a breaking change for some configurations, however
I do not expect it to impact many people. I will make it clear in the
release notes that this change has occurred.
2020-01-10 01:00:13 +08:00
|
|
|
dialInfoVarKey: dialInfo,
|
|
|
|
})
|
2019-09-06 03:14:39 +08:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
|
2019-09-04 02:10:11 +08:00
|
|
|
if err != nil {
|
2019-09-06 03:14:39 +08:00
|
|
|
return fmt.Errorf("making request: %v", err)
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
2023-01-07 04:06:38 +08:00
|
|
|
ctx = context.WithValue(ctx, caddyhttp.OriginalRequestCtxKey, *req)
|
|
|
|
req = req.WithContext(ctx)
|
2023-10-11 23:50:28 +08:00
|
|
|
|
|
|
|
// set headers, using a replacer with only globals (env vars, system info, etc.)
|
|
|
|
repl := caddy.NewReplacer()
|
|
|
|
for key, vals := range h.HealthChecks.Active.Headers {
|
|
|
|
key = repl.ReplaceAll(key, "")
|
2023-05-06 05:19:22 +08:00
|
|
|
if key == "Host" {
|
2023-10-11 23:50:28 +08:00
|
|
|
req.Host = repl.ReplaceAll(h.HealthChecks.Active.Headers.Get(key), "")
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
for _, val := range vals {
|
|
|
|
req.Header.Add(key, repl.ReplaceKnown(val, ""))
|
2021-01-05 02:26:18 +08:00
|
|
|
}
|
2019-10-05 07:21:38 +08:00
|
|
|
}
|
2019-09-04 02:10:11 +08:00
|
|
|
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy := func() {
|
|
|
|
// dispatch an event that the host newly became unhealthy
|
|
|
|
if upstream.setHealthy(false) {
|
|
|
|
h.events.Emit(h.ctx, "unhealthy", map[string]any{"host": hostAddr})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-06 03:14:39 +08:00
|
|
|
// do the request, being careful to tame the response body
|
2019-09-04 02:10:11 +08:00
|
|
|
resp, err := h.HealthChecks.Active.httpClient.Do(req)
|
|
|
|
if err != nil {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Info("HTTP request failed",
|
|
|
|
zap.String("host", hostAddr),
|
|
|
|
zap.Error(err),
|
|
|
|
)
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy()
|
2019-09-04 02:10:11 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var body io.Reader = resp.Body
|
|
|
|
if h.HealthChecks.Active.MaxSize > 0 {
|
|
|
|
body = io.LimitReader(body, h.HealthChecks.Active.MaxSize)
|
|
|
|
}
|
|
|
|
defer func() {
|
2019-09-06 03:14:39 +08:00
|
|
|
// drain any remaining body so connection could be re-used
|
2021-09-30 01:17:48 +08:00
|
|
|
_, _ = io.Copy(io.Discard, body)
|
2019-09-04 02:10:11 +08:00
|
|
|
resp.Body.Close()
|
|
|
|
}()
|
|
|
|
|
|
|
|
// if status code is outside criteria, mark down
|
|
|
|
if h.HealthChecks.Active.ExpectStatus > 0 {
|
|
|
|
if !caddyhttp.StatusCodeMatches(resp.StatusCode, h.HealthChecks.Active.ExpectStatus) {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Info("unexpected status code",
|
|
|
|
zap.Int("status_code", resp.StatusCode),
|
|
|
|
zap.String("host", hostAddr),
|
|
|
|
)
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy()
|
2019-09-04 02:10:11 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
} else if resp.StatusCode < 200 || resp.StatusCode >= 400 {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Info("status code out of tolerances",
|
|
|
|
zap.Int("status_code", resp.StatusCode),
|
|
|
|
zap.String("host", hostAddr),
|
|
|
|
)
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy()
|
2019-09-04 02:10:11 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// if body does not match regex, mark down
|
|
|
|
if h.HealthChecks.Active.bodyRegexp != nil {
|
2021-09-30 01:17:48 +08:00
|
|
|
bodyBytes, err := io.ReadAll(body)
|
2019-09-04 02:10:11 +08:00
|
|
|
if err != nil {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Info("failed to read response body",
|
|
|
|
zap.String("host", hostAddr),
|
|
|
|
zap.Error(err),
|
|
|
|
)
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy()
|
2019-09-04 02:10:11 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
if !h.HealthChecks.Active.bodyRegexp.Match(bodyBytes) {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Active.logger.Info("response body failed expectations",
|
|
|
|
zap.String("host", hostAddr),
|
|
|
|
)
|
2022-09-01 05:01:30 +08:00
|
|
|
markUnhealthy()
|
2019-09-04 02:10:11 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// passed health check parameters, so mark as healthy
|
2022-03-07 08:43:39 +08:00
|
|
|
if upstream.setHealthy(true) {
|
|
|
|
h.HealthChecks.Active.logger.Info("host is up", zap.String("host", hostAddr))
|
2022-09-01 05:01:30 +08:00
|
|
|
h.events.Emit(h.ctx, "healthy", map[string]any{"host": hostAddr})
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// countFailure is used with passive health checks. It
|
|
|
|
// remembers 1 failure for upstream for the configured
|
|
|
|
// duration. If passive health checks are disabled or
|
|
|
|
// failure expiry is 0, this is a no-op.
|
2019-09-04 09:06:54 +08:00
|
|
|
func (h *Handler) countFailure(upstream *Upstream) {
|
2019-09-04 02:10:11 +08:00
|
|
|
// only count failures if passive health checking is enabled
|
|
|
|
// and if failures are configured have a non-zero expiry
|
|
|
|
if h.HealthChecks == nil || h.HealthChecks.Passive == nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
failDuration := time.Duration(h.HealthChecks.Passive.FailDuration)
|
|
|
|
if failDuration == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// count failure immediately
|
2022-03-07 08:43:39 +08:00
|
|
|
err := upstream.Host.countFail(1)
|
2019-09-04 02:10:11 +08:00
|
|
|
if err != nil {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Passive.logger.Error("could not count failure",
|
|
|
|
zap.String("host", upstream.Dial),
|
2020-08-08 08:02:24 +08:00
|
|
|
zap.Error(err))
|
|
|
|
return
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// forget it later
|
2022-03-07 08:43:39 +08:00
|
|
|
go func(host *Host, failDuration time.Duration) {
|
2020-05-13 01:36:20 +08:00
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
2022-03-07 08:43:39 +08:00
|
|
|
h.HealthChecks.Passive.logger.Error("passive health check failure forgetter panicked",
|
|
|
|
zap.Any("error", err),
|
|
|
|
zap.ByteString("stack", debug.Stack()))
|
2020-05-13 01:36:20 +08:00
|
|
|
}
|
|
|
|
}()
|
2022-03-07 08:43:39 +08:00
|
|
|
timer := time.NewTimer(failDuration)
|
|
|
|
select {
|
|
|
|
case <-h.ctx.Done():
|
|
|
|
if !timer.Stop() {
|
|
|
|
<-timer.C
|
|
|
|
}
|
|
|
|
case <-timer.C:
|
|
|
|
}
|
|
|
|
err := host.countFail(-1)
|
2019-09-04 02:10:11 +08:00
|
|
|
if err != nil {
|
2019-10-30 06:02:40 +08:00
|
|
|
h.HealthChecks.Passive.logger.Error("could not forget failure",
|
|
|
|
zap.String("host", upstream.Dial),
|
2020-08-08 08:02:24 +08:00
|
|
|
zap.Error(err))
|
2019-09-04 02:10:11 +08:00
|
|
|
}
|
|
|
|
}(upstream.Host, failDuration)
|
|
|
|
}
|