From a0f22c88d54d351b060c2d0d9f0a8cbf5f412ba2 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 15:02:23 +0000 Subject: enstate: --migrate, renames both ways, kept entries What a generation sees of a snapshot accepted under another schema: same name and type, renamedFrom, a rename in the stored schema read backwards, and entries kept, with their types, in the snapshot's kept/. Plans start from what is seen, and store it under the running schema; a generation change rewrites no snapshot. --migrate (and --dry-run) says what each channel sees, refuses for required slots nothing fills, puts the views in place and runs their reactions; --materialize and --status go by what is seen, too. A view made from an unfilled required slot isn't there. The rollback cases of migrations.md that need no converters or steps are tests. --- README.md | 5 +- src/lib.rs | 2 + src/main.rs | 154 +++++++++++++++++-------- src/migrate.rs | 325 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/plan.rs | 104 ++++++----------- src/schema.rs | 7 ++ src/store.rs | 60 +++++++++- src/view.rs | 12 +- tests/common/mod.rs | 121 +++++++++++++++++++ tests/migrations.rs | 247 +++++++++++++++++++++++++++++++++++++++ tests/receptor.rs | 103 +---------------- 11 files changed, 923 insertions(+), 217 deletions(-) create mode 100644 src/migrate.rs create mode 100644 tests/common/mod.rs create mode 100644 tests/migrations.rs diff --git a/README.md b/README.md index 71ae7e2..709aaf5 100644 --- a/README.md +++ b/README.md @@ -17,11 +17,14 @@ The design is in [docs/design.md](docs/design.md); doing it: complete and partial submissions, items required and optional, groups, removal, the chain as order, validators (a type's and across slots), views and their reactions; +- `--migrate [--dry-run]`: 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; - `--pack PATH --out DIR`: a submission from a source list, JSON or TOML. -Not yet: migrations (`--migrate`), the NixOS module, a NixOS VM test, +Not yet: converters, derived slots and steps; the NixOS module, a NixOS VM test, shell completion, a sandbox for programs. ```sh diff --git a/src/lib.rs b/src/lib.rs index af7de7e..f78f51f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -9,10 +9,12 @@ //! * [`view`]: rendering views, comparing them, installing them; //! * [`store`]: snapshots on disk, and the views in place; //! * [`plan`]: what a submission would do, and applying it; +//! * [`migrate`]: what a generation sees of snapshots accepted under other schemas; //! * [`pack`]: making a submission from a source list. pub mod content; pub mod media; +pub mod migrate; pub mod name; pub mod pack; pub mod plan; diff --git a/src/main.rs b/src/main.rs index 16c553d..3539d76 100644 --- a/src/main.rs +++ b/src/main.rs @@ -80,6 +80,10 @@ const COMMANDS: &[(&str, &str)] = &[ "materialize", "Put every view in place from the snapshots (at boot, after a switch)", ), + ( + "migrate", + "Serve the generation of --schema from the snapshots: what it sees, its views, their reactions", + ), ( "pack", "Make a submission in --out from the source list in PATH", @@ -119,7 +123,13 @@ fn command() -> Command { Arg::new("json") .long("json") .action(ArgAction::SetTrue) - .help("Print JSON (--plan, --apply, --status, --materialize)"), + .help("Print JSON (--plan, --apply, --status, --materialize, --migrate)"), + ) + .arg( + Arg::new("dry-run") + .long("dry-run") + .action(ArgAction::SetTrue) + .help("With --migrate: say what it would do, changing nothing"), ) .arg( Arg::new("out") @@ -188,6 +198,9 @@ fn run() -> Result { if out.is_some() && command != "pack" { bail!("--out is for --pack only"); } + if matches.get_flag("dry-run") && command != "migrate" { + bail!("--dry-run is for --migrate only"); + } if json && command == "pack" { bail!("--json is not for --pack"); } @@ -241,7 +254,7 @@ fn run() -> Result { }) } "materialize" => { - let views = plan::materialize(&schema, &store)?; + let views = enstate::migrate::materialize(&schema, &store)?; if json { println!("{}", serde_json::to_string_pretty(&views)?); } else { @@ -249,6 +262,26 @@ fn run() -> Result { } Ok(ExitCode::SUCCESS) } + "migrate" => { + let migration = enstate::migrate::migrate( + &schema, + &store, + matches.get_flag("dry-run"), + &systemctl, + )?; + if json { + println!("{}", serde_json::to_string_pretty(&migration)?); + } else { + print_migration(&migration)?; + } + Ok(if !migration.accepted { + ExitCode::from(1) + } else if !migration.failed.is_empty() { + ExitCode::from(3) + } else { + ExitCode::SUCCESS + }) + } "status" => { let status = status(&schema, &store)?; if json { @@ -405,6 +438,8 @@ struct ChannelStatus { missing: Vec, /// Kept, but in no slot of the schema. kept: Vec, + /// Where entries came from, what can't be taken. + notes: Vec, } #[derive(serde::Serialize)] @@ -413,27 +448,57 @@ struct ViewStatus { installed: bool, } -fn status(schema: &Schema, store: &Store) -> Result { - let mut channels = Vec::new(); - let mut names: Vec = schema.channels.keys().cloned().collect(); - for channel in store.channels()? { - if !names.contains(&channel) { - names.push(channel); +fn print_status(status: &Status) -> Result<()> { + let style = Style::new(); + let mut out = std::io::stdout().lock(); + for channel in &status.channels { + writeln!( + out, + "channel {}: snapshot {}", + channel.channel, + channel.snapshot.as_deref().unwrap_or("none") + )?; + for slot in &channel.filled { + writeln!(out, " {} {slot}", style.paint("32", "filled"))?; + } + for slot in &channel.unfilled { + let missing = channel.missing.contains(slot); + let label = if missing { + style.paint("31", "missing") + } else { + "unfilled".to_owned() + }; + writeln!(out, " {label} {slot}")?; + } + for slot in &channel.kept { + writeln!(out, " {} {slot}", style.paint("33", "kept"))?; + } + for note in &channel.notes { + writeln!(out, " {note}")?; } } - for channel in names { - let snapshot = store.current(&channel)?; - let content = snapshot - .as_ref() - .map(|snapshot| snapshot.content.clone()) - .unwrap_or_default(); + for view in &status.views { + let state = if view.installed { + style.paint("32", "in place") + } else { + style.paint("33", "not in place") + }; + writeln!(out, "view {}: {state}", view.view)?; + } + Ok(()) +} + +fn status(schema: &Schema, store: &Store) -> Result { + let mut channels = Vec::new(); + for (channel, seen) in enstate::migrate::seen_all(schema, store)? { let slots = schema .channel(&channel) .map(|spec| spec.slots.clone()) .unwrap_or_default(); + let content = &seen.content; channels.push(ChannelStatus { channel: channel.clone(), - snapshot: snapshot.map(|snapshot| snapshot.id), + snapshot: store.current(&channel)?.map(|snapshot| snapshot.id), filled: slots .keys() .filter(|slot| content.contains_key(*slot)) @@ -449,11 +514,8 @@ fn status(schema: &Schema, store: &Store) -> Result { .filter(|(slot, spec)| spec.required && !content.contains_key(*slot)) .map(|(slot, _)| slot.clone()) .collect(), - kept: content - .keys() - .filter(|slot| !slots.contains_key(*slot)) - .cloned() - .collect(), + kept: seen.kept_names(), + notes: seen.notes.clone(), }); } let views = schema @@ -467,39 +529,41 @@ fn status(schema: &Schema, store: &Store) -> Result { Ok(Status { channels, views }) } -fn print_status(status: &Status) -> Result<()> { +fn print_migration(migration: &enstate::migrate::Migration) -> Result<()> { let style = Style::new(); let mut out = std::io::stdout().lock(); - for channel in &status.channels { + let verdict = if migration.accepted { + style.paint("32", "every required slot is filled") + } else { + style.paint("31", "refused") + }; + let dry_run = if migration.dry_run { " (dry run)" } else { "" }; + writeln!(out, "migration{dry_run}: {verdict}")?; + for reason in &migration.refused { + writeln!(out, " {} {reason}", style.paint("31", "refused:"))?; + } + for (channel, channel_migration) in &migration.channels { writeln!( out, - "channel {}: snapshot {}", - channel.channel, - channel.snapshot.as_deref().unwrap_or("none") + "channel {channel}: snapshot {}", + channel_migration.snapshot.as_deref().unwrap_or("none") )?; - for slot in &channel.filled { - writeln!(out, " {} {slot}", style.paint("32", "filled"))?; - } - for slot in &channel.unfilled { - let missing = channel.missing.contains(slot); - let label = if missing { - style.paint("31", "missing") - } else { - "unfilled".to_owned() - }; - writeln!(out, " {label} {slot}")?; + for note in &channel_migration.seen.notes { + writeln!(out, " {note}")?; } - for slot in &channel.kept { - writeln!(out, " {} {slot}", style.paint("33", "kept"))?; + for slot in &channel_migration.kept { + writeln!(out, " {} {channel}/{slot}", style.paint("33", "kept"))?; } } - for view in &status.views { - let state = if view.installed { - style.paint("32", "in place") - } else { - style.paint("33", "not in place") - }; - writeln!(out, "view {}: {state}", view.view)?; + print_views(&mut out, &migration.views, true)?; + if !migration.reactions.restart.is_empty() { + writeln!(out, "restart: {}", migration.reactions.restart.join(" "))?; + } + if !migration.reactions.reload.is_empty() { + writeln!(out, "reload: {}", migration.reactions.reload.join(" "))?; + } + for failed in &migration.failed { + writeln!(out, "{} {failed}", style.paint("31", "failed:"))?; } Ok(()) } diff --git a/src/migrate.rs b/src/migrate.rs new file mode 100644 index 0000000..340180f --- /dev/null +++ b/src/migrate.rs @@ -0,0 +1,325 @@ +//! Migrations (docs/design.md, section 6): what a generation sees of the snapshots, +//! which were accepted under other schemas, and putting views in place for it. +//! +//! What a slot of the running schema is filled with, from the stored snapshot and the +//! schema it was accepted under, the first that fits: +//! +//! 1. the entry of the same name, of the same type; +//! 2. the entry of the name the slot says it was `renamedFrom`; +//! 3. the entry of a slot that says, in the stored schema, it was renamed from this +//! one: the way back after a rollback; +//! 4. an entry kept under the same name, of the same type, unless the stored snapshot +//! has an entry of that name: kept entries are older than any stored. +//! +//! Entries no slot takes are kept, with their types. A generation change never +//! rewrites a snapshot: what is seen is computed each time, and stored only when a +//! submission is applied. Not yet: converters, derived slots, steps. + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::Path; + +use anyhow::{Context, Result}; +use serde::Serialize; + +use crate::content::Content; +use crate::name::Address; +use crate::plan::{ViewOutcome, react}; +use crate::schema::{Reactions, Schema}; +use crate::scratch::Scratch; +use crate::store::{Kept, Snapshot, Store}; +use crate::view; + +/// What the running generation sees of one channel. +#[derive(Debug, Clone, Default, Serialize)] +pub struct Seen { + #[serde(skip)] + pub content: Content, + #[serde(skip)] + pub kept: Kept, + /// Where entries came from, where that isn't their own slot; what can't be taken. + pub notes: Vec, + /// Required slots nothing fills. + pub unfilled: Vec, +} + +impl Seen { + /// The names of the entries kept. + pub fn kept_names(&self) -> Vec { + self.kept.keys().cloned().collect() + } +} + +/// What `schema` sees of `channel`, whose current snapshot is `snapshot`. +pub fn seen(schema: &Schema, channel: &str, snapshot: Option<&Snapshot>) -> Result { + let mut seen = Seen::default(); + let empty_slots = BTreeMap::new(); + let slots = schema + .channel(channel) + .map(|spec| &spec.slots) + .unwrap_or(&empty_slots); + let Some(snapshot) = snapshot else { + seen.unfilled = slots + .iter() + .filter(|(_, spec)| spec.required) + .map(|(slot, _)| format!("{channel}/{slot}")) + .collect(); + return Ok(seen); + }; + let stored = Schema::from_slice(&snapshot.schema) + .with_context(|| format!("the schema channel {channel}'s snapshot was accepted under"))?; + let stored_slots = stored + .channel(channel) + .map(|spec| spec.slots.clone()) + .unwrap_or_default(); + let stored_type = |slot: &str| { + stored + .slot(&Address::entry(channel, slot)) + .map(|spec| spec.media_type.clone()) + }; + let entries = &snapshot.content; + let mut taken: BTreeSet<&str> = BTreeSet::new(); + let mut kept_taken: BTreeSet<&str> = BTreeSet::new(); + let mut filled: BTreeSet<&str> = BTreeSet::new(); + // 1. Same name, same type. + for (slot, spec) in slots { + let Some(bytes) = entries.get(slot) else { + continue; + }; + match stored_type(slot) { + Some(media_type) if media_type == spec.media_type => { + seen.content.insert(slot.clone(), bytes.clone()); + taken.insert(slot); + filled.insert(slot); + } + Some(media_type) => seen.notes.push(format!( + "{channel}/{slot}: type {media_type} is now {}, and there is no converter", + spec.media_type + )), + None => {} + } + } + // 2. Renamed from. + for (slot, spec) in slots { + if filled.contains(slot.as_str()) { + continue; + } + let Some(old) = &spec.renamed_from else { + continue; + }; + if let Some(bytes) = entries.get(old) + && !taken.contains(old.as_str()) + && stored_type(old).as_ref() == Some(&spec.media_type) + { + seen.content.insert(slot.clone(), bytes.clone()); + seen.notes + .push(format!("{channel}/{slot}: from {channel}/{old}, renamed")); + taken.insert(old); + filled.insert(slot); + } + } + // 3. Renamed, by the stored schema, from this one. + for (slot, spec) in slots { + if filled.contains(slot.as_str()) { + continue; + } + let newer = stored_slots.iter().find(|(newer, newer_spec)| { + newer_spec.renamed_from.as_deref() == Some(slot.as_str()) + && newer_spec.media_type == spec.media_type + && entries.contains_key(*newer) + && !taken.contains(newer.as_str()) + }); + if let Some((newer, _)) = newer { + let (newer, bytes) = entries.get_key_value(newer).unwrap(); + seen.content.insert(slot.clone(), bytes.clone()); + seen.notes.push(format!( + "{channel}/{slot}: from {channel}/{newer}, which the schema it was accepted under renamed from it" + )); + taken.insert(newer); + filled.insert(slot); + } + } + // 4. Kept, under the same name, of the same type, unless there is a newer entry + // of that name: what was kept is never used once its slot was filled anew. + for (slot, spec) in slots { + if filled.contains(slot.as_str()) { + continue; + } + if let Some((media_type, bytes)) = snapshot.kept.get(slot) + && *media_type == spec.media_type + && !entries.contains_key(slot) + { + seen.content.insert(slot.clone(), bytes.clone()); + seen.notes + .push(format!("{channel}/{slot}: from what was kept")); + kept_taken.insert(slot); + filled.insert(slot); + } + } + for (slot, spec) in slots { + if spec.required && !filled.contains(slot.as_str()) { + seen.unfilled.push(format!("{channel}/{slot}")); + } + } + // What no slot took is kept: the stored entries, then what was kept before. + for (slot, bytes) in entries { + if !taken.contains(slot.as_str()) { + let media_type = + stored_type(slot).unwrap_or_else(|| "application/octet-stream".to_owned()); + seen.kept.insert(slot.clone(), (media_type, bytes.clone())); + } + } + for (slot, kept) in &snapshot.kept { + if !kept_taken.contains(slot.as_str()) && !seen.kept.contains_key(slot) { + seen.kept.insert(slot.clone(), kept.clone()); + } + } + Ok(seen) +} + +/// What every channel of `schema` sees, by channel. +pub fn seen_all(schema: &Schema, store: &Store) -> Result> { + let mut all = BTreeMap::new(); + let mut channels: BTreeSet = schema.channels.keys().cloned().collect(); + channels.extend(store.channels()?); + for channel in channels { + let snapshot = store.current(&channel)?; + all.insert(channel.clone(), seen(schema, &channel, snapshot.as_ref())?); + } + Ok(all) +} + +/// Renders every view of `schema` from `seen`, and, unless `dry_run`, puts those that +/// differ from what is in place there, and takes away views the schema doesn't have. +/// Returns how each view changes. +pub fn put_views( + schema: &Schema, + store: &Store, + seen: &BTreeMap, + dry_run: bool, +) -> Result> { + let entries: view::Entries = seen + .iter() + .map(|(name, seen)| (name.as_str(), &seen.content)) + .collect(); + let mut outcomes = Vec::new(); + for (name, view_spec) in schema.views_of(None) { + let secret = schema.view_is_secret(view_spec); + let rendered = view::render(schema, name, view_spec, &entries, &store.scratch()) + .with_context(|| format!("view {name}"))?; + let installed = store.installed_view(name); + let (change, files) = view::compare( + installed.as_deref(), + rendered.as_ref().map(Scratch::path), + secret, + )?; + if change != view::Change::Unchanged && !dry_run { + store.install_view(name, rendered, secret)?; + } + outcomes.push(ViewOutcome { + name: name.clone(), + secret, + change, + files, + }); + } + for name in store.installed_views()? { + if !schema.views.contains_key(&name) { + if !dry_run { + store.install_view(&name, None, false)?; + } + outcomes.push(ViewOutcome { + name, + secret: false, + change: view::Change::Removed, + files: Vec::new(), + }); + } + } + Ok(outcomes) +} + +/// Puts every view of `schema` in place from the snapshots, and takes away those it +/// doesn't have: at boot. Runs no reactions. +pub fn materialize(schema: &Schema, store: &Store) -> Result> { + put_views(schema, store, &seen_all(schema, store)?, false) +} + +#[derive(Debug, Clone, Serialize)] +pub struct Migration { + /// Whether the state fills every required slot of the schema. + pub accepted: bool, + pub refused: Vec, + pub channels: BTreeMap, + pub views: Vec, + pub reactions: Reactions, + pub dry_run: bool, + #[serde(skip_serializing_if = "Vec::is_empty")] + pub failed: Vec, +} + +#[derive(Debug, Clone, Serialize)] +pub struct ChannelMigration { + pub snapshot: Option, + #[serde(flatten)] + pub seen: Seen, + 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`. +pub fn migrate( + schema: &Schema, + store: &Store, + dry_run: bool, + systemctl: &Path, +) -> Result { + 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")); + } + channels.insert( + channel.clone(), + ChannelMigration { + snapshot: store.current(channel)?.map(|snapshot| snapshot.id), + seen: channel_seen.clone(), + kept: channel_seen.kept_names(), + }, + ); + } + let views = put_views(schema, store, &seen, dry_run)?; + let mut restart = BTreeSet::new(); + let mut reload = BTreeSet::new(); + for outcome in &views { + if outcome.change == view::Change::Unchanged { + continue; + } + if let Some(spec) = schema.views.get(&outcome.name) { + restart.extend(spec.reactions.restart.iter().cloned()); + reload.extend(spec.reactions.reload.iter().cloned()); + } + } + let reactions = Reactions { + reload: reload.difference(&restart).cloned().collect(), + restart: restart.into_iter().collect(), + }; + let failed = if dry_run { + Vec::new() + } else { + react(&reactions, systemctl) + }; + Ok(Migration { + accepted: refused.is_empty(), + refused, + channels, + views, + reactions, + dry_run, + failed, + }) +} diff --git a/src/plan.rs b/src/plan.rs index 952f3aa..80e2bad 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -16,11 +16,12 @@ use serde::Serialize; use crate::content::{self, Content}; use crate::media; +use crate::migrate; use crate::name::Address; use crate::program::{self, Given, ProgramFailed, Role}; use crate::schema::{Reactions, Schema}; use crate::scratch::Scratch; -use crate::store::Store; +use crate::store::{Kept, Store}; use crate::submission::{Change, Item, Submission}; use crate::view::{self, FileChange}; @@ -72,6 +73,7 @@ pub struct ViewOutcome { pub struct Planned { pub plan: Plan, content: Content, + kept: Kept, content_changes: bool, rendered: Vec<(String, Option, bool)>, } @@ -81,6 +83,7 @@ fn refused(plan: Plan) -> Result { Ok(Planned { plan, content: Content::new(), + kept: Kept::new(), content_changes: false, rendered: Vec::new(), }) @@ -134,8 +137,11 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result

