[edge] Reload and share links: in-process config swap with self-reverting trials, admin socket with health and certificate status, share-link cookies, visitor pages and throttle
This commit is contained in:
+188
-49
@@ -4,57 +4,153 @@
|
||||
|
||||
//! 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 at startup; upstreams start healthy.
|
||||
//! 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;
|
||||
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::runtime::{HostRt, Runtime, UpstreamRt};
|
||||
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 rt: Arc<Runtime>,
|
||||
pub shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
|
||||
let Ok(mut req) = RequestHeader::build("GET", path.as_bytes(), None) else {
|
||||
return false;
|
||||
/// 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,
|
||||
};
|
||||
if req
|
||||
.insert_header(http::header::HOST, u.authority.as_str())
|
||||
.is_err()
|
||||
{
|
||||
return false;
|
||||
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) => f.header.status.is_success(),
|
||||
Err(_) => false,
|
||||
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>) {
|
||||
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 ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
|
||||
Ok(ok) => ok,
|
||||
let probe_host = if watch {
|
||||
host.cfg.hostname.clone()
|
||||
} 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);
|
||||
false
|
||||
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);
|
||||
@@ -65,50 +161,93 @@ async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
||||
async fn watcher(host: Arc<HostRt>, path: String, every: Duration, watch: bool) {
|
||||
let connector = Arc::new(Connector::new(None));
|
||||
loop {
|
||||
round(&host, &path, &connector).await;
|
||||
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 checked: Vec<(Arc<HostRt>, String, Duration)> = self
|
||||
.rt
|
||||
.hosts
|
||||
.values()
|
||||
.filter_map(|h| {
|
||||
h.cfg.health_check.as_ref().map(|hc| {
|
||||
(
|
||||
h.clone(),
|
||||
hc.path.clone(),
|
||||
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
let mut which = std::collections::HashMap::new();
|
||||
for (i, (h, p, every)) in checked.iter().enumerate() {
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
}
|
||||
// A watcher never returns; if one ends anyway, say so and start it again.
|
||||
let mut changes = self.shared.subscribe();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break,
|
||||
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 (h, p, every) = &checked[i];
|
||||
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
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;
|
||||
}
|
||||
}
|
||||
tasks.abort_all();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user