SHA256
Add cleaning of old snaps on pac-start
This commit is contained in:
1 parent
25a706d6ea
commit
01b66cf589
6 files changed
+246
-60
No files matched your search
+15
-1
@@ -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<KernelConfig>,
|
||||
/// Matches [snapshots] in TOML
|
||||
pub snapshots: Option<SnapshotsConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
@@ -36,6 +38,18 @@ pub struct KernelConfig {
|
||||
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)]
|
||||
pub enum ConfigError {
|
||||
|
||||
+153
-43
@@ -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<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 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<String, ExecCommandError> {
|
||||
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
|
||||
///
|
||||
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<Vec<String>, 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<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 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<String> = 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<String> = 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<String> = Vec::new();
|
||||
let mut var_snaps: Vec<String> = 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;
|
||||
|
||||
+1
-1
@@ -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()?
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user