[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

This commit is contained in:
2026-11-08 12:28:35 +01:00
parent 09b8313a04
commit 4d87537a76
5 changed files with 173 additions and 59 deletions
+95 -30
View File
@@ -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<bool, String> {
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<bool, String> {
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<bool, String> {
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<bool, String> {
}
}
/// `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;
}
}
+8 -1
View File
@@ -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<Option<String>>,
}
@@ -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);
+39 -20
View File
@@ -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());
+24 -5
View File
@@ -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}"))