Files
linux-backuper/docs/plans/linux-backuper/03-program-design.md
T

7.8 KiB

Gate 3 — Program Design: linux-backuper

1. Directory & File Layout

linux-backuper/
├── bin/
│   └── linux-backuper                     # Executable launcher (#!/usr/bin/env python3)
├── linux_backuper/
│   ├── __init__.py                        # Version constant (__version__ = "1.0.0")
│   ├── __main__.py                        # Entrypoint for `python3 -m linux_backuper`
│   ├── cli.py                             # Argument parsing and command dispatch
│   ├── config.py                          # Config file loader (/etc/linux-backuper.json)
│   ├── models.py                          # Data transfer objects & schemas
│   ├── core/
│   │   ├── __init__.py
│   │   ├── detector.py                    # OS/distro detector (reuses linux-updater pattern)
│   │   ├── health.py                      # Pre-flight disk space and permission checks
│   │   ├── lock.py                        # Concurrency singleton flock
│   │   ├── inspector.py                   # System inspector (hardware, storage, network)
│   │   ├── archiver.py                    # Tar/gzip/zstd packaging & atomic write
│   │   ├── manifest.py                    # Manifest generator, reader & validator
│   │   ├── retention.py                   # Pruning calculation engine
│   │   └── diff.py                        # Snapshot comparison engine
│   └── managers/
│       ├── __init__.py
│       ├── base.py                        # BasePackageManager class
│       ├── rpm.py                         # RPM/DNF/YUM inspector
│       ├── dpkg.py                        # DPKG/APT inspector
│       └── pacman.py                      # Pacman inspector
├── packaging/
│   ├── build_packages.py                  # Standalone .deb, .rpm and .tar.gz generator
│   ├── install.sh                         # Tarball installer script
│   ├── deb/
│   └── rpm/
├── docs/
│   ├── user-guide.md                      # End-user operator guide
│   ├── admin-guide.md                     # Admin, automation & monitoring guide
│   ├── developer-guide.md                 # Architecture & developer guide
│   └── plans/
│       └── linux-backuper/                # Software Factory planning artifacts
├── man/
│   └── linux-backuper.8                   # Complete Section 8 UNIX man page
├── tests/
│   ├── __init__.py
│   ├── test_cli.py
│   ├── test_detector.py
│   ├── test_inspector.py
│   ├── test_archiver.py
│   ├── test_retention.py
│   ├── test_diff.py
│   └── containers/
│       └── run_tests.sh                   # Podman test runner
└── .gitea/
    └── workflows/
        └── release.yml                    # Gitea Actions CI/CD pipeline

2. Key Type Signatures & Interfaces (No Bodies)

# models.py
from typing import Dict, List, Optional, Any
from dataclasses import dataclass

@dataclass
class OsInfo:
    distro_id: str
    distro_name: str
    version_id: str
    kernel: str
    arch: str

@dataclass
class StorageState:
    block_devices: List[Dict[str, Any]]
    mount_points: List[Dict[str, Any]]
    lvm_pvs: Optional[List[Dict[str, Any]]]
    lvm_vgs: Optional[List[Dict[str, Any]]]
    lvm_lvs: Optional[List[Dict[str, Any]]]
    fstab_raw: str

@dataclass
class NetworkState:
    interfaces: List[Dict[str, Any]]
    routes: List[Dict[str, Any]]
    dns_servers: List[str]

@dataclass
class PackageItem:
    name: str
    version: str
    arch: str

@dataclass
class SnapshotManifest:
    schema_version: str
    snapshot_id: str
    created_at: str
    hostname: str
    os_info: OsInfo
    package_manager: str
    packages: List[PackageItem]
    included_paths: List[str]
    archive_sha256: str
    total_files: int
    uncompressed_size: int
    compressed_size: int

