From b74359e97643be0f43034c3aeab533a2389a939f Mon Sep 17 00:00:00 2001 From: tv Date: Mon, 30 Nov 2026 18:21:16 +0000 Subject: enstate: submissions waiting for the next switch --migrate first takes the submissions in STATE/incoming, in the order of their names: planned against the schema, stored if accepted (their views follow with the rest), removed, and moved to STATE/refused if refused, which refuses the migration. A dry run (the check before a switch) does so on a copy of the snapshots, changing nothing. --stage leaves a marker, STATE/migrate-due, for the next switch to migrate even if the schema doesn't change; --migrate removes it. Scratch directories are cleaned up without following the symbolic links in them. --- src/main.rs | 12 +++++++ src/migrate.rs | 104 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- src/plan.rs | 17 ++++++++-- src/scratch.rs | 6 +++- src/store.rs | 77 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 206 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index df8b5c0..4c1e24b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -281,6 +281,7 @@ fn run() -> Result { "migrate" => { let migration = enstate::migrate::migrate( &schema, + &schema_bytes, &store, matches.get_flag("dry-run"), &systemctl, @@ -564,6 +565,17 @@ fn print_migration(migration: &enstate::migrate::Migration) -> Result<()> { for reason in &migration.refused { writeln!(out, " {} {reason}", style.paint("31", "refused:"))?; } + for incoming in &migration.incoming { + let what = match (&incoming.plan, migration.dry_run) { + (Some(plan), true) if plan.accepted => "would go in".to_owned(), + (Some(plan), false) if plan.accepted => match &plan.snapshot { + Some(id) => format!("went in: snapshot {id}"), + None => "went in, changing nothing".to_owned(), + }, + _ => style.paint("31", "refused"), + }; + writeln!(out, "incoming {}: {what}", incoming.name)?; + } for (channel, channel_migration) in &migration.channels { writeln!( out, diff --git a/src/migrate.rs b/src/migrate.rs index dbbf38d..ca1e6b5 100644 --- a/src/migrate.rs +++ b/src/migrate.rs @@ -23,10 +23,11 @@ use serde::Serialize; use crate::content::Content; use crate::name::Address; -use crate::plan::{Reacting, ViewOutcome, react}; +use crate::plan::{self, Plan, Reacting, ViewOutcome, react}; use crate::schema::{Reactions, Schema}; use crate::scratch::Scratch; use crate::store::{Kept, Snapshot, Store}; +use crate::submission::Submission; use crate::view; /// What the running generation sees of one channel. @@ -253,6 +254,9 @@ pub struct Migration { pub views: Vec, pub reactions: Reactions, pub dry_run: bool, + /// The submissions taken from the incoming directory. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub incoming: Vec, #[serde(skip_serializing_if = "Vec::is_empty")] pub failed: Vec, } @@ -265,20 +269,98 @@ pub struct ChannelMigration { pub kept: Vec, } -/// Serves the generation of `schema` from the snapshots, after a generation change, or -/// before it (`dry_run`): what each channel sees, which required slots nothing fills -/// (which refuses the switch), and how the views change. Unless `dry_run`, the views -/// are put in place, those of unfilled required slots taken away, and the reactions of -/// those that changed run by `systemctl`. +/// An incoming submission, and what became of it. +#[derive(Debug, Clone, Serialize)] +pub struct IncomingOutcome { + pub name: String, + #[serde(skip_serializing_if = "Option::is_none")] + pub plan: Option, + /// Why it couldn't even be planned. + #[serde(skip_serializing_if = "Option::is_none")] + pub error: Option, +} + +/// Serves the generation of `schema` (as `schema_bytes`) from the snapshots, after a +/// generation change, or before it (`dry_run`). First the submissions waiting in the +/// incoming directory are planned against `schema`, in order, and stored if accepted +/// (no views, no reactions yet); they are removed, and those refused moved to the +/// refused directory. Then: what each channel sees, which required slots nothing +/// fills, and how the views change. A refused submission, or an unfilled required +/// slot, refuses the switch. Unless `dry_run`, the views are put in place, those of +/// unfilled required slots taken away, and the reactions of those that changed run by +/// `systemctl`. A dry run does all of it on a copy of the snapshots. pub fn migrate( schema: &Schema, + schema_bytes: &[u8], store: &Store, 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-")?), + false => None, + }; + let copy = scratch + .as_ref() + .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 store = work; let seen = seen_all(schema, store)?; let mut channels = BTreeMap::new(); - let mut refused = Vec::new(); for (channel, channel_seen) in &seen { for slot in &channel_seen.unfilled { refused.push(format!("required slot {slot} can't be filled")); @@ -311,6 +393,13 @@ pub fn migrate( let failed = if dry_run { Vec::new() } else { + match std::fs::remove_file(store.migrate_due()) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error) + .with_context(|| format!("removing {}", store.migrate_due().display())); + } + _ => {} + } react(&reactions, systemctl, Reacting::Migrate) }; Ok(Migration { @@ -320,6 +409,7 @@ pub fn migrate( views, reactions, dry_run, + incoming, failed, }) } diff --git a/src/plan.rs b/src/plan.rs index 9a56505..b37510d 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -514,8 +514,22 @@ impl Planned { /// in place and no reactions run: those of the running generation stay as they /// are, and the switch (`--migrate`) brings the new generation's. The running /// generation sees the snapshot as any accepted under another schema: what it has - /// no slot for is kept. + /// no slot for is kept. A staged snapshot leaves a marker, so that the next switch + /// serves the views anew, even if the schema doesn't change. pub fn stage(self, store: &Store, schema_bytes: &[u8], lock: Lock) -> Result { + let plan = self.store(store, schema_bytes)?; + if plan.snapshot.is_some() { + std::fs::write(store.migrate_due(), b"") + .with_context(|| format!("writing {}", store.migrate_due().display()))?; + } + drop(lock); + Ok(plan) + } + + /// Stores the new snapshot, if the plan was accepted, and nothing else: no views, + /// no reactions. For staging, and for submissions taken from the incoming + /// directory, whose views `--migrate` puts in place after. + pub fn store(self, store: &Store, schema_bytes: &[u8]) -> Result { let mut plan = self.plan; plan.staged = true; if plan.accepted && self.content_changes { @@ -527,7 +541,6 @@ impl Planned { schema_bytes, )?); } - drop(lock); Ok(plan) } } diff --git a/src/scratch.rs b/src/scratch.rs index dddd91b..8d469c3 100644 --- a/src/scratch.rs +++ b/src/scratch.rs @@ -63,7 +63,11 @@ pub fn set_modes(dir: &Path, mode: u32) -> Result<()> { std::fs::set_permissions(dir, reach).with_context(|| format!("chmod {}", dir.display()))?; for entry in std::fs::read_dir(dir)? { let entry = entry?; - if entry.file_type()?.is_dir() { + let kind = entry.file_type()?; + if kind.is_symlink() { + // A link's own mode means nothing, and following it would change its target. + continue; + } else if kind.is_dir() { set_modes(&entry.path(), mode)?; } else { std::fs::set_permissions(entry.path(), std::fs::Permissions::from_mode(mode))?; diff --git a/src/store.rs b/src/store.rs index 4ac5ef2..7e6531e 100644 --- a/src/store.rs +++ b/src/store.rs @@ -7,6 +7,9 @@ //! STATE/channels/CHANNEL/snapshots/ID/schema.json the schema it was accepted under //! STATE/channels/CHANNEL/snapshots/ID/entries/SLOT //! STATE/channels/CHANNEL/snapshots/ID/kept/SLOT what no slot wanted, types in snapshot.json +//! STATE/incoming/NAME/ submissions for the next --migrate +//! STATE/refused/NAME/ those it refused +//! STATE/migrate-due something was staged for the next switch //! RUN/views/VIEW -> .generations/VIEW.ID //! RUN/tmp/ scratch //! ``` @@ -202,6 +205,55 @@ impl Store { Ok(id) } + /// Where submissions wait for the next `--migrate`, each in a directory of its own, + /// taken in the order of their names. + pub fn incoming_dir(&self) -> PathBuf { + self.state.join("incoming") + } + + /// Where `--migrate` moves incoming submissions it refused. + pub fn refused_dir(&self) -> PathBuf { + self.state.join("refused") + } + + /// A marker that a submission was staged, so the next switch serves the views + /// anew (`--migrate`), even if the schema doesn't change. `--migrate` removes it. + pub fn migrate_due(&self) -> PathBuf { + self.state.join("migrate-due") + } + + /// The submissions waiting in the incoming directory, in order. + pub fn incoming(&self) -> Result> { + let dir = self.incoming_dir(); + let mut submissions = Vec::new(); + match std::fs::read_dir(&dir) { + Ok(entries) => { + for entry in entries { + let entry = entry?; + if entry.file_type()?.is_dir() + && !entry.file_name().to_string_lossy().starts_with('.') + { + submissions.push(entry.path()); + } + } + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), + } + submissions.sort(); + Ok(submissions) + } + + /// 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 { + copy_tree(&self.state.join("channels"), &dir.join("channels"))?; + Ok(Store { + state: dir.to_owned(), + run: self.run.clone(), + }) + } + /// The views in place. pub fn installed_views(&self) -> Result> { let views = self.run.join("views"); @@ -279,3 +331,28 @@ fn replace_link(link: &Path, target: &Path) -> Result<()> { std::os::unix::fs::symlink(target, &new)?; std::fs::rename(&new, link).with_context(|| format!("replacing {}", link.display())) } + +/// Copies the tree `from` to `to`: directories, regular files and symbolic links. A +/// missing `from` copies nothing. +fn copy_tree(from: &Path, to: &Path) -> Result<()> { + let entries = match std::fs::read_dir(from) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(error).with_context(|| format!("reading {}", from.display())), + }; + create_dir(to, 0o700)?; + for entry in entries { + let entry = entry?; + let (source, target) = (entry.path(), to.join(entry.file_name())); + let kind = entry.file_type()?; + if kind.is_symlink() { + std::os::unix::fs::symlink(std::fs::read_link(&source)?, &target)?; + } else if kind.is_dir() { + copy_tree(&source, &target)?; + } else { + std::fs::copy(&source, &target) + .with_context(|| format!("copying {}", source.display()))?; + } + } + Ok(()) +} -- cgit v1.3.1