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)
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user