//! Rollback and recovery model. //! //! Rollback is deliberately explicit about the pieces that must move together: //! the root subvolume selection (kernel command line *and* fstab *and* the Btrfs //! default), the separately mounted `@var` volume (package database, Portage //! state, caches), and the kernel/initramfs pairing on the ESP. These are pure //! types and planners; the privileged executor performs the commands. //! //! The reader must never assume that changing the Btrfs default subvolume //! overrides the explicit `rootflags=subvol=...` in the kernel command line: the //! explicit argument wins, so boot entries are rewritten as well. use serde::{Deserialize, Serialize}; use crate::snapshot::{compact_utc, SnapshotHistory, SnapshotRecord, SnapshotStatus}; /// Snapshot subvolumes kept by default before the oldest committed ones are /// pruned. pub const DEFAULT_KEEP_SNAPSHOTS: usize = 8; /// Root generations (`@restore-*`) kept by default. pub const DEFAULT_KEEP_ROOT_GENERATIONS: usize = 3; /// Free space required before a rollback, on top of the snapshot's own usage. pub const MIN_FREE_SPACE_BYTES: u64 = 1024 * 1024 * 1024; /// The lifecycle of a rollback. A rollback is only `Verified` after the system /// has booted from the restored root and the package state checked out. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "snake_case")] pub enum RollbackStatus { /// No rollback has been attempted. #[default] Idle, /// Subvolumes were prepared; boot entries still point at the previous root /// until activation completes. An interruption here is safe: the system /// boots the previous root. Planned, /// Boot entries now select the restored root; awaiting the next boot. Activated, /// The system booted the restored root and the package state is consistent. Verified, /// A step failed. The system still boots a known root; re-running resumes. Failed, } impl RollbackStatus { /// Whether a rollback is in flight and its target must be protected from /// retention pruning. pub fn in_flight(self) -> bool { matches!(self, RollbackStatus::Planned | RollbackStatus::Activated) } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(default)] pub struct RollbackState { pub status: RollbackStatus, /// Monotonic generation number, for human diagnostics and ordering. pub generation: u64, /// The snapshot id that was selected as the restore source. pub target_snapshot: String, /// The paired `@var` snapshot, when one was captured. pub target_var_snapshot: Option, /// The root subvolume that was active before the rollback. pub previous_root: String, /// The new root subvolume booted after the rollback. pub root_subvol: String, /// The paired new `/var` subvolume, when applicable. pub var_subvol: Option, /// The BLS entry file selected to boot the restored root. pub boot_entry: Option, pub started_unix: u64, pub finished_unix: u64, pub note: String, } impl Default for RollbackState { fn default() -> Self { Self { status: RollbackStatus::Idle, generation: 0, target_snapshot: String::new(), target_var_snapshot: None, previous_root: "@".into(), root_subvol: "@".into(), var_subvol: None, boot_entry: None, started_unix: 0, finished_unix: 0, note: String::new(), } } } impl RollbackState { /// The subvolume id/name that should be protected from pruning. pub fn protected_subvols(&self) -> Vec { let mut out = vec![self.root_subvol.clone()]; if let Some(var) = &self.var_subvol { out.push(var.clone()); } out } } /// A root generation created by a rollback (a writable clone of a snapshot). pub fn restore_root_name(ts: u64) -> String { format!("@restore-{}", compact_utc(ts)) } /// The paired `/var` generation created by a rollback. pub fn restore_var_name(ts: u64) -> String { format!("@varrestore-{}", compact_utc(ts)) } /// A safety snapshot of the current root, taken before a rollback overwrites /// the boot selection. pub fn pre_rollback_snapshot_name(ts: u64) -> String { format!("@-{}-pre-rollback", compact_utc(ts)) } /// A safety snapshot of the current `/var`. pub fn pre_rollback_var_snapshot_name(ts: u64) -> String { format!("@var-{}-pre-rollback", compact_utc(ts)) } /// The subvolume path of a snapshot record relative to the Btrfs top level /// (subvolid 5): snapshots live under the `@snapshots` subvolume. pub fn snapshot_top_level_path(name: &str) -> String { format!("@snapshots/{name}") } /// The device backing the running root, from `/proc/self/mounts` text /// (`source mountpoint fstype options dump pass`). pub fn root_device_from_mounts(text: &str) -> Option { for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); if fields.len() >= 3 && fields[1] == "/" { return Some(fields[0].to_string()); } } None } /// The ESP mount point (a vfat filesystem, conventionally `/efi`), from /// `/proc/self/mounts` text. pub fn esp_mount_from_mounts(text: &str) -> Option { for line in text.lines() { let fields: Vec<&str> = line.split_whitespace().collect(); if fields.len() >= 3 && fields[2] == "vfat" && fields[1] != "/" { return Some(fields[1].to_string()); } } None } /// Rewrite the `subvol=` component of the fstab line for `mountpoint`, /// preserving every other field and option. Returns the text unchanged when no /// matching line exists so the caller can detect the miss separately. pub fn rewrite_fstab_subvol(text: &str, mountpoint: &str, new_subvol: &str) -> String { let mut out = String::new(); for line in text.lines() { let trimmed = line.trim_start(); if trimmed.starts_with('#') || trimmed.is_empty() { out.push_str(line); out.push('\n'); continue; } let fields: Vec<&str> = line.split_whitespace().collect(); if fields.len() >= 4 && fields[1] == mountpoint { let opts = fields[3]; let mut parts: Vec = Vec::new(); let mut replaced = false; for part in opts.split(',') { if part.starts_with("subvol=") { parts.push(format!("subvol={new_subvol}")); replaced = true; } else if !part.is_empty() { parts.push(part.to_string()); } } if !replaced { parts.push(format!("subvol={new_subvol}")); } let new_opts = parts.join(","); let mut rebuilt = line.to_string(); if let Some(pos) = line.find(opts) { rebuilt.replace_range(pos..pos + opts.len(), &new_opts); } out.push_str(&rebuilt); out.push('\n'); } else { out.push_str(line); out.push('\n'); } } out } /// Whether an fstab line exists for `mountpoint`. pub fn fstab_has_mountpoint(text: &str, mountpoint: &str) -> bool { text.lines().any(|line| { let trimmed = line.trim_start(); !trimmed.starts_with('#') && line .split_whitespace() .nth(1) .map(|m| m == mountpoint) .unwrap_or(false) }) } /// The newest committed snapshot, skipping records without a real subvolume. pub fn latest_committed(history: &SnapshotHistory) -> Option<&SnapshotRecord> { history .records .iter() .rev() .find(|r| r.status == SnapshotStatus::Committed && !r.snapshot_subvol.is_empty()) } /// Whether the history contains the given id as a committed snapshot. pub fn is_committed(history: &SnapshotHistory, id: &str) -> bool { history .records .iter() .any(|r| r.id == id && r.status == SnapshotStatus::Committed) } /// Generic newest-first retention: return the items to delete, keeping the /// newest `keep`, never deleting anything in `protect`. /// /// Input order is oldest-first (the order the history is appended in). pub fn retention_deletions(items: &[String], keep: usize, protect: &[String]) -> Vec { if items.len() <= keep { return Vec::new(); } let cutoff = items.len() - keep; items .iter() .take(cutoff) .filter(|id| !protect.iter().any(|p| p == *id)) .cloned() .collect() } /// Prune the snapshot history to at most `keep` committed snapshots. /// /// Records that are still in flight (`Created`) or `Failed` are never selected, /// and the newest committed snapshot is always retained so a recovery point /// survives. pub fn snapshot_retention_deletions( history: &SnapshotHistory, keep: usize, protect: &[String], ) -> Vec { let mut committed: Vec = history .records .iter() .filter(|r| r.status == SnapshotStatus::Committed) .map(|r| r.id.clone()) .collect(); committed.dedup(); if committed.is_empty() { return Vec::new(); } let newest = committed.last().cloned(); let mut protect = protect.to_vec(); if let Some(n) = newest { if !protect.contains(&n) { protect.push(n); } } retention_deletions(&committed, keep, &protect) } #[cfg(test)] mod tests { use super::*; fn record(id: &str, status: SnapshotStatus) -> SnapshotRecord { SnapshotRecord { id: id.into(), created_unix: 0, operation: "op".into(), source_subvol: "@".into(), snapshot_subvol: id.into(), var_snapshot: None, status, } } #[test] fn names_are_deterministic_and_safe() { let ts = 1_700_000_000; assert_eq!(restore_root_name(ts), "@restore-20231114T221320"); assert_eq!(restore_var_name(ts), "@varrestore-20231114T221320"); assert_eq!( pre_rollback_snapshot_name(ts), "@-20231114T221320-pre-rollback" ); assert_eq!(snapshot_top_level_path("@-x"), "@snapshots/@-x"); for name in [restore_root_name(ts), restore_var_name(ts)] { assert!(!name.contains('/')); assert!(!name.contains(char::is_whitespace)); } } #[test] fn retention_keeps_the_newest_and_protects_in_flight() { let items: Vec = (0..5).map(|i| format!("s{i}")).collect(); let deletions = retention_deletions(&items, 2, &["s2".to_string()]); assert_eq!(deletions, vec!["s0", "s1"]); // Nothing to delete when under the limit. assert!(retention_deletions(&items, 9, &[]).is_empty()); } #[test] fn retention_never_deletes_the_newest_committed() { let history = SnapshotHistory { records: vec![ record("a", SnapshotStatus::Committed), record("b", SnapshotStatus::Committed), record("c", SnapshotStatus::Committed), ], }; let deletions = snapshot_retention_deletions(&history, 0, &[]); // `c` is the newest and is always kept. assert_eq!(deletions, vec!["a", "b"]); assert!(!deletions.contains(&"c".to_string())); } #[test] fn retention_skips_in_flight_and_failed_records() { let history = SnapshotHistory { records: vec![ record("a", SnapshotStatus::Committed), record("b", SnapshotStatus::Created), record("c", SnapshotStatus::Failed), record("d", SnapshotStatus::Committed), ], }; let deletions = snapshot_retention_deletions(&history, 1, &[]); assert_eq!(deletions, vec!["a"]); } #[test] fn status_in_flight_is_planned_or_activated() { assert!(RollbackStatus::Planned.in_flight()); assert!(RollbackStatus::Activated.in_flight()); assert!(!RollbackStatus::Verified.in_flight()); assert!(!RollbackStatus::Idle.in_flight()); } #[test] fn latest_committed_prefers_the_last_record() { let history = SnapshotHistory { records: vec![ record("a", SnapshotStatus::Committed), record("b", SnapshotStatus::Failed), record("c", SnapshotStatus::Committed), ], }; assert_eq!(latest_committed(&history).unwrap().id, "c"); assert!(is_committed(&history, "a")); assert!(!is_committed(&history, "b")); } #[test] fn mount_parsers_find_root_device_and_esp() { let mounts = "/dev/mapper/cryptroot / btrfs rw,subvol=/\t0 0\n\ /dev/vda1 /efi vfat umask=0077\t0 0\n\ proc /proc proc rw\t0 0\n"; assert_eq!( root_device_from_mounts(mounts).as_deref(), Some("/dev/mapper/cryptroot") ); assert_eq!(esp_mount_from_mounts(mounts).as_deref(), Some("/efi")); assert!(root_device_from_mounts("").is_none()); assert!(esp_mount_from_mounts("proc /proc proc rw 0 0").is_none()); } #[test] fn fstab_subvol_rewrite_only_touches_the_requested_mountpoint() { let fstab = "\ # /etc/fstab UUID=AAAA-1111\t/efi\tvfat\tumask=0077,shortname=winnt\t0\t2 /dev/mapper/cryptroot\t/\tbtrfs\tnoatime,compress=zstd:3,subvol=@\t0\t1 /dev/mapper/cryptroot\t/home\tbtrfs\tnoatime,compress=zstd:3,subvol=@home\t0\t2 /dev/mapper/cryptroot\t/var\tbtrfs\tnoatime,compress=zstd:3,subvol=@var\t0\t2 /swap/swapfile\tnone\tswap\tdefaults\t0\t0 "; let out = rewrite_fstab_subvol(fstab, "/", "@restore-20260101T000000"); assert!(out.contains("subvol=@restore-20260101T000000\t0\t1")); // /var is untouched here; it is rewritten separately. assert!(out.contains("\t/var\tbtrfs\tnoatime,compress=zstd:3,subvol=@var\t0\t2")); assert!(out.contains("subvol=@home")); let var = rewrite_fstab_subvol(&out, "/var", "@varrestore-20260101T000000"); assert!(var.contains("subvol=@varrestore-20260101T000000\t0\t2")); assert!(fstab_has_mountpoint(&var, "/")); assert!(fstab_has_mountpoint(&var, "/var")); assert!(!fstab_has_mountpoint(&var, "/nonexistent")); } }