aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--README.md7
-rw-r--r--share/bash-completion/completions/enstate5
-rw-r--r--src/main.rs117
-rw-r--r--src/migrate.rs163
-rw-r--r--src/store.rs117
-rw-r--r--tests/migrations.rs63
6 files changed, 407 insertions, 65 deletions
diff --git a/README.md b/README.md
index e08b3ac..8f7b9f8 100644
--- a/README.md
+++ b/README.md
@@ -24,8 +24,11 @@ The design is in [docs/design.md](docs/design.md);
`STATE/incoming/`, then serving a generation from snapshots accepted
under another schema (same names, `renamedFrom` both ways, kept
entries), refusing where a required slot can't be filled;
-- `--status`, `--materialize`: the snapshots, and putting every view in
- place from them;
+- `--status`, `--materialize`: the snapshots, what waits in the incoming
+ directory and what the switch refused (with why; `--status` exits with 1
+ if something needs attention: a refused submission, one waiting that the
+ running generation would refuse, an unfilled required slot), and putting
+ every view in place; `--forget NAME`: a waiting or refused submission;
- `--pack PATH --out DIR`: a submission from a source list, JSON or TOML;
`--pack PATH --dry-run [--json]`: what keeps it from one, every problem by
channel and slot, with location and variables, writing nothing.
diff --git a/share/bash-completion/completions/enstate b/share/bash-completion/completions/enstate
index dc90101..3774be5 100644
--- a/share/bash-completion/completions/enstate
+++ b/share/bash-completion/completions/enstate
@@ -4,7 +4,7 @@
_enstate() {
local cur=${COMP_WORDS[COMP_CWORD]} prev=${COMP_WORDS[COMP_CWORD-1]}
- local commands="--plan --apply --stage --status --materialize --migrate --pack"
+ local commands="--plan --apply --stage --status --materialize --migrate --pack --forget"
# the settings, and those each command uses
local general="--config --unset --print-config"
local settings="$general --state-dir --run-dir --schema --sandbox --unit"
@@ -19,7 +19,7 @@ _enstate() {
for ((i = 1; i < COMP_CWORD; i++)); do
w=${COMP_WORDS[i]}
case $w in
- --plan | --apply | --stage | --status | --materialize | --migrate | --pack)
+ --plan | --apply | --stage | --status | --materialize | --migrate | --pack | --forget)
cmd=${w#--} ;;
--out | --config | --unset | --state-dir | --run-dir | --schema | --sandbox | --unit)
used="$used$w "
@@ -42,6 +42,7 @@ _enstate() {
plan | stage) options="--json $store --sandbox" ;;
apply) options="--json $store --sandbox --unit" ;;
status) options="--json $store" ;;
+ forget) options="$general --state-dir" ;;
materialize) options="--json $store --sandbox" ;;
migrate) options="--json --dry-run $store --sandbox" ;;
pack)
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<ExitCode> {
let path = matches.get_one::<String>("path").map(PathBuf::from);
let out = matches.get_one::<String>("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<ExitCode> {
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<ExitCode> {
})
}
"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<ChannelStatus>,
views: Vec<ViewStatus>,
+ /// Submissions waiting in the incoming directory, each with whether the running
+ /// generation would refuse it, and why.
+ incoming: Vec<IncomingStatus>,
+ /// Submissions the switch refused, with why.
+ refused: Vec<enstate::store::Refusal>,
+ /// 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<Status> {
+fn status(schema: &Schema, schema_bytes: &[u8], store: &Store) -> Result<Status> {
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<Status> {
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<IncomingStatus> =
+ 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<String>,
+}
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<Migration> {
- 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<IncomingOutcome>, Vec<String>)> {
+ 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<Vec<IncomingOutcome>> {
+ 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, &copy, &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<String> {
+ 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<Vec<Refusal>> {
+ 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<Vec<PathBuf>> {
+ 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<Store> {
@@ -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<String>,
+}
+
+/// 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
+ )
+}
diff --git a/tests/migrations.rs b/tests/migrations.rs
index c892f72..18451a7 100644
--- a/tests/migrations.rs
+++ b/tests/migrations.rs
@@ -401,13 +401,74 @@ fn incoming_submissions() {
let check = host.migrate(&s2, true);
assert!(!check.accepted);
assert!(
- check.refused[0].starts_with("incoming 4: required item secrets/nope"),
+ check.refused[0].starts_with("incoming 4 (")
+ && check.refused[0].contains("/state/incoming/4): required item secrets/nope"),
"{check:?}"
);
assert!(host.root.join("state/incoming/4").exists());
+ // Waiting, and refused by the running generation: --status says so, and why.
+ let (code, stdout) = enstate(&host, &["--status", "--json"]);
+ assert_eq!(code, Some(1));
+ let status: Value = serde_json::from_str(&stdout).unwrap();
+ assert_eq!(status["incoming"][0]["name"], json!("4"));
+ assert_eq!(status["incoming"][0]["refused"], json!(true));
+ assert!(
+ status["incoming"][0]["reasons"][0]
+ .as_str()
+ .unwrap()
+ .contains("secrets/nope")
+ );
let migration = host.migrate(&s2, false);
assert!(!migration.accepted);
assert!(host.root.join("state/refused/4").exists());
+ // Visible, with why and when: in the store, and by --status, which exits with 1.
+ let refusals = host.store().refused().unwrap();
+ assert_eq!(refusals.len(), 1);
+ assert_eq!(refusals[0].name, "4");
+ assert!(
+ refusals[0].reasons[0].contains("secrets/nope"),
+ "{refusals:?}"
+ );
+ assert!(
+ refusals[0].at.ends_with('Z') && refusals[0].at.len() == 20,
+ "{refusals:?}"
+ );
+ let (code, stdout) = enstate(&host, &["--status", "--json"]);
+ assert_eq!(code, Some(1));
+ let output = stdout;
+ let status: Value = serde_json::from_str(&output).unwrap();
+ assert_eq!(status["attention"], json!(true));
+ assert_eq!(status["refused"][0]["name"], json!("4"));
assert!(!host.root.join("state/incoming/4").exists());
assert_eq!(host.view("a", "a").unwrap(), b"C");
+ // Forgotten, and nothing needs attention any more.
+ let (code, stdout) = enstate(&host, &["--forget", "4"]);
+ assert_eq!(code, Some(0), "{stdout}");
+ assert!(!host.root.join("state/refused/4").exists());
+ assert!(!host.root.join("state/refused/4.json").exists());
+ let (code, _) = enstate(&host, &["--status"]);
+ assert_eq!(code, Some(0));
+ let (code, _) = enstate(&host, &["--forget", "4"]);
+ assert_eq!(code, Some(2));
+}
+
+/// Runs enstate on `host`'s store with `arguments`: its exit status and output.
+fn enstate(host: &Host, arguments: &[&str]) -> (Option<i32>, String) {
+ let mut command = std::process::Command::new(env!("CARGO_BIN_EXE_enstate"));
+ command
+ .args(arguments)
+ .arg(format!("--state-dir={}", host.root.join("state").display()));
+ if arguments[0] != "--forget" {
+ command
+ .arg(format!("--run-dir={}", host.root.join("run").display()))
+ .arg(format!(
+ "--schema={}",
+ host.root.join("schema.json").display()
+ ));
+ }
+ let output = command.output().unwrap();
+ (
+ output.status.code(),
+ String::from_utf8_lossy(&output.stdout).into_owned(),
+ )
}