From 01b66cf589904e35704e2752701b483cb8702a7fb8853ec0ee53ae2f4813835e Mon Sep 17 00:00:00 2001 From: kira Date: Sun, 11 Oct 2026 15:54:49 +0200 Subject: [PATCH] Add cleaning of old snaps on pac-start --- Cargo.lock | 77 ++++++++++++++---- Cargo.toml | 3 +- files/hive-up.toml | 12 +++ src/hive_config.rs | 16 +++- src/hive_system.rs | 196 +++++++++++++++++++++++++++++++++++---------- src/main.rs | 2 +- 6 files changed, 246 insertions(+), 60 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index fdd8260..e10586b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -116,6 +116,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "deranged" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c" + [[package]] name = "equivalent" version = "1.0.2" @@ -146,13 +152,14 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" [[package]] name = "hive-up" -version = "0.2.2" +version = "0.2.3" dependencies = [ "clap", "nix", "regex-lite", "serde", "signal-hook", + "time", "time-format", "toml", ] @@ -191,12 +198,24 @@ dependencies = [ "libc", ] +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + [[package]] name = "once_cell_polyfill" version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -253,9 +272,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.1" +version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" dependencies = [ "serde_core", ] @@ -288,15 +307,35 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" [[package]] name = "syn" -version = "3.0.6" +version = "3.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +checksum = "d62a2e0561533f2ca2561d0cf27fd9fedb640a1bf2616ff5d5c80d99017faadc" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + [[package]] name = "time-format" version = "1.2.4" @@ -304,10 +343,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c21b401b09485cb2403a336b3c6f9d53bd8a7273463f71b71d4f6325f7f74f6c" [[package]] -name = "toml" -version = "1.1.6+spec-1.1.0" +name = "time-macros" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" dependencies = [ "indexmap", "serde_core", @@ -320,27 +369,27 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.1+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" dependencies = [ "serde_core", ] [[package]] name = "toml_parser" -version = "1.1.3+spec-1.1.0" +version = "1.1.5+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" dependencies = [ "winnow", ] [[package]] name = "toml_writer" -version = "1.1.2+spec-1.1.0" +version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" [[package]] name = "unicode-ident" diff --git a/Cargo.toml b/Cargo.toml index da6c84c..32f2bc7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hive-up" -version = "0.2.2" +version = "0.2.3" edition = "2024" [dependencies] @@ -9,6 +9,7 @@ nix = { version = "0", features = ["user"] } regex-lite = "0.1" serde = { version = "1", features = ["derive"] } signal-hook = "0.4" +time = { version = "0.3", features = ["parsing", "macros"] } time-format = "1.2" toml = "1.1" diff --git a/files/hive-up.toml b/files/hive-up.toml index 6b05df2..674863c 100644 --- a/files/hive-up.toml +++ b/files/hive-up.toml @@ -3,3 +3,15 @@ # In [kernel] section user may specify kernel cmd # [kernel] # cmd = "" + +# [snapshots] section +[snapshots] +# enable shapshots +enable = true +# keep at max this number of snapshots, 0 - keep all +keep_max = 1 +# keep shapshots not older than specified days. 0 - indefinatly. +keep_days = 0 +# Keep atleast that much snapshots +keep_min = 1 + diff --git a/src/hive_config.rs b/src/hive_config.rs index 9695fa6..f15c988 100644 --- a/src/hive_config.rs +++ b/src/hive_config.rs @@ -26,8 +26,10 @@ const CONFIG_PATH: &str = "/etc/hive-up.toml"; #[derive(Debug, Serialize, Deserialize)] pub struct HiveConfig { - // Matches [kernel] in TOML + /// Matches [kernel] in TOML pub kernel: Option, + /// Matches [snapshots] in TOML + pub snapshots: Option, } #[derive(Debug, Serialize, Deserialize)] @@ -36,6 +38,18 @@ pub struct KernelConfig { pub cmd: Option, } +#[derive(Debug, Serialize, Deserialize)] +pub struct SnapshotsConfig { + /// enable shapshots + pub enable: Option, + /// keep at max this number of snapshots, 0 - keep all + pub keep_max: Option, + /// keep shapshots not older than specified days. 0 - indefinatly. + pub keep_days: Option, + /// keep atleast that much snapshots + pub keep_min: Option +} + #[derive(Debug)] pub enum ConfigError { diff --git a/src/hive_system.rs b/src/hive_system.rs index 69299dc..25692a7 100644 --- a/src/hive_system.rs +++ b/src/hive_system.rs @@ -23,6 +23,8 @@ use std::process::Command; use std::vec; use time_format; +use crate::hive_config::{HiveConfig, SnapshotsConfig}; + const SNAPS_DIR: &str = "/bzz-snaps"; const EFI_BOOT_MOUNT_POINT: &str = "/beefi"; const EFI_BOOT_DIR: &str = "/beefi/EFI/boot"; @@ -210,15 +212,8 @@ pub fn snapshot(subvolume: &str, target: &str) -> Result<(), ExecCommandError> { /// returns snapshot time on sucess /// pub fn snapshot_system() -> Result { - use std::path::Path; - // if snaps dir path do not exist - create it - let snaps_path = Path::new(SNAPS_DIR); - if !snaps_path.exists() { - fs::create_dir(snaps_path)?; - } - let ts = time_format::now().unwrap(); - let local_time = time_format::strftime_local("%Y-%m-%dT%H:%M:%S", ts).unwrap(); + let local_time = time_format::strftime_local("%Y-%m-%dT%H-%M-%S", ts).unwrap(); let usr_snapshot_name = format!("{}/bzz-usr-{}", SNAPS_DIR, local_time); let var_snapshot_name = format!("{}/bzz-var-{}", SNAPS_DIR, local_time); @@ -228,20 +223,113 @@ pub fn snapshot_system() -> Result { Ok(local_time) } +/// +/// bcachefs subvolume delete shortcut +/// +fn subvolume_delete(subvolume: &str) -> Result<(), ExecCommandError> { + exec_command("bcachefs", &vec!["subvolume", "delete", subvolume])?; + + Ok(()) +} + +fn iso_to_unix(time_str: &str) -> Result { + use time::OffsetDateTime; + use time::macros::format_description; + let be_format = format_description!("[year]-[month]-[day]T[hour]-[minute]-[second]"); + let dt: OffsetDateTime = + OffsetDateTime::parse(time_str, be_format).map_err(|r| r.to_string())?; + Ok(dt.unix_timestamp()) +} +/// +/// Cleaning old snapshots according to settings +/// +pub fn clean_snaps(snaps_conf: &SnapshotsConfig) -> Result<(), ExecCommandError> { + let current_time = time_format::now().unwrap(); + + // get snapshots list (newest comes last) + let snaps_list = list_bzzpss_snaps()?; + let snaps_count = snaps_list.len(); + if snaps_count > 0 { + let keep_days = snaps_conf.keep_days.unwrap_or(0) as u64; + let keep_max = snaps_conf.keep_max.unwrap_or(0) as usize; + let keep_min = snaps_conf.keep_max.unwrap_or(1) as usize; + + let mut keep_num: usize = keep_min; + + if keep_days > 0 { + let mut remove_count = 0; + // iteratingfrom oldest + for dt in &snaps_list { + // 86400 - sec in day + let days_passed: u64 = (current_time - iso_to_unix(dt)?).unsigned_abs() / 86400; + if days_passed < keep_days { + break; + } + remove_count += 1; + } + keep_num = keep_min.max(snaps_count.checked_sub(remove_count).unwrap()); + } + if keep_max > 0 { + keep_num = keep_num.min(keep_max); + } + keep_num = keep_num.max(keep_min); + + let remove_num = snaps_count.checked_sub(keep_num).unwrap(); + + println!("Snapshots to delete: {}", remove_num); + + // deleting snapshots + for snap_date_time in snaps_list.iter().take(remove_num) { + let usr_snap = format!("{}/bzz-{}-{}", SNAPS_DIR, "usr", snap_date_time); + let var_snap = format!("{}/bzz-{}-{}", SNAPS_DIR, "var", snap_date_time); + println!("Deleting {}", &usr_snap); + subvolume_delete(&usr_snap)?; + println!("Deleting {}", &var_snap); + subvolume_delete(&var_snap)?; + } + println!("Done."); + } else { + println!("No snapshots found. Skipping cleaning.") + } + Ok(()) +} + /// Function for pacman preTransaction hook /// -pub fn pac_start() -> Result<(), ExecCommandError> { +pub fn pac_start(hive_config: &HiveConfig) -> Result<(), ExecCommandError> { use std::path::Path; - // Check if lock file exist - let pack_lock_path = Path::new(PAC_LOCK_FILE); - if pack_lock_path.exists() { - println!("Warning! Pac Lock file exist, skipping system snapshot..."); - return Ok(()); + + // if snapshots is configured + if let Some(snaps_conf) = &hive_config.snapshots { + if snaps_conf.enable.unwrap_or(false) { + // if snaps dir path do not exist - exit + let snaps_path = Path::new(SNAPS_DIR); + if snaps_path.exists() { + // Check if lock file exist + let pack_lock_path = Path::new(PAC_LOCK_FILE); + if pack_lock_path.exists() { + println!("Warning! Pac Lock file exist, skipping system snapshot..."); + return Ok(()); + } + + // cleaning old snapshots + clean_snaps(snaps_conf)?; + + println!("Creating system snapshot..."); + let snap_time = snapshot_system()?; + println!("Ok."); + + // placing pac-lock file + fs::write(PAC_LOCK_FILE, snap_time)?; + } else { + println!( + "Warning! snapshot dir {} do not exists - skiping snapshot creation", + SNAPS_DIR + ); + } + } } - println!("Creating system snapshot..."); - let snap_time = snapshot_system()?; - println!("Ok."); - fs::write(PAC_LOCK_FILE, snap_time)?; + Ok(()) } @@ -253,38 +341,60 @@ pub fn pac_finish() -> Result<(), ExecCommandError> { println!("Remowing pac-lock..."); fs::remove_file(pack_lock_path)?; } else { - println!("Warning! Pac Lock file does not exist - something is wrong..."); + println!("Warning! Pac Lock file does not exist..."); } Ok(()) } -//const TMP_ROOT: &str = "/mnt/bee-root"; -// pub fn list_bzzpss_snaps() -> Result, ExecCommandError> { -// use regex::Regex; -// use std::path::Path; +/// +/// Looking for snapshots in snaps_dir for usr and var +/// And return list of date-time part of filename if both snapshots exists +/// List sorted in ascending order - newest snapshots comes last. +/// +pub fn list_bzzpss_snaps() -> Result, ExecCommandError> { + use regex_lite::Regex; + use std::path::Path; + // usr or var snapshoot in a form of bzz-usr|var-yyyy-mm-ddTHH-MM-SS + let re = Regex::new(r"^bzz-(usr|var)-([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2})$") + .unwrap(); -// // root snapshoot in a form of bzz-yyyy-mm-ddTHH-MM-SS -// let re = Regex::new(r"^bzz-[a-z]+-[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}$").unwrap(); + let mut res: Vec = Vec::new(); + // if snaps dir path do not exist return empty list + if !Path::new(SNAPS_DIR).exists() { + return Ok(res); + } -// let mut res: Vec = Vec::new(); -// // if snaps dir path do not exist return empty list -// if !Path::new(SNAPS_DIR).exists() { -// return Ok(res); -// } + // contains only date-time part + let mut usr_snaps: Vec = Vec::new(); + let mut var_snaps: Vec = Vec::new(); -// for maybe_entry in fs::read_dir(SNAPS_DIR)? { -// let entry = maybe_entry?; -// if entry.file_type()?.is_dir() { -// if let Some(dir_name) = entry.file_name().to_str() -// && re.is_match(dir_name) -// { -// res.push(dir_name.to_string()); -// } -// } -// } -// res.sort(); -// Ok(res) -// } + // collect snapshots date-time + for maybe_entry in fs::read_dir(SNAPS_DIR)? { + let entry = maybe_entry?; + if entry.file_type()?.is_dir() { + if let Some(dir_name) = entry.file_name().to_str() { + if let Some(captured) = re.captures(&dir_name) { + let subvol_name = &captured[1]; + let date_time = captured[2].to_string(); + if subvol_name == "usr" { + usr_snaps.push(date_time); + } else { + var_snaps.push(date_time); + } + } + } + } + } + // now we need to make sure snapshots of /usr and /var both exist + // just fools safe, may reconsider in future + usr_snaps.sort(); + for snap_time in usr_snaps { + if var_snaps.contains(&snap_time) { + res.push(snap_time); + } + } + Ok(res) +} pub fn check_if_run_as_root() -> bool { use nix::unistd::Uid; diff --git a/src/main.rs b/src/main.rs index c4458cf..748e936 100644 --- a/src/main.rs +++ b/src/main.rs @@ -166,7 +166,7 @@ fn main() -> Result<(), HiveUpError> { let _ = hive_system::snapshot_system()?; println!("Ok."); }, - Pac::Start => hive_system::pac_start()?, + Pac::Start => hive_system::pac_start(&bzz_config)?, Pac::Finis => hive_system::pac_finish()? } }