//! Btrfs snapshot creation and transaction history. //! //! Snapshots are read-only and live under the `@snapshots` subvolume //! (`/.snapshots`). A record is appended to the history before the operation //! and marked committed only afterwards. Real rollback (default-subvolume //! switching plus `/boot` handling) is deliberately *not* implemented here; the //! foundations are. //! //! `/home` is a separate subvolume and is intentionally not snapshotted by //! default, so a future system rollback cannot discard user documents. use std::path::{Path, PathBuf}; use phoebus_core::rollback::{ snapshot_retention_deletions, DEFAULT_KEEP_SNAPSHOTS, MIN_FREE_SPACE_BYTES, }; use phoebus_core::snapshot::{snapshot_name, SnapshotHistory, SnapshotRecord, SnapshotStatus}; use crate::auth::DestructiveAuthorization; use crate::command::CommandSpec; use crate::error::{ExecError, Result}; use crate::exec::Exec; pub const SNAPSHOT_DIR: &str = ".snapshots"; pub const HISTORY_REL: &str = "var/lib/phoebus/snapshot-history.toml"; /// The separately mounted `/var` subvolume holding package-manager state. pub const VAR_SUBVOL: &str = "@var"; pub fn snapshots_path(root: &Path) -> PathBuf { root.join(SNAPSHOT_DIR) } pub fn history_path(root: &Path) -> PathBuf { root.join(HISTORY_REL) } /// Read the transaction history, surfacing a corrupt file instead of hiding it. /// /// A missing or zero-length file is empty; anything else is an error so a /// caller never mistakes an unreadable history for "no snapshots". pub fn read_history(root: &Path) -> Result { SnapshotHistory::load(&history_path(root)).map_err(ExecError::Core) } /// The transaction history, or a logged warning and the last-known-empty /// history. Only for read paths that must not fail a `sys` query. pub fn read_history_lossy(exec: &Exec, root: &Path) -> SnapshotHistory { match read_history(root) { Ok(history) => history, Err(e) => { exec.logger.warn(format!( "snapshot history is unreadable: {e}; treating as unavailable" )); SnapshotHistory::default() } } } pub fn write_history(root: &Path, history: &SnapshotHistory) -> Result<()> { use std::os::unix::fs::PermissionsExt; let target = phoebus_core::TargetRoot::new(root); let text = toml::to_string_pretty(history) .map_err(|e| ExecError::operation("snapshot", "serialize history", e.to_string()))?; let path = target.write(HISTORY_REL, text)?; // This contains snapshot identifiers/status, not credentials. `sys history` // is a normal-user query; keep its metadata readable and root writable. if let Some(parent) = path.parent() { std::fs::set_permissions(parent, std::fs::Permissions::from_mode(0o755)) .map_err(|e| ExecError::io(parent.to_path_buf(), e))?; } std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)) .map_err(|e| ExecError::io(path, e))?; Ok(()) } fn now_unix() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } /// Create a read-only snapshot of `source_subvol` (usually the mounted root). pub fn create( exec: &Exec, _auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, operation: &str, ) -> Result { let dir = snapshots_path(root); std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; let unix = now_unix(); let name = snapshot_name("@", unix, operation); let dest = dir.join(&name); exec.run( CommandSpec::new("snapshot", format!("create snapshot {name}"), "btrfs") .args(["subvolume", "snapshot", "-r"]) .arg(source_subvol) .arg(dest.to_string_lossy().to_string()), )?; let record = SnapshotRecord { id: name.clone(), created_unix: unix, operation: operation.to_string(), source_subvol: source_subvol.to_string(), snapshot_subvol: name, var_snapshot: None, status: SnapshotStatus::Created, }; Ok(record) } /// Create a read-only snapshot of one source subvolume by explicit name. pub fn create_named( exec: &Exec, _auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, name: &str, ) -> Result<()> { let dir = snapshots_path(root); std::fs::create_dir_all(&dir).map_err(|e| ExecError::io(dir.clone(), e))?; let dest = dir.join(name); exec.run( CommandSpec::new("snapshot", format!("create snapshot {name}"), "btrfs") .args(["subvolume", "snapshot", "-r"]) .arg(source_subvol) .arg(dest.to_string_lossy().to_string()), )?; Ok(()) } /// Snapshot the mounted root and, when `/var` is a separate Btrfs subvolume, /// its `/var` volume under the same timestamp/operation name. /// /// `/home` is intentionally excluded so a system rollback cannot discard user /// documents. pub fn create_set( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, operation: &str, ) -> Result { let var_source = if var_is_separate_subvol(root) { Some("/var") } else { None }; create_set_at(exec, auth, root, source_subvol, var_source, operation) } /// As `create_set`, but with an explicit `/var` source so the installer can /// capture the target's `@var` (whose mount point is not the host `/var`). pub fn create_set_at( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, var_source: Option<&str>, operation: &str, ) -> Result { let unix = now_unix(); let name = snapshot_name("@", unix, operation); create_named(exec, auth, root, source_subvol, &name)?; let var_snapshot = match var_source { Some(source) => { let var_name = snapshot_name("@var", unix, operation); create_named(exec, auth, root, source, &var_name)?; Some(var_name) } None => None, }; Ok(SnapshotRecord { id: name.clone(), created_unix: unix, operation: operation.to_string(), source_subvol: source_subvol.to_string(), snapshot_subvol: name, var_snapshot, status: SnapshotStatus::Created, }) } /// Whether `/var` is a separate Btrfs subvolume of the running system. /// /// `/home` and `/var` are separate subvolumes in the proven layout. A target /// root that is not the running `/` (the installer) has no separate `/var`, and /// tests use a temporary directory, so this is false there. pub fn var_is_separate_subvol(root: &Path) -> bool { if root != Path::new("/") { return false; } match std::fs::read_to_string("/proc/self/mountinfo") { Ok(text) => parse_mountinfo_var(&text), Err(_) => false, } } /// Pure parser used by `var_is_separate_subvol` so the decision is testable. pub fn parse_mountinfo_var(text: &str) -> bool { for line in text.lines() { // mountinfo: id parent maj:min root mountpoint opts... - fstype source ... let fields: Vec<&str> = line.split_whitespace().collect(); let Some(sep) = fields.iter().position(|f| *f == "-") else { continue; }; let mountpoint = fields.get(4).copied(); let fstype = fields.get(sep + 1).copied(); if mountpoint == Some("/var") && fstype == Some("btrfs") { return true; } } false } /// Create a snapshot set and record it as committed in the history. pub fn create_set_and_record( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, operation: &str, ) -> Result { create_set_and_record_at(exec, auth, root, source_subvol, None, operation) } /// As `create_set_and_record`, with an explicit `/var` source (installer). pub fn create_set_and_record_at( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, var_source: Option<&str>, operation: &str, ) -> Result { let mut record = if var_source.is_some() { create_set_at(exec, auth, root, source_subvol, var_source, operation)? } else { create_set(exec, auth, root, source_subvol, operation)? }; record.status = SnapshotStatus::Committed; let mut history = read_history(root)?; history.append(record.clone()); write_history(root, &history)?; exec.logger .info(format!("snapshot committed: {}", record.id)); Ok(record) } /// Create a snapshot and record it as committed in the history. /// /// This captures the root and the separately mounted `/var` together so a /// restored system has consistent package-manager state. pub fn create_and_record( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, source_subvol: &str, operation: &str, ) -> Result { create_set_and_record(exec, auth, root, source_subvol, operation) } pub fn list(_exec: &Exec, root: &Path) -> Result> { let dir = snapshots_path(root); if !dir.is_dir() { return Ok(Vec::new()); } let mut names: Vec = std::fs::read_dir(&dir) .map_err(|e| ExecError::io(dir.clone(), e))? .flatten() .map(|e| e.file_name().to_string_lossy().to_string()) .collect(); names.sort(); Ok(names) } pub fn delete(exec: &Exec, _auth: &DestructiveAuthorization, root: &Path, id: &str) -> Result<()> { let target = snapshots_path(root).join(id); exec.run( CommandSpec::new("snapshot", format!("delete snapshot {id}"), "btrfs") .args(["subvolume", "delete"]) .arg(target.to_string_lossy().to_string()), )?; Ok(()) } /// Parse the available-bytes figure from `df -B1 --output=avail` output. pub fn parse_df_avail(text: &str) -> Option { text.lines() .rev() .find_map(|line| line.trim().parse::().ok()) } /// Free bytes on the filesystem backing `path`, or an error if it cannot be /// determined. A rollback refuses to run when space cannot be checked. pub fn free_space_bytes(exec: &Exec, path: &Path) -> Result { let out = exec.run_capture( CommandSpec::new("snapshot", "check free space", "df") .args(["-B1", "--output=avail"]) .arg(path.to_string_lossy().to_string()), )?; parse_df_avail(&out.stdout_lossy()).ok_or_else(|| { ExecError::operation( "snapshot", "check free space", format!("could not parse df output for {}", path.display()), ) }) } /// Require at least `min_bytes` free before a space-consuming operation. pub fn require_free_space(exec: &Exec, path: &Path, min_bytes: u64) -> Result { let avail = free_space_bytes(exec, path)?; if avail < min_bytes { return Err(ExecError::operation( "snapshot", "check free space", format!( "only {avail} bytes free on {}; {min_bytes} required", path.display() ), )); } Ok(avail) } /// Prune committed snapshots beyond `keep`, protecting the latest and any /// in-flight rollback target. Returns the ids that were deleted. pub fn apply_retention( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, ) -> Result> { apply_retention_with(exec, auth, root, DEFAULT_KEEP_SNAPSHOTS, &[]) } pub fn apply_retention_with( exec: &Exec, auth: &DestructiveAuthorization, root: &Path, keep: usize, protect: &[String], ) -> Result> { let history = read_history(root)?; let deletions = snapshot_retention_deletions(&history, keep, protect); if deletions.is_empty() { return Ok(Vec::new()); } for id in &deletions { if let Some(record) = history.records.iter().find(|r| &r.id == id) { if let Some(var) = &record.var_snapshot { let _ = delete(exec, auth, root, var); } } delete(exec, auth, root, id)?; exec.logger.info(format!("pruned snapshot {id}")); } // Drop the pruned records from the history so it stays truthful. let mut pruned = SnapshotHistory::default(); for record in history.records { if !deletions.contains(&record.id) { pruned.append(record); } } write_history(root, &pruned)?; Ok(deletions) } /// The minimum free space a rollback requires. pub fn rollback_space_requirement() -> u64 { MIN_FREE_SPACE_BYTES } #[cfg(test)] mod tests { use super::*; use crate::command::RecordingRunner; use crate::log::Logger; use phoebus_core::Redactor; fn make_exec(runner: RecordingRunner) -> Exec { let path = tempfile::tempdir().unwrap().keep(); let logger = Logger::open(path.join("l.log"), Redactor::new(), false); Exec::new(Box::new(runner), logger, false, path.join("root"), path) } #[test] fn snapshot_metadata_remains_readable_after_private_bootstrap() { use std::os::unix::fs::PermissionsExt; let exec = make_exec(RecordingRunner::new()); let path = history_path(&exec.root); std::fs::create_dir_all(path.parent().unwrap()).unwrap(); std::fs::write(&path, "").unwrap(); std::fs::set_permissions( path.parent().unwrap(), std::fs::Permissions::from_mode(0o700), ) .unwrap(); std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); write_history(&exec.root, &SnapshotHistory::default()).unwrap(); assert_eq!( std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o644 ); assert_eq!( std::fs::metadata(path.parent().unwrap()) .unwrap() .permissions() .mode() & 0o777, 0o755 ); assert!(read_history(&exec.root).unwrap().records.is_empty()); } #[test] fn create_uses_readonly_btrfs_snapshot() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let record = create(&exec, &auth, Path::new(&exec.root), "/", "sys update").unwrap(); assert_eq!(record.status, SnapshotStatus::Created); let spec = &runner.recorded()[0]; assert_eq!(spec.program, "btrfs"); assert_eq!(&spec.args[0..3], &["subvolume", "snapshot", "-r"]); assert!(spec.args.iter().any(|a| a.contains(".snapshots"))); } #[test] fn create_and_record_commits_history() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let record = create_and_record(&exec, &auth, Path::new(&exec.root), "/", "risk").unwrap(); assert_eq!(record.status, SnapshotStatus::Committed); let history = read_history(Path::new(&exec.root)).unwrap(); assert_eq!(history.records.len(), 1); assert_eq!(history.latest().unwrap().id, record.id); } #[test] fn corrupt_history_is_surfaced() { let runner = RecordingRunner::new(); let exec = make_exec(runner); let history_path = history_path(Path::new(&exec.root)); std::fs::create_dir_all(history_path.parent().unwrap()).unwrap(); std::fs::write(&history_path, "not = = toml [[[").unwrap(); assert!(read_history(Path::new(&exec.root)).is_err()); // The lossy variant keeps read paths working but does not pretend the // history was empty. let lossy = read_history_lossy(&exec, Path::new(&exec.root)); assert!(lossy.records.is_empty()); } #[test] fn coordinated_snapshot_captures_var_when_explicit() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let record = create_set_at( &exec, &auth, Path::new(&exec.root), "/mnt/phoebus", Some("/mnt/phoebus/var"), "sys update", ) .unwrap(); assert!(record.var_snapshot.is_some()); let args: Vec = runner .recorded() .iter() .flat_map(|s| s.args.clone()) .collect(); assert!(args.iter().any(|a| a.contains("@var"))); } #[test] fn df_avail_parser_takes_the_last_numeric_line() { assert_eq!(parse_df_avail("Avail\n1073741824\n"), Some(1_073_741_824)); assert_eq!(parse_df_avail("10\n20\n30\n"), Some(30)); assert_eq!(parse_df_avail("no numbers here\n"), None); } #[test] fn mountinfo_detects_a_separate_var() { let line = "25 30 0:23 / /var rw,relatime - btrfs /dev/vda2 rw,subvolid=258,subvol=/@var"; assert!(parse_mountinfo_var(line)); assert!(!parse_mountinfo_var( "1 0 8:1 / / ext4 rw - ext4 /dev/sda1 rw" )); } #[test] fn retention_prunes_old_committed_and_rewrites_history() { let runner = RecordingRunner::new(); let exec = make_exec(runner.clone()); let auth = crate::auth::authorize(&crate::auth::AutoConfirm, "p", "f").unwrap(); let root = Path::new(&exec.root); let mut history = SnapshotHistory::default(); for i in 0..4u64 { history.append(SnapshotRecord { id: format!("@-{i}"), created_unix: i, operation: "op".into(), source_subvol: "@".into(), snapshot_subvol: format!("@-{i}"), var_snapshot: Some(format!("@var-{i}")), status: SnapshotStatus::Committed, }); } // Materialise the snapshot directories so existence is realistic. let dir = snapshots_path(root); for i in 0..4u64 { std::fs::create_dir_all(dir.join(format!("@-{i}"))).unwrap(); std::fs::create_dir_all(dir.join(format!("@var-{i}"))).unwrap(); } write_history(root, &history).unwrap(); let deletions = apply_retention_with(&exec, &auth, root, 2, &[]).unwrap(); assert_eq!(deletions, vec!["@-0", "@-1"]); let after = read_history(root).unwrap(); assert_eq!(after.records.len(), 2); assert!(!after.records.iter().any(|r| r.id == "@-0")); } #[test] fn space_and_retention_constants_are_sane() { assert!(rollback_space_requirement() >= 512 * 1024 * 1024); } }