Files
linux-backuper/docs/plans/linux-backuper/02-architecture.md
T

12 KiB

Gate 2 — Architecture: linux-backuper

1. System Fit & Architecture Diagram

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,   │
                          │  restore, prune           │
                          └─────────────┬─────────────┘
                                        │
                         ┌──────────────┴──────────────┐
                         ▼                             ▼
              ┌─────────────────────┐       ┌─────────────────────┐
              │  Host Inspector     │       │  Profile & Archiver │
              │  - Hardware & Kernel│       │  - quick/system/full│
              │  - Users & Groups   │       │  - Stdlib Gzip/Tar  │
              │  - Storage / LVM    │       │  - SHA-256 Manifest │
              │  - Network / Routes │       │  - Atomic write 0600│
              │  - Package Manager  │       └──────────┬──────────┘
              │  - System Services  │                  │
              └──────────┬──────────┘                  │
                         │                             │
                         └──────────────┬──────────────┘
                                        ▼
                         ┌─────────────────────────────┐
                         │   Safe Restore & Diff       │
                         │   - Live system diff        │
                         │   - Selective extraction    │
                         │   - Pre-restore snapshot    │
                         │   - Exclusion guardrails    │
                         └──────────────┬──────────────┘
                                        ▼
                         ┌─────────────────────────────┐
                         │      Storage & Sync         │
                         │  - Local (/var/backups/)    │
                         │  - Retention Engine         │
                         │  - Local-first --push sync  │
                         │    (SFTP / rsync / NFS)     │
                         └─────────────────────────────┘

2. Profiles Architecture

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 single .tar.gz archive with strict 0600 permissions (readable/writeable only by root) inside /var/backups/linux-backuper/ (0700 directory). No loose companion files are generated.

To guarantee instant performance of linux-backuper list, manifest.json is always written as the very first entry in the archive. Reading metadata takes < 10ms by reading only the first tar member from the gzip stream without decompressing the rest of the archive.

backup_enterprise_20261002_211500.tar.gz
├── manifest.json                  # FIRST member: machine-readable metadata & file SHA-256 table
├── 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

{
  "schema_version": "1.0",
  "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",
    "version_id": "9.4",
    "kernel": "5.14.0-427.el9",
    "arch": "x86_64"
  },
  "package_manager": "dnf",
  "package_count": 642,
  "included_paths": ["/etc"],
  "stats": {
    "uncompressed_bytes": 48291040,
    "compressed_bytes": 14881024,
    "file_count": 1420
  },
  "files_sha256": {
    "meta/packages.txt": "a823f...",
    "data/etc/nginx/nginx.conf": "b712c..."
  }
}

Integrity Verification: linux-backuper verify <id> validates gzip stream CRC integrity and recalculates the SHA-256 for all indexed files against manifest.json. Local catalog index (/var/lib/linux-backuper/catalog.json) caches the post-write archive SHA-256 for quick reference.


5. Compression & Security Architecture

  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).

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:
      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 (exit code 5).
    • 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.
    • Atomic File Replacement: Files are written to a temporary sibling file in the same directory (.tmp.<file>) with target permissions and atomically swapped via os.replace to prevent half-written configuration files from being read by running daemons.
    • SELinux Context Restoration: On systems where SELinux is active (detected via /sys/fs/selinux), the restore engine automatically executes restorecon -R across all restored paths to guarantee correct SELinux context and prevent daemon permission denials.
    • Strict Exclusion & Symlink Guardrails: Automatically skips dynamic sockets (*.sock), named pipes (FIFOs), temporary lock files (*.lock, *.pid), and dynamic mount links (/etc/resolv.conf, /etc/mtab, /run/). Symlinks pointing outside the restore root are strictly blocked to protect against Zip Slip / Directory Traversal attacks.

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]):
    • Zero Mandatory Pip Dependencies: Primary transport utilizes system CLI tools (rsync, ssh/scp/sftp via subprocess) or direct file copy to mounted NFS/SMB shares using the Python standard library.
    • Optional Paramiko Backend: If the paramiko library is installed on the system, an internal pure-Python SFTP backend can be utilized.
    • 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 companion manifests.


9. Exit Codes & JSON Output

Exit Code Name Meaning
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.