//! 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::{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. #[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, /// 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, } #[derive(Debug, Clone, Serialize)] pub struct ChannelMigration { pub snapshot: Option, #[serde(flatten)] pub seen: Seen, pub kept: Vec, } /// 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(); 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 { 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 { accepted: refused.is_empty(), refused, channels, views, reactions, dry_run, incoming, failed, }) }