aboutsummaryrefslogtreecommitdiffstats
path: root/src/migrate.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/migrate.rs')
-rw-r--r--src/migrate.rs325
1 files changed, 325 insertions, 0 deletions
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<String>,
+ /// Required slots nothing fills.
+ pub unfilled: Vec<String>,
+}
+
+impl Seen {
+ /// The names of the entries kept.
+ pub fn kept_names(&self) -> Vec<String> {
+ 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<Seen> {
+ 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<BTreeMap<String, Seen>> {
+ let mut all = BTreeMap::new();
+ let mut channels: BTreeSet<String> = 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<String, Seen>,
+ dry_run: bool,
+) -> Result<Vec<ViewOutcome>> {
+ 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<Vec<ViewOutcome>> {
+ 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<String>,
+ pub channels: BTreeMap<String, ChannelMigration>,
+ pub views: Vec<ViewOutcome>,
+ pub reactions: Reactions,
+ pub dry_run: bool,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub failed: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ChannelMigration {
+ pub snapshot: Option<String>,
+ #[serde(flatten)]
+ pub seen: Seen,
+ pub kept: Vec<String>,
+}
+
+/// 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<Migration> {
+ 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,
+ })
+}