"""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_GENERIC_ERROR, EXIT_PERM_DENIED, EXIT_PREFLIGHT_FAIL, EXIT_SUCCESS, ) from linux_backuper.core.detector import detect_distro 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.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() 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), "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 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})") # 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") # 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 == "verify": return handle_verify(args) return EXIT_SUCCESS if __name__ == "__main__": sys.exit(main())