diff --git a/bin/linux-backuper b/bin/linux-backuper new file mode 100755 index 0000000..46b8df0 --- /dev/null +++ b/bin/linux-backuper @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Executable launcher for linux-backuper.""" + +import os +import sys + +# Ensure library path is discoverable when run directly from repo +repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if repo_root not in sys.path: + sys.path.insert(0, repo_root) + +from linux_backuper.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/docs/plans/linux-backuper/00-status.md b/docs/plans/linux-backuper/00-status.md index 627c22f..27f75ff 100644 --- a/docs/plans/linux-backuper/00-status.md +++ b/docs/plans/linux-backuper/00-status.md @@ -6,7 +6,7 @@ - Gate 4 — Slice Plan: APPROVED 2026-10-03 ## Slices -- [ ] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests) +- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests) - [ ] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages) - [ ] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest - [ ] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot) diff --git a/linux_backuper/__init__.py b/linux_backuper/__init__.py new file mode 100644 index 0000000..3ba57dd --- /dev/null +++ b/linux_backuper/__init__.py @@ -0,0 +1,4 @@ +"""linux-backuper - Enterprise Linux system snapshot and configuration backup utility.""" + +__version__ = "1.0.0" +__author__ = "wiredLAB" diff --git a/linux_backuper/__main__.py b/linux_backuper/__main__.py new file mode 100644 index 0000000..718059f --- /dev/null +++ b/linux_backuper/__main__.py @@ -0,0 +1,7 @@ +"""Entrypoint when executed as a module: python3 -m linux_backuper.""" + +import sys +from linux_backuper.cli import main + +if __name__ == "__main__": + sys.exit(main()) diff --git a/linux_backuper/cli.py b/linux_backuper/cli.py new file mode 100644 index 0000000..7c6ad8d --- /dev/null +++ b/linux_backuper/cli.py @@ -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()) diff --git a/linux_backuper/core/__init__.py b/linux_backuper/core/__init__.py new file mode 100644 index 0000000..446dec6 --- /dev/null +++ b/linux_backuper/core/__init__.py @@ -0,0 +1 @@ +"""Core modules for linux-backuper.""" diff --git a/linux_backuper/core/archiver.py b/linux_backuper/core/archiver.py new file mode 100644 index 0000000..2412fb0 --- /dev/null +++ b/linux_backuper/core/archiver.py @@ -0,0 +1,260 @@ +"""Archive creation, extraction, and verification using Python standard library.""" + +import gzip +import hashlib +import json +import os +import stat +import tarfile +import time +from typing import Dict, List, Optional, Tuple, Any + +from linux_backuper.models import SnapshotManifest + +BUFFER_SIZE = 64 * 1024 # 64 KB chunks for hashing and streaming + +def calculate_file_sha256(filepath: str) -> str: + """Calculate SHA-256 checksum of a file.""" + hasher = hashlib.sha256() + with open(filepath, "rb") as f: + while chunk := f.read(BUFFER_SIZE): + hasher.update(chunk) + return hasher.hexdigest() + +def is_socket_or_fifo(filepath: str) -> bool: + """Check if path is a UNIX socket, named pipe (FIFO) or character device.""" + try: + st = os.lstat(filepath) + return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode) + except OSError: + return True + +class SnapshotArchiver: + """Manages creation, listing, and verification of snapshot archives.""" + + def __init__(self, target_dir: str, compression: str = "gzip"): + self.target_dir = target_dir + self.compression = "gzip" if compression in ("gz", "gzip") else "none" + + def _ensure_target_dir() -> None: + pass + + def _ensure_target_dir_inst(self) -> None: + """Ensure target directory exists with 0700 permissions.""" + os.makedirs(self.target_dir, exist_ok=True) + try: + os.chmod(self.target_dir, 0o700) + except OSError: + pass + + def collect_file_list( + self, + paths: List[str], + exclude_patterns: Optional[List[str]] = None + ) -> Tuple[List[Tuple[str, str]], Dict[str, str], int]: + """ + Scan paths and compute pre-archive hashes and metadata. + Returns: + - list of (filesystem_abs_path, tar_rel_path) + - dict of {tar_rel_path: sha256_hash} + - total uncompressed bytes + """ + file_entries: List[Tuple[str, str]] = [] + files_sha256: Dict[str, str] = {} + total_bytes = 0 + exclude_patterns = exclude_patterns or [] + + for base_path in paths: + abs_base = os.path.abspath(base_path) + if not os.path.exists(abs_base): + continue + + if os.path.isfile(abs_base) or os.path.islink(abs_base): + if not is_socket_or_fifo(abs_base): + rel_name = os.path.join("data", os.path.basename(abs_base)) + file_entries.append((abs_base, rel_name)) + if not os.path.islink(abs_base): + sha = calculate_file_sha256(abs_base) + files_sha256[rel_name] = sha + total_bytes += os.path.getsize(abs_base) + continue + + # Directory tree traversal + for root, dirs, files in os.walk(abs_base, followlinks=False): + # Filter subdirectories in place + dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)] + + for filename in files: + abs_filepath = os.path.join(root, filename) + if is_socket_or_fifo(abs_filepath): + continue + + # Calculate archive path under data/ + rel_to_base = os.path.relpath(abs_filepath, os.path.dirname(abs_base)) + arc_path = os.path.join("data", rel_to_base) + + file_entries.append((abs_filepath, arc_path)) + + if not os.path.islink(abs_filepath): + try: + sha = calculate_file_sha256(abs_filepath) + files_sha256[arc_path] = sha + total_bytes += os.path.getsize(abs_filepath) + except (OSError, IOError): + pass + + return file_entries, files_sha256, total_bytes + + def create_snapshot_archive( + self, + snapshot_id: str, + manifest: SnapshotManifest, + file_entries: List[Tuple[str, str]] + ) -> str: + """ + Create atomic .tar.gz archive with manifest.json as the very first member. + Enforces 0600 file permissions. + """ + self._ensure_target_dir_inst() + ext = ".tar.gz" if self.compression == "gzip" else ".tar" + final_archive_path = os.path.join(self.target_dir, f"{snapshot_id}{ext}") + temp_archive_path = os.path.join(self.target_dir, f".{snapshot_id}.tmp{ext}") + + # Encode manifest JSON bytes + manifest_dict = manifest.to_dict() + manifest_bytes = json.dumps(manifest_dict, indent=2, sort_keys=True).encode("utf-8") + + # Open temp archive for writing with gzip or plain tar + tar_mode = "w:gz" if self.compression == "gzip" else "w:" + with tarfile.open(temp_archive_path, tar_mode) as tar: + # 1. ADD MANIFEST.JSON AS THE VERY FIRST MEMBER + manifest_info = tarfile.TarInfo(name="manifest.json") + manifest_info.size = len(manifest_bytes) + manifest_info.mtime = int(time.time()) + manifest_info.mode = 0o600 + manifest_info.type = tarfile.REGTYPE + + import io + tar.addfile(tarinfo=manifest_info, fileobj=io.BytesIO(manifest_bytes)) + + # 2. ADD ALL COLLECTED DATA FILES + for abs_path, arc_path in file_entries: + try: + tar.add(abs_path, arcname=arc_path, recursive=False) + except (OSError, IOError): + pass + + # Set strict 0600 permissions + try: + os.chmod(temp_archive_path, 0o600) + except OSError: + pass + + # Atomic rename to final path + os.replace(temp_archive_path, final_archive_path) + + # Update manifest compressed size stat + compressed_size = os.path.getsize(final_archive_path) + manifest.stats["compressed_bytes"] = compressed_size + + return final_archive_path + + @staticmethod + def read_manifest_from_archive(archive_path: str) -> SnapshotManifest: + """ + Read manifest.json from the first member of the archive stream. + Ultra-fast: avoids decompressing the rest of the archive. + """ + with tarfile.open(archive_path, "r:*") as tar: + first_member = tar.next() + if not first_member or first_member.name != "manifest.json": + # Fallback: scan for manifest.json if not first + member = tar.getmember("manifest.json") + else: + member = first_member + + manifest_file = tar.extractfile(member) + if not manifest_file: + raise ValueError(f"Could not read manifest from {archive_path}") + + data = json.loads(manifest_file.read().decode("utf-8")) + return SnapshotManifest.from_dict(data) + + @staticmethod + def verify_archive(archive_path: str) -> Tuple[bool, str]: + """ + Verify gzip stream integrity and all file SHA-256 checksums against manifest.json. + Returns (is_valid, error_message). + """ + if not os.path.isfile(archive_path): + return False, f"Archive not found: {archive_path}" + + # 1. Check if file is gzip by inspecting header + is_gz = False + try: + with open(archive_path, "rb") as f: + header = f.read(2) + is_gz = (header == b"\x1f\x8b") + except OSError as e: + return False, f"Cannot open archive: {e}" + + # If gzipped, verify complete stream integrity + if is_gz: + try: + with gzip.open(archive_path, "rb") as gz: + while gz.read(BUFFER_SIZE): + pass + except Exception as e: + return False, f"Gzip stream corrupted: {e}" + + # 2. Manifest and member checksum verification + try: + with tarfile.open(archive_path, "r:*") as tar: + # Read manifest + try: + manifest_member = tar.getmember("manifest.json") + manifest_data = json.loads(tar.extractfile(manifest_member).read().decode("utf-8")) + except Exception as e: + return False, f"Invalid or missing manifest.json: {e}" + + expected_hashes: Dict[str, str] = manifest_data.get("files_sha256", {}) + + for arc_name, expected_sha in expected_hashes.items(): + try: + member = tar.getmember(arc_name) + except KeyError: + return False, f"Missing file in archive: {arc_name}" + + if member.isreg(): + f = tar.extractfile(member) + if not f: + return False, f"Unable to read file: {arc_name}" + + hasher = hashlib.sha256() + while chunk := f.read(BUFFER_SIZE): + hasher.update(chunk) + actual_sha = hasher.hexdigest() + + if actual_sha != expected_sha: + return False, f"Checksum mismatch for {arc_name}: expected {expected_sha}, got {actual_sha}" + + except Exception as e: + return False, f"Tar archive corrupted: {e}" + + return True, "Integrity verified successfully" + + def list_snapshots(self) -> List[SnapshotManifest]: + """List all valid snapshots in the target directory.""" + if not os.path.isdir(self.target_dir): + return [] + + snapshots: List[SnapshotManifest] = [] + for filename in sorted(os.listdir(self.target_dir), reverse=True): + if filename.endswith(".tar.gz") and not filename.startswith("."): + filepath = os.path.join(self.target_dir, filename) + try: + manifest = self.read_manifest_from_archive(filepath) + snapshots.append(manifest) + except Exception: + pass + return snapshots diff --git a/linux_backuper/core/constants.py b/linux_backuper/core/constants.py new file mode 100644 index 0000000..3590460 --- /dev/null +++ b/linux_backuper/core/constants.py @@ -0,0 +1,18 @@ +"""Constants and exit codes for linux-backuper.""" + +# Exit Codes +EXIT_SUCCESS = 0 +EXIT_GENERIC_ERROR = 1 +EXIT_PREFLIGHT_FAIL = 2 +EXIT_CORRUPTED = 3 +EXIT_PERM_DENIED = 4 +EXIT_DRY_RUN = 5 + +# Default filesystem locations +DEFAULT_BACKUP_DIR = "/var/backups/linux-backuper" +DEFAULT_CONFIG_PATH = "/etc/linux-backuper.json" +DEFAULT_PID_PATH = "/var/run/linux-backuper.pid" +DEFAULT_LOG_DIR = "/var/log/linux-backuper" + +# Minimum free disk space in megabytes for preflight check +MIN_FREE_DISK_MB = 1024 diff --git a/linux_backuper/core/detector.py b/linux_backuper/core/detector.py new file mode 100644 index 0000000..5d5d4e7 --- /dev/null +++ b/linux_backuper/core/detector.py @@ -0,0 +1,66 @@ +"""Linux distribution and operating system detector.""" + +import os +import platform +from typing import Dict, Optional +from linux_backuper.models import OsInfo + +DEFAULT_OS_RELEASE_PATH = "/etc/os-release" +FALLBACK_OS_RELEASE_PATH = "/usr/lib/os-release" + +def parse_os_release(content: str) -> Dict[str, str]: + """Parse key-value pairs from os-release format string.""" + data = {} + for line in content.splitlines(): + line = line.strip() + if not line or line.startswith("#"): + continue + if "=" in line: + key, val = line.split("=", 1) + key = key.strip().lower() + val = val.strip().strip("\"'") + data[key] = val + + distro_id = data.get("id", "linux").lower() + distro_name = data.get("name", "Linux") + version_id = data.get("version_id", data.get("build_id", "rolling")) + + return { + "id": distro_id, + "name": distro_name, + "version_id": version_id, + "id_like": data.get("id_like", "") + } + +def detect_distro(os_release_path: Optional[str] = None) -> OsInfo: + """Detect current operating system distribution and kernel release.""" + content = "" + candidate_paths = [os_release_path] if os_release_path else [DEFAULT_OS_RELEASE_PATH, FALLBACK_OS_RELEASE_PATH] + + for path in candidate_paths: + if path and os.path.isfile(path): + try: + with open(path, "r", encoding="utf-8", errors="replace") as f: + content = f.read() + break + except (OSError, IOError): + pass + + if content: + parsed = parse_os_release(content) + distro_id = parsed["id"] + distro_name = parsed["name"] + version_id = parsed["version_id"] + else: + # Fallback for non-Linux or testing environments + distro_id = platform.system().lower() + distro_name = platform.system() + version_id = platform.release() + + return OsInfo( + distro_id=distro_id, + distro_name=distro_name, + version_id=version_id, + kernel=platform.release(), + arch=platform.machine() + ) diff --git a/linux_backuper/models.py b/linux_backuper/models.py new file mode 100644 index 0000000..cc555d6 --- /dev/null +++ b/linux_backuper/models.py @@ -0,0 +1,93 @@ +"""Data transfer objects and models for linux-backuper.""" + +from dataclasses import dataclass, asdict, field +from typing import Dict, List, Optional, Any + +@dataclass +class OsInfo: + distro_id: str + distro_name: str + version_id: str + kernel: str + arch: str + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "OsInfo": + return cls( + distro_id=data.get("distro_id", "unknown"), + distro_name=data.get("distro_name", "Unknown Linux"), + version_id=data.get("version_id", "0"), + kernel=data.get("kernel", ""), + arch=data.get("arch", "") + ) + +@dataclass +class PackageItem: + name: str + version: str + arch: str + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "PackageItem": + return cls( + name=data["name"], + version=data["version"], + arch=data.get("arch", "") + ) + +@dataclass +class ProfileConfig: + name: str + description: str + included_paths: List[str] + exclude_patterns: List[str] = field(default_factory=list) + collect_users: bool = True + collect_kernel: bool = True + collect_storage: bool = True + collect_network: bool = True + collect_packages: bool = True + max_journal_mb: int = 0 + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + +@dataclass +class SnapshotManifest: + schema_version: str + snapshot_id: str + created_at: str + hostname: str + profile: str + compression: str + os: Dict[str, Any] + package_manager: str + package_count: int + included_paths: List[str] + stats: Dict[str, Any] + files_sha256: Dict[str, str] = field(default_factory=dict) + + def to_dict(self) -> Dict[str, Any]: + return asdict(self) + + @classmethod + def from_dict(cls, data: Dict[str, Any]) -> "SnapshotManifest": + return cls( + schema_version=data.get("schema_version", "1.0"), + snapshot_id=data["snapshot_id"], + created_at=data["created_at"], + hostname=data["hostname"], + profile=data.get("profile", "quick"), + compression=data.get("compression", "gzip"), + os=data.get("os", {}), + package_manager=data.get("package_manager", "none"), + package_count=data.get("package_count", 0), + included_paths=data.get("included_paths", []), + stats=data.get("stats", {}), + files_sha256=data.get("files_sha256", {}) + ) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..ae78246 --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +# tests/__init__.py diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..2a8815a --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,125 @@ +import io +import json +import os +import stat +import sys +import tarfile +import tempfile +import unittest +from unittest.mock import patch + +from linux_backuper.cli import main +from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED + +class TestCliTracerBullet(unittest.TestCase): + def setUp(self): + self.temp_dir = tempfile.mkdtemp(prefix="test_linux_backuper_") + self.backup_dir = os.path.join(self.temp_dir, "backups") + os.makedirs(self.backup_dir, exist_ok=True) + # Mock etc directory with dummy file + self.mock_etc = os.path.join(self.temp_dir, "etc") + os.makedirs(self.mock_etc, exist_ok=True) + with open(os.path.join(self.mock_etc, "hostname"), "w") as f: + f.write("test-host.local\n") + with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f: + f.write("key=value\n") + + def tearDown(self): + import shutil + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def test_version_flag(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout): + with self.assertRaises(SystemExit) as cm: + main(["--version"]) + self.assertEqual(cm.exception.code, EXIT_SUCCESS) + self.assertIn("1.0.0", stdout.getvalue()) + + def test_help_flag(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout): + with self.assertRaises(SystemExit) as cm: + main(["--help"]) + self.assertEqual(cm.exception.code, EXIT_SUCCESS) + self.assertIn("linux-backuper", stdout.getvalue()) + self.assertIn("snapshot", stdout.getvalue()) + + def test_snapshot_tracer_bullet_creates_archive(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + exit_code = main([ + "snapshot", + "--target-dir", self.backup_dir, + "--paths", self.mock_etc, + "--profile", "quick", + "--json" + ]) + self.assertEqual(exit_code, EXIT_SUCCESS) + + output_data = json.loads(stdout.getvalue().strip()) + self.assertIn("snapshot_id", output_data) + self.assertIn("archive_path", output_data) + + archive_path = output_data["archive_path"] + self.assertTrue(os.path.exists(archive_path)) + + # Check file permissions (0600 on POSIX) + file_mode = stat.S_IMODE(os.stat(archive_path).st_mode) + self.assertEqual(file_mode, 0o600) + + # Verify tar members: manifest.json MUST be the very first member + with tarfile.open(archive_path, "r:gz") as tar: + members = tar.getmembers() + self.assertGreater(len(members), 0) + self.assertEqual(members[0].name, "manifest.json") + + # Extract manifest and verify structure + manifest_file = tar.extractfile(members[0]) + manifest = json.loads(manifest_file.read().decode("utf-8")) + self.assertEqual(manifest["snapshot_id"], output_data["snapshot_id"]) + self.assertEqual(manifest["profile"], "quick") + self.assertIn("os", manifest) + self.assertIn("files_sha256", manifest) + + def test_list_command(self): + # First create a snapshot + with patch("sys.stdout", io.StringIO()), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc]) + + # Now test listing + stdout = io.StringIO() + with patch("sys.stdout", stdout): + exit_code = main(["list", "--target-dir", self.backup_dir, "--json"]) + self.assertEqual(exit_code, EXIT_SUCCESS) + + listed = json.loads(stdout.getvalue().strip()) + self.assertEqual(len(listed), 1) + self.assertIn("snapshot_id", listed[0]) + self.assertEqual(listed[0]["profile"], "quick") + + def test_verify_command(self): + stdout = io.StringIO() + with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}): + main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"]) + snap_data = json.loads(stdout.getvalue().strip()) + snap_id = snap_data["snapshot_id"] + + # Verify should succeed on untouched archive + with patch("sys.stdout", io.StringIO()): + exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir]) + self.assertEqual(exit_code, EXIT_SUCCESS) + + # Corrupt archive CRC + archive_path = snap_data["archive_path"] + with open(archive_path, "r+b") as f: + f.seek(-4, os.SEEK_END) + f.write(b"\x00\x00\x00\x00") + + # Verify should detect corruption and return EXIT_CORRUPTED (3) + with patch("sys.stdout", io.StringIO()): + exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir]) + self.assertEqual(exit_code, EXIT_CORRUPTED) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_detector.py b/tests/test_detector.py new file mode 100644 index 0000000..ba76a63 --- /dev/null +++ b/tests/test_detector.py @@ -0,0 +1,80 @@ +import os +import tempfile +import unittest +from linux_backuper.core.detector import detect_distro, parse_os_release +from linux_backuper.models import OsInfo + +class TestOsDetector(unittest.TestCase): + def test_parse_almalinux_9(self): + content = """NAME="AlmaLinux" +VERSION="9.4 (Seafoam)" +ID="almalinux" +ID_LIKE="rhel centos fedora" +VERSION_ID="9.4" +PRETTY_NAME="AlmaLinux 9.4 (Seafoam)" +""" + info = parse_os_release(content) + self.assertEqual(info["id"], "almalinux") + self.assertEqual(info["name"], "AlmaLinux") + self.assertEqual(info["version_id"], "9.4") + + def test_parse_debian_12(self): + content = """PRETTY_NAME="Debian GNU/Linux 12 (bookworm)" +NAME="Debian GNU/Linux" +VERSION_ID="12" +VERSION="12 (bookworm)" +VERSION_CODENAME=bookworm +ID=debian +""" + info = parse_os_release(content) + self.assertEqual(info["id"], "debian") + self.assertEqual(info["name"], "Debian GNU/Linux") + self.assertEqual(info["version_id"], "12") + + def test_parse_ubuntu_2204(self): + content = """NAME="Ubuntu" +VERSION="22.04.4 LTS (Jammy Jellyfish)" +ID=ubuntu +ID_LIKE=debian +PRETTY_NAME="Ubuntu 22.04.4 LTS" +VERSION_ID="22.04" +""" + info = parse_os_release(content) + self.assertEqual(info["id"], "ubuntu") + self.assertEqual(info["name"], "Ubuntu") + self.assertEqual(info["version_id"], "22.04") + + def test_parse_arch(self): + content = """NAME="Arch Linux" +PRETTY_NAME="Arch Linux" +ID=arch +BUILD_ID=rolling +""" + info = parse_os_release(content) + self.assertEqual(info["id"], "arch") + self.assertEqual(info["name"], "Arch Linux") + self.assertEqual(info["version_id"], "rolling") + + def test_detect_distro_with_custom_file(self): + with tempfile.NamedTemporaryFile("w+", delete=False) as f: + f.write("""NAME="Fedora Linux" +VERSION="40 (Cloud Edition)" +ID=fedora +VERSION_ID="40" +""") + temp_path = f.name + + try: + os_info = detect_distro(os_release_path=temp_path) + self.assertIsInstance(os_info, OsInfo) + self.assertEqual(os_info.distro_id, "fedora") + self.assertEqual(os_info.distro_name, "Fedora Linux") + self.assertEqual(os_info.version_id, "40") + self.assertTrue(len(os_info.arch) > 0) + self.assertTrue(len(os_info.kernel) > 0) + finally: + if os.path.exists(temp_path): + os.remove(temp_path) + +if __name__ == "__main__": + unittest.main()