//! Snapshots on disk, and the views in place (docs/design.md, 5.8). //! //! ```text //! STATE/lock //! STATE/channels/CHANNEL/current -> snapshots/ID //! 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 //! 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 //! ``` //! //! Entries are root's (mode 0600), and the state directory is 0700. A new snapshot //! or view generation is written next to the old one and put in place by replacing //! a symbolic link, so a reader sees one or the other, never a mix; a snapshot is //! flushed to disk before that, so a crash leaves the old one or the new one. use std::fs::File; use std::os::unix::fs::DirBuilderExt; use std::path::{Path, PathBuf}; use anyhow::{Context, Result, bail}; 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, /// bubblewrap, for running programs in a sandbox (`program::Runner`). pub sandbox: Option, } #[derive(Debug, Clone)] 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, } #[derive(Serialize, Deserialize)] #[serde(deny_unknown_fields)] 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. pub struct Lock(#[allow(dead_code)] File); impl Store { /// The store in `state` and `run`, made absolute: programs run in a directory of /// their own. pub fn new(state: &Path, run: &Path) -> Self { let absolute = |path: &Path| std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); Self { state: absolute(state), run: absolute(run), sandbox: None, } } /// Waits for, and takes, the store's lock: one receptor at a time. pub fn lock(&self) -> Result { create_dir(&self.state, 0o700)?; // Whatever created it (a deploy copying into incoming/, say), it is root's. use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(&self.state, std::fs::Permissions::from_mode(0o700)) .with_context(|| format!("chmod {}", self.state.display()))?; let path = self.state.join("lock"); let file = File::options() .create(true) .truncate(false) .write(true) .open(&path) .with_context(|| format!("opening {}", path.display()))?; file.lock() .with_context(|| format!("locking {}", path.display()))?; Ok(Lock(file)) } /// Where programs get their scratch directories. pub fn scratch(&self) -> PathBuf { self.run.join("tmp") } /// How programs run: their scratch directories, and the sandbox. pub fn runner(&self) -> crate::program::Runner { crate::program::Runner { scratch: self.scratch(), sandbox: self.sandbox.clone(), } } /// The store, its programs run in a sandbox by `bwrap` (bubblewrap), or not. pub fn with_sandbox(mut self, bwrap: Option) -> Self { self.sandbox = bwrap; self } fn channel_dir(&self, channel: &str) -> PathBuf { self.state.join("channels").join(channel) } /// The channels that have a snapshot. pub fn channels(&self) -> Result> { let dir = self.state.join("channels"); let mut channels = Vec::new(); match std::fs::read_dir(&dir) { Ok(entries) => { for entry in entries { if let Ok(name) = entry?.file_name().into_string() { channels.push(name); } } } Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} Err(error) => return Err(error).with_context(|| format!("reading {}", dir.display())), } channels.sort(); Ok(channels) } /// The current snapshot of `channel`, if there is one. pub fn current(&self, channel: &str) -> Result> { let link = self.channel_dir(channel).join("current"); let target = match std::fs::read_link(&link) { Ok(target) => target, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(error).with_context(|| format!("reading {}", link.display())), }; let dir = self.channel_dir(channel).join(target); let path = dir.join("snapshot.json"); let file: SnapshotFile = serde_json::from_slice( &std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?, ) .with_context(|| format!("reading {}", path.display()))?; if file.channel != channel { bail!("{} is of channel {}", path.display(), file.channel); } 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`, 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 { let id = crate::new_id()?; let snapshots = self.channel_dir(channel).join("snapshots"); create_dir(&snapshots, 0o700)?; let new = snapshots.join(format!(".{id}.new")); create_dir(&new, 0o700)?; let file = SnapshotFile { 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"), &serde_json::to_vec_pretty(&file)?, 0o600, )?; 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)?; } // On disk before it is put in place, and in place before the old one goes: a // crash leaves the old snapshot or the new one, whole. sync_tree(&new)?; std::fs::rename(&new, snapshots.join(&id))?; sync_dir(&snapshots)?; let old = std::fs::read_link(self.channel_dir(channel).join("current")).ok(); replace_link( &self.channel_dir(channel).join("current"), &Path::new("snapshots").join(&id), )?; sync_dir(&self.channel_dir(channel))?; if let Some(old) = old { std::fs::remove_dir_all(self.channel_dir(channel).join(old))?; } 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(), sandbox: self.sandbox.clone(), }) } /// 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); std::fs::read_link(&link).ok()?; Some(link) } /// Puts what was rendered for the view `name` in place (or, if nothing was, takes /// it away), readable by root only if it is secret. pub fn install_view(&self, name: &str, rendered: Option, secret: bool) -> Result<()> { let views = self.run.join("views"); create_dir(&views, 0o755)?; let link = views.join(name); let old = std::fs::read_link(&link).ok(); match rendered { Some(rendered) => { let generations = views.join(".generations"); create_dir(&generations, 0o755)?; let mode = if secret { 0o600 } else { 0o644 }; rendered.set_modes(mode)?; let target = Path::new(".generations").join(format!("{name}.{}", crate::new_id()?)); std::fs::rename(rendered.path(), views.join(&target)) .with_context(|| format!("moving view {name} in place"))?; rendered.keep(); replace_link(&link, &target)?; } None => { if old.is_some() { std::fs::remove_file(&link)?; } } } if let Some(old) = old { std::fs::remove_dir_all(views.join(old))?; } Ok(()) } } fn create_dir(path: &Path, mode: u32) -> Result<()> { std::fs::DirBuilder::new() .recursive(true) .mode(mode) .create(path) .with_context(|| format!("creating {}", path.display())) } /// Points the symbolic link `link` at `target`, atomically. fn replace_link(link: &Path, target: &Path) -> Result<()> { let name = link.file_name().unwrap_or_default().to_string_lossy(); let new = link.with_file_name(format!(".{name}.new-link")); let _ = std::fs::remove_file(&new); 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(()) } /// Flushes the files below `dir`, and the directories (`dir` too), to disk. fn sync_tree(dir: &Path) -> Result<()> { for entry in std::fs::read_dir(dir)? { let entry = entry?; let kind = entry.file_type()?; if kind.is_dir() { sync_tree(&entry.path())?; } else if kind.is_file() { File::open(entry.path()) .and_then(|file| file.sync_all()) .with_context(|| format!("flushing {}", entry.path().display()))?; } } sync_dir(dir) } /// Flushes the directory `dir`, its entries' names, to disk. fn sync_dir(dir: &Path) -> Result<()> { File::open(dir) .and_then(|file| file.sync_all()) .with_context(|| format!("flushing {}", dir.display())) }