From 4d87537a766dfaf4889678d954722c39aba156bb Mon Sep 17 00:00:00 2001 From: mnovak Date: Sun, 8 Nov 2026 12:28:35 +0100 Subject: [PATCH] [control] Fix round 3: revocations never wait for an apply (files and edge at once; under Caddy the reload is left to the end of a running trial), confirmed before the deadline is claimed, the guard marks a trial expired only after a verified load and retries, caddy-revert clears a stale deadline when Pingora serves --- crates/control/src/caddy_guard.rs | 125 +++++++++++++++++------ crates/control/src/engine.rs | 9 +- crates/control/src/engine/caddy_apply.rs | 59 +++++++---- crates/control/src/pki_ctl.rs | 29 +++++- docs/api.md | 10 +- 5 files changed, 173 insertions(+), 59 deletions(-) diff --git a/crates/control/src/caddy_guard.rs b/crates/control/src/caddy_guard.rs index cac05a2..e931672 100644 --- a/crates/control/src/caddy_guard.rs +++ b/crates/control/src/caddy_guard.rs @@ -13,9 +13,12 @@ //! - `ianitor-control caddy-guard` (its own unit next to caddy-fallback, so a hung control is //! covered too): once a second, it reverts a trial whose deadline has passed. //! -//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial -//! and *claims* it (an atomic rename) before it confirms; the guard *expires* it with the same -//! kind of rename. Whoever renames first wins, so a trial is either confirmed by control or +//! Control *arms* the deadline (`caddy-trial.json` in its state dir) before it loads a trial, +//! and *claims* it (an atomic rename) right after its journal says `confirmed`; the guard +//! takes it with the same kind of rename (to `.reverting`, then `.expired` once Caddy is +//! verified on caddy.json; given back if the load fails, so it is tried again). A crash between +//! `confirmed` and the claim leaves both: the guard and caddy-revert see `confirmed` and leave +//! the trial to recovery, which promotes it. Whoever renames first wins, so a trial is either confirmed by control or //! reverted by the guard, never both. caddy.json itself is only ever written with a confirmed //! config, so loading it is always safe. @@ -65,7 +68,7 @@ pub fn claim(state_dir: &Path) -> bool { /// After a trial is reverted (or at start): nothing is out any more. pub fn disarm(state_dir: &Path) { - for s in ["", ".claimed", ".expired"] { + for s in ["", ".claimed", ".expired", ".reverting"] { let _ = std::fs::remove_file(path(state_dir, s)); } } @@ -97,43 +100,99 @@ pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop } } -/// Take the deadline away from control (rename) and load the last good caddy.json. +/// Whether Caddy is the engine that serves (the engine file; Pingora without `[engine]`). +fn caddy_serves(cfg: &Config) -> bool { + cfg.engine + .as_ref() + .is_some_and(|e| crate::switch::read_engine_file(&e.file) == "caddy") +} + +/// A revert that stopped half way (the guard died while loading) counts as armed again. +fn resume_half_done(dir: &Path) { + let reverting = path(dir, ".reverting"); + if reverting.exists() && !path(dir, "").exists() { + let _ = std::fs::rename(reverting, path(dir, "")); + } +} + +/// Take the deadline away from control (rename to `.reverting`), load the last good +/// caddy.json and check that Caddy runs it; only then is the deadline marked expired. If the +/// load fails, the deadline is given back, so the next try (or control's own claim, while +/// Caddy still runs the trial) decides. async fn revert(cfg: &Config, why: &str) -> Result { let dir = &cfg.state_dir; - let expired = path(dir, ".expired"); - if std::fs::rename(path(dir, ""), &expired).is_err() { + let reverting = path(dir, ".reverting"); + if std::fs::rename(path(dir, ""), &reverting).is_err() { // Control claimed it a moment ago: it confirms; nothing to do. return Ok(false); } - let sock = cfg - .caddy_compile() - .caddy_admin_socket - .clone() - .ok_or("no caddy_admin_socket is configured")?; - let text = std::fs::read(&cfg.caddy.config) - .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; - crate::caddy_link::load(Path::new(&sock), &text).await?; - log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config"); - Ok(true) + let loaded = async { + let sock = cfg + .caddy_compile() + .caddy_admin_socket + .clone() + .ok_or("no caddy_admin_socket is configured")?; + let text = std::fs::read(&cfg.caddy.config) + .map_err(|e| format!("cannot read {}: {e}", cfg.caddy.config.display()))?; + crate::caddy_link::load(Path::new(&sock), &text).await?; + if !crate::caddy_link::runs(Path::new(&sock), &text).await? { + return Err("Caddy took caddy.json but does not run it".to_owned()); + } + Ok::<_, String>(()) + } + .await; + match loaded { + Ok(()) => { + let _ = std::fs::rename(&reverting, path(dir, ".expired")); + log::warn!(target: "ianitor::caddy-guard", "{why}: Caddy is back on the last good config"); + Ok(true) + } + Err(e) => { + let _ = std::fs::rename(&reverting, path(dir, "")); + Err(format!("{why}, but Caddy could not be put back yet: {e}")) + } + } } -/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once. +/// `ianitor-control caddy-revert`: after control stops, a trial still out goes back at once +/// (retried a few times, 1, 2, 4 and 8 s apart). With another engine serving there is no +/// Caddy trial: a deadline left behind is cleared and nothing fails. pub async fn revert_after_stop(cfg: &Config) -> Result { let dir = &cfg.state_dir; - match verdict( - armed(dir).as_ref(), - confirmed(dir), - crate::util::now(), - true, - ) { - Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await, - Verdict::Nothing => Ok(false), + if !caddy_serves(cfg) { + disarm(dir); + return Ok(false); + } + resume_half_done(dir); + let mut wait = 1; + loop { + let r = match verdict( + armed(dir).as_ref(), + confirmed(dir), + crate::util::now(), + true, + ) { + Verdict::Revert => revert(cfg, "control stopped with a trial loaded into Caddy").await, + Verdict::Nothing => Ok(false), + }; + match r { + Err(e) if wait <= 8 => { + log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {wait} s"); + tokio::time::sleep(std::time::Duration::from_secs(wait)).await; + wait *= 2; + } + other => return other, + } } } /// One tick of `ianitor-control caddy-guard`. pub async fn tick(cfg: &Config) -> Result { let dir = &cfg.state_dir; + if !caddy_serves(cfg) { + return Ok(false); + } + resume_half_done(dir); match verdict( armed(dir).as_ref(), confirmed(dir), @@ -145,14 +204,20 @@ pub async fn tick(cfg: &Config) -> Result { } } -/// `ianitor-control caddy-guard`: forever, once a second. +/// `ianitor-control caddy-guard`: forever, once a second; after a failed revert it tries +/// again with a growing pause (2, 4, … 30 s). pub async fn run(cfg: Config) -> Result<(), String> { log::info!(target: "ianitor::caddy-guard", "watching {} for trials under Caddy", cfg.state_dir.display()); + let mut pause = 1u64; loop { - if let Err(e) = tick(&cfg).await { - log::error!(target: "ianitor::caddy-guard", "{e}"); + match tick(&cfg).await { + Ok(_) => pause = 1, + Err(e) => { + pause = (pause * 2).min(30); + log::error!(target: "ianitor::caddy-guard", "{e}; trying again in {pause} s"); + } } - tokio::time::sleep(std::time::Duration::from_secs(1)).await; + tokio::time::sleep(std::time::Duration::from_secs(pause)).await; } } diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index d5d1a8c..e49bf61 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -164,6 +164,9 @@ pub struct Control { pub(crate) apply_lock: tokio::sync::Mutex<()>, /// Held while an engine is switched or told to reload its device or certificate files. pub(crate) engine_lock: tokio::sync::Mutex<()>, + /// Serialises reading the device records and writing the device files (never held + /// across an apply or a switch). + pub(crate) devices_lock: tokio::sync::Mutex<()>, /// Why the device files are not (yet) in force, until a retry succeeds. pub devices_problem: Mutex>, } @@ -275,6 +278,7 @@ impl Control { pause_saved: std::sync::atomic::AtomicBool::new(true), apply_lock: tokio::sync::Mutex::new(()), engine_lock: tokio::sync::Mutex::new(()), + devices_lock: tokio::sync::Mutex::new(()), devices_problem: Mutex::new(None), cfg, }); @@ -1541,7 +1545,10 @@ impl Control { remove_if_exists(&p).map_err(|e| e.to_string())?; } if caddy { - // Caddy must run caddy.json again, the last good config; no trial is out any more. + // Caddy must run caddy.json again, the last good config (with the device files as + // they are now); then no trial is out any more. Under the engine lock, so a device + // change that saw the trial and left the reload to this point is not lost. + let _engine = self.engine_lock.lock().await; self.caddy_reload().await?; crate::caddy_guard::disarm(&self.cfg.state_dir); return Ok(rev); diff --git a/crates/control/src/engine/caddy_apply.rs b/crates/control/src/engine/caddy_apply.rs index d1ee226..9b61bee 100644 --- a/crates/control/src/engine/caddy_apply.rs +++ b/crates/control/src/engine/caddy_apply.rs @@ -187,15 +187,23 @@ impl Control { let window = self.cfg.watch_secs; // The deadline goes out before the trial does (crate::caddy_guard). let deadline = now() + window + self.cfg.trial_margin_secs + 5; - if let Err(e) = caddy_guard::arm(&self.cfg.state_dir, id, deadline) { - let mut r = reason("internal", Params::new()); - r.detail = Some(e); - return self.revert(id, &j, r, "failed").await; - } - if let Err(e) = caddy_link::load(&sock, caddy_text.as_bytes()).await { - return self - .revert(id, &j, fail("apply.failed.reload", e), "failed") - .await; + // Under the engine lock: a device change that looked a moment ago saw no trial and + // reloads caddy.json; it must not land after the trial is in. + let loaded = { + let _engine = self.engine_lock.lock().await; + match caddy_guard::arm(&self.cfg.state_dir, id, deadline) { + Err(e) => { + let mut r = reason("internal", Params::new()); + r.detail = Some(e); + Err((r, "failed")) + } + Ok(()) => caddy_link::load(&sock, caddy_text.as_bytes()) + .await + .map_err(|e| (fail("apply.failed.reload", e), "failed")), + } + }; + if let Err((r, state)) = loaded { + return self.revert(id, &j, r, state).await; } j.stage = "trial_loaded".into(); if let Err(e) = self.journal(&j) { @@ -265,16 +273,10 @@ impl Control { self.update(id, |r| r.step("watch", "done")); } crash::point("watched"); - // The guard may have reverted a trial that ran past its deadline (a stalled control): - // then this change is not kept. - if !caddy_guard::claim(&self.cfg.state_dir) { - let mut r = reason("apply.interrupted", Params::new()); - r.detail = Some( - "the trial ran past its deadline, so Caddy went back to the last good config" - .into(), - ); - return self.revert(id, &j, r, "reverted").await; - } + // Confirmed first, then the deadline is claimed (fix round 3): a crash in between + // leaves the deadline armed *and* the journal confirmed, so the guard and caddy-revert + // leave the trial alone and recovery promotes it. The other order would leave a window + // with nothing armed and nothing confirmed, where nobody reverts Caddy. j.stage = "confirmed".into(); if let Err(e) = self.journal(&j) { let mut r = reason("internal", Params::new()); @@ -282,7 +284,22 @@ impl Control { return self.revert(id, &j, r, "failed").await; } crash::point("confirmed"); + // From the claim to Caddy running the promoted caddy.json, no device reload may load + // the old caddy.json in between. + let engine = self.engine_lock.lock().await; + // The guard may have reverted a trial that ran past its deadline (a stalled control): + // then this change is not kept. + if !caddy_guard::claim(&self.cfg.state_dir) { + drop(engine); + let mut r = reason("apply.interrupted", Params::new()); + r.detail = Some( + "the trial ran past its deadline, so Caddy went back to the last good config" + .into(), + ); + return self.revert(id, &j, r, "reverted").await; + } if let Err(e) = self.promote() { + drop(engine); log::error!(target: "ianitor::apply", "cannot write the config files: {e}"); let mut p = reason("control.files_unwritten", Params::new()); p.detail = Some(e.to_string()); @@ -296,10 +313,12 @@ impl Control { return; } crash::point("promoted"); - // caddy.json now holds the change: Caddy loads what was written, and must run it. + // caddy.json now holds the change: Caddy loads what was written (with the device and + // certificate files as they are now) and must run it. if let Err(e) = self.caddy_reload().await { log::error!(target: "ianitor::apply", "Caddy did not load the promoted caddy.json: {e}"); } + drop(engine); let push_step = self.push_step(); self.update(id, |r| r.step("push", push_step)); self.finish(id, "kept", Some(kept_reason), Vec::new()); diff --git a/crates/control/src/pki_ctl.rs b/crates/control/src/pki_ctl.rs index 145e2da..c870e49 100644 --- a/crates/control/src/pki_ctl.rs +++ b/crates/control/src/pki_ctl.rs @@ -164,12 +164,16 @@ impl Control { } /// The device files changed (issue or revoke): rewrite them and tell the engine at once. + /// + /// It never waits for an apply (fix round 3): the files go to disk at once and edge is told + /// at once, also during a watch (edge's trial reads the same files). Only when Caddy serves + /// *and* a trial is out is the Caddy reload left to the end of that apply: a reload now + /// would drop the trial, and the end of every Caddy trial loads caddy.json again (promote, + /// revert, caddy-guard, caddy-revert), which reads the new files. During an engine switch + /// (engine lock busy for more than a second) the engine being started reads them anyway. pub async fn devices_changed(&self) -> Result<(), String> { let Some(p) = &self.pki else { return Ok(()) }; - // Behind a running apply (QC round 2, M2): a reload during a Caddy trial's watch would - // drop the trial; afterwards it loads whatever is current. - let _apply = self.apply_lock.lock().await; - let _engine = self.engine_lock.lock().await; + let _files = self.devices_lock.lock().await; let t = now(); let mut result = Ok(()); for dir in self.cert_dirs() { @@ -180,9 +184,24 @@ impl Control { )); } } + // The engine lock is held for long only by a switch; an apply holds it for a moment + // (loading a trial, or from the claim to the promoted reload), so then this waits. + let engine = + match tokio::time::timeout(Duration::from_secs(1), self.engine_lock.lock()).await { + Ok(g) => Some(g), + Err(_) if self.engine_state().state == "switching" => None, + Err(_) => Some(self.engine_lock.lock().await), + }; // Tell the serving engine every time, changed or not: a repeated Revoke nudges again. if result.is_ok() { - result = if self.engine_running() == "caddy" { + let caddy = self.engine_running() == "caddy"; + result = if engine.is_none() { + log::info!(target: "ianitor::pki", "an engine switch is under way; the engine it starts reads the new device list"); + Ok(()) + } else if caddy && crate::caddy_guard::armed(&self.cfg.state_dir).is_some() { + log::info!(target: "ianitor::pki", "a change is being tried on Caddy; Caddy reads the new device list when it ends"); + Ok(()) + } else if caddy { self.caddy_reload_checked() .await .map_err(|e| format!("Caddy did not reload the device list: {e}")) diff --git a/docs/api.md b/docs/api.md index 00f72f4..f7548da 100644 --- a/docs/api.md +++ b/docs/api.md @@ -328,12 +328,16 @@ While Caddy serves (decisions Q3, Q4; Mark 2026-11-08): Caddy fails with `apply.failed.reload` and nothing changes; - **an unconfirmed trial never outlives control**, as with edge: control arms a deadline (`caddy-trial.json` in its state directory: watch + margin) before loading the trial and claims - it before confirming. `ianitor-caddy-guard` (a unit that runs with caddy-fallback, + it right after the journal says `confirmed` (a crash in between leaves both, and recovery + promotes). A guard revert counts only once Caddy is verified on caddy.json; a failed load is + retried with a growing pause. With Pingora serving, caddy-revert only clears a stale deadline. `ianitor-caddy-guard` (a unit that runs with caddy-fallback, `ianitor-control caddy-guard`) reverts a trial past its deadline, which covers a hung control; ianitor-control's `ExecStopPost=ianitor-control caddy-revert` reverts at once after any stop or crash. Whoever renames the deadline file first wins, so a trial is either kept or reverted; -- device issues and revocations wait for a running apply, then reload Caddy and check that it - serves the certificate on disk for a Domi host (else `devices_problem`, retried); +- device issues and revocations never wait for an apply: the files are written and edge is told + at once. Under Caddy, Caddy is reloaded at once and checked to serve the certificate on disk + for a Domi host (else `devices_problem`, retried), except while a trial is out: then the end + of that apply (promote or revert, both load caddy.json) brings the new files in; - **share links are off**: minting is `409 share.engine_caddy`, and a visitor with a link gets the normal sign-in (fails closed). Caddy cannot check a share token and control never serves visitors; a validator Caddy calls through `forward_auth` is planned before v1.1;