Files
ianitor/crates/control/src/engine.rs
T

2049 lines
78 KiB
Rust

// SPDX-License-Identifier: CPAL-1.0
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
//! The apply pipeline (ROADMAP §3): validate → compile both outputs → commit → write the
//! trial files → edge loads the trial → watch the touched hosts → confirm and promote ("kept"),
//! or git-revert and abort ("reverted"). One worker runs applies one at a time, in the order
//! they were asked for; everything else waits in the queue.
//!
//! Crash safety: `edge.json` and `caddy.json` only ever hold configs that passed their
//! watch. The new config reaches edge as a *trial*, which edge drops by itself if control
//! does not confirm it in time; the journal (see `records`) tells a restarted control what
//! to finish or undo, so the repository, both files and edge agree again.
// A refusal is built once per failed request or apply; boxing it buys nothing.
#![allow(clippy::result_large_err)]
mod caddy_apply;
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use ianitor_core::compile;
use ianitor_core::share::ShareKey;
use tokio::sync::Notify;
use crate::config::Config;
use crate::crash;
use crate::edgelink::{Check, EdgeLink, EdgeLinkError, EdgeStatus};
use crate::hostspec::HostSpec;
use crate::messages::{self, Params, message};
use crate::records::{ApplyRecord, FieldError, Journal, PushState, Reason, Watch, WatchHost};
use crate::repo::{Repo, RepoError, RouteTree};
use crate::shares::Shares;
use crate::tokens::Tokens;
use crate::util::{
hex, now, random, read_json, remove_if_exists, rename_durable, rfc3339, write_atomic,
write_json,
};
/// What a user asked for.
#[derive(Debug, Clone)]
pub enum Change {
Put { spec: HostSpec, create: bool },
ShareLinks { hostname: String, on: bool },
Delete { hostname: String },
Undo { target: String },
Restore { change_id: String },
}
struct Job {
id: String,
change: Change,
base_rev: Option<String>,
}
/// A refusal, before or during an apply.
#[derive(Debug, Clone)]
pub struct Fail {
pub status: u16,
pub reason: Reason,
pub errors: Vec<FieldError>,
}
impl Fail {
pub fn new(status: u16, code: &str, params: Params) -> Fail {
Fail {
status,
reason: reason(code, params),
errors: Vec::new(),
}
}
pub fn detail(mut self, d: impl Into<String>) -> Fail {
self.reason.detail = Some(d.into());
self
}
}
pub fn reason(code: &str, params: Params) -> Reason {
Reason {
code: code.into(),
message: message(code, &params),
hostname: params.get("hostname").cloned(),
upstream: params.get("upstream").cloned(),
field: params.get("field").cloned(),
count: params.get("count").and_then(|c| c.parse().ok()),
of: params.get("of").and_then(|c| c.parse().ok()),
detail: None,
params,
}
}
/// Core validation errors in the API's shape.
pub fn field_errors(errs: &ianitor_core::ValidationErrors) -> Vec<FieldError> {
errs.errors()
.iter()
.map(|e| {
let params: Params = e
.params()
.into_iter()
.map(|(k, v)| (k.to_owned(), v))
.collect();
FieldError {
code: e.code().into(),
message: message(e.code(), &params),
field: e.field(),
params,
detail: Some(e.to_string()),
}
})
.collect()
}
struct Plan {
kind: &'static str,
summary: String,
verb: &'static str,
hosts: Vec<String>,
target: RouteTree,
model: ianitor_core::Model,
attempted: Option<HostSpec>,
undo_of: Option<String>,
restore_of: Option<String>,
effect: Option<String>,
}
/// Health as control last read it from edge.
#[derive(Debug, Clone, Default)]
pub struct HealthCache {
pub status: Option<EdgeStatus>,
pub error: Option<String>,
pub read_at: Option<u64>,
/// hostname → (state, since).
pub since: HashMap<String, (&'static str, u64)>,
}
pub struct Control {
pub cfg: Config,
pub repo: Repo,
pub edge: EdgeLink,
pub tokens: Tokens,
pub shares: Shares,
pub share_key: Option<ShareKey>,
/// The Domi CA, when `[pki]` is configured.
pub pki: Option<crate::pki::Pki>,
/// The per-boot secret edge adds on the admin host (`X-Ianitor-Proof`), from `[ui]`.
pub ui_proof: Option<Vec<u8>>,
/// Which engine serves (see `switch`).
pub engine: Mutex<crate::switch::EngineState>,
/// How control starts and stops the engines; `None` without `[engine]`.
pub units: Option<Arc<dyn crate::switch::Units>>,
records: Mutex<Vec<ApplyRecord>>,
queue: Mutex<VecDeque<Job>>,
wake: Notify,
pub health: Mutex<HealthCache>,
push: Mutex<PushState>,
pub push_wake: Notify,
paused: Mutex<Option<Reason>>,
/// False while the pause is only in memory (paused.json could not be written).
pause_saved: std::sync::atomic::AtomicBool,
/// Serialises applies with share-revocation writes and recovery.
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>>,
}
const MAX_RECORDS: usize = 1000;
const MAX_QUEUE: usize = 50;
fn host_verb(kind: &str) -> &'static str {
match kind {
"add" => "added",
"remove" => "removed",
_ => "changed",
}
}
fn repo_fail(e: RepoError) -> Fail {
match e {
RepoError::Shape(errs) => {
let file = errs
.first()
.map(|e| e.file().to_owned())
.unwrap_or_default();
let mut f = Fail::new(409, "repo.unreadable", messages::params([("file", file)]));
f.errors = field_errors(&ianitor_core::ValidationErrors::from_errors(errs));
f
}
e => Fail::new(500, "internal", Params::new()).detail(e.to_string()),
}
}
fn short(id: &str) -> String {
id.chars().take(10).collect()
}
impl Control {
/// Open the stores and the repository, recover from an interrupted apply, and make the
/// files and edge agree with the repository.
pub async fn open(cfg: Config) -> Result<Arc<Control>, String> {
std::fs::create_dir_all(&cfg.state_dir)
.map_err(|e| format!("cannot create {}: {e}", cfg.state_dir.display()))?;
let repo = Repo::open(
&cfg.git,
&cfg.routes.repo,
&cfg.state_dir,
&cfg.routes.branch,
)
.map_err(|e| e.to_string())?;
let edge = match &cfg.edge.admin_socket {
Some(p) => EdgeLink::Unix(p.clone()),
None => EdgeLink::None,
};
let share_key = cfg
.credential(ianitor_core::share::KEY_CREDENTIAL)
.and_then(|k| ShareKey::new(&k).ok());
if share_key.is_none() {
log::warn!(target: "ianitor::control", "no usable share-link-key credential: share links cannot be made");
}
let keys = crate::pki::root_key_files(&cfg.state_dir);
if let Some(k) = keys.first() {
return Err(format!(
"{} looks like a root CA key inside the state directory; the Domi root key must never be on the server (ROADMAP §1.2). Move it to the offline machine.",
k.display()
));
}
let pki = match &cfg.pki {
Some(p) => Some(crate::pki::Pki::open(
p,
&cfg.state_dir,
cfg.credential(&p.password_credential),
)?),
None => None,
};
let records: Vec<ApplyRecord> =
read_json(&cfg.state_dir.join("applies.json"))?.unwrap_or_default();
let push: PushState = read_json(&cfg.state_dir.join("push.json"))?.unwrap_or_default();
let paused: Option<Reason> = read_json(&cfg.state_dir.join("paused.json"))?;
let c = Arc::new(Control {
tokens: Tokens::new(&cfg.state_dir),
shares: Shares::new(&cfg.state_dir, &cfg.edge.share_revocations),
repo,
edge,
share_key,
ui_proof: cfg
.ui
.as_ref()
.and_then(|u| u.proof_credential.as_deref())
.and_then(|n| cfg.credential(n))
.filter(|p| p.len() >= 32),
pki,
engine: Mutex::new(crate::switch::EngineState {
running: cfg
.engine
.as_ref()
.map(|e| crate::switch::read_engine_file(&e.file))
.unwrap_or_else(|| "pingora".into()),
state: "running".into(),
since: now(),
target: None,
last_error: None,
}),
units: crate::switch::units_for(cfg.engine.as_ref()),
records: Mutex::new(records),
queue: Mutex::new(VecDeque::new()),
wake: Notify::new(),
health: Mutex::new(HealthCache::default()),
push: Mutex::new(push),
push_wake: Notify::new(),
paused: Mutex::new(paused),
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,
});
if let Ok((_, _, m)) = c.head_model()
&& let Err(f) = c.pki_prepare(&m)
{
log::error!(target: "ianitor::pki", "{}", f.reason.message);
}
c.recover().await?;
Ok(c)
}
// ------------------------------------------------------------ records
fn save_records(&self, recs: &[ApplyRecord]) {
if let Err(e) = write_json(&self.cfg.state_dir.join("applies.json"), &recs) {
log::error!(target: "ianitor::control", "{e}");
}
}
fn update<F: FnOnce(&mut ApplyRecord)>(&self, id: &str, f: F) {
if let Ok(mut recs) = self.records.lock() {
if let Some(r) = recs.iter_mut().find(|r| r.id == id) {
f(r);
}
self.save_records(&recs);
}
}
pub fn record(&self, id: &str) -> Option<ApplyRecord> {
self.records
.lock()
.ok()?
.iter()
.find(|r| r.id == id)
.cloned()
}
pub fn records(&self) -> Vec<ApplyRecord> {
self.records.lock().map(|r| r.clone()).unwrap_or_default()
}
/// The latest kept change with a commit: the Undo target.
pub fn undo_target(&self) -> Option<ApplyRecord> {
self.records
.lock()
.ok()?
.iter()
.rev()
.find(|r| r.is_kept_change())
.cloned()
}
pub fn paused(&self) -> Option<Reason> {
self.paused.lock().ok().and_then(|p| p.clone())
}
/// Pause changes. Always in memory; `Err` when it could not be saved, and then the
/// caller must keep the journal so a restart still knows.
fn pause(&self, r: Reason) -> Result<(), String> {
let saved = write_json(&self.cfg.state_dir.join("paused.json"), &r);
self.pause_saved
.store(saved.is_ok(), std::sync::atomic::Ordering::SeqCst);
if let Ok(mut p) = self.paused.lock() {
*p = Some(r);
}
saved
}
/// Is the current pause on disk? If not, try to write it now.
fn pause_durable(&self) -> bool {
use std::sync::atomic::Ordering;
let Some(p) = self.paused() else {
return true;
};
if self.pause_saved.load(Ordering::SeqCst) {
return true;
}
match write_json(&self.cfg.state_dir.join("paused.json"), &p) {
Ok(()) => {
self.pause_saved.store(true, Ordering::SeqCst);
log::info!(target: "ianitor::apply", "the pause is saved now");
true
}
Err(e) => {
log::error!(target: "ianitor::apply", "the pause still cannot be saved: {e}");
false
}
}
}
/// The way out of `control.files_unwritten`. Runs only in the apply worker, under the
/// apply lock, so no apply is in flight: write both files from the branch head, make edge
/// run exactly that (reload and compare its hash), and drop the journal only if it is the
/// `confirmed` journal of the apply that caused the pause.
async fn retry_files(&self) -> bool {
let Some(p) = self
.paused()
.filter(|p| p.code == "control.files_unwritten")
else {
return false;
};
let written = self
.head_model()
.map_err(|f| f.reason.message)
.and_then(|(_, _, m)| {
let (e, c) = self.compile(&m).map_err(|f| f.reason.message)?;
write_atomic(&self.cfg.edge.config, e.as_bytes(), 0o644)
.and_then(|_| write_atomic(&self.cfg.caddy.config, c.as_bytes(), 0o644))
.map_err(|e| e.to_string())?;
Ok(crate::util::sha256_hex(e.as_bytes()))
});
let want = match written {
Ok(w) => w,
Err(e) => {
log::error!(target: "ianitor::apply", "the config files still cannot be written: {e}");
return false;
}
};
if self.edge.attached() {
match self.edge.reload().await {
Ok(got) if got == want => {}
Ok(got) => {
log::error!(target: "ianitor::apply", "edge reloaded to {got}, not to the files just written ({want}); still paused");
return false;
}
Err(e) => {
log::error!(target: "ianitor::apply", "the files are written, but edge did not reload them ({e}); still paused");
return false;
}
}
}
let cause = p.params.get("apply_id").cloned();
match read_json::<Journal>(&self.journal_path()) {
Ok(Some(j)) if Some(&j.apply_id) == cause.as_ref() && j.stage == "confirmed" => {
for t in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
if let Err(e) = remove_if_exists(&t) {
log::warn!(target: "ianitor::apply", "cannot remove {}: {e}", t.display());
}
}
self.clear_journal();
}
Ok(Some(j)) => {
log::warn!(target: "ianitor::apply", "leaving the journal of apply {} (stage {}) alone", j.apply_id, j.stage);
}
Ok(None) => {}
Err(e) => log::error!(target: "ianitor::apply", "{e}"),
}
log::info!(target: "ianitor::apply", "the config files are written and edge runs them; changes resume");
self.unpause();
true
}
fn unpause(&self) {
if let Err(e) = remove_if_exists(&self.cfg.state_dir.join("paused.json")) {
log::error!(target: "ianitor::apply", "cannot remove paused.json ({e}); the next start re-checks it");
}
if let Ok(mut p) = self.paused.lock() {
*p = None;
}
}
/// While paused, only a Restore of a kept version may run: it is the way out of
/// `needs_attention` (docs/ui-api.md §3.2).
///
/// A Restore runs only once the pause is saved: until then the `reverting` journal is the
/// only record of it on disk, and a Restore would replace that journal with its own.
/// `in_worker` is false when a request is first checked: a change that the worker may
/// still let through (after it retried the files) is queued rather than refused.
fn paused_for(&self, change: &Change, in_worker: bool) -> Option<Reason> {
let p = self.paused()?;
if !in_worker && p.code == "control.files_unwritten" {
return None;
}
let restorable = matches!(
p.code.as_str(),
"apply.needs_attention" | "control.files_unwritten"
);
if !(matches!(change, Change::Restore { .. }) && restorable) {
return Some(p);
}
if self.pause_durable() {
return None;
}
Some(Reason {
message: format!(
"{} Ianitor cannot save this pause to disk, so even Restore waits until it can.",
p.message
),
..p
})
}
pub fn push_state(&self) -> PushState {
self.push.lock().map(|p| p.clone()).unwrap_or_default()
}
/// Position (1-based) in the queue, and the running apply.
pub fn queue_position(&self, id: &str) -> Option<usize> {
let q = self.queue.lock().ok()?;
q.iter().position(|j| j.id == id).map(|p| p + 1)
}
pub fn queued_count(&self) -> usize {
self.queue.lock().map(|q| q.len()).unwrap_or(0)
}
// ------------------------------------------------------------ planning
fn conflict(
&self,
base_rev: Option<&str>,
head: &str,
tree: &RouteTree,
hosts: &[String],
) -> Result<(), Fail> {
let Some(base) = base_rev else { return Ok(()) };
if base == head {
return Ok(());
}
if !self.repo.in_history(base).map_err(repo_fail)? {
return Err(Fail::new(422, "request.base_rev", Params::new()));
}
let old = self.repo.tree(base).map_err(repo_fail)?;
for h in hosts {
if old.host(h) != tree.host(h) {
let last = self
.records()
.into_iter()
.rev()
.find(|r| r.is_kept_change() && r.hosts.contains(h));
let (time, summary) = match last {
Some(r) => (rfc3339(r.finished.unwrap_or(r.created)), r.summary),
None => (String::new(), "a change outside Ianitor".into()),
};
return Err(Fail::new(
409,
"change.conflict",
messages::params([
("hostname", h.clone()),
("time", time),
("summary", summary),
]),
));
}
}
Ok(())
}
fn plan(
&self,
change: &Change,
head: &str,
tree: &RouteTree,
base_rev: Option<&str>,
) -> Result<Plan, Fail> {
let mut target = tree.clone();
let (kind, summary, hosts, attempted, undo_of, restore_of, effect);
match change {
Change::Put { spec, create } => {
let h = spec.hostname.clone();
let exists = tree.host(&h).is_some();
if *create && exists {
let mut f = Fail::new(
422,
"host.hostname.taken",
messages::params([("hostname", h.clone())]),
);
f.reason.field = Some("hostname".into());
f.errors.push(FieldError {
code: "host.hostname.taken".into(),
message: f.reason.message.clone(),
field: Some("hostname".into()),
params: f.reason.params.clone(),
detail: None,
});
return Err(f);
}
if !*create && !exists {
return Err(Fail::new(
404,
"host.not_found",
messages::params([("hostname", h)]),
));
}
let text = spec.to_toml().map_err(|e| {
Fail::new(422, "request.body", messages::params([("problem", e)]))
})?;
target.set_host(&h, text);
kind = if *create { "add" } else { "edit" };
summary = format!("{} {h}", if *create { "Added" } else { "Changed" });
hosts = vec![h];
attempted = Some(spec.clone());
(undo_of, restore_of, effect) = (None, None, None);
}
Change::ShareLinks { hostname, on } => {
let Some(text) = tree.host(hostname) else {
return Err(Fail::new(
404,
"host.not_found",
messages::params([("hostname", hostname.clone())]),
));
};
let mut spec = HostSpec::from_toml(text).map_err(|e| {
Fail::new(
409,
"repo.unreadable",
messages::params([("file", ianitor_core::routes::host_path(hostname))]),
)
.detail(e)
})?;
spec.share_links = *on;
let text = spec
.to_toml()
.map_err(|e| Fail::new(500, "internal", Params::new()).detail(e))?;
target.set_host(hostname, text);
kind = "share_links";
summary = format!(
"Turned share links {} for {hostname}",
if *on { "on" } else { "off" }
);
hosts = vec![hostname.clone()];
attempted = Some(spec);
(undo_of, restore_of, effect) = (None, None, None);
}
Change::Delete { hostname } => {
if !target.remove_host(hostname) {
return Err(Fail::new(
404,
"host.not_found",
messages::params([("hostname", hostname.clone())]),
));
}
kind = "remove";
summary = format!("Removed {hostname}");
hosts = vec![hostname.clone()];
(attempted, undo_of, restore_of, effect) = (None, None, None, None);
}
Change::Undo { target: wanted } => {
let Some(t) = self.undo_target() else {
return Err(Fail::new(409, "undo.nothing", Params::new()));
};
let (Some(commit), Some(base)) = (t.commit.clone(), t.base.clone()) else {
return Err(Fail::new(409, "undo.nothing", Params::new()));
};
if &t.id != wanted || self.repo.tree(&commit).map_err(repo_fail)?.as_ref() != tree {
return Err(Fail::new(
409,
"undo.target_moved",
messages::params([("summary", t.summary.clone())]),
));
}
target = (*self.repo.tree(&base).map_err(repo_fail)?).clone();
kind = "undo";
summary = format!("Undid: {}", t.summary);
hosts = changed_hosts(tree, &target);
effect = Some(effect_text(tree, &target));
undo_of = Some(t.id.clone());
(attempted, restore_of) = (None, None);
}
Change::Restore { change_id } => {
let Some(r) = self.record(change_id) else {
return Err(Fail::new(404, "change.not_found", Params::new()));
};
let Some(commit) = r.commit.clone().filter(|_| r.state == "kept") else {
return Err(Fail::new(409, "restore.not_kept", Params::new()));
};
target = (*self.repo.tree(&commit).map_err(repo_fail)?).clone();
if &target == tree {
return Err(Fail::new(409, "restore.same", Params::new()));
}
kind = "restore";
summary = format!(
"Restored the version of {}",
ianitor_core::time::long_date(r.finished.unwrap_or(r.created))
);
hosts = changed_hosts(tree, &target);
restore_of = Some(r.id.clone());
(attempted, undo_of, effect) = (None, None, None);
}
}
if &target == tree {
return Err(Fail::new(409, "change.unchanged", Params::new()));
}
if !matches!(change, Change::Undo { .. }) {
self.conflict(base_rev, head, tree, &hosts)?;
}
let model = target.model().map_err(|errs| {
let fe = field_errors(&errs);
let first = fe.first().map(|e| e.message.clone()).unwrap_or_default();
Fail {
status: 422,
reason: reason(
"apply.failed.validation",
messages::params([("first_error", first)]),
),
errors: fe,
}
})?;
self.policy(&model)?;
Ok(Plan {
kind,
verb: host_verb(kind),
summary,
hosts,
target,
model,
attempted,
undo_of,
restore_of,
effect,
})
}
/// What control allows beyond core's schema, for every tree it applies and for the live
/// tree at start: the UI proof only on the [ui] host, a socket upstream only there and only
/// to control's own UI socket.
fn policy(&self, model: &ianitor_core::Model) -> Result<(), Fail> {
// The UI proof belongs to the [ui] host only (core already demands forward-auth for it).
let ui_host = self.cfg.ui.as_ref().and_then(|u| u.hostname.as_deref());
// A socket upstream likewise: only the [ui] host, and only control's own UI socket (a
// route file must not point edge at any other socket on the machine).
let ui_socket = self
.cfg
.ui
.as_ref()
.and_then(|u| u.socket.as_deref())
.and_then(|p| p.to_str());
for h in model.hosts() {
for (i, u) in h.upstreams.iter().enumerate() {
let Some(path) = u.unix_path() else { continue };
if ui_host == Some(h.hostname.as_str()) && ui_socket == Some(path) {
continue;
}
let p = messages::params([
("hostname", h.hostname.to_string()),
("url", u.to_string()),
]);
let fe = FieldError {
code: "host.upstream.unix_socket".into(),
message: message("host.upstream.unix_socket", &p),
field: Some(format!("upstreams[{i}]")),
params: p.clone(),
detail: None,
};
return Err(Fail {
status: 422,
reason: reason(
"apply.failed.validation",
messages::params([("first_error", fe.message.clone())]),
),
errors: vec![fe],
});
}
}
for h in model.hosts() {
let proof = h.request_headers.iter().any(|r| {
matches!(r, ianitor_core::HeaderRule::Set { value: ianitor_core::HeaderValue::Secret(s), .. } if s.as_str() == ianitor_core::UI_PROOF_SECRET)
});
if proof && ui_host != Some(h.hostname.as_str()) {
let p = messages::params([("hostname", h.hostname.to_string())]);
let fe = FieldError {
code: "host.header.proof_host".into(),
message: message("host.header.proof_host", &p),
field: Some("request_headers".into()),
params: p.clone(),
detail: None,
};
return Err(Fail {
status: 422,
reason: reason(
"apply.failed.validation",
messages::params([("first_error", fe.message.clone())]),
),
errors: vec![fe],
});
}
}
Ok(())
}
fn compile(&self, model: &ianitor_core::Model) -> Result<(String, String), Fail> {
let e = compile::edge(model, &self.cfg.compile.options());
let c = compile::caddy(model, &self.cfg.caddy_compile().options());
match (e, c) {
(Ok(e), Ok(c)) => Ok((e, c)),
(Err(x), _) | (_, Err(x)) => {
Err(Fail::new(500, "apply.failed.build", Params::new()).detail(x.to_string()))
}
}
}
fn head_and_tree(&self) -> Result<(String, Arc<RouteTree>), Fail> {
let head = self.repo.head_required().map_err(repo_fail)?;
let tree = self.repo.tree(&head).map_err(repo_fail)?;
Ok((head, tree))
}
/// Check a change now (for the 422/409 answers) and queue it. Returns the queued record.
pub fn submit(
&self,
change: Change,
base_rev: Option<String>,
actor: &str,
) -> Result<ApplyRecord, Fail> {
if let Some(p) = self.paused_for(&change, false) {
return Err(Fail::new(
409,
"control.paused",
messages::params([("reason", p.message)]),
));
}
let (head, tree) = self.head_and_tree()?;
let plan = self.plan(&change, &head, &tree, base_rev.as_deref())?;
self.compile(&plan.model)?;
let id = format!(
"ch_{}",
hex(&random::<6>()
.map_err(|e| Fail::new(500, "internal", Params::new()).detail(e.to_string()))?)
);
let mut rec = ApplyRecord::new(
id.clone(),
plan.kind,
plan.summary,
plan.hosts,
actor,
now(),
);
rec.attempted_host = plan.attempted;
rec.undo_of = plan.undo_of;
rec.restore_of = plan.restore_of;
rec.effect = plan.effect;
{
let mut q = self
.queue
.lock()
.map_err(|_| Fail::new(500, "internal", Params::new()))?;
if q.len() >= MAX_QUEUE {
return Err(Fail::new(
429,
"rate.limited",
messages::params([("seconds", "60".into())]),
));
}
let mut recs = self
.records
.lock()
.map_err(|_| Fail::new(500, "internal", Params::new()))?;
recs.push(rec.clone());
let excess = recs.len().saturating_sub(MAX_RECORDS);
recs.drain(..excess);
self.save_records(&recs);
q.push_back(Job {
id,
change,
base_rev,
});
}
self.wake.notify_one();
Ok(rec)
}
/// Check a host body against the current routes without applying it.
pub fn validate(&self, spec: &HostSpec, create: bool) -> Result<(), Fail> {
let (head, tree) = self.head_and_tree()?;
let change = Change::Put {
spec: spec.clone(),
create,
};
match self.plan(&change, &head, &tree, None) {
Ok(p) => self.compile(&p.model).map(|_| ()),
Err(f) if f.reason.code == "change.unchanged" => Ok(()),
Err(f) => Err(f),
}
}
/// Cancel a queued apply. `Ok(false)` if it is not queued any more.
pub fn cancel(&self, id: &str) -> bool {
let removed = match self.queue.lock() {
Ok(mut q) => {
let before = q.len();
q.retain(|j| j.id != id);
q.len() != before
}
Err(_) => false,
};
if removed {
let t = now();
self.update(id, |r| {
r.state = "failed".into();
r.finished = Some(t);
r.reason = Some(reason("apply.cancelled", Params::new()));
for s in &mut r.steps {
s.state = "skipped".into();
}
});
}
removed
}
// ------------------------------------------------------------ the worker
/// Run queued applies one at a time, forever.
pub async fn worker(self: Arc<Self>) {
loop {
let job = self.queue.lock().ok().and_then(|mut q| q.pop_front());
match job {
Some(j) => {
let me = self.clone();
// Its own task: a panic in one apply does not stop the worker.
let id = j.id.clone();
if let Err(e) = tokio::spawn(async move { me.run(j).await }).await {
log::error!(target: "ianitor::apply", "apply {id} crashed: {e}");
let t = now();
self.update(&id, |r| {
r.state = "failed".into();
r.finished = Some(t);
r.reason = Some(reason("internal", Params::new()));
});
}
}
None => self.wake.notified().await,
}
}
}
fn finish(&self, id: &str, state: &str, r: Option<Reason>, errors: Vec<FieldError>) {
let t = now();
self.update(id, |rec| {
rec.state = state.into();
rec.finished = Some(t);
rec.reason = r;
if !errors.is_empty() {
rec.errors = errors;
}
for s in &mut rec.steps {
if s.state == "running" {
s.state = if state == "kept" {
"done".into()
} else {
"failed".into()
};
} else if s.state == "pending" && s.key != "push" {
s.state = "skipped".into();
}
}
if state != "kept" {
rec.step("push", "skipped");
}
});
log::info!(target: "ianitor::apply", "apply {id}: {state}");
}
fn journal_path(&self) -> std::path::PathBuf {
self.cfg.state_dir.join("journal.json")
}
fn journal(&self, j: &Journal) -> Result<(), String> {
write_json(&self.journal_path(), j)
}
fn clear_journal(&self) {
if let Err(e) = remove_if_exists(&self.journal_path())
.and_then(|_| crate::util::sync_dir(&self.cfg.state_dir))
{
log::error!(target: "ianitor::apply", "cannot remove the journal: {e}");
}
}
async fn run(self: Arc<Self>, job: Job) {
let _lock = self.apply_lock.lock().await;
let id = job.id.clone();
let t = now();
self.update(&id, |r| {
r.state = "validating".into();
r.started = Some(t);
r.step("validate", "running");
});
self.retry_files().await;
if let Some(p) = self.paused_for(&job.change, true) {
return self.finish(
&id,
"failed",
Some(reason(
"control.paused",
messages::params([("reason", p.message)]),
)),
Vec::new(),
);
}
let (head, tree) = match self.head_and_tree() {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
};
let plan = match self.plan(&job.change, &head, &tree, job.base_rev.as_deref()) {
Ok(p) => p,
Err(f) => return self.finish(&id, "failed", Some(f.reason), f.errors),
};
self.update(&id, |r| {
r.step("validate", "done");
r.step("compile", "running");
r.base = Some(head.clone());
r.hosts = plan.hosts.clone();
if plan.effect.is_some() {
r.effect = plan.effect.clone();
}
});
let (edge_text, caddy_text) = match self.compile(&plan.model) {
Ok(x) => x,
Err(f) => return self.finish(&id, "failed", Some(f.reason), Vec::new()),
};
// Domi certificates for the hosts of the new tree, before anything is committed (new
// files only: a certificate edge serves now is never replaced by a worse one).
if let Err(f) = self.pki_prepare(&plan.model) {
return self.finish(&id, "failed", Some(f.reason), Vec::new());
}
self.update(&id, |r| {
r.step("compile", "done");
r.step("write", "running");
r.state = "applying".into();
});
let fail_internal = |e: String| {
Some(reason("internal", Params::new())).map(|mut r| {
r.detail = Some(e);
r
})
};
let tree_id = match self.repo.write_tree(&plan.target, None) {
Ok(t) => t,
Err(e) => return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new()),
};
let rec = self.record(&id);
let actor = rec.as_ref().map(|r| r.actor.clone()).unwrap_or_default();
let commit = match self.repo.commit(&tree_id, &[&head], &plan.summary, &actor) {
Ok(c) => c,
Err(e) => return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new()),
};
let mut j = Journal {
apply_id: id.clone(),
stage: "prepared".into(),
base: head.clone(),
commit: commit.clone(),
edge_sha256: None,
reason: None,
};
if let Err(e) = self.journal(&j) {
return self.finish(&id, "failed", fail_internal(e), Vec::new());
}
crash::point("prepared");
if let Err(e) = self.repo.update_ref(&commit, Some(&head)) {
self.clear_journal();
return self.finish(&id, "failed", fail_internal(e.to_string()), Vec::new());
}
self.update(&id, |r| r.commit = Some(commit.clone()));
j.stage = "committed".into();
if let Err(e) = self.journal(&j) {
// The journal still says `prepared` with this commit, which recovery also reverts.
return self
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
.await;
}
crash::point("committed");
if !self.edge.attached() {
// Development without an edge: write the files directly, nothing to watch.
let r = write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644));
self.clear_journal();
if let Err(e) = r {
return self
.revert(
&id,
&j,
fail_internal(e.to_string()).unwrap_or_default(),
"failed",
)
.await;
}
let push_step = self.push_step();
self.update(&id, |r| {
r.step("write", "done");
r.step("reload", "skipped");
r.step("watch", "skipped");
r.step("push", push_step);
});
self.finish(
&id,
"kept",
Some(reason("apply.kept.no_edge", Params::new())),
Vec::new(),
);
self.push_wake.notify_one();
return;
}
let trial = self.cfg.trial_path();
let caddy_trial = self.cfg.caddy_trial_path();
if let Err(e) = write_atomic(&trial, edge_text.as_bytes(), 0o644)
.and_then(|_| write_atomic(&caddy_trial, caddy_text.as_bytes(), 0o644))
{
return self
.revert(
&id,
&j,
fail_internal(e.to_string()).unwrap_or_default(),
"failed",
)
.await;
}
j.stage = "trial_written".into();
if let Err(e) = self.journal(&j) {
return self
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
.await;
}
crash::point("trial_written");
self.update(&id, |r| {
r.step("write", "done");
r.step("reload", "running");
});
// Caddy serves: load the trial into Caddy and watch through it (Mark, 2026-11-08).
if self.engine_running() == "caddy" {
return self
.run_under_caddy(&id, j, &plan, &caddy_text, &job.change)
.await;
}
// Which hosts to judge: those this change adds or changes, not those it removes.
let watch_hosts: Vec<String> = plan
.hosts
.iter()
.filter(|h| plan.target.host(h).is_some())
.cloned()
.collect();
let was_down = self.down_hosts();
let window = self.cfg.watch_secs;
let sha = match self
.edge
.trial(
window + self.cfg.trial_margin_secs,
&watch_hosts,
self.cfg.watch_every_secs,
)
.await
{
Ok(s) => s,
Err(EdgeLinkError::Refused { message: m, .. }) => {
let r = reason(
"apply.failed.reload",
messages::params([("engine", "Pingora".into())]),
);
return self
.revert(
&id,
&j,
Reason {
detail: Some(m),
..r
},
"failed",
)
.await;
}
Err(EdgeLinkError::Unreachable(m)) => {
let r = reason("apply.failed.edge_unreachable", Params::new());
return self
.revert(
&id,
&j,
Reason {
detail: Some(m),
..r
},
"failed",
)
.await;
}
};
j.stage = "trial_loaded".into();
j.edge_sha256 = Some(sha.clone());
let want = crate::util::sha256_hex(edge_text.as_bytes());
if sha != want {
let r = reason(
"apply.failed.reload",
messages::params([("engine", "Pingora".into())]),
);
let detail = format!(
"edge loaded a trial with SHA-256 {sha}, not the one control wrote ({want})"
);
return self
.revert(
&id,
&j,
Reason {
detail: Some(detail),
..r
},
"failed",
)
.await;
}
if let Err(e) = self.journal(&j) {
return self
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
.await;
}
crash::point("trial_loaded");
self.update(&id, |r| r.step("reload", "done"));
let judged: Vec<String> = watch_hosts
.iter()
.filter(|h| !was_down.contains(*h))
.cloned()
.collect();
let mut kept_reason = if watch_hosts.is_empty() {
reason(
"apply.kept.removed",
messages::params([("hostname", plan.hosts.join(", "))]),
)
} else {
reason(
"apply.kept",
messages::params([
("hostname", watch_hosts.join(", ")),
("seconds", window.to_string()),
]),
)
};
if judged.is_empty() {
self.update(&id, |r| r.step("watch", "skipped"));
} else {
let ends = now() + window;
self.update(&id, |r| {
r.state = "watching".into();
r.step("watch", "running");
r.watch = Some(Watch {
ends,
hosts: judged
.iter()
.map(|h| WatchHost {
hostname: h.clone(),
..Default::default()
})
.collect(),
});
});
match self.watch(&id, &sha, &judged, &plan, ends).await {
Ok(no_check) => {
if !no_check.is_empty() && no_check.len() == judged.len() {
kept_reason = reason(
"apply.kept.no_watch",
messages::params([("hostname", no_check.join(", "))]),
);
}
}
Err(r) => return self.revert(&id, &j, r, "reverted").await,
}
self.update(&id, |r| r.step("watch", "done"));
}
crash::point("watched");
if let Err(e) = self.edge.confirm(&sha).await {
let r = reason("apply.reverted.edge_lost", Params::new());
return self
.revert(
&id,
&j,
Reason {
detail: Some(e.to_string()),
..r
},
"reverted",
)
.await;
}
j.stage = "confirmed".into();
if let Err(e) = self.journal(&j) {
// Without a `confirmed` journal a crash would revert a kept change; so revert now
// (the revert also brings edge back to edge.json).
return self
.revert(&id, &j, fail_internal(e).unwrap_or_default(), "failed")
.await;
}
crash::point("confirmed");
let promoted = self.promote().or_else(|e| {
log::error!(target: "ianitor::apply", "cannot promote the trial files ({e}); writing them again");
write_atomic(&self.cfg.edge.config, edge_text.as_bytes(), 0o644)
.and_then(|_| write_atomic(&self.cfg.caddy.config, caddy_text.as_bytes(), 0o644))
});
if let Err(e) = promoted {
// Edge serves the change and the repository has it, but the files do not: keep
// the journal at `confirmed` (recovery promotes) and pause so nothing overwrites it.
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());
p.params.insert("apply_id".into(), id.clone());
if let Err(pe) = self.pause(p) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
let push_step = self.push_step();
self.update(&id, |r| r.step("push", push_step));
self.finish(&id, "kept", Some(kept_reason), Vec::new());
return;
}
j.stage = "promoted".into();
if let Err(e) = self.journal(&j) {
// Files are promoted; a stale `confirmed` journal only makes recovery promote again.
log::error!(target: "ianitor::apply", "{e}");
}
crash::point("promoted");
// Record first, journal last: a crash in between is finished again by recovery.
let push_step = self.push_step();
self.update(&id, |r| r.step("push", push_step));
self.finish(&id, "kept", Some(kept_reason), Vec::new());
self.clear_journal();
if self.paused().is_some() && matches!(job.change, Change::Restore { .. }) {
log::info!(target: "ianitor::apply", "a kept Restore ends the pause");
self.unpause();
}
self.push_wake.notify_one();
}
/// The push step of a kept apply: pending, or skipped when there is no remote.
fn push_step(&self) -> &'static str {
if self.cfg.routes.remote.is_some() {
"pending"
} else {
"skipped"
}
}
fn promote(&self) -> std::io::Result<()> {
for (trial, fin) in [
(self.cfg.trial_path(), self.cfg.edge.config.clone()),
(self.cfg.caddy_trial_path(), self.cfg.caddy.config.clone()),
] {
if trial.exists() {
rename_durable(&trial, &fin)?;
}
}
Ok(())
}
/// Hosts that were down (every upstream failed its last check) before this apply.
fn down_hosts(&self) -> BTreeSet<String> {
let Ok(h) = self.health.lock() else {
return BTreeSet::new();
};
h.since
.iter()
.filter(|(_, (s, _))| *s == "down")
.map(|(k, _)| k.clone())
.collect()
}
/// Watch the judged hosts until `ends`. `Ok(hosts that only had watch probes)`, or the
/// reason to revert.
async fn watch(
&self,
id: &str,
sha: &str,
hosts: &[String],
plan: &Plan,
ends: u64,
) -> Result<Vec<String>, Reason> {
let mut seen: HashMap<(String, String), BTreeMap<u64, Check>> = HashMap::new();
let mut unreachable_since: Option<u64> = None;
let mut first = true;
let health_path: HashMap<String, String> = plan
.model
.hosts()
.iter()
.map(|h| {
(
h.hostname.to_string(),
h.health_check
.as_ref()
.map_or("/".to_owned(), |c| c.path.clone()),
)
})
.collect();
let mut watch_only = Vec::new();
loop {
let st = match self.edge.status().await {
Ok(s) => {
unreachable_since = None;
s
}
Err(e) => {
let t = now();
let since = *unreachable_since.get_or_insert(t);
if t.saturating_sub(since) > 10 || t >= ends {
let r = reason("apply.reverted.edge_lost", Params::new());
return Err(Reason {
detail: Some(e.to_string()),
..r
});
}
tokio::time::sleep(Duration::from_secs(1)).await;
continue;
}
};
if st.config_sha256 != sha || st.trial.is_none() {
return Err(reason("apply.reverted.edge_lost", Params::new()));
}
if first {
crash::point("watching");
first = false;
}
let mut counts = Vec::new();
watch_only.clear();
for h in hosts {
let Some(hs) = st.hosts.iter().find(|x| &x.hostname == h) else {
continue;
};
if !hs.health_check {
watch_only.push(h.clone());
}
let (mut passed, mut failed) = (0u32, 0u32);
let mut all_failing = !hs.upstreams.is_empty();
for u in &hs.upstreams {
let m = seen.entry((h.clone(), u.address.clone())).or_default();
for c in &u.checks {
m.insert(c.seq, c.clone());
}
passed += m.values().filter(|c| c.ok).count() as u32;
failed += m.values().filter(|c| !c.ok).count() as u32;
let tail_failures = m.values().rev().take_while(|c| !c.ok).count();
if tail_failures < 3 {
all_failing = false;
}
}
counts.push(WatchHost {
hostname: h.clone(),
passed,
failed,
total: passed + failed,
});
if all_failing {
return Err(self.revert_reason(h, plan, &seen, &health_path));
}
}
self.update(id, |r| {
if let Some(w) = &mut r.watch {
w.hosts = counts;
}
});
if now() >= ends {
break;
}
tokio::time::sleep(Duration::from_secs(1)).await;
}
// At the end: every judged host needs an upstream whose last check passed.
for h in hosts {
let last_ok = seen
.iter()
.filter(|((host, _), _)| host == h)
.any(|(_, m)| m.values().next_back().is_some_and(|c| c.ok));
let any = seen.iter().any(|((host, _), m)| host == h && !m.is_empty());
if !any {
return Err(reason(
"apply.reverted.no_answer",
messages::params([
("hostname", h.clone()),
("verb", plan.verb.into()),
("seconds", self.cfg.watch_secs.to_string()),
]),
));
}
if !last_ok {
return Err(self.revert_reason(h, plan, &seen, &health_path));
}
}
Ok(watch_only)
}
fn revert_reason(
&self,
host: &str,
plan: &Plan,
seen: &HashMap<(String, String), BTreeMap<u64, Check>>,
paths: &HashMap<String, String>,
) -> Reason {
let mut worst: Option<(&String, &BTreeMap<u64, Check>)> = None;
for ((h, addr), m) in seen {
if h == host
&& m.values().next_back().is_some_and(|c| !c.ok)
&& worst.is_none_or(|(a, _)| addr < a)
{
worst = Some((addr, m));
}
}
let Some((addr, m)) = worst else {
return reason(
"apply.reverted.no_answer",
messages::params([
("hostname", host.into()),
("verb", plan.verb.into()),
("seconds", self.cfg.watch_secs.to_string()),
]),
);
};
let kind = m
.values()
.next_back()
.and_then(|c| c.kind.clone())
.unwrap_or_else(|| "server_error".into());
let code = match kind.as_str() {
"refused" | "timeout" | "name" | "tls" | "not_found" | "redirect" | "sign_in" => {
format!("apply.reverted.{kind}")
}
_ => "apply.reverted.server_error".into(),
};
let count = m.values().filter(|c| !c.ok).count();
let upstream_host = addr
.rsplit_once(':')
.map_or(addr.as_str(), |(h, _)| h)
.trim_start_matches('[')
.trim_end_matches(']')
.to_owned();
reason(
&code,
messages::params([
("hostname", host.into()),
("verb", plan.verb.into()),
("upstream", addr.clone()),
("upstream_host", upstream_host),
(
"path",
paths.get(host).cloned().unwrap_or_else(|| "/".into()),
),
("count", count.to_string()),
("of", m.len().to_string()),
]),
)
}
/// Undo a commit that is on the branch: abort the trial, git-revert, drop the trial files.
async fn revert(&self, id: &str, j: &Journal, why: Reason, state: &str) {
let mut j = j.clone();
j.stage = "reverting".into();
j.reason = Some(why.clone());
if let Err(e) = self.journal(&j) {
// The earlier stage stays on disk; recovery reverts from it too.
log::error!(target: "ianitor::apply", "{e}");
}
crash::point("reverting");
match self.finish_revert(&j).await {
Ok(rev) => {
self.update(id, |r| r.revert_commit = rev.or(r.revert_commit.clone()));
self.finish(id, state, Some(why), Vec::new());
self.clear_journal();
}
Err(e) => {
log::error!(target: "ianitor::apply", "apply {id}: the revert failed: {e}");
let mut r = reason("apply.needs_attention", Params::new());
r.detail = Some(format!("{}: {e}", why.message));
// The journal stays at `reverting`: a restart retries the revert, and even
// if the pause below cannot be saved, it never loads the unverified head.
if let Err(pe) = self.pause(r.clone()) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
self.finish(id, "needs_attention", Some(r), Vec::new());
}
}
}
/// The idempotent part of a revert. Returns the revert commit, if one was needed.
async fn finish_revert(&self, j: &Journal) -> Result<Option<String>, String> {
let caddy = self.engine_running() == "caddy";
if self.edge.attached() && !caddy {
match self.edge.abort().await {
Ok(_) => {}
// Edge down: it starts from edge.json, which is still the last good config.
Err(e) => {
log::warn!(target: "ianitor::apply", "could not tell edge to abort the trial: {e}")
}
}
}
let head = self.repo.head_required().map_err(|e| e.to_string())?;
let mut rev = None;
if head == j.commit {
let base_tree = self.repo.tree_id(&j.base).map_err(|e| e.to_string())?;
let subject = self
.repo
.info(&j.commit)
.map(|i| i.subject)
.unwrap_or_default();
let why = j
.reason
.as_ref()
.map(|r| r.message.clone())
.unwrap_or_default();
let msg = format!("Revert \"{subject}\"\n\n{why}\n");
let c = self
.repo
.commit(&base_tree, &[&j.commit], &msg, "Ianitor control")
.map_err(|e| e.to_string())?;
self.repo
.update_ref(&c, Some(&j.commit))
.map_err(|e| e.to_string())?;
rev = Some(c);
}
for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
remove_if_exists(&p).map_err(|e| e.to_string())?;
}
if caddy {
// 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);
}
// Edge must now run edge.json, the last good config. If it confirmed the trial after
// all (an answer lost on the way) it does not: reload it. If edge cannot be asked,
// this is not a finished revert (a restart asks again).
if self.edge.attached() {
let disk = std::fs::read(&self.cfg.edge.config)
.map_err(|e| format!("cannot read {}: {e}", self.cfg.edge.config.display()))?;
let want = crate::util::sha256_hex(&disk);
let mut status = self.edge.status().await;
for _ in 0..5 {
if status.is_ok() {
break;
}
tokio::time::sleep(Duration::from_secs(1)).await;
status = self.edge.status().await;
}
let st = status.map_err(|e| format!("cannot see which config edge runs: {e}"))?;
if st.trial.is_some() || st.config_sha256 != want {
log::warn!(target: "ianitor::apply", "edge does not run edge.json; reloading it");
if st.trial.is_some()
&& let Err(e) = self.edge.abort().await
{
log::warn!(target: "ianitor::apply", "edge did not abort its trial: {e}");
}
let got = self
.edge
.reload()
.await
.map_err(|e| format!("edge did not reload edge.json: {e}"))?;
if got != want {
return Err("edge reloaded, but not to edge.json".into());
}
}
}
Ok(rev)
}
// ------------------------------------------------------------ recovery
async fn recover(&self) -> Result<(), String> {
let _lock = self.apply_lock.lock().await;
let journal: Option<Journal> = read_json(&self.journal_path())?;
let mut keep_paused = false;
if let Some(j) = journal {
log::warn!(target: "ianitor::apply", "apply {} was interrupted at stage {}; recovering", j.apply_id, j.stage);
let head = self.repo.head_required().map_err(|e| e.to_string())?;
match j.stage.as_str() {
"prepared" if head != j.commit => {
self.finish(
&j.apply_id,
"failed",
Some(reason("apply.interrupted.queued", Params::new())),
Vec::new(),
);
self.clear_journal();
}
"confirmed" | "promoted" => {
if let Err(e) = self.promote() {
// Start anyway, paused: edge serves the change, the files lag behind.
log::error!(target: "ianitor::apply", "cannot promote the trial files at start: {e}");
let mut p = reason("control.files_unwritten", Params::new());
p.detail = Some(e.to_string());
p.params.insert("apply_id".into(), j.apply_id.clone());
if let Err(pe) = self.pause(p) {
log::error!(target: "ianitor::apply", "cannot save the pause ({pe}); the journal keeps it");
}
keep_paused = true;
self.finish(&j.apply_id, "kept", None, Vec::new());
} else {
let push_step = self.push_step();
self.update(&j.apply_id, |r| r.step("push", push_step));
let kept = self
.record(&j.apply_id)
.and_then(|r| r.reason.filter(|x| x.code.starts_with("apply.kept")));
self.finish(&j.apply_id, "kept", kept, Vec::new());
self.clear_journal();
}
}
_ => {
let mut why = j
.reason
.clone()
.unwrap_or_else(|| reason("apply.interrupted", Params::new()));
if j.reason.is_none() {
why.detail = Some(format!("control stopped at stage {}", j.stage));
}
let mut jj = j.clone();
jj.reason = Some(why.clone());
match self.finish_revert(&jj).await {
Ok(rev) => {
self.update(&j.apply_id, |r| {
r.commit = r.commit.clone().or(Some(j.commit.clone()));
r.revert_commit = rev.or(r.revert_commit.clone());
});
// A revert that was already under way keeps its own outcome.
let state = if why.code.starts_with("apply.failed") {
"failed"
} else {
"reverted"
};
self.finish(&j.apply_id, state, Some(why), Vec::new());
self.clear_journal();
if self
.paused()
.is_some_and(|p| p.code == "apply.needs_attention")
{
log::info!(target: "ianitor::apply", "the interrupted revert is done; changes resume");
self.unpause();
}
}
Err(e) => {
// Journal kept: the next start tries again.
let mut r = reason("apply.needs_attention", Params::new());
r.detail = Some(e);
if let Err(pe) = self.pause(r.clone()) {
log::error!(target: "ianitor::apply", "cannot save the pause: {pe}");
}
self.finish(&j.apply_id, "needs_attention", Some(r), Vec::new());
}
}
}
}
}
// Applies that were still queued never ran.
let stale: Vec<String> = self
.records()
.iter()
.filter(|r| r.is_active())
.map(|r| r.id.clone())
.collect();
for id in stale {
let code = if self.record(&id).is_some_and(|r| r.state == "queued") {
"apply.interrupted.queued"
} else {
"apply.interrupted"
};
self.finish(&id, "failed", Some(reason(code, Params::new())), Vec::new());
}
// A trial nobody owns any more.
if self.edge.attached()
&& let Ok(st) = self.edge.status().await
&& st.trial.is_some()
&& let Err(e) = self.edge.abort().await
{
log::warn!(target: "ianitor::control", "edge did not abort a leftover trial: {e}");
}
// An apply whose revert failed left an unverified commit at the branch head: edge keeps
// the last good config until a Restore. Any other pause is re-checked now.
if self
.paused()
.is_some_and(|p| p.code == "apply.needs_attention")
{
log::warn!(target: "ianitor::control", "changes are paused (needs attention); edge keeps the last good config until a Restore");
} else if keep_paused {
log::warn!(target: "ianitor::control", "changes are paused until the config files can be written");
} else {
self.unpause();
self.sync_files().await;
}
if self.engine_running() == "caddy" {
match self.caddy_reload().await {
Ok(()) => crate::caddy_guard::disarm(&self.cfg.state_dir),
Err(e) => {
log::warn!(target: "ianitor::control", "Caddy did not load caddy.json at start: {e}")
}
}
} else {
crate::caddy_guard::disarm(&self.cfg.state_dir);
}
if let Err(e) = self.shares.ensure_revocation_file() {
log::error!(target: "ianitor::share", "{e}");
}
Ok(())
}
/// Make edge.json, caddy.json and edge agree with the branch head. Only at start, under
/// the apply lock (from `recover`). The files and the journal are written only by the apply
/// worker (`run`, `revert`, `retry_files`) and by `recover`, all under that lock.
async fn sync_files(&self) {
let (_, tree) = match self.head_and_tree() {
Ok(x) => x,
Err(f) => {
log::error!(target: "ianitor::control", "{}", f.reason.message);
if let Err(e) = self.pause(f.reason) {
log::error!(target: "ianitor::control", "cannot save the pause: {e}");
}
return;
}
};
let model = match tree.model() {
Ok(m) => m,
Err(errs) => {
let fe = field_errors(&errs);
let file = errs
.errors()
.first()
.map(|e| e.file().to_owned())
.unwrap_or_default();
let mut r = reason("repo.unreadable", messages::params([("file", file)]));
r.detail = fe.first().and_then(|e| e.detail.clone());
log::error!(target: "ianitor::control", "the routes repository does not validate: {}", r.detail.clone().unwrap_or_default());
if let Err(e) = self.pause(r) {
log::error!(target: "ianitor::control", "cannot save the pause: {e}");
}
return;
}
};
// A tree kept under an earlier control.toml may break today's rules (a changed [ui]
// hostname or socket): it is not written to the engines, and the reason is logged; the
// engines keep the last files written. The next apply is refused for the same reason.
if let Err(f) = self.policy(&model) {
let detail = f
.errors
.first()
.map(|e| e.message.clone())
.unwrap_or_else(|| f.reason.message.clone());
log::error!(target: "ianitor::control", "the routes repository breaks control's rules ({detail}); the engines keep the files they have");
return;
}
let Ok((edge_text, caddy_text)) = self.compile(&model) else {
return;
};
let mut changed = false;
for (path, text) in [
(&self.cfg.edge.config, &edge_text),
(&self.cfg.caddy.config, &caddy_text),
] {
if std::fs::read(path).ok().as_deref() != Some(text.as_bytes()) {
if let Err(e) = write_atomic(path, text.as_bytes(), 0o644) {
log::error!(target: "ianitor::control", "cannot write {}: {e}", path.display());
}
changed = true;
}
}
if self.edge.attached() {
let want = crate::util::sha256_hex(edge_text.as_bytes());
let running = self.edge.status().await.ok().map(|s| s.config_sha256);
if changed || running.as_deref().is_some_and(|r| r != want) {
match self.edge.reload().await {
Ok(_) => {
log::info!(target: "ianitor::control", "edge reloaded to match the routes repository")
}
Err(e) => {
log::warn!(target: "ianitor::control", "edge reload after recovery: {e}")
}
}
}
}
}
// ------------------------------------------------------------ share links
/// Tell edge the revocation file changed (it also notices by itself within 5 s).
pub async fn revocations_changed(&self) {
if self.edge.attached()
&& let Err(e) = self.edge.reload_revocations().await
{
log::warn!(target: "ianitor::share", "edge did not reload the revocation file now ({e}); it will within 5 s");
}
}
/// The validated model at the branch head.
pub fn head_model(&self) -> Result<(String, Arc<RouteTree>, ianitor_core::Model), Fail> {
let (head, tree) = self.head_and_tree()?;
let model = tree.model().map_err(|errs| {
let mut f = Fail::new(
409,
"repo.unreadable",
messages::params([(
"file",
errs.errors()
.first()
.map(|e| e.file().to_owned())
.unwrap_or_default(),
)]),
);
f.errors = field_errors(&errs);
f
})?;
Ok((head, tree, model))
}
// ------------------------------------------------------------ background
/// Read health from edge every few seconds for the overview.
pub async fn health_poller(self: Arc<Self>) {
loop {
let st = self.edge.status().await;
if let Ok(mut h) = self.health.lock() {
let t = now();
h.read_at = Some(t);
match st {
Ok(s) => {
let mut since = HashMap::new();
for host in &s.hosts {
let state = crate::api::health_state(host);
let prev = h.since.get(&host.hostname).copied();
let start = match prev {
Some((p, at)) if p == state => at,
_ => t,
};
since.insert(host.hostname.clone(), (state, start));
}
h.since = since;
h.status = Some(s);
h.error = None;
}
Err(e) => {
h.error = Some(e.to_string());
}
}
}
tokio::time::sleep(Duration::from_secs(self.cfg.health_poll_secs.max(1))).await;
}
}
/// Push kept changes to the remote; retry with backoff on failure.
pub async fn pusher(self: Arc<Self>) {
let Some(remote) = self.cfg.routes.remote.clone() else {
return;
};
loop {
let wait = self.push_once(&remote).await;
tokio::select! {
_ = self.push_wake.notified() => {}
_ = tokio::time::sleep(wait) => {}
}
}
}
/// One push attempt. Returns how long to wait before the next.
pub async fn push_once(&self, remote: &str) -> Duration {
// Only push a settled head: never in the middle of an apply.
let head = {
let _lock = self.apply_lock.lock().await;
match self.repo.head_required() {
Ok(h) => h,
Err(_) => return Duration::from_secs(60),
}
};
let state = self.push_state();
if state.pushed.as_deref() == Some(head.as_str()) {
return Duration::from_secs(3600);
}
let askpass = self.cfg.routes.push_credential.as_ref().and_then(|c| {
let file = self.cfg.credentials_dir()?.join(c);
let exe = std::env::current_exe().ok()?;
Some((exe, self.cfg.routes.push_username.clone(), file))
});
let t = now();
let result = self
.repo
.push(remote, &head, askpass, Duration::from_secs(60))
.await;
let mut next = Duration::from_secs(3600);
if let Ok(mut p) = self.push.lock() {
p.last_attempt_at = Some(t);
match result {
Ok(()) => {
p.pushed = Some(head.clone());
p.last_push_at = Some(now());
p.error_code = None;
p.error_detail = None;
p.failures = 0;
p.next_try_at = None;
log::info!(target: "ianitor::push", "pushed {} to the remote", short(&head));
}
Err(e) => {
let text = e.to_string();
let low = text.to_ascii_lowercase();
let code = if low.contains("rejected")
|| low.contains("non-fast-forward")
|| low.contains("fetch first")
{
"push.failed.rejected"
} else if low.contains("authentication failed")
|| low.contains(" 401")
|| low.contains(" 403")
|| low.contains("permission denied (publickey")
|| low.contains("could not read username")
|| low.contains("could not read password")
{
"push.failed.auth"
} else {
"push.failed.unreachable"
};
p.failures = p.failures.saturating_add(1);
let secs = (30u64 << p.failures.min(7)).min(3600);
next = Duration::from_secs(secs);
p.next_try_at = Some(now() + secs);
p.error_code = Some(code.into());
p.error_detail = Some(text.chars().take(300).collect());
log::warn!(target: "ianitor::push", "push failed ({code}); next try in {secs} s");
}
}
let _ = write_json(&self.cfg.state_dir.join("push.json"), &*p);
}
// Mark records whose commit is now pushed.
let pushed = self.push_state().pushed;
if let Ok(mut recs) = self.records.lock() {
for r in recs
.iter_mut()
.rev()
.filter(|r| {
r.state == "kept"
&& r.steps.iter().any(|s| s.key == "push" && s.state != "done")
})
.take(50)
{
let s = match (&pushed, &r.commit) {
(Some(p), Some(c))
if p == c || self.repo.count_between(Some(p), c).ok() == Some(0) =>
{
"done"
}
_ if self.push_state().error_code.is_some() => "failed",
_ => "pending",
};
r.step("push", s);
}
self.save_records(&recs);
}
next
}
}
fn changed_hosts(a: &RouteTree, b: &RouteTree) -> Vec<String> {
let mut names: BTreeSet<String> = a.hostnames().into_iter().collect();
names.extend(b.hostnames());
names
.into_iter()
.filter(|h| a.host(h) != b.host(h))
.collect()
}
/// What going from `from` to `to` does, in the Undo bar's words.
fn effect_text(from: &RouteTree, to: &RouteTree) -> String {
let parts: Vec<String> = changed_hosts(from, to)
.into_iter()
.map(|h| match (from.host(&h).is_some(), to.host(&h).is_some()) {
(true, false) => format!("Removes {h}"),
(false, true) => format!("Adds {h} back"),
_ => format!("Changes {h} back"),
})
.collect();
if parts.is_empty() {
"Changes the site settings back".into()
} else {
parts.join("; ")
}
}