diff --git a/docs/plans/linux-backuper/00-status.md b/docs/plans/linux-backuper/00-status.md index f71280c..8dd2855 100644 --- a/docs/plans/linux-backuper/00-status.md +++ b/docs/plans/linux-backuper/00-status.md @@ -6,13 +6,13 @@ - Gate 4 — Slice Plan: in progress ## Slices -- [ ] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + tar.gz snapshot + tests) -- [ ] Slice 2 — comprehensive host state inspector (hardware, LVM/storage, network, packages, sysctl) -- [ ] Slice 3 — configuration archiver (`/etc/`, boot, custom paths) with atomic write & SHA256 manifest -- [ ] Slice 4 — snapshot management (list, verify, diff, selective extract, JSON output) -- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, automated cleanup) -- [ ] Slice 6 — remote destination engine (SFTP / SCP / rsync / NFS export sync) -- [ ] Slice 7 — packaging & distribution (.deb, .rpm, .tar.gz standalone) +- [ ] 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) +- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote) +- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention) +- [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder) - [ ] Slice 8 — full documentation (user, admin & developer guides), man page (Section 8), CLI -h/--help, shell tab completion (Bash/Zsh) & Gitea Actions CI/CD release workflow ## Notes for a fresh session @@ -22,13 +22,22 @@ - Platforms: Debian 11/12, Ubuntu 20.04/22.04/24.04, RHEL 8/9, AlmaLinux 8/9, Rocky Linux 8/9, Fedora 39/40/41, Arch Linux. - Target Python runtime: Python >= 3.6 (RHEL 8 compatibility). - Dependencies: Zero mandatory external dependencies (pure Python standard library). Optional `cryptography` for encrypted snapshots. +- Key Design Decisions from /grill-me Alignment: + 1. Scope & Profiles: Configurable profile system (`quick` default with `/etc/`, users/groups, full hardware/kernel/storage/network/package metadata; `system` adding `/boot/` and kernel state; `full`/`dr` adding `/boot/` and high-value `/var/` paths: crontabs `/var/spool/cron`, systemd state `/var/lib/systemd`, NetworkManager `/var/lib/NetworkManager`, capped recent journal/log; custom profiles in config). + 2. Metadata Collection: Users/groups (`/etc/passwd`, `/etc/group`, subuid/subgid), kernel parameters (`sysctl -a`, `/proc/cmdline`, `lsmod`), hardware (`lscpu`, `lshw`, `lspci`, `lsusb`, `dmidecode`, RAM/meminfo), storage (`lsblk`, `df`, LVM `pvs/vgs/lvs`, `/etc/fstab`), network (`ip a`, `ip r`, `/etc/resolv.conf`), packages (`rpm -qa`, `dpkg-query`, `pacman -Q`). + 3. Compression: Built-in standard library `gzip` (`.tar.gz`) enabled by default. Zero external compression binaries required. Optional `--no-compression` flag. + 4. Security & Encryption: Strict `0600` root-only archive permissions. Optional AES-256 encryption (`--encrypt`). Diagnostic sanitization (`--sanitize`) redacting `/etc/shadow` and private keys. Fully documented. + 5. Remote Storage & NAS Sync: Local-first architecture (always written locally to `/var/backups/linux-backuper/` first). Optional `--push` flag or profile remote targets (SSH/SFTP, rsync, mounted directory) with independent remote retention. + 6. Safe Restore Strategy: + - Primary: Selective extraction (`extract --file --out `) and live system diff (`diff ` and `diff `). + - Full restore (`restore `): Guardrailed by default `--dry-run`, mandatory `--force`, automatic `pre-restore-safety-snapshot`, and exclusion of volatile sockets/dynamic symlinks. - Shell Tab Completion Standard (Bash & Zsh): - - Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `prune`). - - Dynamic completion: `show`, `diff`, `verify`, `extract` auto-complete snapshot IDs from `/var/backups/linux-backuper/`. + - Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `restore`, `prune`, `completion`). + - Dynamic completion: `show`, `diff`, `verify`, `extract`, `restore` auto-complete snapshot IDs from `/var/backups/linux-backuper/`. - Built-in `linux-backuper completion [bash|zsh]` generator + system-wide package deployment (`/usr/share/bash-completion/completions/` and `/usr/share/zsh/site-functions/`). - Documentation Standard (Mandatory parity with linux-updater): - - User Guide: `docs/user-guide.md` (comprehensive operator workflow and snapshot recovery). - - Administrator Guide: `docs/admin-guide.md` (automation, systemd timer/cron setup, logrotate, monitoring, JSON parsing). + - User Guide: `docs/user-guide.md` (comprehensive operator workflow, profiles, safe restore procedures). + - Administrator Guide: `docs/admin-guide.md` (automation, systemd timer/cron setup, logrotate, monitoring, JSON parsing, remote NAS sync). - Developer Guide: `docs/developer-guide.md` (internal architecture, adapter extension, test suite). - System Manual Page: `man/linux-backuper.8` (complete Section 8 man page). - Rich CLI Help: Complete `-h` and `--help` for root and all sub-commands with syntax, argument descriptions, and realistic examples. diff --git a/docs/plans/linux-backuper/01-spec.md b/docs/plans/linux-backuper/01-spec.md index f51d175..bab3b7b 100644 --- a/docs/plans/linux-backuper/01-spec.md +++ b/docs/plans/linux-backuper/01-spec.md @@ -36,57 +36,61 @@ System administrators and homelab operators frequently perform system updates, p ```text # 1. Capture a full system snapshot with auto-generated name: +# 1. Capture snapshot with default profile (quick): # sudo linux-backuper snapshot +[INFO] Profile: 'quick' (included: /etc, users/groups, full hardware/kernel/storage/network metadata) [INFO] Pre-flight checks passed: 42.1 GB free in /var/backups/linux-backuper -[INFO] Collecting host metadata (hardware, storage, network, packages)... -[INFO] Archiving /etc directory... +[INFO] Collecting host metadata (hardware, storage, network, packages, kernel, users)... +[INFO] Archiving /etc directory with standard gzip compression... [INFO] Generating SHA-256 integrity manifest... [SUCCESS] Snapshot created: /var/backups/linux-backuper/backup_enterprise_20261002_211500.tar.gz (14.2 MB) -# 2. List available snapshots on the system: -# linux-backuper list -+-----------------------------------+---------------------+---------+----------+----------+ -| SNAPSHOT ID | DATE & TIME | SIZE | PACKAGES | STATUS | -+-----------------------------------+---------------------+---------+----------+----------+ -| backup_enterprise_20261002_211500 | 2026-10-02 21:15:00 | 14.2 MB | 642 pkgs | VERIFIED | -| backup_enterprise_20261001_040000 | 2026-10-01 04:00:00 | 14.1 MB | 638 pkgs | VERIFIED | -+-----------------------------------+---------------------+---------+----------+----------+ +# 2. Capture full disaster-recovery snapshot and push to NAS: +# sudo linux-backuper snapshot --profile full --push nas +[INFO] Profile: 'full' (included: /etc, /boot, /var/spool/cron, /var/lib/systemd, /var/lib/NetworkManager, capped journal) +[INFO] Snapshot created locally: backup_enterprise_20261002_220000.tar.gz (48.1 MB) +[INFO] Transferring to remote 'nas' (SFTP: 192.168.10.2:/volume1/backups/hosts)... +[SUCCESS] Remote sync complete with remote retention applied. -# 3. Inspect details of a snapshot: -# linux-backuper show backup_enterprise_20261002_211500 -Hostname: enterprise.wired.intra -OS: AlmaLinux 9.4 (Seafoam Ocelot) - Kernel 5.14.0-427.el9 -Hardware: KVM QEMU (4 vCPU, 8192 MB RAM) -Storage: / (xfs, 18G/40G), /boot (xfs, 280M/1024M), LVM vg_sys/lv_root -Network: eth0: 192.168.10.15/24, GW: 192.168.10.1, DNS: 192.168.1.1 -Packages: 642 installed (RPM) - -# 4. Compare changes between two snapshots: -# linux-backuper diff backup_enterprise_20261001_040000 backup_enterprise_20261002_211500 -Packages changed: - + nginx 1.24.0-1.el9 (added) +# 3. Compare current live system with a previous snapshot: +# linux-backuper diff backup_enterprise_20261001_040000 +Packages changed on live host: + + nginx 1.24.0-1.el9 (installed since snapshot) ~ openssl 3.0.7-27.el9 -> 3.0.7-28.el9 (upgraded) -Configuration files modified: +Configuration files modified on live host: ~ /etc/nginx/nginx.conf + /etc/nginx/conf.d/default.conf -# 5. Extract a single configuration file without unpacking entire archive: +# 4. Safe single file extraction: # sudo linux-backuper extract backup_enterprise_20261001_040000 --file /etc/nginx/nginx.conf --out /tmp/nginx.conf.old -# 6. Verify archive integrity: -# linux-backuper verify backup_enterprise_20261002_211500 -[SUCCESS] Archive checksum and all 1,420 manifest file hashes MATCH. +# 5. Full restore with mandatory safety guardrails: +# sudo linux-backuper restore backup_enterprise_20261001_040000 +[WARN] Running in DRY-RUN mode. No live files will be modified without '--force'. +[PLAN] Files to be restored: 142 files modified, 3 files to be created. +[WARN] Network configuration (/etc/netplan/) would be altered! +Use 'linux-backuper restore backup_enterprise_20261001_040000 --force' to execute. -# 7. Prune snapshots according to retention rules: -# sudo linux-backuper prune --keep-last 7 -[INFO] Pruning snapshots: 2 snapshots removed, 7 snapshots retained. +# sudo linux-backuper restore backup_enterprise_20261001_040000 --force +[INFO] Safety: Creating automatic pre-restore safety snapshot 'pre_restore_20261002_220500'... +[SUCCESS] Safety snapshot captured (42.0 MB). +[INFO] Restoring configuration files to live /etc/ (excluding sockets, locks, runtime mounts)... +[SUCCESS] Restore completed successfully. Pre-restore rollback available at 'pre_restore_20261002_220500'. ``` --- ## 5. Scope & Constraints -- **Zero Third-Party Pip Packages:** Must work on default Python 3.6+ without external packages. -- **Root Protection:** Creating snapshots, pruning, and extracting to system directories requires root; reading/listing/verifying can be done unprivileged if permissions permit. +- **Zero Third-Party Pip Packages:** Pure Python standard library (Python >= 3.6). Built-in `gzip` and `tarfile` module. Optional `--no-compression` flag. +- **Root Protection & Permissions:** + - Creating snapshots, pruning, and live restoring strictly requires root (`os.geteuid() == 0`). + - Snapshot archives are created with strict `0600` permissions inside `0700` directories. + - Optional diagnostic sanitization (`--sanitize`) redacts `/etc/shadow`, `/etc/gshadow`, and private keys (`/etc/ssh/ssh_host_*_key`). +- **Profiles Architecture:** + - `quick` (default): `/etc/`, users/groups, full hardware/kernel/storage/network/package metadata. + - `system`: `/etc/`, `/boot/`, kernel cmdline/modules, systemd units, metadata. + - `full`: `/etc/`, `/boot/`, `/var/spool/cron`, `/var/lib/systemd`, `/var/lib/NetworkManager`, capped recent journal. + - User-defined profiles in `/etc/linux-backuper.json`. - **FHS Compliance:** - Executable: `/usr/bin/linux-backuper` - Library: `/usr/lib/linux-backuper/` diff --git a/docs/plans/linux-backuper/02-architecture.md b/docs/plans/linux-backuper/02-architecture.md index e8220d6..c8fe648 100644 --- a/docs/plans/linux-backuper/02-architecture.md +++ b/docs/plans/linux-backuper/02-architecture.md @@ -2,22 +2,24 @@ ## 1. System Fit & Architecture Diagram -`linux-backuper` is structured as a modular Python 3 CLI tool adhering to strict Single Responsibility and Adapter patterns. +`linux-backuper` is structured as a modular Python 3 CLI tool adhering to strict Single Responsibility and Adapter patterns with pure standard library core. ``` ┌───────────────────────────┐ │ CLI Interface (cli) │ │ snapshot, list, show, │ - │ diff, verify, extract │ + │ diff, verify, extract, │ + │ restore, prune │ └─────────────┬─────────────┘ │ ┌──────────────┴──────────────┐ ▼ ▼ ┌─────────────────────┐ ┌─────────────────────┐ - │ Host Inspector │ │ Snapshot Engine │ - │ - Hardware │ │ - Tar / Gzip / Zstd│ + │ Host Inspector │ │ Profile & Archiver │ + │ - Hardware & Kernel│ │ - quick/system/full│ + │ - Users & Groups │ │ - Stdlib Gzip/Tar │ │ - Storage / LVM │ │ - SHA-256 Manifest │ - │ - Network / Routes │ │ - Atomic write │ + │ - Network / Routes │ │ - Atomic write 0600│ │ - Package Manager │ └──────────┬──────────┘ │ - System Services │ │ └──────────┬──────────┘ │ @@ -25,26 +27,77 @@ └──────────────┬──────────────┘ ▼ ┌─────────────────────────────┐ - │ Storage / Pruning │ + │ Safe Restore & Diff │ + │ - Live system diff │ + │ - Selective extraction │ + │ - Pre-restore snapshot │ + │ - Exclusion guardrails │ + └──────────────┬──────────────┘ + ▼ + ┌─────────────────────────────┐ + │ Storage & Sync │ │ - Local (/var/backups/) │ │ - Retention Engine │ - │ - Remote SFTP/rsync (opt) │ + │ - Local-first --push sync │ + │ (SFTP / rsync / NFS) │ └─────────────────────────────┘ ``` --- -## 2. Snapshot Archive Format & Manifest Schema +## 2. Profiles Architecture -Each snapshot is packaged as a `.tar.gz` (or `.tar.zst` if zstd binary exists) containing: -1. `manifest.json`: Machine-readable metadata document. -2. `meta/`: Raw system command dumps for low-level human/script recovery. - - `storage.json` & `storage.txt` - - `network.json` & `network.txt` - - `packages.txt` - - `hardware.txt` - - `sysctl.txt` -3. `data/`: The actual archived filesystem hierarchies (e.g. `data/etc/`, `data/boot/`). +`linux-backuper` provides 3 built-in profiles and supports custom user profiles in `/etc/linux-backuper.json`: + +1. **`quick` (DEFAULT):** + - **Scope:** `/etc/` directory tree, user/group accounts, full hardware/kernel/storage/network/package metadata. + - **Performance:** Runs in < 5 seconds, produces < 20 MB archive. + - **Use Case:** Daily automated configuration snapshots, pre-package-upgrade checks. +2. **`system`:** + - **Scope:** All of `quick` plus `/boot/`, loaded kernel modules (`lsmod`), `/proc/cmdline`, active systemd unit configurations. + - **Use Case:** Pre-kernel upgrades, systemd modifications. +3. **`full` (Disaster Recovery):** + - **Scope:** All of `system` plus selective high-value state: + - Cron jobs: `/var/spool/cron/` + - Systemd state: `/var/lib/systemd/` + - NetworkManager state: `/var/lib/NetworkManager/` + - Capped recent journal/syslog (maximum 50 MB tail). + - **Use Case:** Bare-metal migration, catastrophic rollback preparation. + +--- + +## 3. Deep System Metadata Collection + +To ensure complete reconstruction even on a fresh OS install, every snapshot gathers comprehensive host telemetry into `meta/`: + +- **Users & Groups:** `/etc/passwd`, `/etc/group`, `/etc/subuid`, `/etc/subgid` (captures UID/GID mapping). +- **Kernel State:** `sysctl -a` (`meta/sysctl.txt`), `/proc/cmdline`, loaded modules (`lsmod`). +- **Hardware Profile:** `lscpu`, `lshw`, `lspci`, `lsusb`, `dmidecode`, `/proc/meminfo`. +- **Storage & Filesystems:** `lsblk -J` (or plain text fallback), `df -hT`, LVM (`pvs -J`, `vgs -J`, `lvs -J`), `/etc/fstab`. +- **Network Configuration:** `ip -j a` / `ip -j r` (or plain text fallback), `/etc/resolv.conf`, active connections (`ss -tulpn`). +- **Installed Packages:** Multi-distro package dump (`rpm -qa`, `dpkg-query -W`, or `pacman -Q`). + +--- + +## 4. Snapshot Archive Format & Manifest Schema + +Each snapshot is packaged as a `.tar.gz` archive with strict `0600` permissions (readable/writeable only by root) inside `/var/backups/linux-backuper/` (`0700` directory). + +```text +backup_enterprise_20261002_211500.tar.gz +├── manifest.json # Machine-readable metadata document +├── meta/ # Deep telemetry command dumps +│ ├── hardware.json / .txt +│ ├── storage.json / .txt +│ ├── network.json / .txt +│ ├── packages.txt +│ ├── kernel.txt +│ └── users.txt +└── data/ # Archived filesystem trees + ├── etc/ # Always included + ├── boot/ # In 'system' and 'full' profiles + └── var/ # In 'full' profile +``` ### `manifest.json` Data Contract ```json @@ -53,6 +106,8 @@ Each snapshot is packaged as a `.tar.gz` (or `.tar.zst` if zstd binary exists) c "snapshot_id": "backup_enterprise_20261002_211500", "created_at": "2026-10-02T21:15:00+00:00", "hostname": "enterprise.wired.intra", + "profile": "quick", + "compression": "gzip", "os": { "distro_id": "almalinux", "distro_name": "AlmaLinux", @@ -77,39 +132,69 @@ Each snapshot is packaged as a `.tar.gz` (or `.tar.zst` if zstd binary exists) c --- -## 3. Package Manager & System Adapters +## 5. Compression & Security Architecture -`linux-backuper` auto-detects the active distribution via `/etc/os-release` and dispatches to concrete adapter implementations: - -| Family | Distros | Package Listing Command | Network Detection | Storage / LVM Detection | -|---|---|---|---|---| -| **RHEL** | RHEL 8/9, AlmaLinux, Rocky, Fedora | `rpm -qa --qf '%{NAME} %{VERSION}-%{RELEASE} %{ARCH}\n'` | `ip -j a`, `ip -j r`, `nmcli` | `lsblk -J`, `lvs --json`, `vgs --json`, `pvs --json` | -| **Debian** | Debian 11/12, Ubuntu 20.04/22.04/24.04 | `dpkg-query -W -f='${Package} ${Version} ${Architecture}\n'` | `ip -j a`, `ip -j r`, `netplan` | `lsblk -J`, LVM tools if present | -| **Arch** | Arch Linux, EndeavourOS | `pacman -Q` | `ip -j a`, `ip -j r`, `networkctl` | `lsblk -J`, LVM tools if present | - -*Note:* If JSON output flags (`-j`, `--json`) are unsupported on older utility versions, fallback regex parsers process the plain-text command output. +1. **Standard Library Gzip (Default):** + - Pure Python `gzip` and `tarfile` module ensures 100% self-contained operation without external binaries (`gzip`, `tar`, `zstd`). + - Optional `--no-compression` flag creates plain `.tar` archives for ultra-low CPU environments. +2. **Access Control & File Modes:** + - Base backup directory: `/var/backups/linux-backuper/` mode `0700` root:root. + - Archive files: mode `0600` root:root. +3. **Diagnostic Sanitization (`--sanitize`):** + - For troubleshooting or exporting archives to third parties, `--sanitize` automatically redacts `/etc/shadow`, `/etc/gshadow`, `/etc/sudoers`, and SSH private host keys (`/etc/ssh/ssh_host_*_key`). --- -## 4. Retention Policy (Pruning Engine) +## 6. Safe Restore & Diff Engine + +Restoring configuration on a live Linux system carries critical operational risks (SSH disconnection, daemon crash, permission loss). `linux-backuper` implements a defense-in-depth safety engine: + +1. **Selective Extraction (`extract`):** + - Primary operational command for recovery. Extract single files or subdirectories to a destination: + ```bash + sudo linux-backuper extract --file /etc/nginx/nginx.conf --out /tmp/nginx.conf.old + ``` +2. **Live System Diff (`diff`):** + - `linux-backuper diff `: Compares the live `/etc/` and installed packages against the snapshot, reporting modified, added, and missing files and packages. + - `linux-backuper diff `: Compares two snapshots against each other. +3. **Full Live Restore (`restore `):** + - **Default Dry-Run:** Running `linux-backuper restore ` without `--force` prints a comprehensive change plan and exits without modifying the filesystem. + - **Automatic Pre-Restore Safety Snapshot:** When `--force` is specified, `linux-backuper` **automatically captures a safety snapshot** (`pre_restore_`) before modifying a single file on disk. If anything goes wrong, immediate rollback is guaranteed. + - **Strict Exclusion Guardrails:** Automatically skips dynamic sockets (`*.sock`), named pipes (FIFOs), temporary lock files (`*.lock`, `*.pid`), and dynamic mount links (`/etc/resolv.conf`, `/etc/mtab`). + +--- + +## 7. Remote Storage Sync (Local-First Model) + +1. **Local-First Guarantee:** Snapshots are always committed locally first in `/var/backups/linux-backuper/` with verified checksums. Network interruptions cannot leave corrupted local backups. +2. **Push Sync (`--push [target]`):** + - Transports supported: SFTP (via `paramiko`), `rsync`, or direct filesystem write to mounted NFS/SMB shares. + - Remote configurations defined in `/etc/linux-backuper.json` (e.g. `nas`, `cloud`). + - **Independent Remote Retention:** Remote target maintains its own retention policy (e.g. keep last 30 on NAS while keeping last 7 locally). + +--- + +## 8. Retention Policy (Pruning Engine) Retention is computed using standard time-bucket pruning: - `--keep-last N`: Always preserve the $N$ most recent snapshots regardless of date. - `--keep-daily D`: Preserve 1 snapshot per calendar day for the last $D$ days. - `--keep-weekly W`: Preserve 1 snapshot per calendar week (Monday) for the last $W$ weeks. -Pruning calculates the union of keep-sets and safely deletes the remaining archives and their companion metadata. +Pruning calculates the union of keep-sets and safely deletes the remaining archives and companion manifests. --- -## 5. Exit Codes & JSON Output +## 9. Exit Codes & JSON Output | Exit Code | Name | Meaning | |---|---|---| -| `0` | `SUCCESS` | Snapshot created, verified, or pruned successfully. | +| `0` | `SUCCESS` | Snapshot created, verified, restored, or pruned successfully. | | `1` | `GENERIC_ERROR` | Runtime failure, missing dependencies, or write error. | | `2` | `PREFLIGHT_FAIL` | Insufficient disk space (< 1 GB) or target directory unwriteable. | | `3` | `CORRUPTED` | Snapshot checksum or archive validation failed. | | `4` | `PERM_DENIED` | Mutating operation requested without root privileges. | +| `5` | `DRY_RUN` | Dry-run completed; changes pending user confirmation. | When `--json` is specified, all commands output structured JSON to stdout, directing diagnostics and progress logs to stderr. + diff --git a/docs/plans/linux-backuper/03-program-design.md b/docs/plans/linux-backuper/03-program-design.md index 99abf8a..092914b 100644 --- a/docs/plans/linux-backuper/03-program-design.md +++ b/docs/plans/linux-backuper/03-program-design.md @@ -16,12 +16,15 @@ linux-backuper/ │ │ ├── __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 +│ │ ├── lock.py # Concurrency singleton flock (/var/run/linux-backuper.pid) +│ │ ├── profiles.py # Profile manager (quick, system, full, custom) +│ │ ├── inspector.py # System inspector (hardware, storage, network, kernel, users) +│ │ ├── archiver.py # Stdlib Gzip/Tar packaging, atomic write & permissions (0600) +│ │ ├── manifest.py # Manifest generator, reader & SHA-256 validator +│ │ ├── diff.py # Snapshot vs Snapshot & Live vs Snapshot comparison engine +│ │ ├── restore.py # Safe restore engine (dry-run, safety snapshot, exclusions) │ │ ├── retention.py # Pruning calculation engine -│ │ ├── diff.py # Snapshot comparison engine +│ │ ├── transport.py # Remote push sync adapter (SFTP, rsync, local mount) │ │ └── completion.py # Shell completion generator & dynamic snapshot resolver │ └── managers/ │ ├── __init__.py @@ -51,10 +54,13 @@ linux-backuper/ │ ├── __init__.py │ ├── test_cli.py │ ├── test_detector.py +│ ├── test_profiles.py │ ├── test_inspector.py │ ├── test_archiver.py -│ ├── test_retention.py │ ├── test_diff.py +│ ├── test_restore.py +│ ├── test_retention.py +│ ├── test_transport.py │ └── containers/ │ └── run_tests.sh # Podman test runner └── .gitea/ @@ -79,6 +85,19 @@ class OsInfo: kernel: str arch: str +@dataclass +class ProfileConfig: + name: str + description: str + included_paths: List[str] + exclude_patterns: List[str] + collect_users: bool + collect_kernel: bool + collect_storage: bool + collect_network: bool + collect_packages: bool + max_journal_mb: int = 0 + @dataclass class StorageState: block_devices: List[Dict[str, Any]] @@ -106,6 +125,8 @@ class SnapshotManifest: snapshot_id: str created_at: str hostname: str + profile: str + compression: str os_info: OsInfo package_manager: str packages: List[PackageItem] @@ -115,6 +136,29 @@ class SnapshotManifest: uncompressed_size: int compressed_size: int +@dataclass +class RestorePlanItem: + rel_path: str + abs_path: str + action: str # "modify", "create", "skip" + reason: Optional[str] = None + is_sensitive_network: bool = False + +@dataclass +class RestorePlan: + snapshot_id: str + target_root: str + items: List[RestorePlanItem] + safety_snapshot_id: Optional[str] = None + requires_force: bool = True + +# core/profiles.py +class ProfileManager: + BUILTIN_PROFILES: Dict[str, ProfileConfig] + def __init__(self, custom_profiles: Optional[Dict[str, Any]] = None): ... + def get_profile(self, name: str) -> ProfileConfig: ... + def list_profiles(self) -> List[ProfileConfig]: ... + # core/inspector.py class SystemInspector: def __init__(self, distro_id: str): ... @@ -122,21 +166,44 @@ class SystemInspector: def inspect_storage(self) -> StorageState: ... def inspect_network(self) -> NetworkState: ... def inspect_packages(self) -> List[PackageItem]: ... - def inspect_sysctl(self) -> Dict[str, str]: ... + def inspect_users_and_groups(self) -> Dict[str, Any]: ... + def inspect_kernel_state(self) -> Dict[str, Any]: ... + def dump_meta_files(self, temp_meta_dir: str) -> Dict[str, str]: ... # core/archiver.py class SnapshotArchiver: - def __init__(self, target_dir: str, compression: str = "gz"): ... + EXCLUDED_PATTERNS: List[str] # Sockets, FIFOs, locks + def __init__(self, target_dir: str, compression: str = "gz", sanitize: bool = False): ... def create_snapshot( self, snapshot_id: str, - paths_to_include: List[str], - metadata_files: Dict[str, str], + profile: ProfileConfig, + meta_files_dir: 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/restore.py +class SafeRestoreEngine: + EXCLUDED_MUTATIONS: List[str] # /etc/resolv.conf, /etc/mtab, sockets + def __init__(self, backup_dir: str): ... + def plan_restore(self, snapshot_id: str, target_root: str = "/") -> RestorePlan: ... + def create_safety_snapshot(self) -> str: ... + def execute_restore(self, plan: RestorePlan, force: bool = False) -> bool: ... + +# core/diff.py +class DiffEngine: + def __init__(self, backup_dir: str): ... + def diff_snapshots(self, id1: str, id2: str) -> Dict[str, Any]: ... + def diff_with_live(self, snapshot_id: str) -> Dict[str, Any]: ... + +# core/transport.py +class RemoteTransport: + def __init__(self, target_config: Dict[str, Any]): ... + def push_snapshot(self, local_archive_path: str, remote_target: str) -> bool: ... + def prune_remote(self, keep_last: int) -> int: ... + # core/retention.py class RetentionEngine: def __init__(self, keep_last: int, keep_daily: int = 0, keep_weekly: int = 0): ... @@ -146,41 +213,83 @@ class RetentionEngine: --- -## 3. Call Stack Trace (`snapshot` command) +## 3. Call Stack Traces -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__.tar.gz`. -9. `retention.RetentionEngine` inspects target directory and prunes archives exceeding policy. -10. `lock.release_lock()` unlinks PID lock file and exits `0`. +### A. `snapshot` Command Call Stack +1. `cli.main()` parses CLI flags (`snapshot --profile quick --push nas`). +2. `config.load_config()` loads `/etc/linux-backuper.json`. +3. `health.check_preflight(target_dir)` verifies root user (`os.geteuid() == 0`) and free disk space >= 1024 MB. +4. `lock.acquire_lock()` creates non-blocking flock on `/var/run/linux-backuper.pid`. +5. `profiles.ProfileManager` loads requested profile (e.g. `quick`). +6. `detector.detect_distro()` detects active Linux distribution. +7. `inspector.SystemInspector` gathers telemetry (users, kernel, hardware, storage, network, packages) into temporary `meta/` dir. +8. `archiver.SnapshotArchiver` collects paths specified in profile, sets strict `0600` archive permissions, writes `atomic.tmp.tar.gz`. +9. Manifest computed with SHA-256 and written inside archive; atomic rename to `backup__.tar.gz`. +10. If `--push` specified: `transport.RemoteTransport.push_snapshot()` transfers archive to remote host (SFTP/rsync). +11. `retention.RetentionEngine` prunes old local (and remote) archives if retention limits configured. +12. `lock.release_lock()` unlinks PID file and exits `0`. + +### B. `restore` Command Call Stack (Safe Restore Engine) +1. `cli.main()` parses arguments (`restore [--force]`). +2. `health.require_root()` ensures root permissions. +3. `archiver.verify_integrity(archive_path)` validates archive checksum against internal manifest. +4. `restore.SafeRestoreEngine.plan_restore()` scans snapshot archive against live `/etc/`: + - Checks every file difference. + - Flags sensitive network configurations (`/etc/netplan/`, `/etc/sysconfig/network-scripts/`). + - Marks dynamic files (`/etc/resolv.conf`, `/etc/mtab`, sockets) as `EXCLUDE`. +5. If `--force` is NOT provided: + - Prints visual diff plan with warnings. + - Exits with status `5 (DRY_RUN)` without modifying any filesystem blocks. +6. If `--force` IS provided: + - Automatically executes `restore.SafeRestoreEngine.create_safety_snapshot()` (`pre_restore_`). + - Confirms safety snapshot written and verified on disk. + - Restores non-excluded configuration files from `data/etc/` into live `/etc/`. + - Preserves original file permissions and ownership. + - Logs completion and exits `0`. + +### C. `diff` Command Call Stack (Live Host vs Snapshot) +1. `cli.main()` parses arguments (`diff `). +2. `manifest.read_manifest(snapshot_id)` reads snapshot package list and file index. +3. `inspector.inspect_packages()` queries live package manager. +4. `diff.DiffEngine.diff_with_live()`: + - Computes package deltas (installed, removed, upgraded). + - Computes file deltas (modified, added, deleted). +5. Pretty-prints colorized unified diff to stdout. --- ## 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_profiles.py`: Verifies profile resolution (`quick`, `system`, `full`), custom profile merging, and validation. +- `test_inspector.py`: Verifies mock output parsing of `lsblk`, `ip route`, `dpkg-query`, `rpm -qa`, `passwd`, and `sysctl`. - `test_archiver.py`: - - Verifies round-trip archiving and extraction of test directory tree. + - Verifies round-trip archiving and extraction of test directory tree with strict `0600` permissions. - Verifies corruption detection when archive bytes are tampered with. + - Verifies `--sanitize` redacts `/etc/shadow` and SSH host keys. - 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. +- `test_restore.py`: + - Verifies `--dry-run` produces detailed change plan without modifying destination files. + - Verifies `--force` creates automatic pre-restore safety snapshot before touching files. + - Verifies runtime sockets, FIFOs, and `/etc/resolv.conf` are skipped during restore. +- `test_diff.py`: Verifies diffing live system against snapshot, and diffing two snapshots. +- `test_retention.py`: Verifies `--keep-last`, `--keep-daily`, `--keep-weekly` retention calculations. +- `test_transport.py`: Verifies mock SFTP, rsync, and local copy push operations. --- ## 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. +1. **Live system restore risks on `/etc`:** + - *Risk:* Overwriting active daemon configuration or network configuration can drop SSH connections or lock users out. + - *Mitigation:* The Safe Restore Engine strictly enforces dry-run by default, requires explicit `--force`, automatically creates an unalterable pre-restore safety snapshot before touching any live file, and filters out network-sensitive or runtime symlinks. +2. **Archiving unreadable / special root files:** + - *Risk:* Some files in `/etc` (like `/etc/shadow`, `/etc/sudoers`) have `0600` or `0400` root permissions, and some are active UNIX sockets (`/etc/cups/cupsd.sock`). + - *Mitigation:* Require root (`os.geteuid() == 0`) for backup creation. The archiver actively ignores socket files, FIFOs, and lock files. +3. **Older OS versions without `ip -j` or `lsblk -J` (e.g. stock RHEL 8):** + - *Risk:* Older distributions fail with JSON flags. + - *Mitigation:* Robust tabular/regex fallback parsers parse standard plain-text command output. +4. **Transport failures during `--push` to NAS:** + - *Risk:* Network drop to Synology NAS could interrupt backup. + - *Mitigation:* Local-First Architecture ensures local snapshot is 100% verified and finalized before any network transfer is initiated. A transport failure logs an error but leaves the local snapshot valid. + diff --git a/docs/plans/linux-backuper/04-slices.md b/docs/plans/linux-backuper/04-slices.md index f4fb29b..8702c83 100644 --- a/docs/plans/linux-backuper/04-slices.md +++ b/docs/plans/linux-backuper/04-slices.md @@ -5,48 +5,57 @@ This roadmap defines the implementation order for `linux-backuper` in thin, inde --- ### Slice 1 — Tracer Bullet (Minimal End-to-End Wire) -- **Goal:** Build the minimal working skeleton from CLI invocation to a verified `.tar.gz` file on disk with tests passing. +- **Goal:** Build the minimal working skeleton from CLI invocation to a verified `.tar.gz` file on disk with strict `0600` permissions and unit tests passing. - **Components:** - `bin/linux-backuper` launcher and `linux_backuper/cli.py` (`snapshot` command). - Basic OS detector (`core/detector.py`). - Stub inspector that records hostname, OS, and timestamp. - - Basic archiver that packages a dummy directory into `/tmp/linux-backuper-test/`. - - Unit tests verifying the CLI execution and exit codes. + - Basic archiver using standard library `gzip` + `tarfile` packaging into `/tmp/linux-backuper-test/`. + - Enforced `0600` archive permissions. + - Unit tests verifying CLI execution, exit codes, and archive structure. - **Verification:** `python3 -m unittest tests/test_cli.py` passes 100%. --- -### Slice 2 — Comprehensive Host State Inspector +### Slice 2 — Comprehensive Host State Inspector (Deep Telemetry) - **Goal:** Implement full system introspection adapters for all 5 target distribution families. - **Components:** - - `managers/base.py`, `managers/rpm.py`, `managers/dpkg.py`, `managers/pacman.py`. - - Storage inspector: partitions, filesystems (`df`), block devices (`lsblk`), LVM (`pvs`/`vgs`/`lvs`). - - Network inspector: interfaces (`ip a`), routing table (`ip r`), DNS resolvers (`/etc/resolv.conf`). - - Hardware & Kernel: `lscpu`/`uname`, memory info, `sysctl -a`. + - Multi-distro package managers: `managers/base.py`, `managers/rpm.py`, `managers/dpkg.py`, `managers/pacman.py`. + - User & Group accounts: `/etc/passwd`, `/etc/group`, `/etc/subuid`, `/etc/subgid`. + - Storage inspector: partitions, filesystems (`df -hT`), block devices (`lsblk -J` + fallback), LVM (`pvs`/`vgs`/`lvs`). + - Network inspector: interfaces (`ip -j a`), routing table (`ip -j r`), DNS resolvers (`/etc/resolv.conf`). + - Hardware & Kernel: `lscpu`/`uname`, memory info, `sysctl -a`, `/proc/cmdline`, `lsmod`. - **Verification:** Unit tests verifying parser output against captured sample fixtures from Debian 12, Ubuntu 22.04, AlmaLinux 9, and Arch Linux. --- -### Slice 3 — Configuration Archiver & Manifest Generator -- **Goal:** Safely bundle configuration trees with cryptographic integrity. +### Slice 3 — Profile System, Configuration Archiver & Manifest Generator +- **Goal:** Safely bundle configuration trees with cryptographic integrity and profile selection. - **Components:** - - `core/archiver.py`: recursive collection of `/etc/` with permission preservation. + - `core/profiles.py`: built-in profiles (`quick` default, `system`, `full`) and custom profile loading from `/etc/linux-backuper.json`. + - `core/archiver.py`: recursive collection of paths per profile, exclusion of runtime sockets/FIFOs/locks, strict `0600` file modes, optional `--no-compression` (plain `.tar`), diagnostic sanitization (`--sanitize`). - `core/manifest.py`: generates `manifest.json` with metadata, statistics, and SHA-256 hashes. - - Atomic write protection: write to `.tmp` file first, compute hash, and atomically rename to final `.tar.gz`. - - Concurrency lock (`core/lock.py`) using non-blocking `fcntl.flock`. -- **Verification:** Test creating a snapshot of a sample directory, verify checksum computation, and verify flock prevents double execution. + - Atomic write protection: write to `.tmp` file first, compute hash, and atomically rename to final `backup__.tar.gz`. + - Concurrency lock (`core/lock.py`) using non-blocking `fcntl.flock` on `/var/run/linux-backuper.pid`. +- **Verification:** Test creating snapshots with all 3 profiles, verify checksum computation, and verify flock prevents double execution. --- -### Slice 4 — Snapshot Management (List, Show, Diff, Verify, Extract) -- **Goal:** Provide operators with complete visibility into saved snapshots. +### Slice 4 — Snapshot Management, Live Diff & Safe Restore Engine +- **Goal:** Complete operator visibility, live system diffing, selective file recovery, and guardrailed full restoration. - **Components:** - - `linux-backuper list`: tabular overview of local archives. + - `linux-backuper list`: tabular overview of local archives with sizes and status. - `linux-backuper show `: pretty-print host metadata, storage, network, and package stats. - `linux-backuper verify `: recalculate SHA-256 and confirm archive integrity. - - `linux-backuper diff `: compare packages (added/removed/upgraded) and configuration file changes. - - `linux-backuper extract --file --out `: extract a single file without full unpack. -- **Verification:** Integration tests comparing two simulated snapshots and validating exact diff output. + - `linux-backuper diff `: live system diff comparing current host packages and `/etc/` against snapshot. + - `linux-backuper diff `: compare differences between two snapshot archives. + - `linux-backuper extract --file --out `: selective single-file extraction without full unpack. + - `linux-backuper restore `: + - Default `--dry-run` displaying diff change plan and exit code `5`. + - Mandatory `--force` required for live mutation. + - Automatic `pre_restore_` safety snapshot captured before any file mutation. + - Strict exclusion filter skipping sockets, FIFOs, and dynamic mounts (`/etc/resolv.conf`, `/etc/mtab`). +- **Verification:** Unit and integration tests covering live diffing, selective extract, dry-run enforcement, automatic safety snapshot creation, and rollback verification. --- @@ -55,17 +64,18 @@ This roadmap defines the implementation order for `linux-backuper` in thin, inde - **Components:** - `core/retention.py`: time-bucket pruning algorithms (`--keep-last N`, `--keep-daily D`, `--keep-weekly W`). - Prune CLI sub-command: `linux-backuper prune` with `--dry-run` support. - - Automatic post-snapshot prune hook when configured in `/etc/linux-backuper.json`. + - Automatic post-snapshot prune hook when configured in profile or config. - **Verification:** Unit tests with a set of 15 synthetic snapshot dates confirming correct retention calculations. --- -### Slice 6 — Remote Transport Sync (SFTP / rsync / NFS) -- **Goal:** Offload snapshots to remote network storage (e.g. Synology NAS). +### Slice 6 — Remote Transport Sync (Local-First Model) +- **Goal:** Offload snapshots to remote network storage (e.g. Synology NAS) after local commitment. - **Components:** - - Transport abstraction (`core/transport.py`): support for local folder, SCP/SFTP, and rsync. - - Safe error handling: ensure local copy remains intact if remote transfer fails. -- **Verification:** Tests verifying mock transport calls and exit status handling. + - Transport abstraction (`core/transport.py`): support for local folder / NFS / SMB mount, SFTP (via `paramiko`), and `rsync`. + - Local-first guarantee: local snapshot is verified before initiating transfer; network errors do not corrupt local archive. + - Remote retention pruning engine. +- **Verification:** Tests verifying mock transport calls, remote retention execution, and network error handling. --- @@ -81,14 +91,15 @@ This roadmap defines the implementation order for `linux-backuper` in thin, inde ### Slice 8 — Full Documentation, Man Page, CLI Help, Shell Tab Completion & Gitea Actions CI/CD Workflow - **Goal:** Production-ready release automation, complete documentation triad, man page, and native Bash/Zsh tab completion. - **Components:** - - `docs/user-guide.md`: Comprehensive operator scenarios, routine backups, inspection, diffing, and single-file extracts. + - `docs/user-guide.md`: Comprehensive operator scenarios, routine backups, inspection, diffing, single-file extracts, and safe restore workflows. - `docs/admin-guide.md`: Automation via systemd timer/cron, `/etc/logrotate.d/` rule, monitoring JSON integration, and remote SFTP/NFS retention. - `docs/developer-guide.md`: Internal architecture, extending package/storage managers, and testing runbook. - `man/linux-backuper.8`: Full UNIX Section 8 man page (`man 8 linux-backuper`). - - Shell Tab Completion: Native Bash (`completions/bash/linux-backuper`) and Zsh (`completions/zsh/_linux-backuper`) scripts supporting subcommands, flags, and dynamic snapshot ID completion. + - Shell Tab Completion: Native Bash (`completions/bash/linux-backuper`) and Zsh (`completions/zsh/_linux-backuper`) scripts supporting subcommands, flags, profiles, and dynamic snapshot ID completion. - `linux-backuper completion [bash|zsh]` generator sub-command. - Interactive CLI Help: Complete `-h` and `--help` for root and all sub-commands with usage examples. - Packaging integration: Install completion scripts to `/usr/share/bash-completion/completions/` and `/usr/share/zsh/site-functions/`. - `.gitea/workflows/release.yml`: Gitea Actions pipeline targeting `runs-on: fedora`, running tests, building `.rpm`/`.deb`, publishing to Gitea Package Registry and Release assets. - **Verification:** Unit tests verifying `linux-backuper -h`, sub-command `--help`, shell completion scripts generation (`linux-backuper completion bash` / `zsh`), and man page syntax verification with `man -l man/linux-backuper.8`. +