// 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/. //! Switching the engine at runtime (ROADMAP §1.6 as corrected 2026-11-07, §3, §4). //! //! Exactly one of `ianitor-edge.service` and `caddy-fallback.service` runs. Control may start, //! and stop only those two, through a polkit rule scoped to exactly them (NixOS //! module). `/var/lib/ianitor/engine` names the one to run; the `ianitor-engine-select` unit //! reads it at boot. A switch writes the file first (so a reboot mid-switch boots the //! target), stops the old engine, starts the new one and waits until it serves; if the new //! one does not come up, it goes back to the old one and says so. //! //! Decisions (phase 3): //! - While Caddy serves, changes keep working (Mark, 2026-11-08): an apply is loaded into Caddy //! through its admin socket, watched through Caddy and kept or reverted (`engine/caddy_apply`). //! - Share links are refused while Caddy serves (`share.engine_caddy`, see docs/api.md): //! Caddy cannot check them, and control never serves visitors itself. //! - Device revocations while Caddy serves reload Caddy's config through its admin socket. //! //! The systemd calls go through [`Units`], so tests use a fake. // A refusal is built once per request; boxing it buys nothing. #![allow(clippy::result_large_err)] use std::collections::HashSet; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; use crate::config::EngineConfig; use crate::engine::{Control, Fail, reason}; use crate::messages::{self, Params}; use crate::records::Reason; use crate::util::{now, write_atomic}; /// Start, stop and look at systemd units. pub trait Units: Send + Sync { fn start(&self, unit: &str) -> Result<(), String>; fn stop(&self, unit: &str) -> Result<(), String>; fn is_active(&self, unit: &str) -> Result; } /// `systemctl --no-ask-password `, as the control user (polkit decides). pub struct Systemctl { pub bin: PathBuf, } impl Systemctl { fn run(&self, args: &[&str]) -> Result { std::process::Command::new(&self.bin) .arg("--no-ask-password") .args(args) .stdin(std::process::Stdio::null()) .output() .map_err(|e| format!("cannot run {}: {e}", self.bin.display())) } fn verb(&self, verb: &str, unit: &str) -> Result<(), String> { let o = self.run(&[verb, unit])?; if o.status.success() { Ok(()) } else { Err(format!( "systemctl {verb} {unit} failed: {}", String::from_utf8_lossy(&o.stderr).trim() )) } } } impl Units for Systemctl { fn start(&self, unit: &str) -> Result<(), String> { self.verb("start", unit) } fn stop(&self, unit: &str) -> Result<(), String> { self.verb("stop", unit) } fn is_active(&self, unit: &str) -> Result { Ok(self.run(&["is-active", "--quiet", unit])?.status.success()) } } /// In-memory units for tests: records every call; `fail_start` makes a start fail. #[derive(Default)] pub struct FakeUnits { pub calls: Mutex>, pub active: Mutex>, pub fail_start: Mutex>, } impl Units for FakeUnits { fn start(&self, unit: &str) -> Result<(), String> { if let Ok(mut c) = self.calls.lock() { c.push(format!("start {unit}")); } if self.fail_start.lock().is_ok_and(|f| f.contains(unit)) { return Err(format!("{unit} failed to start")); } if let Ok(mut a) = self.active.lock() { a.insert(unit.to_owned()); } Ok(()) } fn stop(&self, unit: &str) -> Result<(), String> { if let Ok(mut c) = self.calls.lock() { c.push(format!("stop {unit}")); } if let Ok(mut a) = self.active.lock() { a.remove(unit); } Ok(()) } fn is_active(&self, unit: &str) -> Result { Ok(self.active.lock().is_ok_and(|a| a.contains(unit))) } } /// Which engine serves, as control knows it. #[derive(Debug, Clone)] pub struct EngineState { /// `pingora` or `caddy`. pub running: String, /// `running`, `switching` or `stopped`. pub state: String, pub since: u64, /// The target while switching. pub target: Option, /// Why the last switch did not happen. pub last_error: Option, } pub fn read_engine_file(p: &Path) -> String { match std::fs::read_to_string(p) { Ok(s) if s.trim() == "caddy" => "caddy".into(), _ => "pingora".into(), } } pub fn engine_name(e: &str) -> String { if e == "caddy" { "Caddy" } else { "Pingora" }.into() } impl Control { pub fn engine_cfg(&self) -> Option<&EngineConfig> { self.cfg.engine.as_ref() } /// `pingora` or `caddy`. pub fn engine_running(&self) -> String { self.engine .lock() .map(|e| e.running.clone()) .unwrap_or_else(|_| "pingora".into()) } pub fn engine_state(&self) -> EngineState { self.engine .lock() .map(|e| e.clone()) .unwrap_or(EngineState { running: "pingora".into(), state: "running".into(), since: 0, target: None, last_error: None, }) } fn set_engine(&self, f: impl FnOnce(&mut EngineState)) { if let Ok(mut e) = self.engine.lock() { f(&mut e); } } /// Check a switch request and start it. Answers at once; the switch runs in the /// background (`overview.engine.state` is `switching` until it ends). pub fn request_switch(self: &Arc, target: &str) -> Result { if self.engine_cfg().is_none() || self.units.is_none() { return Err(Fail::new(409, "engine.unmanaged", Params::new())); } if target == "caddy" && !self.fallback_buildable() { return Err(Fail::new(409, "engine.not_ready", Params::new())); } if target != "pingora" && target != "caddy" { return Err(Fail::new( 422, "request.body", messages::params([("problem", "target must be \"pingora\" or \"caddy\".".into())]), )); } { let mut e = self .engine .lock() .map_err(|_| Fail::new(500, "internal", Params::new()))?; if e.state == "switching" { return Err(Fail::new(409, "engine.switching", Params::new())); } if e.running == target { return Err(Fail::new( 409, "engine.same", messages::params([("engine", engine_name(target))]), )); } e.state = "switching".into(); e.target = Some(target.to_owned()); e.last_error = None; } let me = self.clone(); let t = target.to_owned(); tokio::spawn(async move { me.switch(&t).await }); Ok(self.engine_state()) } async fn switch(self: Arc, target: &str) { // No apply runs during a switch, and none starts. let _lock = self.apply_lock.lock().await; let _engine = self.engine_lock.lock().await; let from = self.engine_running(); let res = self.switch_inner(&from, target).await; let t = now(); match res { Ok(()) => { log::info!(target: "ianitor::engine", "switched from {from} to {target}"); self.set_engine(|e| { e.running = target.to_owned(); e.state = "running".into(); e.since = t; e.target = None; }); } Err(detail) => { log::error!(target: "ianitor::engine", "switch to {target} failed: {detail}"); // Go back to what served before. let back = self.bring_back(&from).await; let mut r = reason( "engine.switch_failed", messages::params([ ("engine", engine_name(target)), ("previous", engine_name(&from)), ]), ); r.detail = Some(match back { Ok(()) => detail, Err(b) => format!("{detail}; going back also failed: {b}"), }); self.set_engine(|e| { e.running = from.clone(); e.state = "running".into(); e.target = None; e.last_error = Some(r); }); } } // Still under the engine lock: whichever engine serves now reads the device files again // (QC round 4). A device change during the switch only wrote them; a Caddy that was // already running, or started before they changed, would keep the old list. if self.pki.is_some() && let Err(e) = self.nudge_devices().await { log::error!(target: "ianitor::engine", "after the switch: {e}; retrying"); if let Ok(mut p) = self.devices_problem.lock() { *p = Some(e); } } } fn units_and_cfg(&self) -> Result<(Arc, EngineConfig), String> { match (self.units.clone(), self.engine_cfg().cloned()) { (Some(u), Some(c)) => Ok((u, c)), _ => Err("no engine settings".into()), } } fn unit_of(cfg: &EngineConfig, engine: &str) -> String { if engine == "caddy" { cfg.caddy_unit.clone() } else { cfg.edge_unit.clone() } } async fn blocking( f: impl FnOnce() -> Result + Send + 'static, ) -> Result { tokio::task::spawn_blocking(f) .await .map_err(|e| e.to_string())? } async fn switch_inner(&self, from: &str, target: &str) -> Result<(), String> { let (units, cfg) = self.units_and_cfg()?; if target == "caddy" { // Caddy starts from caddy.json: make sure it is the current tree's. self.write_current_caddy()?; } write_atomic(&cfg.file, target.as_bytes(), 0o644) .map_err(|e| format!("cannot write {}: {e}", cfg.file.display()))?; let (old, new) = (Self::unit_of(&cfg, from), Self::unit_of(&cfg, target)); let u = units.clone(); Self::blocking(move || u.stop(&old)).await?; let u = units.clone(); let n = new.clone(); Self::blocking(move || u.start(&n)).await?; self.wait_serving(target, &units, &new).await?; // Edge reads edge.json when it starts; tell it again in case it kept running (changes // kept under Caddy are in edge.json). if target == "pingora" && self.edge.attached() && let Err(e) = self.edge.reload().await { log::warn!(target: "ianitor::engine", "edge did not reload edge.json after the switch: {e}"); } Ok(()) } async fn bring_back(&self, engine: &str) -> Result<(), String> { let (units, cfg) = self.units_and_cfg()?; let other = if engine == "caddy" { "pingora" } else { "caddy" }; write_atomic(&cfg.file, engine.as_bytes(), 0o644).map_err(|e| e.to_string())?; let (stop, start) = (Self::unit_of(&cfg, other), Self::unit_of(&cfg, engine)); let u = units.clone(); let _ = Self::blocking(move || u.stop(&stop)).await; let u = units.clone(); let s = start.clone(); Self::blocking(move || u.start(&s)).await?; self.wait_serving(engine, &units, &start).await } /// Until the unit is active and serves: edge answers on its admin socket, Caddy accepts /// connections on the HTTPS address. async fn wait_serving( &self, engine: &str, units: &Arc, unit: &str, ) -> Result<(), String> { let deadline = tokio::time::Instant::now() + Duration::from_secs(20); let addr = if engine == "caddy" { self.cfg.caddy_compile().https_listen } else { self.cfg.compile.https_listen }; loop { let u = units.clone(); let n = unit.to_owned(); let active = Self::blocking(move || u.is_active(&n)) .await .unwrap_or(false); let serving = active && if engine == "pingora" && self.edge.attached() { self.edge.status().await.is_ok() } else { tokio::net::TcpStream::connect(addr).await.is_ok() }; if serving { return Ok(()); } if tokio::time::Instant::now() > deadline { return Err(format!("{unit} did not come up within 20 s")); } tokio::time::sleep(Duration::from_millis(250)).await; } } /// Compile the current tree for Caddy and write caddy.json (the file only ever holds a /// kept tree, so this only matters when it is missing or older). fn write_current_caddy(&self) -> Result<(), String> { let (_, _, model) = self.head_model().map_err(|f| f.reason.message)?; self.pki_prepare(&model).map_err(|f| f.reason.message)?; let text = ianitor_core::compile::caddy(&model, &self.cfg.caddy_compile().options()) .map_err(|e| e.to_string())?; if std::fs::read_to_string(&self.cfg.caddy.config) .ok() .as_deref() != Some(text.as_str()) { write_atomic(&self.cfg.caddy.config, text.as_bytes(), 0o644) .map_err(|e| e.to_string())?; } Ok(()) } /// Can Caddy's settings be built from the current tree? (Otherwise `engine.not_ready`.) pub fn fallback_buildable(&self) -> bool { self.head_model().ok().is_some_and(|(_, _, m)| { ianitor_core::compile::caddy(&m, &self.cfg.caddy_compile().options()).is_ok() }) } /// Any reason changes wait now: Caddy serving, or a pause. pub fn effective_pause(&self) -> Option { self.paused() } } /// What control.toml's `[engine]` asks for. pub fn units_for(cfg: Option<&EngineConfig>) -> Option> { let c = cfg?; match c.units.as_str() { "systemctl" => Some(Arc::new(Systemctl { bin: c.systemctl.clone(), })), _ => None, } }