[control] Pause fixes: Restore waits until an unsaved pause is on disk, unwritable config files pause with a way out, a failed promote at start starts paused, a revert that cannot see edge is not reverted

This commit is contained in:
2026-11-07 19:17:16 +01:00
parent 339882ec96
commit dd10557b87
4 changed files with 212 additions and 38 deletions
+136 -25
View File
@@ -148,6 +148,8 @@ pub struct Control {
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.
apply_lock: tokio::sync::Mutex<()>,
}
@@ -222,6 +224,7 @@ impl Control {
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(()),
cfg,
});
@@ -278,14 +281,74 @@ impl Control {
/// 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`: write both files from the branch head
/// (which edge already serves) and drop the `confirmed` journal.
fn retry_files(&self) -> bool {
if self
.paused()
.is_none_or(|p| p.code != "control.files_unwritten")
{
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))
.and_then(|_| remove_if_exists(&self.cfg.trial_path()))
.and_then(|_| remove_if_exists(&self.cfg.caddy_trial_path()))
.map_err(|e| e.to_string())
});
match written {
Ok(()) => {
log::info!(target: "ianitor::apply", "the config files are written now; changes resume");
self.clear_journal();
self.unpause();
true
}
Err(e) => {
log::error!(target: "ianitor::apply", "the config files still cannot be written: {e}");
false
}
}
}
fn unpause(&self) {
let _ = remove_if_exists(&self.cfg.state_dir.join("paused.json"));
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;
}
@@ -293,10 +356,29 @@ impl Control {
/// 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.
fn paused_for(&self, change: &Change) -> Option<Reason> {
self.retry_files();
let p = self.paused()?;
let way_out = matches!(change, Change::Restore { .. }) && p.code == "apply.needs_attention";
(!way_out).then_some(p)
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 {
@@ -1301,20 +1383,6 @@ impl Control {
log::warn!(target: "ianitor::apply", "could not tell edge to abort the trial: {e}")
}
}
// If edge confirmed the trial after all (an answer lost on the way), it still runs
// the reverted config: reload it from edge.json, the last good config.
if let (Ok(st), Ok(disk)) = (
self.edge.status().await,
std::fs::read(&self.cfg.edge.config),
) && st.trial.is_none()
&& st.config_sha256 != crate::util::sha256_hex(&disk)
{
log::warn!(target: "ianitor::apply", "edge runs a config that is not edge.json; reloading it");
self.edge
.reload()
.await
.map_err(|e| format!("edge did not reload edge.json: {e}"))?;
}
}
let head = self.repo.head_required().map_err(|e| e.to_string())?;
let mut rev = None;
@@ -1343,6 +1411,37 @@ impl Control {
for p in [self.cfg.trial_path(), self.cfg.caddy_trial_path()] {
remove_if_exists(&p).map_err(|e| e.to_string())?;
}
// 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 _ = self.edge.abort().await;
}
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)
}
@@ -1351,6 +1450,7 @@ impl Control {
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())?;
@@ -1365,14 +1465,23 @@ impl Control {
self.clear_journal();
}
"confirmed" | "promoted" => {
self.promote().map_err(|e| e.to_string())?;
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();
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());
let _ = self.pause(p);
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
@@ -1448,6 +1557,8 @@ impl Control {
.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;
-1
View File
@@ -187,7 +187,6 @@ impl Shares {
// Readable by edge (another user); it holds only random link ids.
let text =
serde_json::to_vec(&RevocationFile { epoch, deny }).map_err(|e| e.to_string())?;
crate::crash::fail_write(&self.revocations)?;
crate::util::write_atomic(&self.revocations, &text, 0o644)
.map_err(|e| format!("cannot write {}: {e}", self.revocations.display()))
}
+2 -1
View File
@@ -55,6 +55,7 @@ pub fn ct_eq(a: &[u8], b: &[u8]) -> bool {
/// the new content survives a crash once this returns: temporary file in the same directory,
/// fsync, rename, fsync of the directory.
pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()> {
crate::crash::fail_write(path).map_err(std::io::Error::other)?;
let dir = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
@@ -80,6 +81,7 @@ pub fn write_atomic(path: &Path, data: &[u8], mode: u32) -> std::io::Result<()>
/// Rename `from` to `to` atomically and durably.
pub fn rename_durable(from: &Path, to: &Path) -> std::io::Result<()> {
crate::crash::fail_write(to).map_err(std::io::Error::other)?;
std::fs::rename(from, to)?;
sync_dir(to.parent().unwrap_or(Path::new(".")))
}
@@ -114,7 +116,6 @@ pub fn read_json<T: DeserializeOwned>(path: &Path) -> Result<Option<T>, String>
/// Write a JSON state file atomically, readable by its owner only.
pub fn write_json<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
crate::crash::fail_write(path)?;
let mut text = serde_json::to_vec_pretty(value).map_err(|e| e.to_string())?;
text.push(b'\n');
write_atomic(path, &text, 0o600).map_err(|e| format!("cannot write {}: {e}", path.display()))
+74 -11
View File
@@ -575,16 +575,29 @@ mod unix {
let good = Echo::start("good").await;
let sick = Echo::start("sick").await;
sick.health.store(500, std::sync::atomic::Ordering::SeqCst);
let mut env = Env::new(EnvSpec { watch_secs: 3, ..Default::default() }).await;
let mut env = Env::new(EnvSpec {
watch_secs: 3,
..Default::default()
})
.await;
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "paused.json")]);
let kept = env.add_host(host("a.test", &good.url(), true)).await;
let good_edge = env.file("edge/edge.json");
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": host("b.test", &sick.url(), true) })))
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &sick.url(), true) })),
)
.await;
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
let deadline = std::time::Instant::now() + Duration::from_secs(10);
while env.call("GET", &format!("/api/v1/applies/{id}"), None).await.json["commit"].is_null() {
while env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await
.json["commit"]
.is_null()
{
assert!(std::time::Instant::now() < deadline);
tokio::time::sleep(Duration::from_millis(20)).await;
}
@@ -594,16 +607,21 @@ mod unix {
assert_eq!(rec["state"], "needs_attention", "{rec}");
// Restore (the way out) while the pause still cannot be saved: refused, journal kept.
let r = env
.call("POST", "/api/v1/restore", Some(json!({ "change_id": kept["id"] })))
.call(
"POST",
"/api/v1/restore",
Some(json!({ "change_id": kept["id"] })),
)
.await;
if r.status == 202 {
env.wait_apply(r.json["apply"]["id"].as_str().unwrap()).await;
env.wait_apply(r.json["apply"]["id"].as_str().unwrap())
.await;
} else {
assert_eq!(r.status, 409, "{}", r.text);
assert_eq!(r.json["error"]["code"], "control.paused", "{}", r.text);
}
let j: serde_json::Value =
serde_json::from_str(&env.file("state/journal.json")).expect("the reverting journal is kept");
let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json"))
.expect("the reverting journal is kept");
assert_eq!(j["stage"], "reverting", "{j}");
// The cause goes away; control restarts and finishes the revert, never loading the
// unverified head.
@@ -615,17 +633,60 @@ mod unix {
env.assert_consistent().await;
}
/// QC fix round 2: when the config files cannot be written after a confirmed apply,
/// control pauses with the journal kept, still starts (paused) if they cannot be written
/// at the next start either, and resumes once they can.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn unwritable_config_files_pause_and_never_stop_control_from_starting() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec::default()).await;
env.start_control(None);
assert_eq!(env.add_host(host("a.test", &good.url(), false)).await["state"], "kept");
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]);
let r = env.add_host(host("b.test", &good.url(), false)).await;
assert_eq!(r["state"], "kept", "{r}");
let j: serde_json::Value = serde_json::from_str(&env.file("state/journal.json")).expect("journal kept");
assert_eq!(j["stage"], "confirmed", "{j}");
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
// Restart while the file still cannot be written: control starts, paused.
env.kill_control();
env.start_control_env(None, &[("IANITOR_TEST_FAIL_WRITE", "edge.json")]);
let o = env.call("GET", "/api/v1/overview", None).await;
assert_eq!(o.status, 200);
assert_eq!(o.json["paused"]["code"], "control.paused", "{}", o.text);
// Once it can be written, a restart finishes the promotion and changes resume.
env.kill_control();
env.start_control(None);
let o = env.call("GET", "/api/v1/overview", None).await;
assert!(o.json["paused"].is_null(), "{}", o.text);
assert!(env.head_files().iter().any(|(p, _)| p == "hosts/b.test.toml"));
env.assert_consistent().await;
}
/// Edge gone while a revert runs: control cannot see what edge serves, so it does not
/// claim `reverted`; it pauses, and a restart with edge back finishes the job.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_revert_that_cannot_see_edge_ends_as_needs_attention() {
let good = Echo::start("good").await;
let mut env = Env::new(EnvSpec { watch_secs: 3, ..Default::default() }).await;
let mut env = Env::new(EnvSpec {
watch_secs: 3,
..Default::default()
})
.await;
env.start_control(None);
assert_eq!(env.add_host(host("a.test", &good.url(), true)).await["state"], "kept");
assert_eq!(
env.add_host(host("a.test", &good.url(), true)).await["state"],
"kept"
);
let good_edge = env.file("edge/edge.json");
let r = env
.call("POST", "/api/v1/hosts", Some(json!({ "host": host("b.test", &good.url(), true) })))
.call(
"POST",
"/api/v1/hosts",
Some(json!({ "host": host("b.test", &good.url(), true) })),
)
.await;
let id = r.json["apply"]["id"].as_str().unwrap().to_owned();
tokio::time::sleep(Duration::from_millis(1500)).await;
@@ -635,7 +696,9 @@ mod unix {
env.start_edge();
env.kill_control();
env.start_control(None);
let rec = env.call("GET", &format!("/api/v1/applies/{id}"), None).await;
let rec = env
.call("GET", &format!("/api/v1/applies/{id}"), None)
.await;
assert_eq!(rec.json["state"], "reverted", "{}", rec.text);
assert_eq!(env.edge_status().await["config_sha256"], sha256(&good_edge));
env.assert_consistent().await;