[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:
@@ -0,0 +1,326 @@
|
||||
// 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/.
|
||||
|
||||
//! The admin socket: a Unix socket (mode 0660, so only edge's user and group, i.e. control,
|
||||
//! can connect; never a TCP port) speaking small JSON over HTTP/1.1.
|
||||
//!
|
||||
//! | Request | Does |
|
||||
//! |:--|:--|
|
||||
//! | `GET /v1/status` | config hash, trial, revocations, health per host and upstream, certificates |
|
||||
//! | `POST /v1/reload` | reload the config file (refused while a trial runs) |
|
||||
//! | `POST /v1/trial {confirm_within_secs, watch_hosts?, watch_every_secs?}` | serve the trial file until confirmed |
|
||||
//! | `POST /v1/confirm {config_sha256}` | keep the running trial |
|
||||
//! | `POST /v1/abort` | back to the config before the trial (idempotent) |
|
||||
//! | `POST /v1/share-revocations/reload` | re-read the share-link revocation file |
|
||||
//! | `POST /v1/acme/retry` | try Let's Encrypt again now |
|
||||
//!
|
||||
//! Bodies are at most 4 KiB with no unknown fields. Answers never carry a secret.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt, Full, Limited};
|
||||
use hyper::body::Incoming;
|
||||
use hyper::server::conn::http1;
|
||||
use hyper::service::service_fn;
|
||||
use hyper::{Request, Response, StatusCode};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use pingora::server::ShutdownWatch;
|
||||
use pingora::services::background::BackgroundService;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::shared::{AdminError, Shared, WatchSpec};
|
||||
|
||||
const MAX_BODY: usize = 4096;
|
||||
/// Longest trial the admin socket accepts.
|
||||
const MAX_TRIAL_SECS: u64 = 3600;
|
||||
|
||||
pub struct AdminSocket {
|
||||
pub shared: Arc<Shared>,
|
||||
pub path: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct TrialBody {
|
||||
confirm_within_secs: u64,
|
||||
#[serde(default)]
|
||||
watch_hosts: Vec<String>,
|
||||
watch_every_secs: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct ConfirmBody {
|
||||
config_sha256: String,
|
||||
}
|
||||
|
||||
type Resp = Response<Full<Bytes>>;
|
||||
|
||||
fn reply(status: StatusCode, v: Value) -> Resp {
|
||||
let mut r = Response::new(Full::new(Bytes::from(v.to_string())));
|
||||
*r.status_mut() = status;
|
||||
r.headers_mut().insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static("application/json"),
|
||||
);
|
||||
r
|
||||
}
|
||||
|
||||
fn error(status: StatusCode, message: impl std::fmt::Display) -> Resp {
|
||||
reply(status, json!({ "error": message.to_string() }))
|
||||
}
|
||||
|
||||
fn admin_error(e: AdminError) -> Resp {
|
||||
match e {
|
||||
AdminError::Refused(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||
AdminError::Conflict(m) => error(StatusCode::CONFLICT, m),
|
||||
}
|
||||
}
|
||||
|
||||
/// The status document.
|
||||
pub fn status(shared: &Shared) -> Value {
|
||||
let rt = shared.current();
|
||||
let mut hosts: Vec<&String> = rt.hosts.keys().collect();
|
||||
hosts.sort();
|
||||
let hosts: Vec<Value> = hosts
|
||||
.into_iter()
|
||||
.filter_map(|name| rt.hosts.get(name))
|
||||
.map(|h| {
|
||||
let name = &h.cfg.hostname;
|
||||
let cert = match &h.cfg.tls {
|
||||
ianitor_core::edge_config::EdgeTls::Files { .. } => json!({
|
||||
"state": "ok",
|
||||
"not_after": rt.file_cert_expiry.get(name),
|
||||
"error": null,
|
||||
}),
|
||||
ianitor_core::edge_config::EdgeTls::Acme => match shared.cert_state(name) {
|
||||
Some(c) => {
|
||||
json!({ "state": c.state, "not_after": c.not_after, "error": c.error })
|
||||
}
|
||||
None => json!({ "state": "pending", "not_after": null, "error": null }),
|
||||
},
|
||||
};
|
||||
json!({
|
||||
"hostname": name,
|
||||
"health_check": h.cfg.health_check.is_some(),
|
||||
"upstreams": h.upstreams.iter().map(|u| json!({
|
||||
"address": u.authority,
|
||||
"healthy": u.healthy.load(std::sync::atomic::Ordering::Relaxed),
|
||||
"checks": u.health.checks(),
|
||||
})).collect::<Vec<_>>(),
|
||||
"certificate": cert,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let rev = shared.revocations();
|
||||
json!({
|
||||
"generation": shared.generation(),
|
||||
"config_sha256": rt.sha256,
|
||||
"started_at": shared.started_at,
|
||||
"trial": shared.trial_info().map(|(sha, left, prev)| json!({
|
||||
"config_sha256": sha,
|
||||
"seconds_left": left,
|
||||
"previous_sha256": prev,
|
||||
})),
|
||||
"share_revocations": {
|
||||
"loaded": rev.loaded,
|
||||
"epoch": rev.revocations.epoch,
|
||||
"stopped": rev.revocations.deny.len(),
|
||||
"error": rev.error,
|
||||
},
|
||||
"hosts": hosts,
|
||||
})
|
||||
}
|
||||
|
||||
async fn body<T: for<'de> Deserialize<'de>>(
|
||||
req: Request<Incoming>,
|
||||
) -> Result<Option<T>, Box<Resp>> {
|
||||
let bytes = Limited::new(req.into_body(), MAX_BODY)
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|_| {
|
||||
error(
|
||||
StatusCode::PAYLOAD_TOO_LARGE,
|
||||
"the body is larger than 4 KiB",
|
||||
)
|
||||
})?
|
||||
.to_bytes();
|
||||
if bytes.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
serde_json::from_slice(&bytes)
|
||||
.map(Some)
|
||||
.map_err(|e| Box::new(error(StatusCode::BAD_REQUEST, format!("bad body: {e}"))))
|
||||
}
|
||||
|
||||
async fn handle(shared: Arc<Shared>, req: Request<Incoming>) -> Resp {
|
||||
let method = req.method().clone();
|
||||
let path = req.uri().path().to_owned();
|
||||
match (method.as_str(), path.as_str()) {
|
||||
("GET", "/v1/status") => reply(StatusCode::OK, status(&shared)),
|
||||
("POST", "/v1/reload") => {
|
||||
let r = tokio::task::spawn_blocking({
|
||||
let s = shared.clone();
|
||||
move || s.reload()
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok(rt)) => reply(
|
||||
StatusCode::OK,
|
||||
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||
),
|
||||
Ok(Err(e)) => admin_error(e),
|
||||
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/trial") => {
|
||||
let b: TrialBody = match body(req).await {
|
||||
Ok(Some(b)) => b,
|
||||
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||
Err(r) => return *r,
|
||||
};
|
||||
if !(1..=MAX_TRIAL_SECS).contains(&b.confirm_within_secs) {
|
||||
return error(
|
||||
StatusCode::BAD_REQUEST,
|
||||
"confirm_within_secs must be between 1 and 3600",
|
||||
);
|
||||
}
|
||||
let every = b.watch_every_secs.unwrap_or(5);
|
||||
if !(1..=60).contains(&every) || b.watch_hosts.len() > 1000 {
|
||||
return error(StatusCode::BAD_REQUEST, "watch_every_secs must be 1 to 60");
|
||||
}
|
||||
let watch = (!b.watch_hosts.is_empty()).then(|| WatchSpec {
|
||||
hosts: b.watch_hosts,
|
||||
every: Duration::from_secs(every),
|
||||
});
|
||||
let within = Duration::from_secs(b.confirm_within_secs);
|
||||
let r = tokio::task::spawn_blocking({
|
||||
let s = shared.clone();
|
||||
move || s.start_trial(within, watch)
|
||||
})
|
||||
.await;
|
||||
match r {
|
||||
Ok(Ok((id, rt))) => {
|
||||
let s = shared.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Some(deadline) = s.trial_deadline(id) {
|
||||
tokio::time::sleep_until(deadline.into()).await;
|
||||
s.expire_trial(id);
|
||||
}
|
||||
});
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({ "config_sha256": rt.sha256, "generation": shared.generation() }),
|
||||
)
|
||||
}
|
||||
Ok(Err(e)) => admin_error(e),
|
||||
Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/confirm") => {
|
||||
let b: ConfirmBody = match body(req).await {
|
||||
Ok(Some(b)) => b,
|
||||
Ok(None) => return error(StatusCode::BAD_REQUEST, "a JSON body is needed"),
|
||||
Err(r) => return *r,
|
||||
};
|
||||
match shared.confirm(&b.config_sha256) {
|
||||
Ok(()) => reply(StatusCode::OK, json!({ "confirmed": true })),
|
||||
Err(e) => admin_error(e),
|
||||
}
|
||||
}
|
||||
("POST", "/v1/abort") => reply(StatusCode::OK, json!({ "reverted": shared.abort() })),
|
||||
("POST", "/v1/share-revocations/reload") => match shared.reload_revocations() {
|
||||
Ok(()) => {
|
||||
let r = shared.revocations();
|
||||
reply(
|
||||
StatusCode::OK,
|
||||
json!({ "epoch": r.revocations.epoch, "stopped": r.revocations.deny.len() }),
|
||||
)
|
||||
}
|
||||
Err(e) => error(StatusCode::UNPROCESSABLE_ENTITY, e),
|
||||
},
|
||||
("POST", "/v1/acme/retry") => {
|
||||
shared.acme_wake.notify_one();
|
||||
reply(StatusCode::OK, json!({ "retrying": true }))
|
||||
}
|
||||
(_, "/v1/status" | "/v1/reload" | "/v1/trial" | "/v1/confirm" | "/v1/abort") => {
|
||||
error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed")
|
||||
}
|
||||
_ => error(StatusCode::NOT_FOUND, "no such admin request"),
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(path: &Path) -> std::io::Result<tokio::net::UnixListener> {
|
||||
use std::os::unix::fs::{FileTypeExt, PermissionsExt};
|
||||
// A socket left over from a previous run is removed; anything else at the path is not.
|
||||
if let Ok(meta) = std::fs::symlink_metadata(path) {
|
||||
if meta.file_type().is_socket() {
|
||||
std::fs::remove_file(path)?;
|
||||
} else {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::AlreadyExists,
|
||||
format!("{} exists and is not a socket", path.display()),
|
||||
));
|
||||
}
|
||||
}
|
||||
let l = tokio::net::UnixListener::bind(path)?;
|
||||
std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o660))?;
|
||||
Ok(l)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for AdminSocket {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
let listener = match bind(&self.path) {
|
||||
Ok(l) => l,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::admin", "cannot listen on {}: {e}; control cannot reach edge", self.path.display());
|
||||
return;
|
||||
}
|
||||
};
|
||||
log::info!(target: "ianitor::admin", "admin socket at {}", self.path.display());
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break,
|
||||
a = listener.accept() => {
|
||||
let Ok((stream, _)) = a else { continue };
|
||||
let shared = self.shared.clone();
|
||||
tokio::spawn(async move {
|
||||
let svc = service_fn(move |req| {
|
||||
let shared = shared.clone();
|
||||
async move { Ok::<_, std::convert::Infallible>(handle(shared, req).await) }
|
||||
});
|
||||
let _ = http1::Builder::new()
|
||||
.serve_connection(TokioIo::new(stream), svc)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = std::fs::remove_file(&self.path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-reads the share-link revocation file when it changes (every 5 s), so a stopped link
|
||||
/// stops even if control's reload request was lost.
|
||||
pub struct RevocationPoller {
|
||||
pub shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl BackgroundService for RevocationPoller {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => return,
|
||||
_ = tokio::time::sleep(Duration::from_secs(5)) => self.shared.poll_revocations(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user