diff --git a/crates/control/src/engine.rs b/crates/control/src/engine.rs index 857bbf8..19ccbeb 100644 --- a/crates/control/src/engine.rs +++ b/crates/control/src/engine.rs @@ -311,15 +311,17 @@ impl Control { } } - /// 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 + /// 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() - .is_none_or(|p| p.code != "control.files_unwritten") - { + .filter(|p| p.code == "control.files_unwritten") + else { return false; - } + }; let written = self .head_model() .map_err(|f| f.reason.message) @@ -327,22 +329,48 @@ impl Control { 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()) + .map_err(|e| e.to_string())?; + Ok(crate::util::sha256_hex(e.as_bytes())) }); - match written { - Ok(()) => { - log::info!(target: "ianitor::apply", "the config files are written now; changes resume"); - self.clear_journal(); - self.unpause(); - true - } + let want = match written { + Ok(w) => w, Err(e) => { log::error!(target: "ianitor::apply", "the config files still cannot be written: {e}"); - false + 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::(&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) { @@ -359,9 +387,13 @@ impl Control { /// /// 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 { - self.retry_files(); + /// `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 { 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" @@ -625,7 +657,7 @@ impl Control { base_rev: Option, actor: &str, ) -> Result { - if let Some(p) = self.paused_for(&change) { + if let Some(p) = self.paused_for(&change, false) { return Err(Fail::new( 409, "control.paused", @@ -798,7 +830,8 @@ impl Control { r.started = Some(t); r.step("validate", "running"); }); - if let Some(p) = self.paused_for(&job.change) { + self.retry_files().await; + if let Some(p) = self.paused_for(&job.change, true) { return self.finish( &id, "failed", @@ -1104,7 +1137,10 @@ impl Control { 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()); - let _ = self.pause(p); + 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()); @@ -1429,8 +1465,10 @@ impl Control { 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; + 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 @@ -1470,7 +1508,10 @@ impl Control { 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); + 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 { @@ -1547,8 +1588,9 @@ impl Control { if self.edge.attached() && let Ok(st) = self.edge.status().await && st.trial.is_some() + && let Err(e) = self.edge.abort().await { - let _ = 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. @@ -1569,13 +1611,17 @@ impl Control { Ok(()) } - /// Make edge.json, caddy.json and edge agree with the branch head. - pub async fn sync_files(&self) { + /// 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); - let _ = self.pause(f.reason); + if let Err(e) = self.pause(f.reason) { + log::error!(target: "ianitor::control", "cannot save the pause: {e}"); + } return; } }; @@ -1591,7 +1637,9 @@ impl Control { 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()); - let _ = self.pause(r); + if let Err(e) = self.pause(r) { + log::error!(target: "ianitor::control", "cannot save the pause: {e}"); + } return; } }; diff --git a/crates/control/src/main.rs b/crates/control/src/main.rs index a4c5332..063e2b3 100644 --- a/crates/control/src/main.rs +++ b/crates/control/src/main.rs @@ -85,19 +85,34 @@ fn state_dir(args: &[String]) -> Result { #[cfg(unix)] fn same_owner(dir: &std::path::Path) -> Result<(), String> { use std::os::unix::fs::MetadataExt; - let owner = std::fs::metadata(dir) - .map_err(|e| format!("cannot read {}: {e}", dir.display()))? + let existing = dir + .ancestors() + .find(|p| p.is_dir()) + .ok_or_else(|| format!("no part of {} exists", dir.display()))?; + let owner = std::fs::metadata(existing) + .map_err(|e| format!("cannot read {}: {e}", existing.display()))? .uid(); - let probe = dir.join(format!(".owner-probe-{}", std::process::id())); - let me = std::fs::File::create(&probe) + // Who we are, without libc: the owner of a file we create (in the temp dir, so nothing is + // created in the state dir by the wrong user). + let probe = std::env::temp_dir().join(format!(".ianitor-owner-probe-{}", std::process::id())); + // create_new: never follows or reuses a file someone else put there. + let me = std::fs::File::create_new(&probe) .and_then(|f| f.metadata()) .map(|m| m.uid()); - let _ = std::fs::remove_file(&probe); - let me = me.map_err(|e| format!("cannot write in {}: {e}", dir.display()))?; + if me.is_ok() { + let _ = std::fs::remove_file(&probe); + } + let me = me.map_err(|e| format!("cannot create a probe file to learn who runs this: {e}"))?; + if me == 0 && !dir.is_dir() { + return Err(format!( + "{} does not exist; create it as the user control runs as (or run this as that user), not as root", + dir.display() + )); + } if me != owner { return Err(format!( "{} belongs to uid {owner}, but this runs as uid {me}; run it as that user (e.g. sudo -u ianitor ianitor-control token ...)", - dir.display() + existing.display() )); } Ok(()) @@ -110,8 +125,10 @@ fn same_owner(_: &std::path::Path) -> Result<(), String> { fn token(args: &[String]) -> Result<(), String> { let dir = state_dir(args)?; - std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; + // Check the owner before creating anything: the nearest existing ancestor must belong to + // whoever runs this (so root does not create a state dir control cannot use). same_owner(&dir)?; + std::fs::create_dir_all(&dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?; let tokens = Tokens::new(&dir); match args.first().map(String::as_str) { Some("create") => { diff --git a/crates/control/tests/apply.rs b/crates/control/tests/apply.rs index c195b3e..fef8c46 100644 --- a/crates/control/tests/apply.rs +++ b/crates/control/tests/apply.rs @@ -679,15 +679,24 @@ mod unix { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn a_request_during_a_restore_watch_never_writes_the_unverified_head() { async fn upstream_of(env: &Env) -> String { - let r = client::https(env.opts.https_listen, "a.test", env.roots(), &Req::get("a.test", "/")) - .await - .unwrap(); + let r = client::https( + env.opts.https_listen, + "a.test", + env.roots(), + &Req::get("a.test", "/"), + ) + .await + .unwrap(); let v: serde_json::Value = serde_json::from_slice(&r.body).unwrap_or_default(); format!("{} {}", r.status, v["upstream"].as_str().unwrap_or("?")) } let one = Echo::start("one").await; let two = Echo::start("two").await; - let mut env = Env::new(EnvSpec { watch_secs: 4, ..Default::default() }).await; + let mut env = Env::new(EnvSpec { + watch_secs: 4, + ..Default::default() + }) + .await; env.start_control(None); let kept1 = env.add_host(host("a.test", &one.url(), true)).await; assert_eq!(kept1["state"], "kept"); @@ -697,35 +706,64 @@ mod unix { std::fs::create_dir(&ej).unwrap(); std::fs::write(ej.join("x"), "x").unwrap(); let r = env - .apply("PUT", "/api/v1/hosts/a.test", Some(json!({ "host": host("a.test", &two.url(), true) }))) + .apply( + "PUT", + "/api/v1/hosts/a.test", + Some(json!({ "host": host("a.test", &two.url(), true) })), + ) .await; assert_eq!(r["state"], "kept", "{r}"); assert_eq!(upstream_of(&env).await, "200 two"); // Restore the first version; its upstream is sick now, so its watch will fail. one.health.store(500, std::sync::atomic::Ordering::SeqCst); - let r = env.call("POST", "/api/v1/restore", Some(json!({ "change_id": kept1["id"] }))).await; + let r = env + .call( + "POST", + "/api/v1/restore", + Some(json!({ "change_id": kept1["id"] })), + ) + .await; assert_eq!(r.status, 202, "{}", r.text); let id = r.json["apply"]["id"].as_str().unwrap().to_owned(); let deadline = std::time::Instant::now() + Duration::from_secs(20); loop { - let s = env.call("GET", &format!("/api/v1/applies/{id}"), None).await; + let s = env + .call("GET", &format!("/api/v1/applies/{id}"), None) + .await; if s.json["state"] == "watching" { break; } - assert!(std::time::Instant::now() < deadline, "never watched: {}", s.text); + assert!( + std::time::Instant::now() < deadline, + "never watched: {}", + s.text + ); tokio::time::sleep(Duration::from_millis(50)).await; } // The disk problem goes away; a write request arrives during the watch. std::fs::remove_dir_all(&ej).unwrap(); let _ = env - .call("POST", "/api/v1/hosts", Some(json!({ "host": host("a.test", &two.url(), true) }))) + .call( + "POST", + "/api/v1/hosts", + Some(json!({ "host": host("a.test", &two.url(), true) })), + ) .await; - assert!(env.dir.join("state/journal.json").exists(), "the Restore's journal is still there"); - assert!(!ej.exists() || env.file("edge/edge.json").contains(&two.url()), "edge.json not written from the head under watch"); + assert!( + env.dir.join("state/journal.json").exists(), + "the Restore's journal is still there" + ); + assert!( + !ej.exists() || env.file("edge/edge.json").contains(&two.url()), + "edge.json not written from the head under watch" + ); let rec = env.wait_apply(&id).await; assert_ne!(rec["state"], "kept", "{rec}"); let now = upstream_of(&env).await; - assert_eq!(now, "200 two", "after the Restore was undone, edge serves the failed Restore's config ({now})"); + assert_eq!( + now, "200 two", + "after the Restore was undone, edge serves the failed Restore's config ({now})" + ); } /// Edge gone while a revert runs: control cannot see what edge serves, so it does not