feat(retention): implement slice 5 retention engine and pruning policies

This commit is contained in:
soda64 committed 2026-10-09 19:29:24 +02:00
1 parent 8d4127de30
commit 361640f5ae
5 files changed
+498 -1

No files matched your search

+1 -1
View File
@@ -10,7 +10,7 @@
- [x] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages)
- [x] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
- [x] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
- [x] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
- [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder)
- [ ] Slice 8 — full documentation (user, admin & developer guides), man page (Section 8), CLI -h/--help, shell tab completion (Bash/Zsh) & Gitea Actions CI/CD release workflow
+116
View File
@@ -27,6 +27,7 @@ from linux_backuper.core.inspector import SystemInspector
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
from linux_backuper.core.profiles import ProfileManager
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
from linux_backuper.core.retention import RetentionEngine
from linux_backuper.models import SnapshotManifest
def check_root_permissions() -> bool:
@@ -151,6 +152,28 @@ def handle_snapshot(args: argparse.Namespace) -> int:
finally:
lock.release()
# Post-snapshot automatic retention pruning if configured
keep_last = getattr(args, "keep_last", 0) or profile.retention_keep_last
keep_daily = getattr(args, "keep_daily", 0) or profile.retention_keep_daily
keep_weekly = getattr(args, "keep_weekly", 0) or profile.retention_keep_weekly
keep_monthly = getattr(args, "keep_monthly", 0) or profile.retention_keep_monthly
auto_pruned_count = 0
if any([keep_last > 0, keep_daily > 0, keep_weekly > 0, keep_monthly > 0]):
retention = RetentionEngine(
keep_last=keep_last,
keep_daily=keep_daily,
keep_weekly=keep_weekly,
keep_monthly=keep_monthly
)
existing_snaps = archiver.list_snapshots()
_, to_prune = retention.calculate_prune_set(existing_snaps)
if to_prune:
prune_res = retention.execute_prune(to_prune, target_dir=target_dir, dry_run=False, pid_path=pid_path)
auto_pruned_count = len(prune_res)
if not args.json:
sys.stdout.write(f"[INFO] Automatically pruned {auto_pruned_count} old snapshot(s) per retention policy.\n")
if args.json:
output_payload = {
"snapshot_id": snapshot_id,
@@ -159,6 +182,7 @@ def handle_snapshot(args: argparse.Namespace) -> int:
"files_count": len(file_entries),
"uncompressed_bytes": uncompressed_bytes,
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
"auto_pruned_count": auto_pruned_count,
"status": "success"
}
print(json.dumps(output_payload, indent=2))
@@ -470,6 +494,81 @@ def handle_restore(args: argparse.Namespace) -> int:
return EXIT_SUCCESS
def handle_prune(args: argparse.Namespace) -> int:
"""Execute prune command based on retention rules."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
force = getattr(args, "force", False)
dry_run = getattr(args, "dry_run", False) or not force
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
# If force delete requested, check root permission
if force and not dry_run and not check_root_permissions():
sys.stderr.write("[ERROR] Pruning snapshots requires root privileges (run with sudo).\n")
return EXIT_PERM_DENIED
archiver = SnapshotArchiver(target_dir=target_dir)
snapshots = archiver.list_snapshots()
retention = RetentionEngine(
keep_last=args.keep_last,
keep_daily=args.keep_daily,
keep_weekly=args.keep_weekly,
keep_monthly=args.keep_monthly
)
if not retention.is_active():
sys.stderr.write("[ERROR] No retention rules specified. Please specify at least one of: --keep-last, --keep-daily, --keep-weekly, --keep-monthly.\n")
return EXIT_GENERIC_ERROR
kept, pruned = retention.calculate_prune_set(snapshots)
results = retention.execute_prune(pruned, target_dir=target_dir, dry_run=dry_run, pid_path=pid_path)
total_freed_bytes = sum(r.get("freed_bytes", 0) for r in results)
freed_mb = total_freed_bytes / (1024 * 1024)
if args.json:
payload = {
"mode": "dry-run" if dry_run else "live",
"total_snapshots": len(snapshots),
"kept_count": len(kept),
"pruned_count": len(pruned),
"freed_bytes": total_freed_bytes,
"kept": [s.snapshot_id for s in kept],
"pruned": results
}
print(json.dumps(payload, indent=2))
return EXIT_SUCCESS
sys.stdout.write("=" * 80 + "\n")
mode_label = "DRY RUN (simulation)" if dry_run else "LIVE PRUNE"
sys.stdout.write(f"RETENTION PRUNE PLAN — {mode_label}\n")
sys.stdout.write(f"Target Directory: {target_dir}\n")
sys.stdout.write(f"Rules: keep-last={args.keep_last}, keep-daily={args.keep_daily}, keep-weekly={args.keep_weekly}, keep-monthly={args.keep_monthly}\n")
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"\nSnapshots to KEEP ({len(kept)}):\n")
for s in kept:
size_mb = s.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f" [KEEP] {s.snapshot_id:<45} ({size_mb:.2f} MB, {s.created_at[:19]})\n")
if pruned:
sys.stdout.write(f"\nSnapshots to PRUNE ({len(pruned)}):\n")
for r in results:
mb = r.get("freed_bytes", 0) / (1024 * 1024)
action_tag = "[WOULD DELETE]" if dry_run else "[DELETED]"
sys.stdout.write(f" {action_tag} {r['snapshot_id']:<45} ({mb:.2f} MB freed)\n")
else:
sys.stdout.write("\nNo snapshots qualify for pruning under current retention rules.\n")
sys.stdout.write("-" * 80 + "\n")
sys.stdout.write(f"Summary: Keeping {len(kept)} snapshots, pruning {len(pruned)} snapshots ({freed_mb:.2f} MB disk space).\n")
if dry_run and pruned:
sys.stdout.write("[NOTICE] Dry run completed without deleting files. Pass --force to execute deletion.\n")
elif not dry_run and pruned:
sys.stdout.write(f"[SUCCESS] Successfully pruned {len(pruned)} snapshot(s).\n")
return EXIT_SUCCESS
def build_parser() -> argparse.ArgumentParser:
"""Construct CLI argument parser."""
common_parser = argparse.ArgumentParser(add_help=False)
@@ -496,6 +595,10 @@ def build_parser() -> argparse.ArgumentParser:
snap_parser.add_argument("--sanitize", action="store_true", help="Redact secrets and private keys for diagnostic export")
snap_parser.add_argument("--config", help=f"Path to JSON configuration file (default: {DEFAULT_CONFIG_PATH})")
snap_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
snap_parser.add_argument("--keep-last", type=int, default=0, help="Prune old backups, keeping N latest snapshots")
snap_parser.add_argument("--keep-daily", type=int, default=0, help="Prune old backups, keeping latest snapshot for D days")
snap_parser.add_argument("--keep-weekly", type=int, default=0, help="Prune old backups, keeping latest snapshot for W weeks")
snap_parser.add_argument("--keep-monthly", type=int, default=0, help="Prune old backups, keeping latest snapshot for M months")
# List command
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
@@ -533,6 +636,17 @@ def build_parser() -> argparse.ArgumentParser:
restore_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
restore_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
# Prune command
prune_parser = subparsers.add_parser("prune", help="Prune old snapshots based on retention policies", parents=[common_parser])
prune_parser.add_argument("--keep-last", type=int, default=0, help="Keep N most recent snapshots")
prune_parser.add_argument("--keep-daily", type=int, default=0, help="Keep most recent snapshot for D distinct days")
prune_parser.add_argument("--keep-weekly", type=int, default=0, help="Keep most recent snapshot for W distinct weeks")
prune_parser.add_argument("--keep-monthly", type=int, default=0, help="Keep most recent snapshot for M distinct months")
prune_parser.add_argument("--dry-run", action="store_true", help="Simulate pruning plan without deleting files")
prune_parser.add_argument("--force", action="store_true", help="Confirm deletion of pruned snapshot archives")
prune_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots")
prune_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
# Verify command
verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser])
verify_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to verify")
@@ -561,6 +675,8 @@ def main(argv: Optional[List[str]] = None) -> int:
return handle_extract(args)
elif args.subcommand == "restore":
return handle_restore(args)
elif args.subcommand == "prune":
return handle_prune(args)
elif args.subcommand == "verify":
return handle_verify(args)
+182
View File
@@ -0,0 +1,182 @@
"""Lifecycle retention and pruning engine for linux-backuper."""
import datetime
import os
import re
from typing import Dict, List, Optional, Set, Tuple, Any
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import DEFAULT_BACKUP_DIR
from linux_backuper.core.lock import SingleInstanceLock
from linux_backuper.models import SnapshotManifest
def parse_snapshot_datetime(manifest: SnapshotManifest) -> datetime.datetime:
"""Parse snapshot creation datetime from manifest or snapshot_id fallback."""
# 1. Try ISO format from manifest.created_at
if manifest.created_at:
try:
# Handle Python 3.6 - 3.10 ISO variations
iso_str = manifest.created_at.replace("Z", "+00:00")
return datetime.datetime.fromisoformat(iso_str)
except (ValueError, AttributeError):
pass
# 2. Try parsing snapshot_id, e.g. backup_hostname_20261009_191639 or pre_restore_hostname_20261009_191644
match = re.search(r"(\d{8})_(\d{6})", manifest.snapshot_id)
if match:
date_part, time_part = match.groups()
try:
dt = datetime.datetime.strptime(f"{date_part}_{time_part}", "%Y%m%d_%H%M%S")
return dt.replace(tzinfo=datetime.timezone.utc)
except ValueError:
pass
# Fallback to epoch
return datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)
class RetentionEngine:
"""Calculates and executes retention policies (keep-last, keep-daily, keep-weekly, keep-monthly)."""
def __init__(
self,
keep_last: int = 0,
keep_daily: int = 0,
keep_weekly: int = 0,
keep_monthly: int = 0
):
self.keep_last = max(0, keep_last)
self.keep_daily = max(0, keep_daily)
self.keep_weekly = max(0, keep_weekly)
self.keep_monthly = max(0, keep_monthly)
def is_active(self) -> bool:
"""Returns True if at least one retention policy rule is configured (> 0)."""
return any([
self.keep_last > 0,
self.keep_daily > 0,
self.keep_weekly > 0,
self.keep_monthly > 0
])
def calculate_prune_set(
self,
snapshots: List[SnapshotManifest]
) -> Tuple[List[SnapshotManifest], List[SnapshotManifest]]:
"""
Evaluate snapshots against retention rules.
Returns:
- kept_snapshots: list of snapshots to preserve (sorted newest to oldest)
- pruned_snapshots: list of snapshots to delete (sorted oldest to newest)
"""
if not snapshots or not self.is_active():
return snapshots, []
# Sort snapshots descending (newest first)
sorted_snaps = sorted(
snapshots,
key=lambda s: parse_snapshot_datetime(s),
reverse=True
)
kept_ids: Set[str] = set()
# 1. Rule: keep-last N
if self.keep_last > 0:
for s in sorted_snaps[:self.keep_last]:
kept_ids.add(s.snapshot_id)
# 2. Rule: keep-daily D (newest snapshot per distinct day)
if self.keep_daily > 0:
seen_days: Dict[Tuple[int, int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
day_key = (dt.year, dt.month, dt.day)
if day_key not in seen_days:
if len(seen_days) < self.keep_daily:
seen_days[day_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
# 3. Rule: keep-weekly W (newest snapshot per ISO week)
if self.keep_weekly > 0:
seen_weeks: Dict[Tuple[int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
iso_year, iso_week, _ = dt.isocalendar()
week_key = (iso_year, iso_week)
if week_key not in seen_weeks:
if len(seen_weeks) < self.keep_weekly:
seen_weeks[week_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
# 4. Rule: keep-monthly M (newest snapshot per calendar month)
if self.keep_monthly > 0:
seen_months: Dict[Tuple[int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
month_key = (dt.year, dt.month)
if month_key not in seen_months:
if len(seen_months) < self.keep_monthly:
seen_months[month_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
kept = [s for s in sorted_snaps if s.snapshot_id in kept_ids]
pruned = [s for s in reversed(sorted_snaps) if s.snapshot_id not in kept_ids]
return kept, pruned
def execute_prune(
self,
prune_list: List[SnapshotManifest],
target_dir: str = DEFAULT_BACKUP_DIR,
dry_run: bool = False,
pid_path: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Delete pruned snapshot archives from target_dir.
If dry_run is True, simulates deletion without removing files.
"""
if not dry_run:
lock = SingleInstanceLock(pid_path=pid_path)
lock.acquire()
results: List[Dict[str, Any]] = []
try:
for snap in prune_list:
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, snap.snapshot_id)
size_bytes = 0
file_exists = os.path.isfile(archive_path)
if file_exists:
try:
size_bytes = os.path.getsize(archive_path)
except OSError:
pass
if dry_run:
results.append({
"snapshot_id": snap.snapshot_id,
"archive_path": archive_path,
"freed_bytes": size_bytes,
"action": "would_delete"
})
else:
if file_exists:
try:
os.unlink(archive_path)
status = "deleted"
except OSError as e:
status = f"error: {e}"
else:
status = "file_not_found"
results.append({
"snapshot_id": snap.snapshot_id,
"archive_path": archive_path,
"freed_bytes": size_bytes,
"action": status
})
finally:
if not dry_run:
lock.release()
return results
+4
View File
@@ -53,6 +53,10 @@ class ProfileConfig:
collect_network: bool = True
collect_packages: bool = True
max_journal_mb: int = 0
retention_keep_last: int = 0
retention_keep_daily: int = 0
retention_keep_weekly: int = 0
retention_keep_monthly: int = 0
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
+195
View File
@@ -0,0 +1,195 @@
"""Unit tests for RetentionEngine and lifecycle pruning."""
import datetime
import io
import json
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR
from linux_backuper.core.retention import RetentionEngine, parse_snapshot_datetime
from linux_backuper.models import SnapshotManifest
class TestRetentionEngine(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_retention_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def _create_synthetic_manifest(self, snap_id: str, dt_str: str) -> SnapshotManifest:
return SnapshotManifest(
schema_version="1.0",
snapshot_id=snap_id,
created_at=dt_str,
hostname="testhost",
profile="quick",
compression="gzip",
os={},
package_manager="dpkg",
package_count=0,
included_paths=["/etc"],
stats={"file_count": 10, "uncompressed_bytes": 1000, "compressed_bytes": 500},
files_sha256={}
)
def test_keep_last(self):
# 5 snapshots
snaps = [
self._create_synthetic_manifest(f"snap_{i}", f"2026-10-0{i+1}T10:00:00Z")
for i in range(5)
]
retention = RetentionEngine(keep_last=2)
kept, pruned = retention.calculate_prune_set(snaps)
self.assertEqual(len(kept), 2)
self.assertEqual(len(pruned), 3)
self.assertEqual([s.snapshot_id for s in kept], ["snap_4", "snap_3"])
self.assertEqual([s.snapshot_id for s in pruned], ["snap_0", "snap_1", "snap_2"])
def test_keep_daily(self):
# Multiple snapshots on same days
snaps = [
# Day 1: 3 snapshots
self._create_synthetic_manifest("d1_1", "2026-10-01T08:00:00Z"),
self._create_synthetic_manifest("d1_2", "2026-10-01T12:00:00Z"),
self._create_synthetic_manifest("d1_3", "2026-10-01T20:00:00Z"),
# Day 2: 2 snapshots
self._create_synthetic_manifest("d2_1", "2026-10-02T10:00:00Z"),
self._create_synthetic_manifest("d2_2", "2026-10-02T22:00:00Z"),
# Day 3: 1 snapshot
self._create_synthetic_manifest("d3_1", "2026-10-03T15:00:00Z"),
]
# Keep 2 daily
retention = RetentionEngine(keep_daily=2)
kept, pruned = retention.calculate_prune_set(snaps)
# Should keep newest of Day 3 (d3_1) and newest of Day 2 (d2_2)
kept_ids = [s.snapshot_id for s in kept]
self.assertEqual(len(kept_ids), 2)
self.assertIn("d3_1", kept_ids)
self.assertIn("d2_2", kept_ids)
self.assertEqual(len(pruned), 4)
def test_keep_weekly_and_monthly(self):
snaps = [
# Month 1, Week 1
self._create_synthetic_manifest("m1_w1", "2026-08-03T10:00:00Z"),
# Month 1, Week 2
self._create_synthetic_manifest("m1_w2", "2026-08-10T10:00:00Z"),
# Month 2, Week 1
self._create_synthetic_manifest("m2_w1", "2026-09-07T10:00:00Z"),
# Month 2, Week 2
self._create_synthetic_manifest("m2_w2", "2026-09-14T10:00:00Z"),
# Month 3, Week 1
self._create_synthetic_manifest("m3_w1", "2026-10-05T10:00:00Z"),
]
# Keep 1 monthly
retention = RetentionEngine(keep_monthly=1)
kept, pruned = retention.calculate_prune_set(snaps)
self.assertEqual(len(kept), 1)
self.assertEqual(kept[0].snapshot_id, "m3_w1")
def test_execute_prune_dry_run_vs_live(self):
archiver = SnapshotArchiver(target_dir=self.backup_dir)
# Create 3 real tiny snapshot archives on disk
snap_ids = []
manifests = []
for i in range(3):
s_id = f"snap_real_{i}"
snap_ids.append(s_id)
dummy_file = os.path.join(self.test_dir, f"file_{i}.txt")
with open(dummy_file, "w") as f:
f.write(f"content {i}\n")
entries, sha, uncomp, _ = archiver.collect_file_list([dummy_file])
m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z")
m.files_sha256 = sha
archiver.create_snapshot_archive(s_id, m, entries)
manifests.append(m)
# Verify all 3 exist
for s_id in snap_ids:
path = SnapshotArchiver.resolve_archive_path(self.backup_dir, s_id)
self.assertTrue(os.path.isfile(path))
retention = RetentionEngine(keep_last=1)
kept, pruned = retention.calculate_prune_set(manifests)
self.assertEqual(len(pruned), 2)
# Test dry-run: files must NOT be deleted
pid_file = os.path.join(self.test_dir, "test.pid")
results = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=True, pid_path=pid_file)
self.assertEqual(len(results), 2)
for r in results:
self.assertEqual(r["action"], "would_delete")
self.assertTrue(os.path.isfile(r["archive_path"]))
# Test live prune: files MUST be deleted
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
results_live = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=False, pid_path=pid_file)
self.assertEqual(len(results_live), 2)
for r in results_live:
self.assertEqual(r["action"], "deleted")
self.assertFalse(os.path.isfile(r["archive_path"]))
# Kept archive must still exist
kept_path = SnapshotArchiver.resolve_archive_path(self.backup_dir, kept[0].snapshot_id)
self.assertTrue(os.path.isfile(kept_path))
def test_cli_prune_command(self):
archiver = SnapshotArchiver(target_dir=self.backup_dir)
# Create 2 archives
for i in range(2):
s_id = f"cli_snap_{i}"
f_path = os.path.join(self.test_dir, f"f_{i}.txt")
with open(f_path, "w") as f:
f.write(f"val {i}")
entries, sha, uncomp, _ = archiver.collect_file_list([f_path])
m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z")
m.files_sha256 = sha
archiver.create_snapshot_archive(s_id, m, entries)
# 1. Prune without rules -> error
stdout = io.StringIO()
with patch("sys.stderr", stdout):
code = main(["prune", "--target-dir", self.backup_dir])
self.assertEqual(code, EXIT_GENERIC_ERROR)
# 2. Prune dry-run (default without --force)
stdout_dry = io.StringIO()
with patch("sys.stdout", stdout_dry):
code = main(["prune", "--keep-last", "1", "--target-dir", self.backup_dir, "--json"])
self.assertEqual(code, EXIT_SUCCESS)
data = json.loads(stdout_dry.getvalue().strip())
self.assertEqual(data["mode"], "dry-run")
self.assertEqual(data["kept_count"], 1)
self.assertEqual(data["pruned_count"], 1)
# 3. Prune with --force
pid_file = os.path.join(self.test_dir, "prune_test.pid")
stdout_live = io.StringIO()
with patch("sys.stdout", stdout_live), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
code = main([
"prune",
"--keep-last", "1",
"--force",
"--target-dir", self.backup_dir,
"--pid-path", pid_file,
"--json"
])
self.assertEqual(code, EXIT_SUCCESS)
data_live = json.loads(stdout_live.getvalue().strip())
self.assertEqual(data_live["mode"], "live")
self.assertEqual(data_live["pruned"][0]["action"], "deleted")
if __name__ == "__main__":
unittest.main()