docs(plans): align linux-backuper gates with grill-me architectural decisions
This commit is contained in:
1 parent
1c4ce51ae6
commit
c1603542af
5 files changed
+354
-136
No files matched your search
@@ -6,13 +6,13 @@
|
|||||||
- Gate 4 — Slice Plan: in progress
|
- Gate 4 — Slice Plan: in progress
|
||||||
|
|
||||||
## Slices
|
## Slices
|
||||||
- [ ] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + tar.gz snapshot + tests)
|
- [ ] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests)
|
||||||
- [ ] Slice 2 — comprehensive host state inspector (hardware, LVM/storage, network, packages, sysctl)
|
- [ ] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages)
|
||||||
- [ ] Slice 3 — configuration archiver (`/etc/`, boot, custom paths) with atomic write & SHA256 manifest
|
- [ ] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
|
||||||
- [ ] Slice 4 — snapshot management (list, verify, diff, selective extract, JSON output)
|
- [ ] 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`, automated cleanup)
|
- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
|
||||||
- [ ] Slice 6 — remote destination engine (SFTP / SCP / rsync / NFS export sync)
|
- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
|
||||||
- [ ] Slice 7 — packaging & distribution (.deb, .rpm, .tar.gz standalone)
|
- [ ] 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
|
- [ ] 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
|
## 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.
|
- 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).
|
- Target Python runtime: Python >= 3.6 (RHEL 8 compatibility).
|
||||||
- Dependencies: Zero mandatory external dependencies (pure Python standard library). Optional `cryptography` for encrypted snapshots.
|
- 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 <id> --file <path> --out <dest>`) and live system diff (`diff <id>` and `diff <id1> <id2>`).
|
||||||
|
- Full restore (`restore <id>`): 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):
|
- Shell Tab Completion Standard (Bash & Zsh):
|
||||||
- Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `prune`).
|
- Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `restore`, `prune`, `completion`).
|
||||||
- Dynamic completion: `show`, `diff`, `verify`, `extract` auto-complete snapshot IDs from `/var/backups/linux-backuper/`.
|
- 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/`).
|
- 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):
|
- Documentation Standard (Mandatory parity with linux-updater):
|
||||||
- User Guide: `docs/user-guide.md` (comprehensive operator workflow and snapshot recovery).
|
- 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).
|
- 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).
|
- Developer Guide: `docs/developer-guide.md` (internal architecture, adapter extension, test suite).
|
||||||
- System Manual Page: `man/linux-backuper.8` (complete Section 8 man page).
|
- 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.
|
- Rich CLI Help: Complete `-h` and `--help` for root and all sub-commands with syntax, argument descriptions, and realistic examples.
|
||||||
|
|||||||
@@ -36,57 +36,61 @@ System administrators and homelab operators frequently perform system updates, p
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
# 1. Capture a full system snapshot with auto-generated name:
|
# 1. Capture a full system snapshot with auto-generated name:
|
||||||
|
# 1. Capture snapshot with default profile (quick):
|
||||||
# sudo linux-backuper snapshot
|
# 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] Pre-flight checks passed: 42.1 GB free in /var/backups/linux-backuper
|
||||||
[INFO] Collecting host metadata (hardware, storage, network, packages)...
|
[INFO] Collecting host metadata (hardware, storage, network, packages, kernel, users)...
|
||||||
[INFO] Archiving /etc directory...
|
[INFO] Archiving /etc directory with standard gzip compression...
|
||||||
[INFO] Generating SHA-256 integrity manifest...
|
[INFO] Generating SHA-256 integrity manifest...
|
||||||
[SUCCESS] Snapshot created: /var/backups/linux-backuper/backup_enterprise_20261002_211500.tar.gz (14.2 MB)
|
[SUCCESS] Snapshot created: /var/backups/linux-backuper/backup_enterprise_20261002_211500.tar.gz (14.2 MB)
|
||||||
|
|
||||||
# 2. List available snapshots on the system:
|
# 2. Capture full disaster-recovery snapshot and push to NAS:
|
||||||
# linux-backuper list
|
# 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)
|
||||||
| SNAPSHOT ID | DATE & TIME | SIZE | PACKAGES | STATUS |
|
[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)...
|
||||||
| backup_enterprise_20261002_211500 | 2026-10-02 21:15:00 | 14.2 MB | 642 pkgs | VERIFIED |
|
[SUCCESS] Remote sync complete with remote retention applied.
|
||||||
| backup_enterprise_20261001_040000 | 2026-10-01 04:00:00 | 14.1 MB | 638 pkgs | VERIFIED |
|
|
||||||
+-----------------------------------+---------------------+---------+----------+----------+
|
|
||||||
|
|
||||||
# 3. Inspect details of a snapshot:
|
# 3. Compare current live system with a previous snapshot:
|
||||||
# linux-backuper show backup_enterprise_20261002_211500
|
# linux-backuper diff backup_enterprise_20261001_040000
|
||||||
Hostname: enterprise.wired.intra
|
Packages changed on live host:
|
||||||
OS: AlmaLinux 9.4 (Seafoam Ocelot) - Kernel 5.14.0-427.el9
|
+ nginx 1.24.0-1.el9 (installed since snapshot)
|
||||||
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)
|
|
||||||
~ openssl 3.0.7-27.el9 -> 3.0.7-28.el9 (upgraded)
|
~ 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/nginx.conf
|
||||||
+ /etc/nginx/conf.d/default.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
|
# sudo linux-backuper extract backup_enterprise_20261001_040000 --file /etc/nginx/nginx.conf --out /tmp/nginx.conf.old
|
||||||
|
|
||||||
# 6. Verify archive integrity:
|
# 5. Full restore with mandatory safety guardrails:
|
||||||
# linux-backuper verify backup_enterprise_20261002_211500
|
# sudo linux-backuper restore backup_enterprise_20261001_040000
|
||||||
[SUCCESS] Archive checksum and all 1,420 manifest file hashes MATCH.
|
[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 restore backup_enterprise_20261001_040000 --force
|
||||||
# sudo linux-backuper prune --keep-last 7
|
[INFO] Safety: Creating automatic pre-restore safety snapshot 'pre_restore_20261002_220500'...
|
||||||
[INFO] Pruning snapshots: 2 snapshots removed, 7 snapshots retained.
|
[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
|
## 5. Scope & Constraints
|
||||||
- **Zero Third-Party Pip Packages:** Must work on default Python 3.6+ without external packages.
|
- **Zero Third-Party Pip Packages:** Pure Python standard library (Python >= 3.6). Built-in `gzip` and `tarfile` module. Optional `--no-compression` flag.
|
||||||
- **Root Protection:** Creating snapshots, pruning, and extracting to system directories requires root; reading/listing/verifying can be done unprivileged if permissions permit.
|
- **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:**
|
- **FHS Compliance:**
|
||||||
- Executable: `/usr/bin/linux-backuper`
|
- Executable: `/usr/bin/linux-backuper`
|
||||||
- Library: `/usr/lib/linux-backuper/`
|
- Library: `/usr/lib/linux-backuper/`
|
||||||
|
|||||||
@@ -2,22 +2,24 @@
|
|||||||
|
|
||||||
## 1. System Fit & Architecture Diagram
|
## 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) │
|
│ CLI Interface (cli) │
|
||||||
│ snapshot, list, show, │
|
│ snapshot, list, show, │
|
||||||
│ diff, verify, extract │
|
│ diff, verify, extract, │
|
||||||
|
│ restore, prune │
|
||||||
└─────────────┬─────────────┘
|
└─────────────┬─────────────┘
|
||||||
│
|
│
|
||||||
┌──────────────┴──────────────┐
|
┌──────────────┴──────────────┐
|
||||||
▼ ▼
|
▼ ▼
|
||||||
┌─────────────────────┐ ┌─────────────────────┐
|
┌─────────────────────┐ ┌─────────────────────┐
|
||||||
│ Host Inspector │ │ Snapshot Engine │
|
│ Host Inspector │ │ Profile & Archiver │
|
||||||
│ - Hardware │ │ - Tar / Gzip / Zstd│
|
│ - Hardware & Kernel│ │ - quick/system/full│
|
||||||
|
│ - Users & Groups │ │ - Stdlib Gzip/Tar │
|
||||||
│ - Storage / LVM │ │ - SHA-256 Manifest │
|
│ - Storage / LVM │ │ - SHA-256 Manifest │
|
||||||
│ - Network / Routes │ │ - Atomic write │
|
│ - Network / Routes │ │ - Atomic write 0600│
|
||||||
│ - Package Manager │ └──────────┬──────────┘
|
│ - Package Manager │ └──────────┬──────────┘
|
||||||
│ - System Services │ │
|
│ - 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/) │
|
│ - Local (/var/backups/) │
|
||||||
│ - Retention Engine │
|
│ - 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:
|
`linux-backuper` provides 3 built-in profiles and supports custom user profiles in `/etc/linux-backuper.json`:
|
||||||
1. `manifest.json`: Machine-readable metadata document.
|
|
||||||
2. `meta/`: Raw system command dumps for low-level human/script recovery.
|
1. **`quick` (DEFAULT):**
|
||||||
- `storage.json` & `storage.txt`
|
- **Scope:** `/etc/` directory tree, user/group accounts, full hardware/kernel/storage/network/package metadata.
|
||||||
- `network.json` & `network.txt`
|
- **Performance:** Runs in < 5 seconds, produces < 20 MB archive.
|
||||||
- `packages.txt`
|
- **Use Case:** Daily automated configuration snapshots, pre-package-upgrade checks.
|
||||||
- `hardware.txt`
|
2. **`system`:**
|
||||||
- `sysctl.txt`
|
- **Scope:** All of `quick` plus `/boot/`, loaded kernel modules (`lsmod`), `/proc/cmdline`, active systemd unit configurations.
|
||||||
3. `data/`: The actual archived filesystem hierarchies (e.g. `data/etc/`, `data/boot/`).
|
- **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
|
### `manifest.json` Data Contract
|
||||||
```json
|
```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",
|
"snapshot_id": "backup_enterprise_20261002_211500",
|
||||||
"created_at": "2026-10-02T21:15:00+00:00",
|
"created_at": "2026-10-02T21:15:00+00:00",
|
||||||
"hostname": "enterprise.wired.intra",
|
"hostname": "enterprise.wired.intra",
|
||||||
|
"profile": "quick",
|
||||||
|
"compression": "gzip",
|
||||||
"os": {
|
"os": {
|
||||||
"distro_id": "almalinux",
|
"distro_id": "almalinux",
|
||||||
"distro_name": "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:
|
1. **Standard Library Gzip (Default):**
|
||||||
|
- Pure Python `gzip` and `tarfile` module ensures 100% self-contained operation without external binaries (`gzip`, `tar`, `zstd`).
|
||||||
| Family | Distros | Package Listing Command | Network Detection | Storage / LVM Detection |
|
- Optional `--no-compression` flag creates plain `.tar` archives for ultra-low CPU environments.
|
||||||
|---|---|---|---|---|
|
2. **Access Control & File Modes:**
|
||||||
| **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` |
|
- Base backup directory: `/var/backups/linux-backuper/` mode `0700` root:root.
|
||||||
| **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 |
|
- Archive files: mode `0600` root:root.
|
||||||
| **Arch** | Arch Linux, EndeavourOS | `pacman -Q` | `ip -j a`, `ip -j r`, `networkctl` | `lsblk -J`, LVM tools if present |
|
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`).
|
||||||
*Note:* If JSON output flags (`-j`, `--json`) are unsupported on older utility versions, fallback regex parsers process the plain-text command output.
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 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 <id> --file /etc/nginx/nginx.conf --out /tmp/nginx.conf.old
|
||||||
|
```
|
||||||
|
2. **Live System Diff (`diff`):**
|
||||||
|
- `linux-backuper diff <id>`: Compares the live `/etc/` and installed packages against the snapshot, reporting modified, added, and missing files and packages.
|
||||||
|
- `linux-backuper diff <id1> <id2>`: Compares two snapshots against each other.
|
||||||
|
3. **Full Live Restore (`restore <id>`):**
|
||||||
|
- **Default Dry-Run:** Running `linux-backuper restore <id>` 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_<timestamp>`) 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:
|
Retention is computed using standard time-bucket pruning:
|
||||||
- `--keep-last N`: Always preserve the $N$ most recent snapshots regardless of date.
|
- `--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-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.
|
- `--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 |
|
| 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. |
|
| `1` | `GENERIC_ERROR` | Runtime failure, missing dependencies, or write error. |
|
||||||
| `2` | `PREFLIGHT_FAIL` | Insufficient disk space (< 1 GB) or target directory unwriteable. |
|
| `2` | `PREFLIGHT_FAIL` | Insufficient disk space (< 1 GB) or target directory unwriteable. |
|
||||||
| `3` | `CORRUPTED` | Snapshot checksum or archive validation failed. |
|
| `3` | `CORRUPTED` | Snapshot checksum or archive validation failed. |
|
||||||
| `4` | `PERM_DENIED` | Mutating operation requested without root privileges. |
|
| `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.
|
When `--json` is specified, all commands output structured JSON to stdout, directing diagnostics and progress logs to stderr.
|
||||||
|
|
||||||
@@ -16,12 +16,15 @@ linux-backuper/
|
|||||||
│ │ ├── __init__.py
|
│ │ ├── __init__.py
|
||||||
│ │ ├── detector.py # OS/distro detector (reuses linux-updater pattern)
|
│ │ ├── detector.py # OS/distro detector (reuses linux-updater pattern)
|
||||||
│ │ ├── health.py # Pre-flight disk space and permission checks
|
│ │ ├── health.py # Pre-flight disk space and permission checks
|
||||||
│ │ ├── lock.py # Concurrency singleton flock
|
│ │ ├── lock.py # Concurrency singleton flock (/var/run/linux-backuper.pid)
|
||||||
│ │ ├── inspector.py # System inspector (hardware, storage, network)
|
│ │ ├── profiles.py # Profile manager (quick, system, full, custom)
|
||||||
│ │ ├── archiver.py # Tar/gzip/zstd packaging & atomic write
|
│ │ ├── inspector.py # System inspector (hardware, storage, network, kernel, users)
|
||||||
│ │ ├── manifest.py # Manifest generator, reader & validator
|
│ │ ├── 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
|
│ │ ├── 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
|
│ │ └── completion.py # Shell completion generator & dynamic snapshot resolver
|
||||||
│ └── managers/
|
│ └── managers/
|
||||||
│ ├── __init__.py
|
│ ├── __init__.py
|
||||||
@@ -51,10 +54,13 @@ linux-backuper/
|
|||||||
│ ├── __init__.py
|
│ ├── __init__.py
|
||||||
│ ├── test_cli.py
|
│ ├── test_cli.py
|
||||||
│ ├── test_detector.py
|
│ ├── test_detector.py
|
||||||
|
│ ├── test_profiles.py
|
||||||
│ ├── test_inspector.py
|
│ ├── test_inspector.py
|
||||||
│ ├── test_archiver.py
|
│ ├── test_archiver.py
|
||||||
│ ├── test_retention.py
|
|
||||||
│ ├── test_diff.py
|
│ ├── test_diff.py
|
||||||
|
│ ├── test_restore.py
|
||||||
|
│ ├── test_retention.py
|
||||||
|
│ ├── test_transport.py
|
||||||
│ └── containers/
|
│ └── containers/
|
||||||
│ └── run_tests.sh # Podman test runner
|
│ └── run_tests.sh # Podman test runner
|
||||||
└── .gitea/
|
└── .gitea/
|
||||||
@@ -79,6 +85,19 @@ class OsInfo:
|
|||||||
kernel: str
|
kernel: str
|
||||||
arch: 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
|
@dataclass
|
||||||
class StorageState:
|
class StorageState:
|
||||||
block_devices: List[Dict[str, Any]]
|
block_devices: List[Dict[str, Any]]
|
||||||
@@ -106,6 +125,8 @@ class SnapshotManifest:
|
|||||||
snapshot_id: str
|
snapshot_id: str
|
||||||
created_at: str
|
created_at: str
|
||||||
hostname: str
|
hostname: str
|
||||||
|
profile: str
|
||||||
|
compression: str
|
||||||
os_info: OsInfo
|
os_info: OsInfo
|
||||||
package_manager: str
|
package_manager: str
|
||||||
packages: List[PackageItem]
|
packages: List[PackageItem]
|
||||||
@@ -115,6 +136,29 @@ class SnapshotManifest:
|
|||||||
uncompressed_size: int
|
uncompressed_size: int
|
||||||
compressed_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
|
# core/inspector.py
|
||||||
class SystemInspector:
|
class SystemInspector:
|
||||||
def __init__(self, distro_id: str): ...
|
def __init__(self, distro_id: str): ...
|
||||||
@@ -122,21 +166,44 @@ class SystemInspector:
|
|||||||
def inspect_storage(self) -> StorageState: ...
|
def inspect_storage(self) -> StorageState: ...
|
||||||
def inspect_network(self) -> NetworkState: ...
|
def inspect_network(self) -> NetworkState: ...
|
||||||
def inspect_packages(self) -> List[PackageItem]: ...
|
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
|
# core/archiver.py
|
||||||
class SnapshotArchiver:
|
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(
|
def create_snapshot(
|
||||||
self,
|
self,
|
||||||
snapshot_id: str,
|
snapshot_id: str,
|
||||||
paths_to_include: List[str],
|
profile: ProfileConfig,
|
||||||
metadata_files: Dict[str, str],
|
meta_files_dir: str,
|
||||||
manifest: SnapshotManifest,
|
manifest: SnapshotManifest,
|
||||||
) -> str: ...
|
) -> str: ...
|
||||||
def verify_integrity(self, archive_path: str) -> bool: ...
|
def verify_integrity(self, archive_path: str) -> bool: ...
|
||||||
def extract_file(self, archive_path: str, member_rel_path: str, destination_path: str) -> None: ...
|
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
|
# core/retention.py
|
||||||
class RetentionEngine:
|
class RetentionEngine:
|
||||||
def __init__(self, keep_last: int, keep_daily: int = 0, keep_weekly: int = 0): ...
|
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`).
|
### A. `snapshot` Command Call Stack
|
||||||
2. `config.load_config()` loads `/etc/linux-backuper.json` and merges CLI overrides.
|
1. `cli.main()` parses CLI flags (`snapshot --profile quick --push nas`).
|
||||||
3. `health.check_preflight(target_dir)` verifies free space >= 1024 MB and directory write permissions.
|
2. `config.load_config()` loads `/etc/linux-backuper.json`.
|
||||||
4. `lock.acquire_lock()` creates advisory flock `/var/run/linux-backuper.pid`.
|
3. `health.check_preflight(target_dir)` verifies root user (`os.geteuid() == 0`) and free disk space >= 1024 MB.
|
||||||
5. `detector.detect_distro()` returns distribution (`almalinux`, `debian`, etc.).
|
4. `lock.acquire_lock()` creates non-blocking flock on `/var/run/linux-backuper.pid`.
|
||||||
6. `inspector.SystemInspector` queries storage (`lsblk`), network (`ip`), and packages (`rpm`/`dpkg`).
|
5. `profiles.ProfileManager` loads requested profile (e.g. `quick`).
|
||||||
7. `archiver.SnapshotArchiver` collects `/etc/`, dumps metadata into tempdir, generates `manifest.json`, packs into `atomic_tmp.tar.gz`.
|
6. `detector.detect_distro()` detects active Linux distribution.
|
||||||
8. Checksum computed and verified; atomically renames `atomic_tmp.tar.gz` to final `backup_<host>_<timestamp>.tar.gz`.
|
7. `inspector.SystemInspector` gathers telemetry (users, kernel, hardware, storage, network, packages) into temporary `meta/` dir.
|
||||||
9. `retention.RetentionEngine` inspects target directory and prunes archives exceeding policy.
|
8. `archiver.SnapshotArchiver` collects paths specified in profile, sets strict `0600` archive permissions, writes `atomic.tmp.tar.gz`.
|
||||||
10. `lock.release_lock()` unlinks PID lock file and exits `0`.
|
9. Manifest computed with SHA-256 and written inside archive; atomic rename to `backup_<host>_<timestamp>.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 <snapshot_id> [--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_<timestamp>`).
|
||||||
|
- 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 <snapshot_id>`).
|
||||||
|
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
|
## 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_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`:
|
- `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 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.
|
- Verifies atomic write rollback on simulated out-of-space or permission errors.
|
||||||
- `test_retention.py`:
|
- `test_restore.py`:
|
||||||
- Verifies `--keep-last 5` on a pool of 10 simulated snapshots retains the 5 newest.
|
- Verifies `--dry-run` produces detailed change plan without modifying destination files.
|
||||||
- Verifies `--keep-daily 7` retains exactly one snapshot per day.
|
- Verifies `--force` creates automatic pre-restore safety snapshot before touching files.
|
||||||
- `test_diff.py`: Verifies diffing two manifests correctly reports added, removed, and upgraded packages and 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)
|
## 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.
|
1. **Live system restore risks on `/etc`:**
|
||||||
- *Mitigation:* Explicit root permission check (`os.geteuid() == 0`) before starting `snapshot`. Handle unreadable sockets/pipes gracefully (exclude `/etc/**` socket files).
|
- *Risk:* Overwriting active daemon configuration or network configuration can drop SSH connections or lock users out.
|
||||||
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:* 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.
|
||||||
- *Mitigation:* Provide robust tabular/regex parsers for plain-text `lsblk` and `ip a`/`ip r` as primary or fallback drivers.
|
2. **Archiving unreadable / special root files:**
|
||||||
3. **Large files or log spam in `/etc`:** Some applications place caches or logs in `/etc`.
|
- *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:* Enforce a per-file size warning (e.g. alert if single file in `/etc` > 10 MB) and skip zero-byte lock files.
|
- *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.
|
||||||
|
|
||||||
@@ -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)
|
### 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:**
|
- **Components:**
|
||||||
- `bin/linux-backuper` launcher and `linux_backuper/cli.py` (`snapshot` command).
|
- `bin/linux-backuper` launcher and `linux_backuper/cli.py` (`snapshot` command).
|
||||||
- Basic OS detector (`core/detector.py`).
|
- Basic OS detector (`core/detector.py`).
|
||||||
- Stub inspector that records hostname, OS, and timestamp.
|
- Stub inspector that records hostname, OS, and timestamp.
|
||||||
- Basic archiver that packages a dummy directory into `/tmp/linux-backuper-test/`.
|
- Basic archiver using standard library `gzip` + `tarfile` packaging into `/tmp/linux-backuper-test/`.
|
||||||
- Unit tests verifying the CLI execution and exit codes.
|
- Enforced `0600` archive permissions.
|
||||||
|
- Unit tests verifying CLI execution, exit codes, and archive structure.
|
||||||
- **Verification:** `python3 -m unittest tests/test_cli.py` passes 100%.
|
- **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.
|
- **Goal:** Implement full system introspection adapters for all 5 target distribution families.
|
||||||
- **Components:**
|
- **Components:**
|
||||||
- `managers/base.py`, `managers/rpm.py`, `managers/dpkg.py`, `managers/pacman.py`.
|
- Multi-distro package managers: `managers/base.py`, `managers/rpm.py`, `managers/dpkg.py`, `managers/pacman.py`.
|
||||||
- Storage inspector: partitions, filesystems (`df`), block devices (`lsblk`), LVM (`pvs`/`vgs`/`lvs`).
|
- User & Group accounts: `/etc/passwd`, `/etc/group`, `/etc/subuid`, `/etc/subgid`.
|
||||||
- Network inspector: interfaces (`ip a`), routing table (`ip r`), DNS resolvers (`/etc/resolv.conf`).
|
- Storage inspector: partitions, filesystems (`df -hT`), block devices (`lsblk -J` + fallback), LVM (`pvs`/`vgs`/`lvs`).
|
||||||
- Hardware & Kernel: `lscpu`/`uname`, memory info, `sysctl -a`.
|
- 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.
|
- **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
|
### Slice 3 — Profile System, Configuration Archiver & Manifest Generator
|
||||||
- **Goal:** Safely bundle configuration trees with cryptographic integrity.
|
- **Goal:** Safely bundle configuration trees with cryptographic integrity and profile selection.
|
||||||
- **Components:**
|
- **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.
|
- `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`.
|
- Atomic write protection: write to `.tmp` file first, compute hash, and atomically rename to final `backup_<host>_<timestamp>.tar.gz`.
|
||||||
- Concurrency lock (`core/lock.py`) using non-blocking `fcntl.flock`.
|
- Concurrency lock (`core/lock.py`) using non-blocking `fcntl.flock` on `/var/run/linux-backuper.pid`.
|
||||||
- **Verification:** Test creating a snapshot of a sample directory, verify checksum computation, and verify flock prevents double execution.
|
- **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)
|
### Slice 4 — Snapshot Management, Live Diff & Safe Restore Engine
|
||||||
- **Goal:** Provide operators with complete visibility into saved snapshots.
|
- **Goal:** Complete operator visibility, live system diffing, selective file recovery, and guardrailed full restoration.
|
||||||
- **Components:**
|
- **Components:**
|
||||||
- `linux-backuper list`: tabular overview of local archives.
|
- `linux-backuper list`: tabular overview of local archives with sizes and status.
|
||||||
- `linux-backuper show <id>`: pretty-print host metadata, storage, network, and package stats.
|
- `linux-backuper show <id>`: pretty-print host metadata, storage, network, and package stats.
|
||||||
- `linux-backuper verify <id>`: recalculate SHA-256 and confirm archive integrity.
|
- `linux-backuper verify <id>`: recalculate SHA-256 and confirm archive integrity.
|
||||||
- `linux-backuper diff <id1> <id2>`: compare packages (added/removed/upgraded) and configuration file changes.
|
- `linux-backuper diff <id>`: live system diff comparing current host packages and `/etc/` against snapshot.
|
||||||
- `linux-backuper extract <id> --file <path> --out <dest>`: extract a single file without full unpack.
|
- `linux-backuper diff <id1> <id2>`: compare differences between two snapshot archives.
|
||||||
- **Verification:** Integration tests comparing two simulated snapshots and validating exact diff output.
|
- `linux-backuper extract <id> --file <path> --out <dest>`: selective single-file extraction without full unpack.
|
||||||
|
- `linux-backuper restore <id>`:
|
||||||
|
- Default `--dry-run` displaying diff change plan and exit code `5`.
|
||||||
|
- Mandatory `--force` required for live mutation.
|
||||||
|
- Automatic `pre_restore_<timestamp>` 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:**
|
- **Components:**
|
||||||
- `core/retention.py`: time-bucket pruning algorithms (`--keep-last N`, `--keep-daily D`, `--keep-weekly W`).
|
- `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.
|
- 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.
|
- **Verification:** Unit tests with a set of 15 synthetic snapshot dates confirming correct retention calculations.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### Slice 6 — Remote Transport Sync (SFTP / rsync / NFS)
|
### Slice 6 — Remote Transport Sync (Local-First Model)
|
||||||
- **Goal:** Offload snapshots to remote network storage (e.g. Synology NAS).
|
- **Goal:** Offload snapshots to remote network storage (e.g. Synology NAS) after local commitment.
|
||||||
- **Components:**
|
- **Components:**
|
||||||
- Transport abstraction (`core/transport.py`): support for local folder, SCP/SFTP, and rsync.
|
- Transport abstraction (`core/transport.py`): support for local folder / NFS / SMB mount, SFTP (via `paramiko`), and `rsync`.
|
||||||
- Safe error handling: ensure local copy remains intact if remote transfer fails.
|
- Local-first guarantee: local snapshot is verified before initiating transfer; network errors do not corrupt local archive.
|
||||||
- **Verification:** Tests verifying mock transport calls and exit status handling.
|
- 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
|
### 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.
|
- **Goal:** Production-ready release automation, complete documentation triad, man page, and native Bash/Zsh tab completion.
|
||||||
- **Components:**
|
- **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/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.
|
- `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`).
|
- `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.
|
- `linux-backuper completion [bash|zsh]` generator sub-command.
|
||||||
- Interactive CLI Help: Complete `-h` and `--help` for root and all sub-commands with usage examples.
|
- 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/`.
|
- 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.
|
- `.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`.
|
- **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`.
|
||||||
|
|
||||||
|
|
||||||
Reference in new issue
Block a user