Files
ianitor/crates/edge/src/health.rs
T

257 lines
8.9 KiB
Rust

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
//! Active health checks, like Caddy's `health_checks.active`: `GET <path>` with the upstream
//! address as Host, healthy on 2xx, 5 s timeout, one result flips the state. The first round
//! runs when a config is loaded; upstreams start healthy.
//!
//! Every result is also recorded (time, latency, why it failed) for the admin socket.
//! During a trial, the watched hosts are probed at least every `every` seconds; a watched
//! host without a health check gets `GET /` with its own hostname as Host, and any answer
//! below 500 counts as alive (docs/ui-api.md G3). Those watch probes never change routing.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::{Duration, Instant};
use async_trait::async_trait;
use pingora::connectors::http::Connector;
use pingora::http::RequestHeader;
use pingora::server::ShutdownWatch;
use pingora::services::background::BackgroundService;
use pingora::{Error, ErrorType};
use crate::fetch::fetch;
use crate::logging::now_secs;
use crate::runtime::{Check, HostRt, UpstreamRt};
use crate::shared::Shared;
const TIMEOUT: Duration = Duration::from_secs(5);
pub struct HealthChecks {
pub shared: Arc<Shared>,
}
/// Why a probe failed, in the words of docs/ui-api.md §3.3.
pub fn failure_kind(e: &Error) -> &'static str {
match e.etype() {
ErrorType::ConnectRefused | ErrorType::ConnectError | ErrorType::ConnectionClosed => {
"refused"
}
ErrorType::ConnectTimedout
| ErrorType::ReadTimedout
| ErrorType::WriteTimedout
| ErrorType::TLSHandshakeTimedout => "timeout",
ErrorType::ConnectNoRoute => "name",
ErrorType::TLSHandshakeFailure | ErrorType::InvalidCert | ErrorType::HandshakeError => {
"tls"
}
_ => "bad_answer",
}
}
fn status_kind(status: u16) -> &'static str {
match status {
300..=399 => "redirect",
401 | 403 => "sign_in",
404 => "not_found",
500..=599 => "server_error",
_ => "bad_answer",
}
}
/// One probe. `watch` probes count any answer below 500 as alive.
async fn probe(
connector: &Connector,
u: &UpstreamRt,
path: &str,
host: &str,
watch: bool,
) -> Check {
let started = Instant::now();
let at = now_secs() as u64;
let source = if watch { "watch" } else { "health_check" };
let fail = |kind: &'static str, status: Option<u16>, latency: Option<u64>| Check {
seq: 0,
at,
ok: false,
source,
kind: Some(kind),
status,
latency_ms: latency,
};
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
return fail("bad_answer", None, None);
};
if req.insert_header(http::header::HOST, host).is_err() {
return fail("bad_answer", None, None);
}
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
Ok(f) => {
let status = f.header.status.as_u16();
let latency = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
let ok = if watch {
(100..500).contains(&status)
} else {
f.header.status.is_success()
};
if ok {
Check {
seq: 0,
at,
ok: true,
source,
kind: None,
status: Some(status),
latency_ms: Some(latency),
}
} else {
fail(status_kind(status), Some(status), Some(latency))
}
}
Err(e) => fail(failure_kind(&e), None, None),
}
}
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
/// ending health checks.
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>, watch: bool) {
for i in 0..host.upstreams.len() {
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
let probe_host = if watch {
host.cfg.hostname.clone()
} else if host.upstreams[i].unix.is_some() {
// A socket has no authority to name; the probe asks as a local client would.
"localhost".to_owned()
} else {
host.upstreams[i].authority.clone()
};
let check = match tokio::spawn(async move {
probe(&c, &h.upstreams[i], &p, &probe_host, watch).await
})
.await
{
Ok(c) => c,
Err(e) => {
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
Check {
seq: 0,
at: now_secs() as u64,
ok: false,
source: if watch { "watch" } else { "health_check" },
kind: Some("bad_answer"),
status: None,
latency_ms: None,
}
}
};
let u = &host.upstreams[i];
let ok = check.ok;
u.health.record(check);
if watch {
// Watch probes only report; routing follows the host's own health check.
continue;
}
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
if ok {
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
} else {
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
}
}
}
}
async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
let connector = Arc::new(Connector::new(None));
loop {
round(&host, &path, &connector, watch).await;
tokio::time::sleep(every).await;
}
}
struct Job {
host: Arc<HostRt>,
path: String,
every: Duration,
watch: bool,
}
fn jobs(shared: &Shared) -> Vec<Job> {
let rt = shared.current();
let spec = shared.watch_spec();
let watched = |h: &str| {
spec.as_ref()
.is_some_and(|s| s.hosts.iter().any(|w| w == h))
};
let every = spec.as_ref().map(|s| s.every);
let mut out = Vec::new();
for h in rt.hosts.values() {
let name = &h.cfg.hostname;
match &h.cfg.health_check {
Some(hc) => {
let mut interval = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
if watched(name)
&& let Some(e) = every
{
interval = interval.min(e);
}
out.push(Job {
host: h.clone(),
path: hc.path.clone(),
every: interval,
watch: false,
});
}
None if watched(name) => out.push(Job {
host: h.clone(),
path: "/".into(),
every: every.unwrap_or(Duration::from_secs(5)),
watch: true,
}),
None => {}
}
}
out
}
#[async_trait]
impl BackgroundService for HealthChecks {
async fn start(&self, mut shutdown: ShutdownWatch) {
let mut changes = self.shared.subscribe();
loop {
let jobs = jobs(&self.shared);
let mut tasks = tokio::task::JoinSet::new();
let mut which = std::collections::HashMap::new();
for (i, j) in jobs.iter().enumerate() {
let id = tasks
.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch))
.id();
which.insert(id, i);
}
// Run until the config or the watch changes; a watcher never returns, and if one
// ends anyway, say so and start it again.
let stop = loop {
tokio::select! {
_ = shutdown.changed() => break true,
r = changes.changed() => break r.is_err(),
Some(done) = tasks.join_next_with_id() => {
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
if let Some(i) = which.remove(&id) {
let j = &jobs[i];
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", j.host.cfg.hostname);
which.insert(tasks.spawn(watcher(j.host.clone(), j.path.clone(), j.every, j.watch)).id(), i);
}
}
}
};
tasks.abort_all();
if stop {
return;
}
}
}
}