// 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 deadline of a trial under Caddy (QC round 2, B2; the Phase 2 guarantee that an //! unconfirmed change never outlives control). Edge drops a trial by itself when control does //! not confirm it in time; Caddy has no such clock, so two things outside control's own process //! stand in for it: //! //! - `ianitor-control caddy-revert` (systemd `ExecStopPost=` of ianitor-control, so it runs //! after every stop, a crash included): with a trial out, Caddy goes back to caddy.json (the //! last good config) at once; //! - `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) 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. use std::path::{Path, PathBuf}; use serde::{Deserialize, Serialize}; use crate::config::Config; use crate::records::Journal; use crate::util::{read_json, write_json}; pub const DEADLINE_FILE: &str = "caddy-trial.json"; #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct TrialDeadline { pub apply_id: String, /// Unix seconds. pub deadline: u64, } fn path(state_dir: &Path, suffix: &str) -> PathBuf { state_dir.join(format!("{DEADLINE_FILE}{suffix}")) } /// Before a trial goes into Caddy. pub fn arm(state_dir: &Path, apply_id: &str, deadline: u64) -> Result<(), String> { write_json( &path(state_dir, ""), &TrialDeadline { apply_id: apply_id.to_owned(), deadline, }, ) } /// Control, before it confirms: `true` if it got the deadline first (the guard has not /// reverted the trial), `false` if the guard did. pub fn claim(state_dir: &Path) -> bool { let claimed = path(state_dir, ".claimed"); if std::fs::rename(path(state_dir, ""), &claimed).is_err() { return false; } let _ = std::fs::remove_file(claimed); true } /// After a trial is reverted (or at start): nothing is out any more. pub fn disarm(state_dir: &Path) { for s in ["", ".claimed", ".expired", ".reverting"] { let _ = std::fs::remove_file(path(state_dir, s)); } } pub fn armed(state_dir: &Path) -> Option { read_json(&path(state_dir, "")).ok().flatten() } /// Whether control's journal says the change is confirmed (then it is being promoted and /// caddy.json will hold it; nothing to revert). fn confirmed(state_dir: &Path) -> bool { read_json::(&state_dir.join("journal.json")) .ok() .flatten() .is_some_and(|j| j.stage == "confirmed" || j.stage == "promoted") } /// What to do now, for a deadline file as found (pure, for the tests). #[derive(Debug, PartialEq, Eq)] pub enum Verdict { Nothing, Revert, } pub fn verdict(armed: Option<&TrialDeadline>, confirmed: bool, now: u64, at_stop: bool) -> Verdict { match armed { Some(d) if !confirmed && (at_stop || now > d.deadline) => Verdict::Revert, _ => Verdict::Nothing, } } /// 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 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 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 /// (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; 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), crate::util::now(), false, ) { Verdict::Revert => revert(cfg, "a trial under Caddy passed its deadline unconfirmed").await, Verdict::Nothing => Ok(false), } } /// `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 { 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(pause)).await; } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; fn d(deadline: u64) -> TrialDeadline { TrialDeadline { apply_id: "ch_1".into(), deadline, } } #[test] fn the_guard_reverts_only_an_unconfirmed_trial_past_its_deadline() { assert_eq!(verdict(None, false, 100, false), Verdict::Nothing); assert_eq!(verdict(Some(&d(100)), false, 100, false), Verdict::Nothing); assert_eq!(verdict(Some(&d(100)), false, 101, false), Verdict::Revert); assert_eq!(verdict(Some(&d(100)), true, 500, false), Verdict::Nothing); } #[test] fn after_a_stop_an_unconfirmed_trial_goes_back_at_once() { assert_eq!(verdict(Some(&d(1000)), false, 1, true), Verdict::Revert); assert_eq!(verdict(Some(&d(1000)), true, 1, true), Verdict::Nothing); assert_eq!(verdict(None, false, 1, true), Verdict::Nothing); } #[test] fn control_and_the_guard_cannot_both_have_the_deadline() { let dir = std::env::temp_dir().join(format!("ianitor-guard-{}", std::process::id())); std::fs::create_dir_all(&dir).unwrap(); arm(&dir, "ch_1", 10).unwrap(); assert_eq!(armed(&dir), Some(d(10))); // The guard took it (as `revert` does): control's claim fails. std::fs::rename(path(&dir, ""), path(&dir, ".expired")).unwrap(); assert!(!claim(&dir)); disarm(&dir); // Control claims first: nothing is left for the guard. arm(&dir, "ch_1", 10).unwrap(); assert!(claim(&dir)); assert!(armed(&dir).is_none()); assert!(std::fs::rename(path(&dir, ""), path(&dir, ".expired")).is_err()); disarm(&dir); let _ = std::fs::remove_dir_all(&dir); } }