&snapshot.content, + (Some(_), false) => &seen.content, _ => &empty, }; // Other channels, for validators and views given their slots. @@ -156,10 +162,7 @@ pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result

Result

Result

Result

Vec { } failed } - -/// Renders every view of `schema` from the current snapshots, puts those that differ -/// from what is in place there, and takes away views the schema doesn't have: at boot, -/// and after a generation change. Runs no reactions. Returns how each view changed. -pub fn materialize(schema: &Schema, store: &Store) -> Result> { - let mut contents: BTreeMap = BTreeMap::new(); - for channel in schema.channels.keys() { - if let Some(snapshot) = store.current(channel)? { - contents.insert(channel.clone(), snapshot.content); - } - } - let entries: view::Entries = contents - .iter() - .map(|(name, content)| (name.as_str(), content)) - .collect(); - let mut outcomes = Vec::new(); - for (name, view_spec) in schema.views_of(None) { - let secret = schema.view_is_secret(view_spec); - let rendered = view::render(schema, name, view_spec, &entries, &store.scratch()) - .with_context(|| format!("view {name}"))?; - let installed = store.installed_view(name); - let (change, files) = view::compare( - installed.as_deref(), - rendered.as_ref().map(Scratch::path), - secret, - )?; - if change != view::Change::Unchanged { - store.install_view(name, rendered, secret)?; - } - outcomes.push(ViewOutcome { - name: name.clone(), - secret, - change, - files, - }); - } - let views = store.run.join("views"); - if let Ok(entries) = std::fs::read_dir(&views) { - for entry in entries { - let name = entry?.file_name().to_string_lossy().into_owned(); - if name == ".generations" - || name.ends_with(".new-link") - || schema.views.contains_key(&name) - { - continue; - } - if store.installed_view(&name).is_some() { - store.install_view(&name, None, false)?; - outcomes.push(ViewOutcome { - name, - secret: false, - change: view::Change::Removed, - files: Vec::new(), - }); - } - } - } - Ok(outcomes) -} diff --git a/src/schema.rs b/src/schema.rs index a44f6f8..8b20777 100644 --- a/src/schema.rs +++ b/src/schema.rs @@ -66,6 +66,9 @@ pub struct SlotSpec { pub required: bool, #[serde(default)] pub secret: bool, + /// The name the slot had in an earlier schema (docs/design.md, section 6). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub renamed_from: Option, } fn yes() -> bool { @@ -123,6 +126,10 @@ impl Schema { name::check("channel", channel)?; for (slot, spec) in &mut spec.slots { name::check("slot", slot)?; + if let Some(old) = &spec.renamed_from { + name::check("slot", old) + .with_context(|| format!("slot {channel}/{slot}: renamedFrom"))?; + } spec.media_type = media::normalize(&spec.media_type) .with_context(|| format!("slot {channel}/{slot}"))?; } diff --git a/src/store.rs b/src/store.rs index b25495e..4ac5ef2 100644 --- a/src/store.rs +++ b/src/store.rs @@ -6,6 +6,7 @@ //! STATE/channels/CHANNEL/snapshots/ID/snapshot.json id, and the id it was built on //! 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 //! RUN/views/VIEW -> .generations/VIEW.ID //! RUN/tmp/ scratch //! ``` @@ -24,6 +25,9 @@ use serde::{Deserialize, Serialize}; use crate::content::{self, Content}; use crate::scratch::Scratch; +/// Entries kept: by slot name, the type each had, and the entry. +pub type Kept = std::collections::BTreeMap)>; + pub struct Store { pub state: PathBuf, pub run: PathBuf, @@ -34,6 +38,9 @@ pub struct Snapshot { pub id: String, pub base: Option, pub content: Content, + /// Entries no slot of the schema it was accepted under wanted, by slot name, with + /// the types they had (docs/design.md, section 6). + pub kept: Kept, /// The schema it was accepted under, as it was. pub schema: Vec, } @@ -44,6 +51,9 @@ struct SnapshotFile { id: String, channel: String, base: Option, + /// The types of the entries in `kept/`. + #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")] + kept: std::collections::BTreeMap, } /// Held while the store is used; released when dropped. @@ -122,20 +132,33 @@ impl Store { } let schema = std::fs::read(dir.join("schema.json")) .with_context(|| format!("reading {}", dir.join("schema.json").display()))?; + let mut kept_entries = content::read_dir(&dir.join("kept"))?; + let mut kept = Kept::new(); + for (slot, media_type) in file.kept { + let bytes = kept_entries + .remove(&slot) + .with_context(|| format!("{}: kept {slot} is missing", dir.display()))?; + kept.insert(slot, (media_type, bytes)); + } + if let Some(slot) = kept_entries.keys().next() { + bail!("{}: kept {slot} has no type", dir.display()); + } Ok(Some(Snapshot { id: file.id, base: file.base, content: content::read_dir(&dir.join("entries"))?, + kept, schema, })) } - /// Makes `content` the current snapshot of `channel`, accepted under `schema`, - /// built on `base`; returns its id. The snapshot it replaces is removed. + /// Makes `content`, and `kept`, the current snapshot of `channel`, accepted under + /// `schema`, built on `base`; returns its id. The snapshot it replaces is removed. pub fn commit( &self, channel: &str, content: &Content, + kept: &Kept, base: Option<&str>, schema: &[u8], ) -> Result { @@ -148,6 +171,10 @@ impl Store { id: id.clone(), channel: channel.to_owned(), base: base.map(str::to_owned), + kept: kept + .iter() + .map(|(slot, (media_type, _))| (slot.clone(), media_type.clone())) + .collect(), }; content::write_file( &new.join("snapshot.json"), @@ -156,6 +183,13 @@ impl Store { )?; content::write_file(&new.join("schema.json"), schema, 0o600)?; content::write_dir(content, &new.join("entries"), 0o600)?; + if !kept.is_empty() { + let kept: Content = kept + .iter() + .map(|(slot, (_, bytes))| (slot.clone(), bytes.clone())) + .collect(); + content::write_dir(&kept, &new.join("kept"), 0o600)?; + } std::fs::rename(&new, snapshots.join(&id))?; let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok(); replace_link( @@ -168,6 +202,28 @@ impl Store { Ok(id) } + /// The views in place. + pub fn installed_views(&self) -> Result> { + let views = self.run.join("views"); + let mut names = Vec::new(); + let entries = match std::fs::read_dir(&views) { + Ok(entries) => entries, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(names), + Err(error) => { + return Err(error).with_context(|| format!("reading {}", views.display())); + } + }; + for entry in entries { + let entry = entry?; + let name = entry.file_name().to_string_lossy().into_owned(); + if entry.file_type()?.is_symlink() && !name.ends_with(".new-link") { + names.push(name); + } + } + names.sort(); + Ok(names) + } + /// The directory the view `name` is in place at, if it is. pub fn installed_view(&self, name: &str) -> Option { let link = self.run.join("views").join(name); diff --git a/src/view.rs b/src/view.rs index b7bab6c..bd4b8f5 100644 --- a/src/view.rs +++ b/src/view.rs @@ -17,8 +17,9 @@ use crate::scratch::Scratch; /// would be, the others as they are. pub type Entries<'a> = BTreeMap<&'a str, &'a Content>; -/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if it -/// is an entry's own and that entry isn't there. +/// Renders the view `name` from `entries` into scratch below `scratch`; nothing if a +/// required slot it is made from is unfilled, or it is an entry's own and that entry +/// isn't there. pub fn render( schema: &Schema, name: &str, @@ -31,6 +32,13 @@ pub fn render( .get(address.channel.as_str()) .and_then(|content| content.get(&address.slot)) }; + // A view made from a required slot that is unfilled isn't there (docs/design.md, + // section 7). + if view.from.iter().any(|address| { + schema.slot(address).is_some_and(|slot| slot.required) && entry(address).is_none() + }) { + return Ok(None); + } match &view.renderer { None => { let address = &view.from[0]; diff --git a/tests/common/mod.rs b/tests/common/mod.rs new file mode 100644 index 0000000..751d809 --- /dev/null +++ b/tests/common/mod.rs @@ -0,0 +1,121 @@ +//! A host on directories, for the tests: its store, programs as shell scripts, +//! schemas, submissions, and what its views and reactions are. + +#![allow(dead_code)] + +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; + +use enstate::migrate::Migration; +use enstate::plan::{self, Plan}; +use enstate::schema::Schema; +use enstate::store::Store; +use enstate::submission::Submission; +use serde_json::{Value, json}; + +pub struct Host { + pub root: PathBuf, +} + +impl Host { + pub fn new(name: &str) -> Self { + let root = Path::new(env!("CARGO_TARGET_TMPDIR")) + .join("receptor") + .join(name); + let _ = std::fs::remove_dir_all(&root); + std::fs::create_dir_all(root.join("programs")).unwrap(); + Self { root } + } + + pub fn store(&self) -> Store { + Store::new(&self.root.join("state"), &self.root.join("run")) + } + + /// A shell script, with the tests' PATH (programs get an empty environment). + pub fn program(&self, name: &str, body: &str) -> String { + let path = self.root.join("programs").join(name); + let script = format!( + "#!/bin/sh\nPATH={}\nset -eu\n{body}\n", + std::env::var("PATH").unwrap() + ); + std::fs::write(&path, script).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.display().to_string() + } + + pub fn schema(&self, schema: Value) -> (Schema, Vec) { + let bytes = serde_json::to_vec_pretty(&schema).unwrap(); + std::fs::write(self.root.join("schema.json"), &bytes).unwrap(); + (Schema::from_slice(&bytes).unwrap(), bytes) + } + + /// A submission named `name`: its manifest, and files below `channels/`. + pub fn submission(&self, name: &str, manifest: Value, files: &[(&str, &[u8])]) -> PathBuf { + let dir = self.root.join("submissions").join(name); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mut manifest = manifest; + manifest["submission"] = json!(1); + std::fs::write(dir.join("manifest.json"), manifest.to_string()).unwrap(); + for (path, bytes) in files { + let path = dir.join("channels").join(path); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); + } + dir + } + + pub fn plan(&self, schema: &Schema, dir: &Path) -> Plan { + let submission = Submission::load(dir).unwrap(); + plan::plan(schema, &self.store(), &submission).unwrap().plan + } + + pub fn apply(&self, schema: &(Schema, Vec), dir: &Path) -> Plan { + let submission = Submission::load(dir).unwrap(); + let store = self.store(); + let _lock = store.lock().unwrap(); + plan::plan(&schema.0, &store, &submission) + .unwrap() + .apply(&store, &schema.1, &self.systemctl()) + .unwrap() + } + + /// A systemctl that writes down what it was asked. + pub fn systemctl(&self) -> PathBuf { + let log = self.root.join("systemctl.log"); + PathBuf::from(self.program("systemctl", &format!("echo \"$*\" >> {}", log.display()))) + } + + pub fn reactions(&self) -> String { + std::fs::read_to_string(self.root.join("systemctl.log")).unwrap_or_default() + } + + pub fn view(&self, view: &str, file: &str) -> Option> { + std::fs::read(self.root.join("run/views").join(view).join(file)).ok() + } + + pub fn mode(&self, view: &str, file: &str) -> u32 { + std::fs::metadata(self.root.join("run/views").join(view).join(file)) + .unwrap() + .permissions() + .mode() + & 0o777 + } +} + +impl Host { + /// Serves the generation of `schema` from the snapshots, or says what that would do. + pub fn migrate(&self, schema: &(Schema, Vec), dry_run: bool) -> Migration { + let store = self.store(); + let _lock = store.lock().unwrap(); + enstate::migrate::migrate(&schema.0, &store, dry_run, &self.systemctl()).unwrap() + } + + /// The current snapshot's id of `channel`. + pub fn snapshot(&self, channel: &str) -> Option { + self.store() + .current(channel) + .unwrap() + .map(|snapshot| snapshot.id) + } +} diff --git a/tests/migrations.rs b/tests/migrations.rs new file mode 100644 index 0000000..7b78b8e --- /dev/null +++ b/tests/migrations.rs @@ -0,0 +1,247 @@ +//! The cases of docs/migrations.md, as far as the first version goes: a renamed slot +//! and a rollback across it, a type that changes without a converter, and what is +//! kept. G1 and G2 are generations, S1 and S2 their schemas. + +mod common; + +use common::Host; +use enstate::view::Change; +use serde_json::{Value, json}; + +fn secrets(slots: Value, views: Value) -> Value { + json!({ "schema": 1, "channels": { "secrets": { "slots": slots } }, "views": views }) +} + +fn rotate(host: &Host, name: &str, slot: &str, bytes: &[u8]) -> std::path::PathBuf { + let address = format!("secrets/{slot}"); + host.submission( + name, + json!({ "channel": "secrets", "items": [{ "address": address, "op": "set" }] }), + &[(address.as_str(), bytes)], + ) +} + +/// Case 1: S2 renames `tinc.key` to `retiolum.key`. Switching to G2 needs no +/// submission; a rotation under G2 stores the state under S2; rolling back to G1 +/// gives it the rotated key, by S2's rename read backwards. +#[test] +fn a_renamed_slot_and_a_rollback() { + let host = Host::new("rename"); + let s1 = host.schema(secrets( + json!({ "tinc.key": { "type": "application/octet-stream", "secret": true } }), + json!({ "tinc.key": { "from": ["secrets/tinc.key"], "reactions": { "restart": ["tinc.service"] } } }), + )); + let s2_value = secrets( + json!({ "retiolum.key": { "type": "application/octet-stream", "secret": true, "renamedFrom": "tinc.key" } }), + json!({ "retiolum.key": { "from": ["secrets/retiolum.key"], "reactions": { "restart": ["tincr.service"] } } }), + ); + // G1 runs, K submitted. + assert!( + host.apply(&s1, &rotate(&host, "k", "tinc.key", b"K")) + .accepted + ); + let first = host.snapshot("secrets").unwrap(); + + // Before switching to G2: it would see K, under its new name. + let s2 = host.schema(s2_value.clone()); + let migration = host.migrate(&s2, true); + assert!(migration.accepted, "{migration:?}"); + assert!( + migration.channels["secrets"].seen.notes[0] + .contains("secrets/retiolum.key: from secrets/tinc.key, renamed"), + "{migration:?}" + ); + assert!(host.view("tinc.key", "tinc.key").is_some()); + + // Switching: the views follow, the snapshot isn't rewritten. + let migration = host.migrate(&s2, false); + assert!( + migration.accepted && migration.failed.is_empty(), + "{migration:?}" + ); + assert_eq!(host.view("retiolum.key", "retiolum.key").unwrap(), b"K"); + assert!(host.view("tinc.key", "tinc.key").is_none()); + assert!(host.reactions().contains("restart tincr.service")); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.id, first); + assert_eq!(stored.schema, s1.1); + + // Rotating under G2 stores the state under S2, and nothing is kept: tinc.key went + // into retiolum.key. + let plan = host.apply(&s2, &rotate(&host, "k2", "retiolum.key", b"K'")); + assert!(plan.accepted && plan.warnings.is_empty(), "{plan:?}"); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.schema, s2.1); + assert_eq!(stored.content.keys().collect::>(), ["retiolum.key"]); + assert!(stored.kept.is_empty()); + + // Rolling back to G1: tinc.key is the rotated key, from S2's rename. + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + let migration = host.migrate(&s1, false); + assert!(migration.accepted, "{migration:?}"); + assert!( + migration.channels["secrets"].seen.notes[0].contains( + "secrets/tinc.key: from secrets/retiolum.key, which the schema it was accepted under renamed from it" + ), + "{migration:?}" + ); + assert_eq!(host.view("tinc.key", "tinc.key").unwrap(), b"K'"); + assert!(host.view("retiolum.key", "retiolum.key").is_none()); +} + +/// Trying an older generation and back costs nothing: the snapshot stays as it was. +#[test] +fn switching_back_and_forth_rewrites_nothing() { + let host = Host::new("back-and-forth"); + let s1 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({ "a": { "from": ["secrets/a"] } }), + )); + assert!(host.apply(&s1, &rotate(&host, "a", "a", b"A")).accepted); + let id = host.snapshot("secrets").unwrap(); + let s2 = host.schema(secrets( + json!({ "b": { "type": "application/octet-stream", "renamedFrom": "a" } }), + json!({ "b": { "from": ["secrets/b"] } }), + )); + assert!(host.migrate(&s2, false).accepted); + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + assert!(host.migrate(&s1, false).accepted); + assert!(host.migrate(&s2, false).accepted); + assert_eq!(host.snapshot("secrets").unwrap(), id); + assert_eq!(host.view("b", "b").unwrap(), b"A"); +} + +/// Case 2, without converters (not in the first version): a slot whose type changes +/// can't be filled, so the switch is refused before switching, naming the slot; after +/// a switch anyway (a boot), the views made from it aren't there. +#[test] +fn a_type_without_a_converter() { + let host = Host::new("type"); + let fleet = |media_type: &str| { + json!({ + "schema": 1, + "channels": { "fleet": { "slots": { "hosts": { "type": media_type } } } }, + "views": { "hosts": { "from": ["fleet/hosts"] } } + }) + }; + let s1 = host.schema(fleet("application/x-hosts1+json")); + let first = host.submission( + "first", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/ne", "op": "set" }] }), + &[("fleet/hosts", br#"{"ne": {"addr": "a"}}"#)], + ); + assert!(host.apply(&s1, &first).accepted); + let s2 = host.schema(fleet("application/x-hosts2+json")); + let migration = host.migrate(&s2, true); + assert!(!migration.accepted); + assert_eq!( + migration.refused, + ["required slot fleet/hosts can't be filled"] + ); + assert!( + migration.channels["fleet"].seen.notes[0].contains( + "fleet/hosts: type application/x-hosts1+json is now application/x-hosts2+json, and there is no converter" + ), + "{migration:?}" + ); + // The dry run changed nothing; a switch anyway takes the view away. + assert!(host.view("hosts", "hosts").is_some()); + let migration = host.migrate(&s2, false); + assert!(!migration.accepted); + assert!( + migration + .views + .iter() + .any(|view| view.name == "hosts" && view.change == Change::Removed) + ); + assert!(host.view("hosts", "hosts").is_none()); + // A submission made for S2 fills it, and the old entry goes: it is older. + let fresh = host.submission( + "fresh", + json!({ "channel": "fleet", "items": [{ "address": "fleet/hosts/ne", "op": "set" }] }), + &[("fleet/hosts", br#"{"ne": {"addrs": ["a", "b"]}}"#)], + ); + let plan = host.apply(&s2, &fresh); + assert!(plan.accepted, "{plan:?}"); + assert_eq!( + plan.warnings, + [ + "goes, as fleet/hosts is filled anew: the entry of type application/x-hosts1+json kept from before" + ] + ); + assert!(host.view("hosts", "hosts").is_some()); + // Back to G1 is refused before switching: nothing in S2 makes S1's type. + let s1 = host.schema(serde_json::from_slice(&s1.1).unwrap()); + let migration = host.migrate(&s1, true); + assert_eq!( + migration.refused, + ["required slot fleet/hosts can't be filled"] + ); + assert!(migration.channels["fleet"].seen.notes[0].contains("is now application/x-hosts1+json")); +} + +/// What no slot wants is kept, and fills its slot again after a rollback; a complete +/// submission lets it go. +#[test] +fn what_is_kept() { + let host = Host::new("kept"); + let both = secrets( + json!({ + "a": { "type": "application/octet-stream" }, + "extra": { "type": "application/octet-stream", "required": false } + }), + json!({ "extra": { "from": ["secrets/extra"] } }), + ); + let s1 = host.schema(both.clone()); + let first = host.submission( + "first", + json!({ "channel": "secrets", "complete": true, "items": [ + { "address": "secrets/a", "op": "set" }, + { "address": "secrets/extra", "op": "set" } + ] }), + &[("secrets/a", b"A"), ("secrets/extra", b"E")], + ); + assert!(host.apply(&s1, &first).accepted); + let s2 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({}), + )); + let migration = host.migrate(&s2, false); + assert_eq!(migration.channels["secrets"].kept, ["extra"]); + assert!(host.view("extra", "extra").is_none()); + let plan = host.apply(&s2, &rotate(&host, "a2", "a", b"A2")); + assert_eq!( + plan.warnings, + ["kept, in no slot of the schema: secrets/extra"] + ); + let stored = host.store().current("secrets").unwrap().unwrap(); + assert_eq!(stored.kept["extra"].1, b"E"); + // Back to G1: extra is there again. + let s1 = host.schema(both); + let migration = host.migrate(&s1, false); + assert!(migration.channels["secrets"].seen.notes[0].contains("from what was kept")); + assert_eq!(host.view("extra", "extra").unwrap(), b"E"); + // Under G2 again, a complete submission lets it go. + let s2 = host.schema(secrets( + json!({ "a": { "type": "application/octet-stream" } }), + json!({}), + )); + let complete = host.submission( + "complete", + json!({ "channel": "secrets", "complete": true, "items": [{ "address": "secrets/a", "op": "set" }] }), + &[("secrets/a", b"A3")], + ); + let plan = host.apply(&s2, &complete); + assert_eq!( + plan.warnings, + ["goes, as the submission is complete: secrets/extra, which was kept"] + ); + assert!( + host.store() + .current("secrets") + .unwrap() + .unwrap() + .kept + .is_empty() + ); +} diff --git a/tests/receptor.rs b/tests/receptor.rs index 496140b..034e2a8 100644 --- a/tests/receptor.rs +++ b/tests/receptor.rs @@ -2,107 +2,15 @@ //! reactions, packing, materializing, and the command line. Validators and renderers //! are shell scripts. -use std::os::unix::fs::PermissionsExt; -use std::path::{Path, PathBuf}; +mod common; + use std::process::Command; -use enstate::plan::{self, Plan}; -use enstate::schema::Schema; -use enstate::store::Store; +use common::Host; use enstate::submission::Submission; use enstate::view::Change; use serde_json::{Value, json}; -struct Host { - root: PathBuf, -} - -impl Host { - fn new(name: &str) -> Self { - let root = Path::new(env!("CARGO_TARGET_TMPDIR")) - .join("receptor") - .join(name); - let _ = std::fs::remove_dir_all(&root); - std::fs::create_dir_all(root.join("programs")).unwrap(); - Self { root } - } - - fn store(&self) -> Store { - Store::new(&self.root.join("state"), &self.root.join("run")) - } - - /// A shell script, with the tests' PATH (programs get an empty environment). - fn program(&self, name: &str, body: &str) -> String { - let path = self.root.join("programs").join(name); - let script = format!( - "#!/bin/sh\nPATH={}\nset -eu\n{body}\n", - std::env::var("PATH").unwrap() - ); - std::fs::write(&path, script).unwrap(); - std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); - path.display().to_string() - } - - fn schema(&self, schema: Value) -> (Schema, Vec) { - let bytes = serde_json::to_vec_pretty(&schema).unwrap(); - std::fs::write(self.root.join("schema.json"), &bytes).unwrap(); - (Schema::from_slice(&bytes).unwrap(), bytes) - } - - /// A submission named `name`: its manifest, and files below `channels/`. - fn submission(&self, name: &str, manifest: Value, files: &[(&str, &[u8])]) -> PathBuf { - let dir = self.root.join("submissions").join(name); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - let mut manifest = manifest; - manifest["submission"] = json!(1); - std::fs::write(dir.join("manifest.json"), manifest.to_string()).unwrap(); - for (path, bytes) in files { - let path = dir.join("channels").join(path); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::fs::write(path, bytes).unwrap(); - } - dir - } - - fn plan(&self, schema: &Schema, dir: &Path) -> Plan { - let submission = Submission::load(dir).unwrap(); - plan::plan(schema, &self.store(), &submission).unwrap().plan - } - - fn apply(&self, schema: &(Schema, Vec), dir: &Path) -> Plan { - let submission = Submission::load(dir).unwrap(); - let store = self.store(); - let _lock = store.lock().unwrap(); - plan::plan(&schema.0, &store, &submission) - .unwrap() - .apply(&store, &schema.1, &self.systemctl()) - .unwrap() - } - - /// A systemctl that writes down what it was asked. - fn systemctl(&self) -> PathBuf { - let log = self.root.join("systemctl.log"); - PathBuf::from(self.program("systemctl", &format!("echo \"$*\" >> {}", log.display()))) - } - - fn reactions(&self) -> String { - std::fs::read_to_string(self.root.join("systemctl.log")).unwrap_or_default() - } - - fn view(&self, view: &str, file: &str) -> Option> { - std::fs::read(self.root.join("run/views").join(view).join(file)).ok() - } - - fn mode(&self, view: &str, file: &str) -> u32 { - std::fs::metadata(self.root.join("run/views").join(view).join(file)) - .unwrap() - .permissions() - .mode() - & 0o777 - } -} - /// A host's secrets: a key, its public half, an optional extra; a validator across /// the key pair; each entry its own view, the key restarting a service. fn secrets_schema(host: &Host) -> Value { @@ -338,6 +246,7 @@ fn refusals_and_what_is_left_out() { ("extra".to_owned(), b"broken".to_vec()), ] .into(), + &Default::default(), None, &schema2.1, ) @@ -483,7 +392,7 @@ fn materialize_after_boot_and_switch() { assert!(host.apply(&schema, &first).accepted); // Boot: /run is empty. std::fs::remove_dir_all(host.root.join("run")).unwrap(); - let views = plan::materialize(&schema.0, &host.store()).unwrap(); + let views = enstate::migrate::materialize(&schema.0, &host.store()).unwrap(); assert!( views.iter().all(|view| view.change == Change::Added), "{views:?}" @@ -493,7 +402,7 @@ fn materialize_after_boot_and_switch() { let mut fewer = secrets_schema(&host); fewer["views"].as_object_mut().unwrap().remove("a.pub"); let fewer = host.schema(fewer); - let views = plan::materialize(&fewer.0, &host.store()).unwrap(); + let views = enstate::migrate::materialize(&fewer.0, &host.store()).unwrap(); assert!( views .iter() -- cgit v1.3.1