[control] Files retry: only in the apply worker under the lock, reloads edge to what it writes, drops only the journal of the apply that caused the pause; swallowed aborts and pauses logged; CLI owner check before creating the state dir
This commit is contained in:
@@ -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::<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) {
|
||||
@@ -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<Reason> {
|
||||
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<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"
|
||||
@@ -625,7 +657,7 @@ impl Control {
|
||||
base_rev: Option<String>,
|
||||
actor: &str,
|
||||
) -> Result<ApplyRecord, Fail> {
|
||||
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;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -85,19 +85,34 @@ fn state_dir(args: &[String]) -> Result<PathBuf, String> {
|
||||
#[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") => {
|
||||
|
||||
Reference in New Issue
Block a user