Files
linux-backuper/linux_backuper/cli.py
T

688 lines
33 KiB
Python

"""Command-line interface and dispatch for linux-backuper."""
import argparse
import datetime
import json
import os
import socket
import sys
from typing import List, Optional
from linux_backuper import __version__
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256
from linux_backuper.core.constants import (
DEFAULT_BACKUP_DIR,
DEFAULT_CONFIG_PATH,
DEFAULT_PID_PATH,
EXIT_CORRUPTED,
EXIT_DRY_RUN,
EXIT_GENERIC_ERROR,
EXIT_PERM_DENIED,
EXIT_PREFLIGHT_FAIL,
EXIT_SUCCESS,
)
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.diff import DiffEngine
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:
"""Check if process has root privileges, respecting test overrides."""
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1":
return True
try:
return os.geteuid() == 0
except AttributeError:
return True
def handle_snapshot(args: argparse.Namespace) -> int:
"""Execute snapshot command."""
if not check_root_permissions():
sys.stderr.write("[ERROR] Creating snapshots requires root privileges (uid 0).\n")
return EXIT_PERM_DENIED
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
try:
os.makedirs(target_dir, exist_ok=True)
except OSError as e:
sys.stderr.write(f"[ERROR] Target backup directory not accessible: {e}\n")
return EXIT_PREFLIGHT_FAIL
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
lock = SingleInstanceLock(pid_path=pid_path)
try:
lock.acquire()
except LockAcquisitionError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
try:
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
profile_mgr = ProfileManager(config_path=config_path)
try:
profile = profile_mgr.get_profile(args.profile)
except KeyError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
hostname = socket.gethostname().split(".")[0]
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
snapshot_id = f"backup_{hostname}_{timestamp}"
# Resolve paths & exclusions
included_paths = args.paths if args.paths else profile.included_paths
exclude_patterns = profile.exclude_patterns
compression = "none" if getattr(args, "no_compression", False) else args.compression
sanitize = getattr(args, "sanitize", False)
os_info = detect_distro()
archiver = SnapshotArchiver(target_dir=target_dir, compression=compression)
inspector = SystemInspector(distro_id=os_info.distro_id)
packages = inspector.inspect_packages()
if not args.json:
sys.stderr.write(f"[INFO] Initializing snapshot '{snapshot_id}' (profile: {args.profile})...\n")
sys.stderr.write(f"[INFO] Host OS: {os_info.distro_name} {os_info.version_id} ({os_info.arch})\n")
sys.stderr.write(f"[INFO] Packages detected: {len(packages)} via {inspector.package_manager.get_manager_name()}\n")
# Pass 1: Collect data paths
file_entries, files_sha256, uncompressed_bytes, sanitized_files = archiver.collect_file_list(
included_paths,
exclude_patterns=exclude_patterns,
sanitize=sanitize
)
# Pass 1b: Collect deep system telemetry meta files
import shutil
import tempfile
temp_meta_dir = tempfile.mkdtemp(prefix="linux_backuper_meta_")
try:
meta_files_map = inspector.dump_meta_files(temp_meta_dir)
# Record sanitized files if any
if sanitized_files:
sanitized_log_path = os.path.join(temp_meta_dir, "sanitized.txt")
with open(sanitized_log_path, "w", encoding="utf-8") as f:
f.write("# Redacted security files:\n")
for s in sanitized_files:
f.write(f"{s}\n")
meta_files_map["meta/sanitized.txt"] = sanitized_log_path
for rel_path, abs_path in meta_files_map.items():
file_entries.append((abs_path, rel_path))
sha = calculate_file_sha256(abs_path)
files_sha256[rel_path] = sha
uncompressed_bytes += os.path.getsize(abs_path)
# Manifest preparation
manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id=snapshot_id,
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
hostname=socket.gethostname(),
profile=args.profile,
compression=compression,
os=os_info.to_dict(),
package_manager=inspector.package_manager.get_manager_name(),
package_count=len(packages),
included_paths=included_paths,
stats={
"file_count": len(file_entries),
"uncompressed_bytes": uncompressed_bytes,
"compressed_bytes": 0,
"sanitized_count": len(sanitized_files)
},
files_sha256=files_sha256
)
# Pass 2: Create archive with manifest.json as the very first member
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
finally:
shutil.rmtree(temp_meta_dir, ignore_errors=True)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
return EXIT_GENERIC_ERROR
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,
"archive_path": archive_path,
"profile": args.profile,
"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))
else:
size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f"[SUCCESS] Snapshot created successfully: {archive_path} ({size_mb:.2f} MB, {len(file_entries)} files)\n")
return EXIT_SUCCESS
def handle_list(args: argparse.Namespace) -> int:
"""Execute list command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archiver = SnapshotArchiver(target_dir=target_dir)
try:
snapshots = archiver.list_snapshots()
except PermissionError as e:
sys.stderr.write(f"[ERROR] {e} (try running with sudo).\n")
return EXIT_PERM_DENIED
if args.json:
result = [s.to_dict() for s in snapshots]
print(json.dumps(result, indent=2))
return EXIT_SUCCESS
if not snapshots:
sys.stdout.write(f"No snapshots found in {target_dir}.\n")
return EXIT_SUCCESS
sys.stdout.write(f"{'SNAPSHOT ID':<40} {'PROFILE':<10} {'FILES':<8} {'SIZE (MB)':<10} {'CREATED AT':<25}\n")
sys.stdout.write("-" * 95 + "\n")
for s in snapshots:
size_mb = s.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f"{s.snapshot_id:<40} {s.profile:<10} {s.stats.get('file_count', 0):<8} {size_mb:<10.2f} {s.created_at[:19]:<25}\n")
return EXIT_SUCCESS
def handle_verify(args: argparse.Namespace) -> int:
"""Execute verify command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
snapshot_id = args.snapshot_id
# Resolve filename
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
filename = snapshot_id
else:
candidate_tar = os.path.join(target_dir, f"{snapshot_id}.tar") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar"
candidate_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar.gz"
if os.path.exists(candidate_tar) and not os.path.exists(candidate_gz):
filename = f"{snapshot_id}.tar"
else:
filename = f"{snapshot_id}.tar.gz"
archive_path = os.path.join(target_dir, filename) if not os.path.isabs(filename) else filename
is_valid, msg = SnapshotArchiver.verify_archive(archive_path)
if args.json:
print(json.dumps({"snapshot_id": snapshot_id, "valid": is_valid, "message": msg}, indent=2))
else:
if is_valid:
sys.stdout.write(f"[SUCCESS] {msg}: {archive_path}\n")
else:
sys.stderr.write(f"[ERROR] Integrity check failed: {msg}\n")
return EXIT_SUCCESS if is_valid else EXIT_CORRUPTED
def handle_show(args: argparse.Namespace) -> int:
"""Execute show command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
if not os.path.isfile(archive_path):
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
return EXIT_GENERIC_ERROR
try:
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to read manifest: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
payload = manifest.to_dict()
payload["archive_path"] = archive_path
if args.packages:
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
payload["packages_dump"] = pkg_txt.splitlines() if pkg_txt else []
print(json.dumps(payload, indent=2))
return EXIT_SUCCESS
size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024)
uncomp_mb = manifest.stats.get("uncompressed_bytes", 0) / (1024 * 1024)
os_name = manifest.os.get("distro_name", "Linux")
os_ver = manifest.os.get("version_id", "")
arch = manifest.os.get("arch", "")
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"Snapshot ID: {manifest.snapshot_id}\n")
sys.stdout.write(f"Archive File: {archive_path}\n")
sys.stdout.write(f"Created At: {manifest.created_at}\n")
sys.stdout.write(f"Hostname: {manifest.hostname}\n")
sys.stdout.write(f"Operating System: {os_name} {os_ver} ({arch})\n")
sys.stdout.write(f"Profile: {manifest.profile}\n")
sys.stdout.write(f"Compression: {manifest.compression}\n")
sys.stdout.write(f"File Count: {manifest.stats.get('file_count', 0)}\n")
sys.stdout.write(f"Size on Disk: {size_mb:.2f} MB (uncompressed: {uncomp_mb:.2f} MB)\n")
sys.stdout.write(f"Package Manager: {manifest.package_manager} ({manifest.package_count} packages recorded)\n")
sys.stdout.write(f"Included Paths: {', '.join(manifest.included_paths)}\n")
if manifest.stats.get("sanitized_count"):
sys.stdout.write(f"Sanitized Files: {manifest.stats.get('sanitized_count')} (secrets redacted)\n")
sys.stdout.write("=" * 80 + "\n")
if args.files:
sys.stdout.write("\nArchived files:\n")
for f in sorted(manifest.files_sha256.keys()):
sys.stdout.write(f" {f}\n")
if args.packages:
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
if pkg_txt:
sys.stdout.write("\nArchived packages:\n")
sys.stdout.write(pkg_txt + "\n")
return EXIT_SUCCESS
def handle_diff(args: argparse.Namespace) -> int:
"""Execute diff command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
engine = DiffEngine(target_dir=target_dir)
try:
if args.snapshot_id_2:
result = engine.diff_snapshots(args.snapshot_id, args.snapshot_id_2)
else:
target_root = getattr(args, "target_root", "/") or "/"
result = engine.diff_with_live(args.snapshot_id, target_root=target_root)
except Exception as e:
sys.stderr.write(f"[ERROR] Diff failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps(result, indent=2))
return EXIT_SUCCESS
if result["type"] == "live_vs_snapshot":
sys.stdout.write(f"--- Live System vs Snapshot '{result['snapshot_id']}' ---\n")
files = result["files"]
if files["modified"]:
sys.stdout.write(f"\nModified files on live system ({len(files['modified'])}):\n")
for f in files["modified"]:
sys.stdout.write(f" [M] {f}\n")
if args.unified:
u_diff = engine.generate_unified_file_diff(result["snapshot_id"], f, target_root=result["target_root"])
if u_diff:
sys.stdout.write(u_diff + "\n")
if files["missing_on_live"]:
sys.stdout.write(f"\nMissing files on live system (present in backup) ({len(files['missing_on_live'])}):\n")
for f in files["missing_on_live"]:
sys.stdout.write(f" [-] {f}\n")
if files["added_on_live"]:
sys.stdout.write(f"\nAdded files on live system (not in backup) ({len(files['added_on_live'])}):\n")
for f in files["added_on_live"]:
sys.stdout.write(f" [+] {f}\n")
sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n")
pkgs = result["packages"]
if pkgs["installed_since_backup"]:
sys.stdout.write(f"\nPackages installed since backup ({len(pkgs['installed_since_backup'])}):\n")
for p, v in list(pkgs["installed_since_backup"].items())[:20]:
sys.stdout.write(f" + {p} ({v})\n")
if len(pkgs["installed_since_backup"]) > 20:
sys.stdout.write(f" ... and {len(pkgs['installed_since_backup']) - 20} more\n")
if pkgs["removed_since_backup"]:
sys.stdout.write(f"\nPackages removed since backup ({len(pkgs['removed_since_backup'])}):\n")
for p, v in list(pkgs["removed_since_backup"].items())[:20]:
sys.stdout.write(f" - {p} ({v})\n")
if pkgs["version_changed"]:
sys.stdout.write(f"\nPackages with changed versions ({len(pkgs['version_changed'])}):\n")
for p, ch in list(pkgs["version_changed"].items())[:20]:
sys.stdout.write(f" ~ {p}: {ch['snapshot']} -> {ch['live']}\n")
else:
sys.stdout.write(f"--- Snapshot '{result['snapshot_1']}' vs Snapshot '{result['snapshot_2']}' ---\n")
files = result["files"]
if files["modified"]:
sys.stdout.write(f"\nModified files ({len(files['modified'])}):\n")
for f in files["modified"]:
sys.stdout.write(f" [M] {f}\n")
if files["added"]:
sys.stdout.write(f"\nFiles added in snapshot 2 ({len(files['added'])}):\n")
for f in files["added"]:
sys.stdout.write(f" [+] {f}\n")
if files["removed"]:
sys.stdout.write(f"\nFiles removed in snapshot 2 ({len(files['removed'])}):\n")
for f in files["removed"]:
sys.stdout.write(f" [-] {f}\n")
sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n")
return EXIT_SUCCESS
def handle_extract(args: argparse.Namespace) -> int:
"""Execute extract command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
if not os.path.isfile(archive_path):
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
return EXIT_GENERIC_ERROR
try:
out_path = SnapshotArchiver.extract_file(archive_path, args.file, args.out)
except Exception as e:
sys.stderr.write(f"[ERROR] Extract failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps({
"status": "success",
"snapshot_id": args.snapshot_id,
"file": args.file,
"destination": out_path
}, indent=2))
else:
sys.stdout.write(f"[SUCCESS] Extracted '{args.file}' to '{out_path}'\n")
return EXIT_SUCCESS
def handle_restore(args: argparse.Namespace) -> int:
"""Execute restore command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
target_root = getattr(args, "target_root", "/") or "/"
force = getattr(args, "force", False)
dry_run = getattr(args, "dry_run", False)
include_fstab = getattr(args, "include_fstab", False)
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
# If live mutation requested, require root unless non-root override
if force and not dry_run and os.geteuid() != 0 and not os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT"):
sys.stderr.write("[ERROR] Restoring files to live system requires root privileges (run with sudo).\n")
return EXIT_PERM_DENIED
engine = SafeRestoreEngine(target_dir=target_dir)
try:
plan = engine.plan_restore(args.snapshot_id, target_root=target_root, include_fstab=include_fstab)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to plan restore: {e}\n")
return EXIT_GENERIC_ERROR
# If --dry-run or not --force
if dry_run or not force:
if args.json:
out_dict = plan.to_dict()
out_dict["mode"] = "dry-run"
print(json.dumps(out_dict, indent=2))
else:
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"RESTORE EXECUTION PLAN (Dry Run) — Snapshot: {plan.snapshot_id}\n")
sys.stdout.write(f"Target Root: {plan.target_root}\n")
sys.stdout.write("=" * 80 + "\n")
create_items = [i for i in plan.items if i.action == "create"]
modify_items = [i for i in plan.items if i.action == "modify"]
skip_items = [i for i in plan.items if i.action == "skip"]
network_items = [i for i in plan.items if i.is_sensitive_network and i.action in ("create", "modify")]
if network_items:
sys.stdout.write("\n[WARNING] SENSITIVE NETWORK CONFIGURATION DETECTED:\n")
for item in network_items:
sys.stdout.write(f" ! {item.abs_path} will be overwritten\n")
sys.stdout.write(" Restoring network files may impact active network connectivity.\n\n")
if create_items:
sys.stdout.write(f"Files to CREATE ({len(create_items)}):\n")
for item in create_items:
sys.stdout.write(f" [+] {item.abs_path}\n")
if modify_items:
sys.stdout.write(f"\nFiles to MODIFY ({len(modify_items)}):\n")
for item in modify_items:
sys.stdout.write(f" [~] {item.abs_path}\n")
if skip_items:
sys.stdout.write(f"\nFiles to SKIP ({len(skip_items)}):\n")
for item in skip_items:
sys.stdout.write(f" [*] {item.abs_path} ({item.reason})\n")
sys.stdout.write("-" * 80 + "\n")
sys.stdout.write(f"Summary: {len(create_items)} to create, {len(modify_items)} to modify, {len(skip_items)} skipped.\n")
sys.stdout.write("[NOTICE] Dry run completed without modifying filesystem blocks.\n")
sys.stdout.write("[ACTION] Pass --force to execute live restore (automatic safety snapshot will be created).\n")
return EXIT_DRY_RUN
# Live restore with --force
if not args.json:
sys.stdout.write(f"[INFO] Initiating live restore for snapshot '{plan.snapshot_id}'...\n")
sys.stdout.write(f"[INFO] Target root directory: {plan.target_root}\n")
try:
res = engine.execute_restore(plan, force=True, pid_path=pid_path)
except Exception as e:
sys.stderr.write(f"[ERROR] Restore failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps(res, indent=2))
else:
sys.stdout.write(f"[SUCCESS] Safety snapshot created: {res['safety_snapshot_id']}\n")
sys.stdout.write(f"[SUCCESS] Restored {res['restored_count']} files to {plan.target_root}\n")
if res.get("selinux_context_restored"):
sys.stdout.write("[INFO] Restored SELinux security contexts via restorecon.\n")
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)
common_parser.add_argument("--json", action="store_true", help="Output machine-readable JSON to stdout")
common_parser.add_argument("--verbose", action="store_true", help="Enable detailed diagnostic logging")
parser = argparse.ArgumentParser(
prog="linux-backuper",
description="Enterprise Linux system snapshot and configuration backup utility.",
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[common_parser]
)
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
subparsers = parser.add_subparsers(dest="subcommand", help="Available sub-commands")
# Snapshot command
snap_parser = subparsers.add_parser("snapshot", help="Capture a new system state snapshot", parents=[common_parser])
snap_parser.add_argument("--profile", default="quick", help="Backup profile (default: quick)")
snap_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help=f"Destination directory (default: {DEFAULT_BACKUP_DIR})")
snap_parser.add_argument("--paths", nargs="+", help="Specific directories or files to include in snapshot")
snap_parser.add_argument("--compression", choices=["gzip", "none"], default="gzip", help="Compression algorithm")
snap_parser.add_argument("--no-compression", action="store_true", help="Store plain uncompressed tar archive")
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])
list_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory to scan for snapshots")
# Show command
show_parser = subparsers.add_parser("show", help="Display details and metadata of a snapshot", parents=[common_parser])
show_parser.add_argument("snapshot_id", help="Snapshot ID or filename to display")
show_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
show_parser.add_argument("--packages", action="store_true", help="List all recorded installed packages")
show_parser.add_argument("--files", action="store_true", help="List all archived file paths")
# Diff command
diff_parser = subparsers.add_parser("diff", help="Compare live system against snapshot, or two snapshots", parents=[common_parser])
diff_parser.add_argument("snapshot_id", help="First snapshot ID (or base snapshot for live diff)")
diff_parser.add_argument("snapshot_id_2", nargs="?", default=None, help="Second snapshot ID (optional, compares two snapshots)")
diff_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots")
diff_parser.add_argument("--target-root", default="/", help="Filesystem root to compare against in live diff (default: /)")
diff_parser.add_argument("--unified", "-u", action="store_true", help="Display unified diff for modified text files")
# Extract command
extract_parser = subparsers.add_parser("extract", help="Selectively extract a single file from a snapshot", parents=[common_parser])
extract_parser.add_argument("snapshot_id", help="Snapshot ID or filename")
extract_parser.add_argument("--file", required=True, help="File path inside snapshot to extract")
extract_parser.add_argument("--out", required=True, help="Destination file or directory path")
extract_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
# Restore command
restore_parser = subparsers.add_parser("restore", help="Restore system configuration from a snapshot", parents=[common_parser])
restore_parser.add_argument("snapshot_id", help="Snapshot ID to restore")
restore_parser.add_argument("--dry-run", action="store_true", help="Display execution plan without modifying filesystem (exit code 5)")
restore_parser.add_argument("--force", action="store_true", help="Execute live restoration (safety snapshot created automatically)")
restore_parser.add_argument("--target-root", default="/", help="Target root directory to restore onto (default: /)")
restore_parser.add_argument("--include-fstab", action="store_true", help="Allow restoring /etc/fstab")
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")
verify_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
return parser
def main(argv: Optional[List[str]] = None) -> int:
"""Main CLI entrypoint."""
parser = build_parser()
args = parser.parse_args(argv)
if not args.subcommand:
parser.print_help()
return EXIT_SUCCESS
if args.subcommand == "snapshot":
return handle_snapshot(args)
elif args.subcommand == "list":
return handle_list(args)
elif args.subcommand == "show":
return handle_show(args)
elif args.subcommand == "diff":
return handle_diff(args)
elif args.subcommand == "extract":
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)
return EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())