feat(core): implement slice 1 tracer bullet end-to-end skeleton
This commit is contained in:
1 parent
0aed5bb003
commit
2602b66a90
13 files changed
+882
-1
No files matched your search
@@ -0,0 +1,211 @@
|
||||
"""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
|
||||
from linux_backuper.core.constants import (
|
||||
DEFAULT_BACKUP_DIR,
|
||||
EXIT_CORRUPTED,
|
||||
EXIT_GENERIC_ERROR,
|
||||
EXIT_PERM_DENIED,
|
||||
EXIT_PREFLIGHT_FAIL,
|
||||
EXIT_SUCCESS,
|
||||
)
|
||||
from linux_backuper.core.detector import detect_distro
|
||||
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
|
||||
|
||||
hostname = socket.gethostname().split(".")[0]
|
||||
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
snapshot_id = f"backup_{hostname}_{timestamp}"
|
||||
|
||||
# Determine paths to back up
|
||||
if args.paths:
|
||||
included_paths = args.paths
|
||||
else:
|
||||
# Default quick profile includes /etc
|
||||
included_paths = ["/etc"]
|
||||
|
||||
os_info = detect_distro()
|
||||
archiver = SnapshotArchiver(target_dir=target_dir, compression=args.compression)
|
||||
|
||||
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")
|
||||
|
||||
# Pass 1: Collect files & calculate checksums
|
||||
file_entries, files_sha256, uncompressed_bytes = archiver.collect_file_list(included_paths)
|
||||
|
||||
# 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=args.compression,
|
||||
os=os_info.to_dict(),
|
||||
package_manager="auto",
|
||||
package_count=0,
|
||||
included_paths=included_paths,
|
||||
stats={
|
||||
"file_count": len(file_entries),
|
||||
"uncompressed_bytes": uncompressed_bytes,
|
||||
"compressed_bytes": 0
|
||||
},
|
||||
files_sha256=files_sha256
|
||||
)
|
||||
|
||||
# Pass 2: Create archive with manifest.json as the very first member
|
||||
try:
|
||||
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
|
||||
except Exception as e:
|
||||
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
|
||||
return EXIT_GENERIC_ERROR
|
||||
|
||||
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)
|
||||
snapshots = archiver.list_snapshots()
|
||||
|
||||
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 not snapshot_id.endswith(".tar.gz"):
|
||||
filename = f"{snapshot_id}.tar.gz"
|
||||
else:
|
||||
filename = snapshot_id
|
||||
|
||||
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")
|
||||
|
||||
# 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())
|
||||
Reference in new issue
Block a user