//! What a submission would do, and doing it (docs/design.md, 5.5). //! //! The plan: check the channel and the base; apply the items to a copy of the current //! snapshot; run the validators on it, leaving out optional items an objection names, //! with their groups, and refusing for a required one or for what is in place; check //! that every required slot is filled; render the views into scratch and compare. //! Applying: the same, then the new snapshot becomes current, the views that changed //! are put in place, and their reactions run, each unit once. use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::process::Command; use anyhow::{Context, Result, anyhow}; 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::{Kept, Lock, Store}; use crate::submission::{Change, Item, Submission}; use crate::view::{self, FileChange}; #[derive(Debug, Clone, Serialize)] pub struct Plan { pub channel: String, /// The current snapshot's id. pub current: Option, /// The snapshot the submission builds on, if it names one. pub base: Option, pub accepted: bool, /// Why not, if not. pub refused: Vec, pub items: Vec, pub warnings: Vec, pub views: Vec, pub reactions: Reactions, /// Whether the snapshot or a view would change. pub changes: bool, /// The new snapshot's id, once applied. #[serde(skip_serializing_if = "Option::is_none")] pub snapshot: Option, /// Whether it was staged (`--stage`): its views and reactions come with the /// switch to the generation it was planned for. #[serde(skip_serializing_if = "std::ops::Not::not")] pub staged: bool, /// Reactions that failed, once applied. #[serde(skip_serializing_if = "Vec::is_empty")] pub failed: Vec, } #[derive(Debug, Clone, Serialize)] pub struct ItemOutcome { pub address: Address, pub op: &'static str, pub required: bool, #[serde(skip_serializing_if = "Option::is_none")] pub group: Option, pub goes_in: bool, #[serde(skip_serializing_if = "Vec::is_empty")] pub reasons: Vec, } #[derive(Debug, Clone, Serialize)] pub struct ViewOutcome { pub name: String, pub secret: bool, pub change: view::Change, pub files: Vec, } /// A plan, and what applying it needs. pub struct Planned { pub plan: Plan, content: Content, kept: Kept, content_changes: bool, rendered: Vec<(String, Option, bool)>, } /// A plan refused: nothing to apply. fn refused(plan: Plan) -> Result { Ok(Planned { plan, content: Content::new(), kept: Kept::new(), content_changes: false, rendered: Vec::new(), }) } /// Plans `submission` against `schema` and what `store` holds. pub fn plan(schema: &Schema, store: &Store, submission: &Submission) -> Result { let channel = submission.channel.as_str(); let current = store.current(channel)?; let mut plan = Plan { channel: channel.to_owned(), current: current.as_ref().map(|snapshot| snapshot.id.clone()), base: submission.base.clone(), accepted: false, refused: Vec::new(), items: submission .items .iter() .map(|item| ItemOutcome { address: item.address.clone(), op: match item.change { Change::Remove => "remove", _ => "set", }, required: item.required, group: item.group.clone(), goes_in: true, reasons: Vec::new(), }) .collect(), warnings: Vec::new(), views: Vec::new(), reactions: Reactions::default(), changes: false, snapshot: None, staged: false, failed: Vec::new(), }; let Some(channel_spec) = schema.channel(channel) else { plan.refused .push(format!("the schema has no channel {channel}")); return refused(plan); }; if let Some(base) = &submission.base { let current_id = current.as_ref().map(|snapshot| snapshot.id.as_str()); if current_id != Some(base.as_str()) { plan.refused.push(format!( "the submission builds on {base}, but the current snapshot is {}", current_id.unwrap_or("none") )); return refused(plan); } } let empty = Content::new(); // What this generation sees of the snapshot, which may have been accepted under // another schema. let seen = migrate::seen(schema, channel, current.as_ref())?; let base_content = match (¤t, submission.complete) { (Some(_), false) => &seen.content, _ => &empty, }; // Other channels, for validators and views given their slots. let mut others: BTreeMap = BTreeMap::new(); let mut other_channels: BTreeSet<&str> = BTreeSet::new(); for validator in schema.validators_of(channel) { for address in validator.slots { if address.channel != channel { other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); } } } for (_, view) in schema.views_of(Some(channel)) { for address in &view.from { if address.channel != channel { other_channels.insert(schema.channels.get_key_value(&address.channel).unwrap().0); } } } for other in other_channels { let content = migrate::seen(schema, other, store.current(other)?.as_ref())?.content; others.insert(other.to_owned(), content); } let items = &submission.items; // Items that can't go in, whatever the validators say. let mut cannot: BTreeMap = BTreeMap::new(); for (index, item) in items.iter().enumerate() { if let Some(reason) = unfit(schema, item, base_content) { cannot.insert(index, reason); } } let mut excluded: BTreeSet = BTreeSet::new(); let leave_out = |plan: &mut Plan, excluded: &mut BTreeSet, index: usize, reason: String| -> bool { // Whether it may be left out: else the submission is refused. let item = &items[index]; if item.required { plan.refused .push(format!("required item {}: {reason}", item.address)); return false; } for (other, other_item) in items.iter().enumerate() { let together = other == index || (item.group.is_some() && other_item.group == item.group); if together && excluded.insert(other) { plan.items[other].goes_in = false; let reason = if other == index { reason.clone() } else { format!( "its group {} can't go in", item.group.as_deref().unwrap_or_default() ) }; plan.warnings .push(format!("left out: {}: {reason}", other_item.address)); plan.items[other].reasons.push(reason); } } true }; for (index, reason) in &cannot { if !excluded.contains(index) && !leave_out(&mut plan, &mut excluded, *index, reason.clone()) { return refused(plan); } } let candidate = loop { let candidate = apply_items(base_content, items, &excluded); let mut blame: Vec<(usize, String)> = Vec::new(); // Required slots first: validators are given filled slots. for (slot, spec) in &channel_spec.slots { if !spec.required || candidate.contains_key(slot) { continue; } let address = Address::entry(channel, slot); let removals: Vec = (0..items.len()) .filter(|index| !excluded.contains(index)) .filter(|index| { items[*index].address == address && items[*index].change == Change::Remove }) .collect(); if removals.is_empty() { plan.refused .push(format!("required slot {address} is unfilled")); } blame.extend( removals .into_iter() .map(|index| (index, format!("required slot {address} would be unfilled"))), ); } if !plan.refused.is_empty() { return refused(plan); } if blame.is_empty() { // Validators. for validator in schema.validators_of(channel) { let entry = |address: &Address| -> Option<&[u8]> { if address.channel == channel { candidate.get(&address.slot).map(Vec::as_slice) } else { others .get(&address.channel)? .get(&address.slot) .map(Vec::as_slice) } }; if validator.of_type && entry(&validator.slots[0]).is_none() { continue; } let given = Given { slots: validator .slots .iter() .map(|address| { let media_type = schema .slot(address) .map(|slot| slot.media_type.as_str()) .unwrap_or_default(); (address.clone(), (media_type, entry(address))) }) .collect(), }; let outcome = match program::run( &validator.program, Role::Validator, &validator.name, &given, &store.scratch(), ) { Ok(outcome) => outcome, Err(error) => match error.downcast::() { Ok(failed) => { plan.refused.push(failed.to_string()); return refused(plan); } Err(error) => return Err(error), }, }; for objection in outcome.objections { let said = format!( "{}: {} (validator {})", objection.address, objection.message, validator.name ); let blamed: Vec = (0..items.len()) .filter(|index| !excluded.contains(index)) .filter(|index| items[*index].address.overlaps(&objection.address)) .collect(); if blamed.is_empty() { plan.refused .push(format!("objection to what is in place: {said}")); } blame.extend(blamed.into_iter().map(|index| (index, said.clone()))); } } if !plan.refused.is_empty() { return refused(plan); } } if blame.is_empty() { break candidate; } for (index, reason) in blame { if !excluded.contains(&index) && !leave_out(&mut plan, &mut excluded, index, reason) { return refused(plan); } } }; // What no slot wants: kept, unless the submission is complete. let kept = if submission.complete { for slot in seen.kept.keys() { plan.warnings.push(format!( "goes, as the submission is complete: {channel}/{slot}, which was kept" )); } Kept::new() } else { let mut kept = seen.kept.clone(); kept.retain(|slot, (media_type, _)| { let superseded = candidate.contains_key(slot); if superseded { plan.warnings.push(format!( "goes, as {channel}/{slot} is filled anew: the entry of type {media_type} kept from before" )); } !superseded }); for slot in kept.keys() { plan.warnings .push(format!("kept, in no slot of the schema: {channel}/{slot}")); } kept }; // Views. let mut rendered_views = Vec::new(); let mut entries: view::Entries = others .iter() .map(|(name, content)| (name.as_str(), content)) .collect(); entries.insert(channel, &candidate); for (name, view_spec) in schema.views_of(Some(channel)) { let secret = schema.view_is_secret(view_spec); let rendered = match view::render(schema, name, view_spec, &entries, &store.scratch()) { Ok(rendered) => rendered, Err(error) => match error.downcast::() { Ok(failed) => { plan.refused.push(failed.to_string()); return refused(plan); } Err(error) => return Err(error), }, }; 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 { plan.reactions .restart .extend(view_spec.reactions.restart.iter().cloned()); plan.reactions .reload .extend(view_spec.reactions.reload.iter().cloned()); } plan.views.push(ViewOutcome { name: name.clone(), secret, change, files, }); rendered_views.push((name.clone(), rendered, secret)); } let restart: BTreeSet = std::mem::take(&mut plan.reactions.restart) .into_iter() .collect(); let reload: BTreeSet = std::mem::take(&mut plan.reactions.reload) .into_iter() .filter(|unit| !restart.contains(unit)) .collect(); plan.reactions = Reactions { restart: restart.into_iter().collect(), reload: reload.into_iter().collect(), }; let content_changes = current.is_none() || candidate != seen.content || kept != seen.kept; plan.changes = content_changes || plan .views .iter() .any(|view| view.change != view::Change::Unchanged); plan.accepted = true; Ok(Planned { plan, content: candidate, kept, content_changes, rendered: rendered_views, }) } /// Why `item` can't go in, whatever the validators say: no such slot, a record in an /// entry that holds none. fn unfit(schema: &Schema, item: &Item, base: &Content) -> Option { let Some(slot) = schema.slot(&item.address) else { return Some(format!( "the schema has no slot {}", item.address.of_entry() )); }; if item.address.key.is_some() { if !media::keyed(&slot.media_type) { return Some(format!("type {} holds no records", slot.media_type)); } if let Some(bytes) = base.get(&item.address.slot) && let Err(error) = content::records(bytes) { return Some(format!("the entry in place holds no records: {error}")); } } None } /// `base` with the items not `excluded` applied. fn apply_items(base: &Content, items: &[Item], excluded: &BTreeSet) -> Content { let mut content = base.clone(); for (index, item) in items.iter().enumerate() { if excluded.contains(&index) { continue; } let slot = &item.address.slot; match (&item.address.key, &item.change) { (None, Change::Entry(bytes)) => { content.insert(slot.clone(), bytes.clone()); } (None, Change::Remove) => { content.remove(slot); } (Some(key), change) => { // `unfit` made sure an entry in place holds records. let mut records = content .get(slot) .and_then(|bytes| content::records(bytes).ok()) .unwrap_or_default(); match change { Change::Record(value) => { records.insert(key.clone(), value.clone()); } Change::Remove => { records.remove(key); } Change::Entry(_) => unreachable!("an entry's item has no key"), } content.insert(slot.clone(), content::from_records(&records)); } (None, Change::Record(_)) => unreachable!("a record's item has a key"), } } content } impl Planned { /// Applies the plan, if it was accepted: the new snapshot, the views that change, /// and, with `lock` released, their reactions. Units restarted may want the unit /// that runs `--migrate`, which waits for the lock: holding it while they restart /// would deadlock. pub fn apply( self, store: &Store, schema_bytes: &[u8], systemctl: &Path, lock: Lock, ) -> Result { let mut plan = self.plan; if !plan.accepted { return Ok(plan); } if self.content_changes { plan.snapshot = Some(store.commit( &plan.channel, &self.content, &self.kept, plan.current.as_deref(), schema_bytes, )?); } for ((name, rendered, secret), outcome) in self.rendered.into_iter().zip(&plan.views) { if outcome.change != view::Change::Unchanged { store .install_view(&name, rendered, secret) .with_context(|| format!("view {name}"))?; } } drop(lock); plan.failed = react(&plan.reactions, systemctl, Reacting::Apply); Ok(plan) } /// Stages the plan, if it was accepted: only the new snapshot, for the generation /// whose schema it was planned against, before switching to it. No views are put /// 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. 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 { plan.snapshot = Some(store.commit( &plan.channel, &self.content, &self.kept, plan.current.as_deref(), schema_bytes, )?); } Ok(plan) } } /// How reactions are run. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Reacting { /// After applying a submission: units are restarted or reloaded, and started if /// they aren't running (they may have failed for want of their views). Apply, /// After a generation change, from the unit that runs `--migrate`, which units /// using views are ordered after: only units that are running, without waiting /// for them (`--no-block`). A unit that isn't running starts with the views in /// place. Migrate, } /// Runs `reactions` by `systemctl`, each unit once; returns what failed. pub fn react(reactions: &Reactions, systemctl: &Path, how: Reacting) -> Vec { let mut failed = Vec::new(); let (options, restart, reload): (&[&str], _, _) = match how { Reacting::Apply => (&[], "restart", "reload-or-restart"), Reacting::Migrate => (&["--no-block"], "try-restart", "try-reload-or-restart"), }; for (verb, units) in [(restart, &reactions.restart), (reload, &reactions.reload)] { if units.is_empty() { continue; } let result = Command::new(systemctl) .args(options) .arg(verb) .args(units) .status() .map_err(|error| anyhow!("{error}")) .and_then(|status| { if status.success() { Ok(()) } else { Err(anyhow!("{status}")) } }); if let Err(error) = result { failed.push(format!( "{} {verb} {}: {error}", systemctl.display(), units.join(" ") )); } } failed } /// Starts `unit` (the one that runs `--migrate`), without waiting for it, if it has /// failed; what failed in doing so. pub fn start_if_failed(unit: &str, systemctl: &Path) -> Option { let failed = Command::new(systemctl) .args(["is-failed", "--quiet", unit]) .status() .is_ok_and(|status| status.success()); if !failed { return None; } match Command::new(systemctl) .args(["start", "--no-block", unit]) .status() { Ok(status) if status.success() => None, Ok(status) => Some(format!("{} start {unit}: {status}", systemctl.display())), Err(error) => Some(format!("{} start {unit}: {error}", systemctl.display())), } }