3 Commits
Author SHA256 Message Date
kira e13806ce05 Add check for /var/lib/hive-up directory existance 2026-10-11 23:17:47 +02:00
kira 37c4d64bee Fixing of finish misspell in cmd 2026-10-11 17:24:10 +02:00
kira 01b66cf589 Add cleaning of old snaps on pac-start 2026-10-11 15:54:49 +02:00
6 changed files with 258 additions and 62 deletions

No files matched your search

Generated
+63 -14
View File
@@ -116,6 +116,12 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
[[package]]
name = "deranged"
version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
[[package]] [[package]]
name = "equivalent" name = "equivalent"
version = "1.0.2" version = "1.0.2"
@@ -146,13 +152,14 @@ checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]] [[package]]
name = "hive-up" name = "hive-up"
version = "0.2.2" version = "0.2.5"
dependencies = [ dependencies = [
"clap", "clap",
"nix", "nix",
"regex-lite", "regex-lite",
"serde", "serde",
"signal-hook", "signal-hook",
"time",
"time-format", "time-format",
"toml", "toml",
] ]
@@ -191,12 +198,24 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]] [[package]]
name = "once_cell_polyfill" name = "once_cell_polyfill"
version = "1.70.2" version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "powerfmt"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.107" version = "1.0.107"
@@ -253,9 +272,9 @@ dependencies = [
[[package]] [[package]]
name = "serde_spanned" name = "serde_spanned"
version = "1.1.1" version = "1.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
@@ -288,15 +307,35 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]] [[package]]
name = "syn" name = "syn"
version = "3.0.6" version = "3.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" checksum = "d62a2e0561533f2ca2561d0cf27fd9fedb640a1bf2616ff5d5c80d99017faadc"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"unicode-ident", "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]] [[package]]
name = "time-format" name = "time-format"
version = "1.2.4" version = "1.2.4"
@@ -304,10 +343,20 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c21b401b09485cb2403a336b3c6f9d53bd8a7273463f71b71d4f6325f7f74f6c" checksum = "c21b401b09485cb2403a336b3c6f9d53bd8a7273463f71b71d4f6325f7f74f6c"
[[package]] [[package]]
name = "toml" name = "time-macros"
version = "1.1.6+spec-1.1.0" version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index" 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 = [ dependencies = [
"indexmap", "indexmap",
"serde_core", "serde_core",
@@ -320,27 +369,27 @@ dependencies = [
[[package]] [[package]]
name = "toml_datetime" 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" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053"
dependencies = [ dependencies = [
"serde_core", "serde_core",
] ]
[[package]] [[package]]
name = "toml_parser" 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" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56" checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"
dependencies = [ dependencies = [
"winnow", "winnow",
] ]
[[package]] [[package]]
name = "toml_writer" 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" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
+2 -1
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "hive-up" name = "hive-up"
version = "0.2.2" version = "0.2.5"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
@@ -9,6 +9,7 @@ nix = { version = "0", features = ["user"] }
regex-lite = "0.1" regex-lite = "0.1"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
signal-hook = "0.4" signal-hook = "0.4"
time = { version = "0.3", features = ["parsing", "macros"] }
time-format = "1.2" time-format = "1.2"
toml = "1.1" toml = "1.1"
+12
View File
@@ -3,3 +3,15 @@
# In [kernel] section user may specify kernel cmd # In [kernel] section user may specify kernel cmd
# [kernel] # [kernel]
# cmd = "" # 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
+15 -1
View File
@@ -26,8 +26,10 @@ const CONFIG_PATH: &str = "/etc/hive-up.toml";
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
pub struct HiveConfig { pub struct HiveConfig {
// Matches [kernel] in TOML /// Matches [kernel] in TOML
pub kernel: Option<KernelConfig>, pub kernel: Option<KernelConfig>,
/// Matches [snapshots] in TOML
pub snapshots: Option<SnapshotsConfig>,
} }
#[derive(Debug, Serialize, Deserialize)] #[derive(Debug, Serialize, Deserialize)]
@@ -36,6 +38,18 @@ pub struct KernelConfig {
pub cmd: Option<String>, pub cmd: Option<String>,
} }
#[derive(Debug, Serialize, Deserialize)]
pub struct SnapshotsConfig {
/// enable shapshots
pub enable: Option<bool>,
/// keep at max this number of snapshots, 0 - keep all
pub keep_max: Option<u32>,
/// keep shapshots not older than specified days. 0 - indefinatly.
pub keep_days: Option<u32>,
/// keep atleast that much snapshots
pub keep_min: Option<u32>
}
#[derive(Debug)] #[derive(Debug)]
pub enum ConfigError { pub enum ConfigError {
+163 -43
View File
@@ -23,6 +23,8 @@ use std::process::Command;
use std::vec; use std::vec;
use time_format; use time_format;
use crate::hive_config::{HiveConfig, SnapshotsConfig};
const SNAPS_DIR: &str = "/bzz-snaps"; const SNAPS_DIR: &str = "/bzz-snaps";
const EFI_BOOT_MOUNT_POINT: &str = "/beefi"; const EFI_BOOT_MOUNT_POINT: &str = "/beefi";
const EFI_BOOT_DIR: &str = "/beefi/EFI/boot"; const EFI_BOOT_DIR: &str = "/beefi/EFI/boot";
@@ -36,6 +38,7 @@ const BOOT_UKI_IMAGE_NAME: &str = "\\EFI\\boot\\linux-kira-lts.efi";
const BOOT_UKI_IMAGE_NAME_BACK: &str = "\\EFI\\boot\\linux-kira-lts-back.efi"; const BOOT_UKI_IMAGE_NAME_BACK: &str = "\\EFI\\boot\\linux-kira-lts-back.efi";
const PAC_LOCK_FILE: &str = "/var/lib/hive-up/pac-lock"; const PAC_LOCK_FILE: &str = "/var/lib/hive-up/pac-lock";
const PAC_LOCK_DIR: &str = "/var/lib/hive-up";
#[derive(Debug)] #[derive(Debug)]
pub struct CommandFailed { pub struct CommandFailed {
@@ -210,15 +213,8 @@ pub fn snapshot(subvolume: &str, target: &str) -> Result<(), ExecCommandError> {
/// returns snapshot time on sucess /// returns snapshot time on sucess
/// ///
pub fn snapshot_system() -> Result<String, ExecCommandError> { pub fn snapshot_system() -> Result<String, ExecCommandError> {
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 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 usr_snapshot_name = format!("{}/bzz-usr-{}", SNAPS_DIR, local_time);
let var_snapshot_name = format!("{}/bzz-var-{}", SNAPS_DIR, local_time); let var_snapshot_name = format!("{}/bzz-var-{}", SNAPS_DIR, local_time);
@@ -228,20 +224,122 @@ pub fn snapshot_system() -> Result<String, ExecCommandError> {
Ok(local_time) 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<i64, String> {
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 /// Function for pacman preTransaction hook
/// ///
pub fn pac_start() -> Result<(), ExecCommandError> { pub fn pac_start(hive_config: &HiveConfig) -> Result<(), ExecCommandError> {
use std::path::Path; use std::path::Path;
// Check if lock file exist
let pack_lock_path = Path::new(PAC_LOCK_FILE); // checking is PAC_LOCK_DIR ("/var/lib/hive-up") exist
if pack_lock_path.exists() { // and creating it if it does not.
println!("Warning! Pac Lock file exist, skipping system snapshot..."); let pack_lock_dir_path = Path::new(PAC_LOCK_DIR);
if !pack_lock_dir_path.exists() {
println!("Warning! {} directory do not exist. Creating...", PAC_LOCK_DIR);
fs::create_dir_all(pack_lock_dir_path)?;
return Ok(()); return Ok(());
} }
println!("Creating system snapshot...");
let snap_time = snapshot_system()?; // if snapshots is configured
println!("Ok."); if let Some(snaps_conf) = &hive_config.snapshots {
fs::write(PAC_LOCK_FILE, snap_time)?; 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
);
}
}
}
Ok(()) Ok(())
} }
@@ -250,41 +348,63 @@ pub fn pac_finish() -> Result<(), ExecCommandError> {
// Check if lock file exist // Check if lock file exist
let pack_lock_path = Path::new(PAC_LOCK_FILE); let pack_lock_path = Path::new(PAC_LOCK_FILE);
if pack_lock_path.exists() { if pack_lock_path.exists() {
println!("Remowing pac-lock..."); println!("Removing pac-lock...");
fs::remove_file(pack_lock_path)?; fs::remove_file(pack_lock_path)?;
} else { } else {
println!("Warning! Pac Lock file does not exist - something is wrong..."); println!("Warning! Pac Lock file does not exist...");
} }
Ok(()) Ok(())
} }
//const TMP_ROOT: &str = "/mnt/bee-root"; ///
// pub fn list_bzzpss_snaps() -> Result<Vec<String>, ExecCommandError> { /// Looking for snapshots in snaps_dir for usr and var
// use regex::Regex; /// And return list of date-time part of filename if both snapshots exists
// use std::path::Path; /// List sorted in ascending order - newest snapshots comes last.
///
pub fn list_bzzpss_snaps() -> Result<Vec<String>, 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 mut res: Vec<String> = Vec::new();
// 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(); // if snaps dir path do not exist return empty list
if !Path::new(SNAPS_DIR).exists() {
return Ok(res);
}
// let mut res: Vec<String> = Vec::new(); // contains only date-time part
// // if snaps dir path do not exist return empty list let mut usr_snaps: Vec<String> = Vec::new();
// if !Path::new(SNAPS_DIR).exists() { let mut var_snaps: Vec<String> = Vec::new();
// return Ok(res);
// }
// for maybe_entry in fs::read_dir(SNAPS_DIR)? { // collect snapshots date-time
// let entry = maybe_entry?; for maybe_entry in fs::read_dir(SNAPS_DIR)? {
// if entry.file_type()?.is_dir() { let entry = maybe_entry?;
// if let Some(dir_name) = entry.file_name().to_str() if entry.file_type()?.is_dir() {
// && re.is_match(dir_name) if let Some(dir_name) = entry.file_name().to_str() {
// { if let Some(captured) = re.captures(&dir_name) {
// res.push(dir_name.to_string()); let subvol_name = &captured[1];
// } let date_time = captured[2].to_string();
// } if subvol_name == "usr" {
// } usr_snaps.push(date_time);
// res.sort(); } else {
// Ok(res) 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 { pub fn check_if_run_as_root() -> bool {
use nix::unistd::Uid; use nix::unistd::Uid;
+3 -3
View File
@@ -98,7 +98,7 @@ enum Pac {
Start, Start,
/// This supposed to be called by pacman hook before transaction. /// This supposed to be called by pacman hook before transaction.
/// Right now only thing it does is removes /var/lib/hive-up/pac-lock file /// Right now only thing it does is removes /var/lib/hive-up/pac-lock file
Finis, Finish,
} }
#[derive(Subcommand, Debug)] #[derive(Subcommand, Debug)]
@@ -166,8 +166,8 @@ fn main() -> Result<(), HiveUpError> {
let _ = hive_system::snapshot_system()?; let _ = hive_system::snapshot_system()?;
println!("Ok."); println!("Ok.");
}, },
Pac::Start => hive_system::pac_start()?, Pac::Start => hive_system::pac_start(&bzz_config)?,
Pac::Finis => hive_system::pac_finish()? Pac::Finish => hive_system::pac_finish()?
} }
} }