1600 lines
58 KiB
Rust
1600 lines
58 KiB
Rust
// 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 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)]
|
|
|
|
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, ¶ms),
|
|
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(), ¶ms),
|
|
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>,
|
|
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>>,
|
|
/// Serialises applies with share-revocation writes and recovery.
|
|
apply_lock: tokio::sync::Mutex<()>,
|
|
}
|
|
|
|
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 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,
|
|
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),
|
|
apply_lock: tokio::sync::Mutex::new(()),
|
|
cfg,
|
|
});
|
|
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())
|
|
}
|
|
|
|
fn pause(&self, r: Reason) {
|
|
let _ = write_json(&self.cfg.state_dir.join("paused.json"), &r);
|
|
if let Ok(mut p) = self.paused.lock() {
|
|
*p = Some(r);
|
|
}
|
|
}
|
|
|
|
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,
|
|
}
|
|
})?;
|
|
Ok(Plan {
|
|
kind,
|
|
verb: host_verb(kind),
|
|
summary,
|
|
hosts,
|
|
target,
|
|
model,
|
|
attempted,
|
|
undo_of,
|
|
restore_of,
|
|
effect,
|
|
})
|
|
}
|
|
|
|
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() {
|
|
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");
|
|
});
|
|
if let Some(p) = self.paused() {
|
|
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()),
|
|
};
|
|
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) {
|
|
log::error!(target: "ianitor::apply", "{e}");
|
|
}
|
|
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();
|
|
let _ = self.journal(&j);
|
|
crash::point("trial_written");
|
|
self.update(&id, |r| {
|
|
r.step("write", "done");
|
|
r.step("reload", "running");
|
|
});
|
|
|
|
// 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 _ = self.journal(&j);
|
|
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();
|
|
let _ = self.journal(&j);
|
|
crash::point("confirmed");
|
|
if let Err(e) = self.promote() {
|
|
// Edge serves the new config and the repository has it; the files catch up at
|
|
// the next start (recovery promotes again).
|
|
log::error!(target: "ianitor::apply", "cannot promote the trial files: {e}");
|
|
}
|
|
j.stage = "promoted".into();
|
|
let _ = self.journal(&j);
|
|
crash::point("promoted");
|
|
self.clear_journal();
|
|
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.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());
|
|
let _ = self.journal(&j);
|
|
crash::point("reverting");
|
|
match self.finish_revert(&j).await {
|
|
Ok(rev) => {
|
|
self.update(id, |r| r.revert_commit = rev);
|
|
self.clear_journal();
|
|
self.finish(id, state, Some(why), Vec::new());
|
|
}
|
|
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));
|
|
self.pause(r.clone());
|
|
self.clear_journal();
|
|
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> {
|
|
if self.edge.attached() {
|
|
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())?;
|
|
}
|
|
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())?;
|
|
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.clear_journal();
|
|
self.finish(
|
|
&j.apply_id,
|
|
"failed",
|
|
Some(reason("apply.interrupted.queued", Params::new())),
|
|
Vec::new(),
|
|
);
|
|
}
|
|
"confirmed" | "promoted" => {
|
|
self.promote().map_err(|e| e.to_string())?;
|
|
self.clear_journal();
|
|
let push_step = self.push_step();
|
|
self.update(&j.apply_id, |r| r.step("push", push_step));
|
|
self.finish(&j.apply_id, "kept", None, Vec::new());
|
|
}
|
|
_ => {
|
|
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;
|
|
});
|
|
self.clear_journal();
|
|
// 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());
|
|
}
|
|
Err(e) => {
|
|
let mut r = reason("apply.needs_attention", Params::new());
|
|
r.detail = Some(e);
|
|
self.pause(r.clone());
|
|
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 _ = self.edge.abort().await;
|
|
}
|
|
self.sync_files().await;
|
|
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.
|
|
pub 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);
|
|
self.pause(f.reason);
|
|
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());
|
|
self.pause(r);
|
|
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("; ")
|
|
}
|
|
}
|