feat(retention): implement slice 5 retention engine and pruning policies
This commit is contained in:
1 parent
8d4127de30
commit
361640f5ae
5 files changed
+498
-1
No files matched your search
@@ -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)
|
||||
|
||||
|
||||
Reference in new issue
Block a user