From 63311f0741d543093e083b9c6004aef6bf2a8421 Mon Sep 17 00:00:00 2001 From: tv Date: Tue, 1 Dec 2026 12:51:55 +0000 Subject: enstate: refused submissions, visible A submission the switch refuses is moved to STATE/refused/NAME with NAME.json next to it: when, and why ("refused" if nothing more). The check's message names the waiting submission's path. --status lists what waits in the incoming directory, planned against the running generation (one the check refused stays waiting, and refuses switches while it does), and what was refused, with the reasons (and --json as data); it exits with 1 if something needs attention: a refused submission, a waiting one the running generation would refuse, an unfilled required slot, so that a deployment running it notices. --forget NAME removes a waiting or refused submission. After hrm's review. --- src/main.rs | 117 ++++++++++++++++++++++++++++++++++++++--- src/migrate.rs | 163 +++++++++++++++++++++++++++++++++++++++------------------ src/store.rs | 117 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 337 insertions(+), 60 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index ca7d0df..8d960f1 100644 --- a/src/main.rs +++ b/src/main.rs @@ -99,7 +99,14 @@ const COMMANDS: &[(&str, &str)] = &[ "stage", "Like --apply, for the generation of --schema before switching to it: the snapshot only, no views, no reactions", ), - ("status", "Show the channels' snapshots and the views"), + ( + "status", + "Show the channels' snapshots and the views, what waits and what was refused", + ), + ( + "forget", + "Remove the waiting or refused submission named PATH, from the incoming or refused directory", + ), ( "materialize", "Put every view in place from the snapshots (at boot, after a switch)", @@ -220,7 +227,7 @@ fn run() -> Result { let path = matches.get_one::("path").map(PathBuf::from); let out = matches.get_one::("out").map(PathBuf::from); // An option that isn't for the command is an error. - let takes_path = matches!(command, "plan" | "apply" | "stage" | "pack"); + let takes_path = matches!(command, "plan" | "apply" | "stage" | "pack" | "forget"); match (&path, takes_path) { (None, true) => bail!("--{command} needs a PATH"), (Some(path), false) => bail!("--{command} takes no PATH ({})", path.display()), @@ -285,6 +292,15 @@ fn run() -> Result { Some(bwrap) => Some(PathBuf::from(bwrap)), None => Some(PathBuf::from("bwrap")), }); + if command == "forget" { + let _lock = store.lock()?; + let name = path.as_deref().unwrap().to_string_lossy().into_owned(); + let removed = store.forget(&name)?; + for path in &removed { + println!("removed {}", path.display()); + } + return Ok(ExitCode::SUCCESS); + } let schema_path = settings .schema .unwrap_or_else(|| PathBuf::from("/etc/enstate/schema.json")); @@ -355,13 +371,18 @@ fn run() -> Result { }) } "status" => { - let status = status(&schema, &store)?; + let status = status(&schema, &schema_bytes, &store)?; if json { println!("{}", serde_json::to_string_pretty(&status)?); } else { print_status(&status)?; } - Ok(ExitCode::SUCCESS) + // A deployment that runs it notices what needs attention. + Ok(if status.attention { + ExitCode::from(1) + } else { + ExitCode::SUCCESS + }) } _ => unreachable!(), } @@ -504,6 +525,16 @@ fn print_views(out: &mut impl Write, views: &[ViewOutcome], only_changes: bool) struct Status { channels: Vec, views: Vec, + /// Submissions waiting in the incoming directory, each with whether the running + /// generation would refuse it, and why. + incoming: Vec, + /// Submissions the switch refused, with why. + refused: Vec, + /// Where they are, to look at or remove. + refused_dir: PathBuf, + /// Whether something needs attention: a required slot unfilled, a refused + /// submission. + attention: bool, } #[derive(serde::Serialize)] @@ -563,10 +594,48 @@ fn print_status(status: &Status) -> Result<()> { }; writeln!(out, "view {}: {state}", view.view)?; } + for incoming in &status.incoming { + if !incoming.refused { + writeln!( + out, + "incoming {}: waiting for the next switch or --migrate", + incoming.name + )?; + continue; + } + writeln!( + out, + "{} {}: the running generation would refuse it; while it waits, a switch \ + to a generation that refuses it too is refused (enstate --forget {} removes it):", + style.paint("31", "incoming"), + incoming.name, + incoming.name + )?; + for reason in &incoming.reasons { + writeln!(out, " {reason}")?; + } + } + for refusal in &status.refused { + let at = if refusal.at.is_empty() { + String::new() + } else { + format!(" at {}", refusal.at) + }; + writeln!( + out, + "{} {}{at}, in {}:", + style.paint("31", "refused"), + refusal.name, + status.refused_dir.join(&refusal.name).display() + )?; + for reason in &refusal.reasons { + writeln!(out, " {reason}")?; + } + } Ok(()) } -fn status(schema: &Schema, store: &Store) -> Result { +fn status(schema: &Schema, schema_bytes: &[u8], store: &Store) -> Result { let mut channels = Vec::new(); for (channel, seen) in enstate::migrate::seen_all(schema, store)? { let slots = schema @@ -604,7 +673,29 @@ fn status(schema: &Schema, store: &Store) -> Result { installed: store.installed_view(view).is_some(), }) .collect(); - Ok(Status { channels, views }) + let refused = store.refused()?; + // What waits, as the running generation would take it: one it would refuse + // refuses every switch (the check plans what waits) until it goes. + let incoming: Vec = + enstate::migrate::plan_incoming(schema, schema_bytes, store)? + .into_iter() + .map(|outcome| IncomingStatus { + refused: !outcome.accepted(), + reasons: outcome.reasons(), + name: outcome.name, + }) + .collect(); + let attention = !refused.is_empty() + || incoming.iter().any(|incoming| incoming.refused) + || channels.iter().any(|channel| !channel.missing.is_empty()); + Ok(Status { + channels, + views, + incoming, + refused_dir: store.refused_dir(), + refused, + attention, + }) } fn print_migration(migration: &enstate::migrate::Migration) -> Result<()> { @@ -661,9 +752,10 @@ fn print_migration(migration: &enstate::migrate::Migration) -> Result<()> { fn uses(command: &str, setting: &str) -> bool { match setting { // Where the snapshots and views are: everything but making a submission. - "state-dir" | "run-dir" => command != "pack", + "state-dir" => command != "pack", + "run-dir" => !matches!(command, "pack" | "forget"), // The schema to plan against, or, for --pack, to check against. - "schema" => true, + "schema" => command != "forget", // Reactions run. "systemctl" => matches!(command, "apply" | "migrate"), "unit" => command == "apply", @@ -697,3 +789,12 @@ fn print_report(report: &enstate::pack::Report) -> Result<()> { )?; Ok(()) } + +#[derive(serde::Serialize)] +struct IncomingStatus { + name: String, + /// Whether the running generation would refuse it. + refused: bool, + #[serde(skip_serializing_if = "Vec::is_empty")] + reasons: Vec, +} diff --git a/src/migrate.rs b/src/migrate.rs index 5b97d27..15dd2f7 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -296,7 +296,6 @@ pub fn migrate( dry_run: bool, systemctl: &Path, ) -> Result { - let mut refused = Vec::new(); let pending = store.incoming()?; let scratch = match dry_run && !pending.is_empty() { true => Some(Scratch::new(&store.scratch(), "state-")?), @@ -307,57 +306,8 @@ pub fn migrate( .map(|scratch| store.copy_to(scratch.path())) .transpose()?; let work = copy.as_ref().unwrap_or(store); - let mut incoming = Vec::new(); - for dir in &pending { - let name = dir - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_default(); - let planned = - Submission::load(dir).and_then(|submission| plan::plan(schema, work, &submission)); - let (outcome, accepted) = match planned { - Err(error) => { - refused.push(format!("incoming {name}: {error:#}")); - let error = Some(format!("{error:#}")); - ( - IncomingOutcome { - name: name.clone(), - plan: None, - error, - }, - false, - ) - } - Ok(planned) => { - let plan = planned.store(work, schema_bytes)?; - if !plan.accepted { - refused.push(format!("incoming {name}: {}", plan.refused.join("; "))); - } - let accepted = plan.accepted; - ( - IncomingOutcome { - name: name.clone(), - plan: Some(plan), - error: None, - }, - accepted, - ) - } - }; - incoming.push(outcome); - if !dry_run { - if accepted { - std::fs::remove_dir_all(dir) - .with_context(|| format!("removing {}", dir.display()))?; - } else { - let target = store.refused_dir().join(&name); - std::fs::create_dir_all(store.refused_dir())?; - let _ = std::fs::remove_dir_all(&target); - std::fs::rename(dir, &target) - .with_context(|| format!("moving {} to {}", dir.display(), target.display()))?; - } - } - } + let (incoming, mut refused) = + take_incoming(schema, schema_bytes, store, work, &pending, dry_run)?; let store = work; let seen = seen_all(schema, store)?; let mut channels = BTreeMap::new(); @@ -413,3 +363,112 @@ pub fn migrate( failed, }) } + +/// Plans the submissions `pending` (in the incoming directory) against `schema`, in +/// order, storing those accepted in `work`, the store or a copy of it; unless `dry_run`, +/// they are removed, and those refused moved to the refused directory. Returns what +/// became of each, and why the refused ones were refused. +fn take_incoming( + schema: &Schema, + schema_bytes: &[u8], + store: &Store, + work: &Store, + pending: &[std::path::PathBuf], + dry_run: bool, +) -> Result<(Vec, Vec)> { + let mut refused = Vec::new(); + let mut incoming = Vec::new(); + for dir in pending { + let name = dir + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + let planned = + Submission::load(dir).and_then(|submission| plan::plan(schema, work, &submission)); + let (outcome, accepted) = match planned { + Err(error) => { + refused.push(format!("incoming {name} ({}): {error:#}", dir.display())); + let error = Some(format!("{error:#}")); + ( + IncomingOutcome { + name: name.clone(), + plan: None, + error, + }, + false, + ) + } + Ok(planned) => { + let plan = planned.store(work, schema_bytes)?; + if !plan.accepted { + refused.push(format!( + "incoming {name} ({}): {}", + dir.display(), + plan.refused.join("; ") + )); + } + let accepted = plan.accepted; + ( + IncomingOutcome { + name: name.clone(), + plan: Some(plan), + error: None, + }, + accepted, + ) + } + }; + let reasons = outcome.reasons(); + incoming.push(outcome); + if !dry_run { + if accepted { + std::fs::remove_dir_all(dir) + .with_context(|| format!("removing {}", dir.display()))?; + } else { + store.refuse_incoming(dir, &name, &reasons)?; + } + } + } + Ok((incoming, refused)) +} + +/// What the submissions waiting in the incoming directory would do, planned against +/// `schema`, in order, on a copy of the snapshots, changing nothing: for `--status`, +/// which shows what the running generation would refuse (a submission the check +/// before a switch refused stays waiting, and refuses every later switch). +pub fn plan_incoming( + schema: &Schema, + schema_bytes: &[u8], + store: &Store, +) -> Result> { + let pending = store.incoming()?; + if pending.is_empty() { + return Ok(Vec::new()); + } + let scratch = Scratch::new(&store.scratch(), "state-")?; + let copy = store.copy_to(scratch.path())?; + Ok(take_incoming(schema, schema_bytes, store, ©, &pending, true)?.0) +} + +impl IncomingOutcome { + pub fn accepted(&self) -> bool { + self.error.is_none() && self.plan.as_ref().is_some_and(|plan| plan.accepted) + } + + /// Why it was refused, if it was. + pub fn reasons(&self) -> Vec { + if self.accepted() { + return Vec::new(); + } + let reasons = match (&self.error, &self.plan) { + (Some(error), _) => vec![error.clone()], + (None, Some(plan)) => plan.refused.clone(), + (None, None) => Vec::new(), + }; + if reasons.is_empty() { + vec!["refused".to_owned()] + } else { + reasons + } + } +} diff --git a/src/store.rs b/src/store.rs index 0c8f50d..35b35aa 100644 --- a/src/store.rs +++ b/src/store.rs @@ -272,6 +272,90 @@ impl Store { Ok(submissions) } + /// Moves the incoming submission `dir`, called `name`, to the refused directory, + /// with why, in `NAME.json` next to it: for `--status` to show. + pub fn refuse_incoming(&self, dir: &Path, name: &str, reasons: &[String]) -> Result<()> { + let refused = self.refused_dir(); + create_dir(&refused, 0o700)?; + let target = refused.join(name); + let _ = std::fs::remove_dir_all(&target); + let _ = std::fs::remove_file(refused.join(format!("{name}.json"))); + std::fs::rename(dir, &target) + .with_context(|| format!("moving {} to {}", dir.display(), target.display()))?; + let refusal = Refusal { + name: name.to_owned(), + at: now(), + reasons: reasons.to_vec(), + }; + content::write_file( + &refused.join(format!("{name}.json")), + &serde_json::to_vec_pretty(&refusal)?, + 0o600, + ) + } + + /// The submissions the switch refused, oldest name first, each with why. + pub fn refused(&self) -> Result> { + let dir = self.refused_dir(); + let mut refusals = Vec::new(); + let entries = match std::fs::read_dir(&dir) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(refusals), + Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), + }; + for entry in entries { + let entry = entry?; + if !entry.file_type()?.is_dir() { + continue; + } + let name = entry.file_name().to_string_lossy().into_owned(); + let record = dir.join(format!("{name}.json")); + let refusal = std::fs::read(&record) + .ok() + .and_then(|bytes| serde_json::from_slice(&bytes).ok()) + .unwrap_or(Refusal { + name: name.clone(), + at: String::new(), + reasons: Vec::new(), + }); + refusals.push(refusal); + } + refusals.sort_by(|one, other| one.name.cmp(&other.name)); + Ok(refusals) + } + + /// Removes the waiting or refused submission `name` (from the incoming or the + /// refused directory, with its record of refusal); what was removed. An error if + /// there is none of that name. + pub fn forget(&self, name: &str) -> Result> { + if name.is_empty() || name.contains('/') || name == "." || name == ".." { + bail!("{name:?} is not the name of a submission"); + } + let mut removed = Vec::new(); + for path in [ + self.incoming_dir().join(name), + self.refused_dir().join(name), + self.refused_dir().join(format!("{name}.json")), + ] { + let result = if path.is_dir() { + std::fs::remove_dir_all(&path) + } else { + std::fs::remove_file(&path) + }; + match result { + Ok(()) => removed.push(path), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => { + return Err(error).with_context(|| format!("removing {}", path.display())); + } + } + } + if removed.is_empty() { + bail!("no submission {name} waits or was refused"); + } + Ok(removed) + } + /// A copy of the snapshots in `dir`, as a store with the same views: for a dry run /// that applies submissions without changing anything. pub fn copy_to(&self, dir: &Path) -> Result { @@ -408,3 +492,36 @@ fn sync_dir(dir: &Path) -> Result<()> { .and_then(|file| file.sync_all()) .with_context(|| format!("flushing {}", dir.display())) } + +/// A submission the switch refused: its name in the incoming directory, when, and why. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct Refusal { + pub name: String, + /// UTC, as `YYYY-MM-DDTHH:MM:SSZ`. + pub at: String, + pub reasons: Vec, +} + +/// Now, in UTC, as `YYYY-MM-DDTHH:MM:SSZ`. +fn now() -> String { + let seconds = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |since| since.as_secs()); + let (days, rest) = (seconds / 86_400, seconds % 86_400); + // Days since 1970-01-01 as a civil date (Howard Hinnant's algorithm). + let z = days as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", + rest / 3_600, + rest % 3_600 / 60, + rest % 60 + ) +} -- cgit v1.3.1