183 lines
6.7 KiB
Python
183 lines
6.7 KiB
Python
"""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
|