feat(restore): implement slice 4 snapshot management, diff engine, and safe restore
This commit is contained in:
1 parent
646bd9d145
commit
8d4127de30
9 files changed
+1386
-4
No files matched your search
@@ -15,15 +15,18 @@ from linux_backuper.core.constants import (
|
||||
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.models import SnapshotManifest
|
||||
|
||||
def check_root_permissions() -> bool:
|
||||
@@ -221,6 +224,252 @@ def handle_verify(args: argparse.Namespace) -> int:
|
||||
|
||||
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 build_parser() -> argparse.ArgumentParser:
|
||||
"""Construct CLI argument parser."""
|
||||
common_parser = argparse.ArgumentParser(add_help=False)
|
||||
@@ -252,6 +501,38 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
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})")
|
||||
|
||||
# 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")
|
||||
@@ -272,6 +553,14 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
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 == "verify":
|
||||
return handle_verify(args)
|
||||
|
||||
@@ -279,3 +568,4 @@ def main(argv: Optional[List[str]] = None) -> int:
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
Reference in new issue
Block a user