# core/inspector.py
class SystemInspector:
    def __init__(self, distro_id: str): ...
    def inspect_hardware(self) -> Dict[str, Any]: ...
    def inspect_storage(self) -> StorageState: ...
    def inspect_network(self) -> NetworkState: ...
    def inspect_packages(self) -> List[PackageItem]: ...
    def inspect_sysctl(self) -> Dict[str, str]: ...

# core/archiver.py
class SnapshotArchiver:
    def __init__(self, target_dir: str, compression: str = "gz"): ...
    def create_snapshot(
        self,
        snapshot_id: str,
        paths_to_include: List[str],
        metadata_files: Dict[str, str],
        manifest: SnapshotManifest,
    ) -> str: ...
    def verify_integrity(self, archive_path: str) -> bool: ...
    def extract_file(self, archive_path: str, member_rel_path: str, destination_path: str) -> None: ...

# core/retention.py
class RetentionEngine:
    def __init__(self, keep_last: int, keep_daily: int = 0, keep_weekly: int = 0): ...
    def calculate_prune_set(self, existing_snapshots: List[SnapshotManifest]) -> List[SnapshotManifest]: ...
    def execute_prune(self, snapshots_to_delete: List[SnapshotManifest], dry_run: bool = False) -> List[str]: ...

3. Call Stack Trace (snapshot command)

  1. cli.main() parses arguments (snapshot --paths /etc --retention 7).
  2. config.load_config() loads /etc/linux-backuper.json and merges CLI overrides.
  3. health.check_preflight(target_dir) verifies free space >= 1024 MB and directory write permissions.
  4. lock.acquire_lock() creates advisory flock /var/run/linux-backuper.pid.
  5. detector.detect_distro() returns distribution (almalinux, debian, etc.).
  6. inspector.SystemInspector queries storage (lsblk), network (ip), and packages (rpm/dpkg).
  7. archiver.SnapshotArchiver collects /etc/, dumps metadata into tempdir, generates manifest.json, packs into atomic_tmp.tar.gz.
  8. Checksum computed and verified; atomically renames atomic_tmp.tar.gz to final backup_<host>_<timestamp>.tar.gz.
  9. retention.RetentionEngine inspects target directory and prunes archives exceeding policy.
  10. lock.release_lock() unlinks PID lock file and exits 0.

4. Test Plan & Assertions

  • test_detector.py: Verifies accurate distribution parsing from mock /etc/os-release files (Debian, Ubuntu, RHEL 8, AlmaLinux 9, Fedora 40, Arch).
  • test_inspector.py: Verifies mock output parsing of lsblk, ip route, dpkg-query, and rpm -qa.
  • test_archiver.py:
    • Verifies round-trip archiving and extraction of test directory tree.
    • Verifies corruption detection when archive bytes are tampered with.
    • Verifies atomic write rollback on simulated out-of-space or permission errors.
  • test_retention.py:
    • Verifies --keep-last 5 on a pool of 10 simulated snapshots retains the 5 newest.
    • Verifies --keep-daily 7 retains exactly one snapshot per day.
  • test_diff.py: Verifies diffing two manifests correctly reports added, removed, and upgraded packages and files.

5. Least Confident Decisions (Adversarial Check)

  1. Packaging /etc with non-readable files: Some files in /etc/ (like /etc/shadow, /etc/sudoers, SSL private keys) have mode 0600 or 0400 owned by root.
    • Mitigation: Explicit root permission check (os.geteuid() == 0) before starting snapshot. Handle unreadable sockets/pipes gracefully (exclude /etc/** socket files).
  2. Older OS versions without ip -j or lsblk -J (e.g. stock RHEL 8): RHEL 8.0 lsblk and older iproute2 versions lack JSON support.
    • Mitigation: Provide robust tabular/regex parsers for plain-text lsblk and ip a/ip r as primary or fallback drivers.
  3. Large files or log spam in /etc: Some applications place caches or logs in /etc.
    • Mitigation: Enforce a per-file size warning (e.g. alert if single file in /etc > 10 MB) and skip zero-byte lock files.