From 6f23f14b765781b38de9fc3c3bdafd1da5734939 Mon Sep 17 00:00:00 2001 From: Mateusz Stomski Date: Fri, 9 Oct 2026 20:22:51 +0200 Subject: [PATCH] feat(docs): implement slice 8 documentation triad, man page, completions and Gitea Actions CI/CD --- .gitea/workflows/release.yml | 144 ++++++++++++ completions/bash/linux-backuper | 158 +++++++++++++ completions/zsh/_linux-backuper | 135 +++++++++++ docs/admin-guide.md | 212 +++++++++++++++++ docs/developer-guide.md | 153 ++++++++++++ docs/plans/linux-backuper/00-status.md | 2 +- docs/user-guide.md | 177 ++++++++++++++ linux_backuper/cli.py | 17 ++ linux_backuper/core/completions.py | 309 +++++++++++++++++++++++++ man/linux-backuper.8 | 201 ++++++++++++++++ packaging/build_packages.py | 119 ++++++++++ packaging/install.sh | 24 +- tests/test_completions.py | 59 +++++ tests/test_packaging.py | 30 ++- 14 files changed, 1730 insertions(+), 10 deletions(-) create mode 100644 .gitea/workflows/release.yml create mode 100644 completions/bash/linux-backuper create mode 100644 completions/zsh/_linux-backuper create mode 100644 docs/admin-guide.md create mode 100644 docs/developer-guide.md create mode 100644 docs/user-guide.md create mode 100644 linux_backuper/core/completions.py create mode 100644 man/linux-backuper.8 create mode 100644 tests/test_completions.py diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml new file mode 100644 index 0000000..cf5f01e --- /dev/null +++ b/.gitea/workflows/release.yml @@ -0,0 +1,144 @@ +name: Build and Publish Release + +on: + push: + tags: + - 'v*' + workflow_dispatch: + inputs: + version: + description: 'Release version (e.g. 1.0.0)' + required: false + default: '' + +jobs: + test-and-release: + runs-on: fedora + steps: + - name: Checkout Source Code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Setup Build Dependencies + run: | + echo "[INFO] Verifying build dependencies..." + python3 --version + if ! command -v rpmbuild >/dev/null 2>&1; then + echo "[INFO] Installing rpm-build..." + sudo dnf install -y rpm-build + fi + + - name: Run Quality Gate Test Suite + run: | + echo "[INFO] Executing comprehensive test suite..." + python3 -m unittest discover tests -v + + - name: Build Distribution Packages + id: build_pkgs + run: | + echo "[INFO] Building .tar.gz, .deb, and .rpm distribution packages..." + rm -rf dist + python3 packaging/build_packages.py --all --out-dir dist + + TAR_FILE=$(find dist -maxdepth 1 -name "*.tar.gz" | head -n 1) + DEB_FILE=$(find dist -maxdepth 1 -name "*.deb" | head -n 1) + RPM_FILE=$(find dist -maxdepth 1 -name "*.rpm" | head -n 1) + + echo "TAR_FILE=$TAR_FILE" >> $GITHUB_ENV + echo "DEB_FILE=$DEB_FILE" >> $GITHUB_ENV + echo "RPM_FILE=$RPM_FILE" >> $GITHUB_ENV + + echo "[INFO] Generated packages:" + ls -lh dist/ + + - name: Publish to Gitea Package Registry + env: + PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }} + run: | + echo "[INFO] Uploading packages to Gitea Package Registry..." + OWNER="${{ github.repository_owner }}" + REPO="${{ github.event.repository.name }}" + SERVER="${{ github.server_url }}" + + # Upload RPM + if [[ -f "$RPM_FILE" ]]; then + echo "[INFO] Publishing RPM to registry..." + curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \ + --upload-file "$RPM_FILE" \ + "${SERVER}/api/packages/${OWNER}/rpm/upload" || echo "[WARNING] RPM upload returned non-zero (may already exist)" + + # Link package to repository + curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \ + "${SERVER}/api/v1/packages/${OWNER}/rpm/linux-backuper/-/link/${REPO}" || true + fi + + # Upload Debian + if [[ -f "$DEB_FILE" ]]; then + echo "[INFO] Publishing Debian to registry..." + curl -k -s -f -X PUT -u "${{ github.actor }}:${PKG_TOKEN}" \ + --upload-file "$DEB_FILE" \ + "${SERVER}/api/packages/${OWNER}/debian/pool/stable/main/upload" || echo "[WARNING] DEB upload returned non-zero (may already exist)" + + # Link package to repository + curl -k -s -X POST -H "Authorization: token ${PKG_TOKEN}" \ + "${SERVER}/api/v1/packages/${OWNER}/debian/linux-backuper/-/link/${REPO}" || true + fi + + - name: Publish Gitea Release & Upload Assets + if: startsWith(github.ref, 'refs/tags/v') + env: + GITEA_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }} + run: | + TAG_NAME="${GITHUB_REF#refs/tags/}" + OWNER="${{ github.repository_owner }}" + REPO="${{ github.event.repository.name }}" + API_URL="${{ github.server_url }}/api/v1/repos/${OWNER}/${REPO}" + + echo "[INFO] Ensuring Gitea Release exists for tag ${TAG_NAME}..." + REL_INFO=$(curl -k -s -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}/releases/tags/${TAG_NAME}") + REL_ID=$(echo "$REL_INFO" | grep -o '"id":[0-9]*' | head -n 1 | cut -d: -f2) + + if [[ -z "$REL_ID" || "$REL_ID" == "null" ]]; then + echo "[INFO] Creating release for tag ${TAG_NAME}..." + CREATE_PAYLOAD=$(cat </dev/null + fi +} + +_linux_backuper() { + local cur prev words cword + _init_completion || return + + local commands="snapshot list show diff extract restore prune push verify completion" + local profiles="quick system full dr" + + if [[ $cword -eq 1 ]]; then + COMPREPLY=( $(compgen -W "$commands -h --help -v --version" -- "$cur") ) + return 0 + fi + + local cmd="${words[1]}" + + case "$cmd" in + snapshot) + case "$prev" in + --profile) + COMPREPLY=( $(compgen -W "$profiles" -- "$cur") ) + return 0 + ;; + --compression) + COMPREPLY=( $(compgen -W "gzip none" -- "$cur") ) + return 0 + ;; + --target-dir|--config|--pid-path|--ssh-key) + _filedir + return 0 + ;; + --paths) + _filedir + return 0 + ;; + esac + local snap_opts="--profile --target-dir --paths --compression --no-compression --sanitize --config --pid-path --keep-last --keep-daily --keep-weekly --keep-monthly --push --ssh-key --remote-keep-last --remote-keep-daily --remote-keep-weekly --remote-keep-monthly --json --verbose -h --help" + COMPREPLY=( $(compgen -W "$snap_opts" -- "$cur") ) + return 0 + ;; + + list) + case "$prev" in + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "--target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + show|verify) + case "$prev" in + show|verify) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --packages --files --target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + diff) + case "$prev" in + --target-dir|--target-root) + _filedir -d + return 0 + ;; + diff) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --target-dir --target-root --unified -u --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + extract) + case "$prev" in + extract) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --file) + # File inside snapshot + return 0 + ;; + --out|--target-dir) + _filedir + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --file --out --target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + restore) + case "$prev" in + restore) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --target-root|--target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --dry-run --force --target-root --include-fstab --target-dir --pid-path --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + prune) + case "$prev" in + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "--keep-last --keep-daily --keep-weekly --keep-monthly --dry-run --force --target-dir --pid-path --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + push) + case "$prev" in + push) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --ssh-key|--target-dir|--config) + _filedir + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --target --ssh-key --remote-keep-last --remote-keep-daily --remote-keep-weekly --remote-keep-monthly --target-dir --config --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + completion) + COMPREPLY=( $(compgen -W "bash zsh" -- "$cur") ) + return 0 + ;; + esac +} + +complete -F _linux_backuper linux-backuper diff --git a/completions/zsh/_linux-backuper b/completions/zsh/_linux-backuper new file mode 100644 index 0000000..9d29ace --- /dev/null +++ b/completions/zsh/_linux-backuper @@ -0,0 +1,135 @@ +#compdef linux-backuper +# zsh completion for linux-backuper +# Generated automatically by linux-backuper completion zsh + +_linux_backuper_snapshots() { + local backup_dir="/var/backups/linux-backuper" + if [[ -d "$backup_dir" ]]; then + local -a snaps + snaps=(${(@f)$(find "$backup_dir" -maxdepth 1 -name "backup_*.tar.gz" -exec basename {} .tar.gz \; 2>/dev/null)}) + _describe -t snapshots 'snapshot' snaps + fi +} + +_linux_backuper() { + local -a commands + commands=( + 'snapshot:Capture a new system state snapshot' + 'list:List existing local snapshots' + 'show:Display details and metadata of a snapshot' + 'diff:Compare live system against snapshot, or two snapshots' + 'extract:Selectively extract a single file from a snapshot' + 'restore:Restore system configuration from a snapshot' + 'prune:Prune old snapshots based on retention policies' + 'push:Push an existing snapshot to remote storage' + 'verify:Verify snapshot cryptographic integrity' + 'completion:Generate shell autocompletion script' + ) + + _arguments -C \ + '(-v --version)'{-v,--version}'[Show version]' \ + '(-h --help)'{-h,--help}'[Show help message]' \ + '--json[Output machine-readable JSON to stdout]' \ + '--verbose[Enable detailed diagnostic logging]' \ + '1:command:->command' \ + '*::arg:->args' + + case "$state" in + command) + _describe -t commands 'linux-backuper commands' commands + ;; + args) + case "$words[1]" in + snapshot) + _arguments \ + '--profile[Backup profile]:profile:(quick system full dr)' \ + '--target-dir[Destination directory]:directory:_files -/' \ + '--paths[Directories or files to include]:file:_files' \ + '--compression[Compression algorithm]:compression:(gzip none)' \ + '--no-compression[Store plain uncompressed tar archive]' \ + '--sanitize[Redact secrets and private keys for diagnostic export]' \ + '--config[Path to configuration file]:file:_files' \ + '--pid-path[Path to lockfile]:file:_files' \ + '--keep-last[Keep N most recent snapshots]:count:' \ + '--keep-daily[Keep latest snapshot for D days]:days:' \ + '--keep-weekly[Keep latest snapshot for W weeks]:weeks:' \ + '--keep-monthly[Keep latest snapshot for M months]:months:' \ + '--push[Transfer snapshot to remote destination]:target:' \ + '--ssh-key[SSH private key]:key:_files' \ + '--remote-keep-last[Remote retention keep last]:count:' \ + '--remote-keep-daily[Remote retention keep daily]:days:' \ + '--remote-keep-weekly[Remote retention keep weekly]:weeks:' \ + '--remote-keep-monthly[Remote retention keep monthly]:months:' + ;; + list) + _arguments \ + '--target-dir[Directory to scan]:directory:_files -/' + ;; + show) + _arguments \ + '1:snapshot:_linux_backuper_snapshots' \ + '--packages[List all recorded installed packages]' \ + '--files[List all archived file paths]' \ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + diff) + _arguments \ + '1:snapshot 1:_linux_backuper_snapshots' \ + '2:snapshot 2 (optional):_linux_backuper_snapshots' \ + '--target-dir[Directory containing snapshots]:directory:_files -/' \ + '--target-root[Filesystem root to compare against]:directory:_files -/' \ + '(-u --unified)'{-u,--unified}'[Display unified diff for modified text files]' + ;; + extract) + _arguments \ + '1:snapshot:_linux_backuper_snapshots' \ + '--file[File path inside snapshot to extract]:path:' \ + '--out[Destination file or directory]:output:_files' \ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + restore) + _arguments \ + '1:snapshot:_linux_backuper_snapshots' \ + '--dry-run[Display execution plan without modifying filesystem]' \ + '--force[Execute live restoration]' \ + '--target-root[Target root directory]:directory:_files -/' \ + '--include-fstab[Allow restoring /etc/fstab]' \ + '--target-dir[Directory containing snapshot]:directory:_files -/' \ + '--pid-path[Path to lockfile]:file:_files' + ;; + prune) + _arguments \ + '--keep-last[Keep N most recent snapshots]:count:' \ + '--keep-daily[Keep D daily snapshots]:days:' \ + '--keep-weekly[Keep W weekly snapshots]:weeks:' \ + '--keep-monthly[Keep M monthly snapshots]:months:' \ + '--dry-run[Simulate pruning plan]' \ + '--force[Confirm deletion of pruned snapshots]' \ + '--target-dir[Directory containing snapshots]:directory:_files -/' + ;; + push) + _arguments \ + '1:snapshot:_linux_backuper_snapshots' \ + '--target[Remote destination (e.g. user@host:/path or alias)]:target:' \ + '--ssh-key[SSH private key]:key:_files' \ + '--remote-keep-last[Remote retention keep last]:count:' \ + '--remote-keep-daily[Remote retention keep daily]:days:' \ + '--remote-keep-weekly[Remote retention keep weekly]:weeks:' \ + '--remote-keep-monthly[Remote retention keep monthly]:months:' \ + '--target-dir[Directory containing snapshot]:directory:_files -/' \ + '--config[Config path]:file:_files' + ;; + verify) + _arguments \ + '1:snapshot:_linux_backuper_snapshots' \ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + completion) + _arguments '1:shell:(bash zsh)' + ;; + esac + ;; + esac +} + +_linux_backuper "$@" diff --git a/docs/admin-guide.md b/docs/admin-guide.md new file mode 100644 index 0000000..9a5f266 --- /dev/null +++ b/docs/admin-guide.md @@ -0,0 +1,212 @@ +# linux-backuper Administrator Guide + +This guide is designed for system administrators and DevOps engineers deploying, automating, and operating **linux-backuper** across production Linux fleets. + +--- + +## 1. System Architecture & Security Model + +`linux-backuper` is built according to enterprise hardening standards: + +1. **Zero External Dependencies:** Implemented in pure Python >= 3.6 standard library. Runs out of the box on minimal RHEL 8/9, AlmaLinux, Rocky Linux, CentOS Stream, Fedora, Debian 11/12/13, Ubuntu 20.04/22.04/24.04, and Arch Linux. +2. **Strict Root Boundary & Permissions:** + - Storage directory `/var/backups/linux-backuper/` is created with mode `0700` (`drwx------ root:root`). + - Every generated snapshot archive is created with mode `0600` (`-rw------- root:root`). + - Diagnostic sanitization mode (`--sanitize`) redacts shadow password hashes and private keys before export. +3. **Flock Concurrency Lock:** + - Prevents race conditions and overlapping runs via `/var/run/linux-backuper.pid` using non-blocking kernel `fcntl.flock`. +4. **Local-First Safety:** + - When transferring snapshots to remote storage (e.g. Synology NAS), the local snapshot is 100% written, verified, and sealed before any network transfer begins. Network timeouts or SSH disconnections never corrupt local backups. + +--- + +## 2. Configuration (`/etc/linux-backuper/config.json`) + +`linux-backuper` can be configured via `/etc/linux-backuper/config.json`: + +```json +{ + "default_profile": "quick", + "storage": { + "local_dir": "/var/backups/linux-backuper", + "compression": "gzip" + }, + "retention": { + "keep_last": 7, + "keep_daily": 14, + "keep_weekly": 4, + "keep_monthly": 6 + }, + "remotes": { + "nas_backup": { + "target": "lain@nas.wired.intra:/volume1/backups/linux-servers", + "ssh_key": "/root/.ssh/id_ed25519", + "remote_keep_last": 30, + "remote_keep_monthly": 12 + }, + "local_nfs": { + "target": "/mnt/nfs_backups", + "remote_keep_last": 14 + } + }, + "profiles": { + "database_host": { + "description": "PostgreSQL & system configuration", + "included_paths": [ + "/etc", + "/var/lib/pgsql/data/postgresql.conf", + "/var/lib/pgsql/data/pg_hba.conf" + ], + "exclude_patterns": [ + "*.log", + "/etc/mtab" + ] + } + } +} +``` + +--- + +## 3. Automation with Systemd (Recommended) + +To schedule automated daily configuration backups, configure a systemd service and timer. + +### Service: `/etc/systemd/system/linux-backuper.service` +```ini +[Unit] +Description=Daily Linux System Configuration Snapshot +Documentation=man:linux-backuper(8) +After=network.target + +[Service] +Type=oneshot +User=root +ExecStart=/usr/bin/linux-backuper snapshot --profile quick --keep-last 7 --keep-daily 14 --push nas_backup +StandardOutput=journal +StandardError=journal +Nice=10 +IOSchedulingClass=idle +``` + +### Timer: `/etc/systemd/system/linux-backuper.timer` +```ini +[Unit] +Description=Run Daily Linux System Snapshot at 02:00 AM +Documentation=man:linux-backuper(8) + +[Timer] +OnCalendar=*-*-* 02:00:00 +RandomizedDelaySec=600 +Persistent=true + +[Install] +WantedBy=timers.target +``` + +### Enable & Verify Timer: +```bash +sudo systemctl daemon-reload +sudo systemctl enable --now linux-backuper.timer +sudo systemctl list-timers linux-backuper.timer +``` + +--- + +## 4. Retention & Lifecycle Pruning + +To prevent backup storage from filling the root partition, `linux-backuper` implements a time-bucket pruning algorithm: + +- `--keep-last N`: Keeps the $N$ most recent snapshots regardless of date. +- `--keep-daily D`: Retains the latest snapshot for each of the last $D$ days. +- `--keep-weekly W`: Retains the latest snapshot for each of the last $W$ calendar weeks. +- `--keep-monthly M`: Retains the latest snapshot for each of the last $M$ calendar months. + +### Running Prune Manually +```bash +# 1. Preview which snapshots would be deleted (dry-run): +sudo linux-backuper prune --keep-last 7 --keep-daily 14 --keep-weekly 4 --dry-run + +# 2. Confirm and execute live deletion: +sudo linux-backuper prune --keep-last 7 --keep-daily 14 --keep-weekly 4 --force +``` + +### Automatic Post-Snapshot Prune Hook +You can also supply retention flags directly during snapshot creation: +```bash +sudo linux-backuper snapshot --profile quick --keep-last 7 --keep-daily 14 +``` + +--- + +## 5. Remote Storage & NAS Synchronization + +### Supported Transport Types +1. **Local / NFS / SMB Mounts:** e.g. `/mnt/synology/backups` (uses fast atomic copy and SHA-256 validation). +2. **SSH / SCP / Rsync:** e.g. `lain@192.168.5.51:/tmp/remote_backups`. Rsync is used for fast delta transfer with automatic SCP fallback if `rsync` is unavailable on minimal hosts (e.g. Debian minimal). + +### Dual-Layer Independent Retention +Remote retention is configured independently from local retention: +```bash +# Keep 7 snapshots locally on the server, but keep 30 on the remote NAS: +sudo linux-backuper snapshot --profile quick \ + --keep-last 7 \ + --push lain@nas.wired.intra:/volume1/backups \ + --remote-keep-last 30 +``` + +--- + +## 6. Monitoring, Alerting & JSON Telemetry + +Every command supports `--json` for monitoring agents (e.g. Zabbix, Wazuh SIEM, Nagios, Prometheus node-exporter textfile collector). + +### Example: Checking Snapshot Status with jq +```bash +# Verify the latest snapshot +linux-backuper show $(linux-backuper list --json | jq -r '.[-1].id') --json | jq '{ + id: .id, + created_at: .created_at, + os: .os.pretty_name, + packages: .os.packages_count, + archive_bytes: .archive_bytes, + sha256: .sha256 +}' +``` + +### Generating Prometheus Node-Exporter Metrics +Create a daily cron job script `/etc/cron.daily/linux-backuper-metrics`: +```bash +#!/bin/bash +METRIC_FILE="/var/lib/node_exporter/textfile_collector/linux_backuper.prom" + +LAST_STATUS=$(linux-backuper list --json 2>/dev/null | jq -r '.[-1]') +if [[ -n "$LAST_STATUS" && "$LAST_STATUS" != "null" ]]; then + SIZE=$(echo "$LAST_STATUS" | jq '.archive_size_bytes') + FILES=$(echo "$LAST_STATUS" | jq '.file_count') + cat < "$METRIC_FILE" +# HELP linux_backuper_last_archive_bytes Size in bytes of latest configuration snapshot +# TYPE linux_backuper_last_archive_bytes gauge +linux_backuper_last_archive_bytes $SIZE +# HELP linux_backuper_last_files_count Number of files stored in latest snapshot +# TYPE linux_backuper_last_files_count gauge +linux_backuper_last_files_count $FILES +# HELP linux_backuper_success Whether backup completed successfully +# TYPE linux_backuper_success gauge +linux_backuper_success 1 +EOF +else + echo "linux_backuper_success 0" > "$METRIC_FILE" +fi +``` + +--- + +## 7. Troubleshooting & Disaster Recovery Runbook + +| Symptom | Root Cause | Solution | +| :--- | :--- | :--- | +| `[ERROR] Another linux-backuper process is currently running` | Stale or active lockfile in `/var/run/linux-backuper.pid`. | Check `ps aux \| grep linux-backuper`. If no process is running, verify flock or remove stale PID file. | +| `[WARNING] Local snapshot succeeded, but remote push failed` | SSH authentication failure, network disconnect, or insufficient remote permissions. | Local snapshot is safe and intact. Inspect SSH key with `--ssh-key /path/to/key` and target directory permissions on remote server. | +| `[ERROR] Exit code 5 on restore` | Expected behaviour during dry-run simulation. | Inspect diff plan. If valid, rerun with `--force` to perform live restoration. | +| SELinux permission denials post-restore | Restored files had wrong file contexts. | `linux-backuper` runs `restorecon -R` automatically on RHEL/Alma/Fedora. If restoring manually via tar, run `restorecon -Rv /etc/`. | diff --git a/docs/developer-guide.md b/docs/developer-guide.md new file mode 100644 index 0000000..1b6162e --- /dev/null +++ b/docs/developer-guide.md @@ -0,0 +1,153 @@ +# linux-backuper Developer Guide + +This guide details the internal architecture, design principles, extension interfaces, and testing workflows for contributing to **linux-backuper**. + +--- + +## 1. Design Principles & Hard Constraints + +1. **Zero External Pip Dependencies:** + - The core runtime must remain strictly reliant on the Python >= 3.6 standard library (`os`, `sys`, `json`, `tarfile`, `gzip`, `hashlib`, `socket`, `subprocess`, `fcntl`, `shutil`, `tempfile`). + - Third-party packages (such as `requests`, `pyyaml`, or `paramiko`) are strictly forbidden in the core execution path. +2. **Local-First Reliability:** + - Snapshots must always be finalized and verified locally before initiating any external network action. +3. **Deterministic & Atomic Restorations:** + - File mutations during restoration must be staged in temporary files and moved into place via atomic `os.replace`. +4. **Cross-Distro Parity:** + - All features must behave consistently across RHEL/AlmaLinux/Fedora (RPM), Debian/Ubuntu (DEB), and Arch Linux (Pacman). + +--- + +## 2. Codebase Layout + +``` +linux-backuper/ +├── bin/ +│ └── linux-backuper # Executable launcher script +├── linux_backuper/ +│ ├── __init__.py # Package metadata and __version__ +│ ├── __main__.py # Direct module execution entrypoint +│ ├── cli.py # Argparse CLI builder and dispatchers +│ ├── models.py # Dataclasses / models (SnapshotManifest, etc.) +│ ├── core/ +│ │ ├── archiver.py # Tar/gzip engine with front-loaded manifest +│ │ ├── completions.py # Bash and Zsh completion generators +│ │ ├── constants.py # Exit codes, default paths, permissions +│ │ ├── detector.py # Linux distribution and OS detection +│ │ ├── diff.py # File & package diff engine (unified diffs) +│ │ ├── inspector.py # System state & telemetry collectors +│ │ ├── lock.py # Non-blocking fcntl.flock instance locking +│ │ ├── profiles.py # Profile configuration resolution +│ │ ├── restore.py # Atomic restore engine with safety snapshots +│ │ ├── retention.py # Time-bucket pruning algorithm +│ │ └── transport.py # Local-first transport (Local, SSH, Rsync) +│ └── managers/ +│ ├── base.py # Abstract PackageManagerBase +│ ├── dpkg.py # Debian / Ubuntu dpkg-query adapter +│ ├── pacman.py # Arch Linux pacman adapter +│ └── rpm.py # RHEL / Alma / Fedora rpm adapter +├── packaging/ +│ ├── build_packages.py # Pure Python .deb, .rpm and .tar.gz builder +│ └── install.sh # Generic tarball installer +├── man/ +│ └── linux-backuper.8 # UNIX Section 8 manual page +├── completions/ +│ ├── bash/linux-backuper # Bash autocompletion script +│ └── zsh/_linux-backuper # Zsh autocompletion script +├── tests/ # Unittest suite (52+ unit tests) +└── docs/ # Documentation triad and guides +``` + +--- + +## 3. Core Engine Mechanics + +### Front-Loaded Archive Manifest (`core/archiver.py`) +To prevent `linux-backuper list` from having to decompress gigabytes of archive data to read metadata, `SnapshotArchiver` guarantees that `manifest.json` is always written as the **first member** of the tar stream. +When reading: +```python +with tarfile.open(archive_path, "r:gz") as tar: + first_member = tar.next() + if first_member and first_member.name == "manifest.json": + manifest_data = json.load(tar.extractfile(first_member)) +``` +This enables sub-millisecond metadata lookups across large sets of archives. + +### Time-Bucket Pruning Algorithm (`core/retention.py`) +`RetentionEngine.calculate_prune_plan()` classifies snapshots into calendar buckets: +1. **Latest Count (`keep_last`):** Evaluated strictly on creation timestamp order. +2. **Daily Buckets (`keep_daily`):** Grouped by `YYYY-MM-DD`. Keeps the most recent snapshot per day across $D$ distinct days. +3. **Weekly Buckets (`keep_weekly`):** Grouped by ISO calendar week `YYYY-Www`. Keeps the most recent snapshot per week across $W$ distinct weeks. +4. **Monthly Buckets (`keep_monthly`):** Grouped by `YYYY-MM`. Keeps the most recent snapshot per month across $M$ distinct months. +Snapshots not matching any active retention rule are slated for pruning. + +--- + +## 4. Extension Interfaces + +### Implementing a New Package Manager (`managers/base.py`) +To support a new packaging format (e.g. `apk` for Alpine Linux): +1. Subclass `PackageManagerBase`: +```python +from linux_backuper.managers.base import PackageManagerBase + +class ApkPackageManager(PackageManagerBase): + def is_available(self) -> bool: + return shutil.which("apk") is not None + + def list_packages(self) -> List[Dict[str, str]]: + # Run 'apk info -v' or parse /lib/apk/db/installed + ... +``` +2. Register the manager in `core/detector.py`. + +### Implementing a New Transport Target (`core/transport.py`) +To add a new transport backend (e.g. S3 or WebDAV): +1. Subclass `TransportBase`: +```python +from linux_backuper.core.transport import TransportBase + +class S3Transport(TransportBase): + def push(self, archive_path: str) -> Dict[str, Any]: + # Transfer archive and verify remote hash + ... + + def prune_remote(self, retention: RetentionEngine) -> List[str]: + # List remote objects and prune expired snapshots + ... +``` +2. Add target scheme recognition to `TransportFactory.get_transport()`. + +--- + +## 5. Development & Testing Workflow + +### Running Unit Tests Locally +All tests use Python's built-in `unittest` framework: +```bash +python3 -m unittest discover tests -v +``` + +### Environment Overrides for Non-Root Testing +When running tests on developer workstations (macOS or Linux non-root), use environment flags: +```bash +# Allow running without root euid == 0: +export LINUX_BACKUPER_ALLOW_NON_ROOT=1 + +# Relocate PID lockfile to temp directory: +export LINUX_BACKUPER_PID_PATH=/tmp/linux_backuper.pid +``` + +### Building Packages +To build all packages (`.deb`, `.rpm`, `.tar.gz`) locally: +```bash +python3 packaging/build_packages.py --all --out-dir dist +``` +Verify the generated artifacts: +```bash +# Check Debian package +ar -t dist/linux-backuper_1.0.0_all.deb + +# Check binary tarball +tar -ztvf dist/linux-backuper-1.0.0.tar.gz +``` diff --git a/docs/plans/linux-backuper/00-status.md b/docs/plans/linux-backuper/00-status.md index fe901c9..402ba59 100644 --- a/docs/plans/linux-backuper/00-status.md +++ b/docs/plans/linux-backuper/00-status.md @@ -13,7 +13,7 @@ - [x] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote) - [x] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention) - [x] 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 +- [x] 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 - Project: Enterprise-grade Linux system snapshot and configuration backup utility. diff --git a/docs/user-guide.md b/docs/user-guide.md new file mode 100644 index 0000000..29301dd --- /dev/null +++ b/docs/user-guide.md @@ -0,0 +1,177 @@ +# linux-backuper User Guide + +Welcome to the **linux-backuper** user guide. This document explains how operators and system users can create snapshots, inspect system telemetry, compare configuration drift, extract individual files, and safely restore system states. + +--- + +## 1. Overview & Key Concepts + +`linux-backuper` is an enterprise Linux system snapshot and configuration backup utility written in pure Python >= 3.6 with zero mandatory external pip dependencies. + +### Key Highlights: +- **Fast Single-Archive Format:** Snapshots are single `.tar.gz` archives with a pre-indexed `manifest.json` at the front of the archive stream, allowing instant listing and metadata inspection without unpacking. +- **Root-Only Security:** Every snapshot is created with strict `0600` permissions (root read/write only) in `/var/backups/linux-backuper/`. +- **Safe Restoration Engine:** Full restores require `--force`, run a dry-run plan by default (exit code 5), automatically create a `pre_restore_*` safety snapshot before touching any file, use atomic file replacement, and protect dynamic system mounts and sockets. + +--- + +## 2. Creating Snapshots + +Snapshot creation is performed using `linux-backuper snapshot`: + +```bash +sudo linux-backuper snapshot [OPTIONS] +``` + +### Backup Profiles +`linux-backuper` comes with pre-configured backup profiles: + +| Profile | Target Paths | Use Case | +| :--- | :--- | :--- | +| `quick` *(default)* | `/etc/` | Routine configuration backups, daily cronjobs, fast pre-upgrade snapshots. | +| `system` | `/etc/`, `/boot/`, kernel state | Pre-kernel upgrade, bootloader changes, driver updates. | +| `full` / `dr` | `/etc/`, `/boot/`, high-value `/var/` (crontabs, systemd state, NetworkManager) | Full disaster recovery baseline before major OS migration. | + +#### Examples: +```bash +# Quick configuration snapshot (default) +sudo linux-backuper snapshot --profile quick + +# System boot and configuration snapshot +sudo linux-backuper snapshot --profile system + +# Snapshot specific custom paths +sudo linux-backuper snapshot --paths /etc/nginx /etc/ssl /var/www/config + +# Store without gzip compression (plain tar) +sudo linux-backuper snapshot --no-compression + +# Redact passwords, shadow hashes, and SSL private keys (for sharing diagnostics) +sudo linux-backuper snapshot --sanitize +``` + +--- + +## 3. Listing & Inspecting Snapshots + +### Listing Local Snapshots +```bash +linux-backuper list +``` +Outputs a formatted table showing snapshot IDs, creation dates, profiles, file counts, and archive sizes. Add `--json` for machine-readable output: +```bash +linux-backuper list --json +``` + +### Inspecting Snapshot Details +To inspect metadata, host hardware, kernel parameters, network interfaces, and storage mounts recorded at snapshot time: +```bash +linux-backuper show backup_host_20261009_120000 +``` + +To list all package versions installed on the system when the snapshot was taken: +```bash +linux-backuper show backup_host_20261009_120000 --packages +``` + +To list every file archived in the snapshot: +```bash +linux-backuper show backup_host_20261009_120000 --files +``` + +--- + +## 4. Comparing System State (Diff Engine) + +The diff engine detects configuration drift and package updates. + +### Live System Diff +Compare the current running operating system against a past snapshot: +```bash +sudo linux-backuper diff backup_host_20261009_120000 +``` +This checks: +- Packages added, removed, or upgraded since the snapshot. +- Files added, modified, or deleted in configuration trees. + +To inspect line-by-line differences in modified configuration files, use `-u` or `--unified`: +```bash +sudo linux-backuper diff backup_host_20261009_120000 --unified +``` + +### Snapshot-to-Snapshot Diff +Compare two distinct snapshots to see what changed between maintenance windows: +```bash +linux-backuper diff backup_host_20261001_100000 backup_host_20261009_120000 --unified +``` + +--- + +## 5. Selective Single-File Extraction + +If an accidental edit broke a single configuration file (e.g. `/etc/ssh/sshd_config`), you do not need to restore the whole system. Extract the specific file directly: + +```bash +sudo linux-backuper extract backup_host_20261009_120000 \ + --file /etc/ssh/sshd_config \ + --out /tmp/sshd_config.recovered +``` + +`linux-backuper extract` features strict Zip Slip / Path Traversal protection to ensure files are never extracted outside the requested output target. + +--- + +## 6. Safe System Restoration + +Full restores are protected by multiple safety guardrails: + +### Step 1: Dry-Run Simulation (Default) +Running `restore` without `--force` prints a complete execution plan and exits with status code `5`: +```bash +sudo linux-backuper restore backup_host_20261009_120000 --dry-run +``` +Output summarizes: +- Files to be updated, added, or deleted. +- Volatile sockets, FIFOs, and dynamic mounts skipped automatically (`/etc/resolv.conf`, `/etc/mtab`, `/run/`). + +### Step 2: Live Restoration (`--force`) +When satisfied with the dry-run, execute the restore with `--force`: +```bash +sudo linux-backuper restore backup_host_20261009_120000 --force +``` + +### Safety Guarantees During Live Restore: +1. **Automated Safety Snapshot:** `linux-backuper` immediately captures a full `pre_restore_` snapshot before modifying any system file. If needed, you can roll back instantly. +2. **Atomic File Replacement:** Files are written to temporary staging files (`.linux_backuper_restore.*`) and moved into place via atomic `os.replace` to prevent corrupted configurations if interrupted. +3. **SELinux Auto-Relabeling:** On SELinux-enforcing systems (RHEL, AlmaLinux, CentOS, Fedora), `restorecon -R` is automatically executed on all restored trees to ensure correct security contexts. +4. **Fstab Safety Guard:** Restoring `/etc/fstab` is blocked by default to prevent boot failures. If you specifically intend to restore fstab, provide `--include-fstab`. + +--- + +## 7. Cryptographic Integrity Verification + +To verify that an archive has not been corrupted or tampered with: +```bash +linux-backuper verify backup_host_20261009_120000 +``` +This validates: +- The SHA-256 cryptographic digest against the embedded archive manifest. +- The gzip compression stream integrity. +- The tar entry checksums and header formatting. + +--- + +## 8. Shell Autocompletion + +`linux-backuper` supports full tab completion for Bash and Zsh, including automatic dynamic completion of snapshot IDs: + +```bash +# Enable in current Bash session: +source <(linux-backuper completion bash) + +# Persist system-wide for Bash: +linux-backuper completion bash | sudo tee /usr/share/bash-completion/completions/linux-backuper > /dev/null + +# Persist for Zsh: +linux-backuper completion zsh | sudo tee /usr/share/zsh/site-functions/_linux-backuper > /dev/null +``` diff --git a/linux_backuper/cli.py b/linux_backuper/cli.py index 1bb59ab..f63f6ad 100644 --- a/linux_backuper/cli.py +++ b/linux_backuper/cli.py @@ -784,8 +784,23 @@ def build_parser() -> argparse.ArgumentParser: verify_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to verify") verify_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot") + # Completion command + comp_parser = subparsers.add_parser("completion", help="Generate shell autocompletion script (bash or zsh)", parents=[common_parser]) + comp_parser.add_argument("shell", choices=["bash", "zsh"], help="Target shell (bash or zsh)") + return parser +def handle_completion(args: argparse.Namespace) -> int: + """Generate shell autocompletion script.""" + from linux_backuper.core.completions import generate_completion + try: + script = generate_completion(args.shell) + sys.stdout.write(script) + return EXIT_SUCCESS + except ValueError as e: + sys.stderr.write(f"[ERROR] {e}\n") + return EXIT_GENERIC_ERROR + def main(argv: Optional[List[str]] = None) -> int: """Main CLI entrypoint.""" parser = build_parser() @@ -813,6 +828,8 @@ def main(argv: Optional[List[str]] = None) -> int: return handle_push(args) elif args.subcommand == "verify": return handle_verify(args) + elif args.subcommand == "completion": + return handle_completion(args) return EXIT_SUCCESS diff --git a/linux_backuper/core/completions.py b/linux_backuper/core/completions.py new file mode 100644 index 0000000..c70b896 --- /dev/null +++ b/linux_backuper/core/completions.py @@ -0,0 +1,309 @@ +"""Shell completion script generator for Bash and Zsh.""" + +BASH_COMPLETION = """# bash completion for linux-backuper +# Generated automatically by linux-backuper completion bash + +_linux_backuper_get_snapshots() { + local backup_dir="/var/backups/linux-backuper" + if [[ -d "$backup_dir" ]]; then + find "$backup_dir" -maxdepth 1 -name "backup_*.tar.gz" -exec basename {} .tar.gz \\; 2>/dev/null + fi +} + +_linux_backuper() { + local cur prev words cword + _init_completion || return + + local commands="snapshot list show diff extract restore prune push verify completion" + local profiles="quick system full dr" + + if [[ $cword -eq 1 ]]; then + COMPREPLY=( $(compgen -W "$commands -h --help -v --version" -- "$cur") ) + return 0 + fi + + local cmd="${words[1]}" + + case "$cmd" in + snapshot) + case "$prev" in + --profile) + COMPREPLY=( $(compgen -W "$profiles" -- "$cur") ) + return 0 + ;; + --compression) + COMPREPLY=( $(compgen -W "gzip none" -- "$cur") ) + return 0 + ;; + --target-dir|--config|--pid-path|--ssh-key) + _filedir + return 0 + ;; + --paths) + _filedir + return 0 + ;; + esac + local snap_opts="--profile --target-dir --paths --compression --no-compression --sanitize --config --pid-path --keep-last --keep-daily --keep-weekly --keep-monthly --push --ssh-key --remote-keep-last --remote-keep-daily --remote-keep-weekly --remote-keep-monthly --json --verbose -h --help" + COMPREPLY=( $(compgen -W "$snap_opts" -- "$cur") ) + return 0 + ;; + + list) + case "$prev" in + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "--target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + show|verify) + case "$prev" in + show|verify) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --packages --files --target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + diff) + case "$prev" in + --target-dir|--target-root) + _filedir -d + return 0 + ;; + diff) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --target-dir --target-root --unified -u --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + extract) + case "$prev" in + extract) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --file) + # File inside snapshot + return 0 + ;; + --out|--target-dir) + _filedir + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --file --out --target-dir --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + restore) + case "$prev" in + restore) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --target-root|--target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --dry-run --force --target-root --include-fstab --target-dir --pid-path --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + prune) + case "$prev" in + --target-dir) + _filedir -d + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "--keep-last --keep-daily --keep-weekly --keep-monthly --dry-run --force --target-dir --pid-path --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + push) + case "$prev" in + push) + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots)" -- "$cur") ) + return 0 + ;; + --ssh-key|--target-dir|--config) + _filedir + return 0 + ;; + esac + COMPREPLY=( $(compgen -W "$(_linux_backuper_get_snapshots) --target --ssh-key --remote-keep-last --remote-keep-daily --remote-keep-weekly --remote-keep-monthly --target-dir --config --json --verbose -h --help" -- "$cur") ) + return 0 + ;; + + completion) + COMPREPLY=( $(compgen -W "bash zsh" -- "$cur") ) + return 0 + ;; + esac +} + +complete -F _linux_backuper linux-backuper +""" + +ZSH_COMPLETION = """#compdef linux-backuper +# zsh completion for linux-backuper +# Generated automatically by linux-backuper completion zsh + +_linux_backuper_snapshots() { + local backup_dir="/var/backups/linux-backuper" + if [[ -d "$backup_dir" ]]; then + local -a snaps + snaps=(${(@f)$(find "$backup_dir" -maxdepth 1 -name "backup_*.tar.gz" -exec basename {} .tar.gz \\; 2>/dev/null)}) + _describe -t snapshots 'snapshot' snaps + fi +} + +_linux_backuper() { + local -a commands + commands=( + 'snapshot:Capture a new system state snapshot' + 'list:List existing local snapshots' + 'show:Display details and metadata of a snapshot' + 'diff:Compare live system against snapshot, or two snapshots' + 'extract:Selectively extract a single file from a snapshot' + 'restore:Restore system configuration from a snapshot' + 'prune:Prune old snapshots based on retention policies' + 'push:Push an existing snapshot to remote storage' + 'verify:Verify snapshot cryptographic integrity' + 'completion:Generate shell autocompletion script' + ) + + _arguments -C \\ + '(-v --version)'{-v,--version}'[Show version]' \\ + '(-h --help)'{-h,--help}'[Show help message]' \\ + '--json[Output machine-readable JSON to stdout]' \\ + '--verbose[Enable detailed diagnostic logging]' \\ + '1:command:->command' \\ + '*::arg:->args' + + case "$state" in + command) + _describe -t commands 'linux-backuper commands' commands + ;; + args) + case "$words[1]" in + snapshot) + _arguments \\ + '--profile[Backup profile]:profile:(quick system full dr)' \\ + '--target-dir[Destination directory]:directory:_files -/' \\ + '--paths[Directories or files to include]:file:_files' \\ + '--compression[Compression algorithm]:compression:(gzip none)' \\ + '--no-compression[Store plain uncompressed tar archive]' \\ + '--sanitize[Redact secrets and private keys for diagnostic export]' \\ + '--config[Path to configuration file]:file:_files' \\ + '--pid-path[Path to lockfile]:file:_files' \\ + '--keep-last[Keep N most recent snapshots]:count:' \\ + '--keep-daily[Keep latest snapshot for D days]:days:' \\ + '--keep-weekly[Keep latest snapshot for W weeks]:weeks:' \\ + '--keep-monthly[Keep latest snapshot for M months]:months:' \\ + '--push[Transfer snapshot to remote destination]:target:' \\ + '--ssh-key[SSH private key]:key:_files' \\ + '--remote-keep-last[Remote retention keep last]:count:' \\ + '--remote-keep-daily[Remote retention keep daily]:days:' \\ + '--remote-keep-weekly[Remote retention keep weekly]:weeks:' \\ + '--remote-keep-monthly[Remote retention keep monthly]:months:' + ;; + list) + _arguments \\ + '--target-dir[Directory to scan]:directory:_files -/' + ;; + show) + _arguments \\ + '1:snapshot:_linux_backuper_snapshots' \\ + '--packages[List all recorded installed packages]' \\ + '--files[List all archived file paths]' \\ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + diff) + _arguments \\ + '1:snapshot 1:_linux_backuper_snapshots' \\ + '2:snapshot 2 (optional):_linux_backuper_snapshots' \\ + '--target-dir[Directory containing snapshots]:directory:_files -/' \\ + '--target-root[Filesystem root to compare against]:directory:_files -/' \\ + '(-u --unified)'{-u,--unified}'[Display unified diff for modified text files]' + ;; + extract) + _arguments \\ + '1:snapshot:_linux_backuper_snapshots' \\ + '--file[File path inside snapshot to extract]:path:' \\ + '--out[Destination file or directory]:output:_files' \\ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + restore) + _arguments \\ + '1:snapshot:_linux_backuper_snapshots' \\ + '--dry-run[Display execution plan without modifying filesystem]' \\ + '--force[Execute live restoration]' \\ + '--target-root[Target root directory]:directory:_files -/' \\ + '--include-fstab[Allow restoring /etc/fstab]' \\ + '--target-dir[Directory containing snapshot]:directory:_files -/' \\ + '--pid-path[Path to lockfile]:file:_files' + ;; + prune) + _arguments \\ + '--keep-last[Keep N most recent snapshots]:count:' \\ + '--keep-daily[Keep D daily snapshots]:days:' \\ + '--keep-weekly[Keep W weekly snapshots]:weeks:' \\ + '--keep-monthly[Keep M monthly snapshots]:months:' \\ + '--dry-run[Simulate pruning plan]' \\ + '--force[Confirm deletion of pruned snapshots]' \\ + '--target-dir[Directory containing snapshots]:directory:_files -/' + ;; + push) + _arguments \\ + '1:snapshot:_linux_backuper_snapshots' \\ + '--target[Remote destination (e.g. user@host:/path or alias)]:target:' \\ + '--ssh-key[SSH private key]:key:_files' \\ + '--remote-keep-last[Remote retention keep last]:count:' \\ + '--remote-keep-daily[Remote retention keep daily]:days:' \\ + '--remote-keep-weekly[Remote retention keep weekly]:weeks:' \\ + '--remote-keep-monthly[Remote retention keep monthly]:months:' \\ + '--target-dir[Directory containing snapshot]:directory:_files -/' \\ + '--config[Config path]:file:_files' + ;; + verify) + _arguments \\ + '1:snapshot:_linux_backuper_snapshots' \\ + '--target-dir[Directory containing snapshot]:directory:_files -/' + ;; + completion) + _arguments '1:shell:(bash zsh)' + ;; + esac + ;; + esac +} + +_linux_backuper "$@" +""" + + +def generate_completion(shell: str) -> str: + """Return completion script for specified shell.""" + shell = shell.lower().strip() + if shell == "bash": + return BASH_COMPLETION + elif shell == "zsh": + return ZSH_COMPLETION + else: + raise ValueError(f"Unsupported shell: '{shell}'. Supported shells: bash, zsh") diff --git a/man/linux-backuper.8 b/man/linux-backuper.8 new file mode 100644 index 0000000..d931fbd --- /dev/null +++ b/man/linux-backuper.8 @@ -0,0 +1,201 @@ +.TH LINUX-BACKUPER 8 "October 2026" "linux-backuper 1.0.0" "System Administration Commands" +.SH NAME +linux-backuper \- Enterprise Linux system snapshot, configuration backup, and safe restore utility +.SH SYNOPSIS +.B linux-backuper +[\fIOPTIONS\fR] \fICOMMAND\fR [\fIARGS...\fR] +.SH DESCRIPTION +.B linux-backuper +is an enterprise-grade Linux system snapshot and configuration backup utility written in pure Python >= 3.6 with zero mandatory external pip dependencies. It creates deterministic, cryptographically verifiable, and safe-to-restore configuration snapshots across Debian, Ubuntu, RHEL, AlmaLinux, Fedora, and Arch Linux distributions. +.PP +Snapshots are self-contained gzip archives (storing permissions, ownership, and timestamps) with an embedded +.B manifest.json +at the beginning of the archive stream, enabling sub-millisecond metadata queries without decompressing full archives. +.PP +Every snapshot is stored with strict root-only permissions (\fB0600\fR) by default. Restorations feature mandatory dry-run verification, atomic file replacement, automatic pre-restore safety snapshots, dynamic socket/mount protection, and automatic SELinux label restoration. + +.SH COMMANDS +.TP +.B snapshot [\fIOPTIONS\fR] +Capture a new system state snapshot. Collects comprehensive system metadata (OS distribution, packages, users/groups, kernel parameters, hardware, storage, and networking) and packages specified configuration trees. +.RS +.IP "\fB\-\-profile\fR \fINAME\fR" +Select backup profile: \fBquick\fR (default, covers /etc), \fBsystem\fR (adds /boot and kernel state), \fBfull\fR (adds critical /var paths), or custom profile defined in config. +.IP "\fB\-\-target\-dir\fR \fIDIR\fR" +Target backup directory (default: \fI/var/backups/linux-backuper\fR). +.IP "\fB\-\-paths\fR \fIPATH...\fR" +Explicit paths to include, overriding profile defaults. +.IP "\fB\-\-compression\fR {\fBgzip\fR,\fBnone\fR}" +Compression algorithm (default: \fBgzip\fR). +.IP "\fB\-\-no\-compression\fR" +Store plain uncompressed tar archive. +.IP "\fB\-\-sanitize\fR" +Redact sensitive credentials, shadow hashes, and private cryptographic keys for diagnostic export. +.IP "\fB\-\-push\fR \fITARGET\fR" +Transfer snapshot to remote storage (e.g. \fIuser@host:/path\fR or \fI/mnt/nas\fR) immediately upon creation. +.IP "\fB\-\-keep\-last\fR \fIN\fR, \fB\-\-keep\-daily\fR \fID\fR, \fB\-\-keep\-weekly\fR \fIW\fR, \fB\-\-keep\-monthly\fR \fIM\fR" +Prune local snapshots based on retention policies. +.IP "\fB\-\-remote\-keep\-last\fR \fIN\fR, \fB\-\-remote\-keep\-daily\fR \fID\fR, \fB\-\-remote\-keep\-weekly\fR \fIW\fR, \fB\-\-remote\-keep\-monthly\fR \fIM\fR" +Prune remote storage snapshots based on independent remote retention policies. +.RE + +.TP +.B list [\fIOPTIONS\fR] +List existing local snapshots with creation timestamps, profiles, file counts, and archive sizes. +.RS +.IP "\fB\-\-target\-dir\fR \fIDIR\fR" +Directory to scan for snapshot archives. +.RE + +.TP +.B show \fISNAPSHOT_ID\fR [\fIOPTIONS\fR] +Display detailed manifest, telemetry, and system state recorded in a snapshot. +.RS +.IP "\fB\-\-packages\fR" +List all recorded installed package versions. +.IP "\fB\-\-files\fR" +List all archived file paths contained in the snapshot. +.RE + +.TP +.B diff \fISNAPSHOT_ID\fR [\fISNAPSHOT_ID_2\fR] [\fIOPTIONS\fR] +Compare configuration state. If one snapshot is provided, performs a live diff comparing current host configuration and packages against the snapshot. If two snapshots are provided, compares differences between the two archives. +.RS +.IP "\fB\-u\fR, \fB\-\-unified\fR" +Display unified text diff for modified files. +.IP "\fB\-\-target\-root\fR \fIROOT\fR" +Filesystem root to compare against in live diff (default: \fI/\fR). +.RE + +.TP +.B extract \fISNAPSHOT_ID\fR \fB\-\-file\fR \fIPATH\fR \fB\-\-out\fR \fIDEST\fR +Extract a single file selectively from an archive without unpacking the entire snapshot. Protected against Zip Slip path traversal attacks. + +.TP +.B restore \fISNAPSHOT_ID\fR [\fIOPTIONS\fR] +Restore system configuration from a snapshot. +.RS +.IP "\fB\-\-dry\-run\fR" +Simulate execution plan without modifying filesystem (exits with code 5). +.IP "\fB\-\-force\fR" +Execute live restoration. Automatically creates a safety snapshot (\fBpre_restore_\fR) before making any modifications. +.IP "\fB\-\-include\-fstab\fR" +Explicitly allow restoring \fI/etc/fstab\fR (skipped by default to prevent mount failures). +.RE + +.TP +.B prune [\fIOPTIONS\fR] +Prune old snapshots using time-bucket retention algorithms. +.RS +.IP "\fB\-\-keep\-last\fR \fIN\fR" +Keep \fIN\fR most recent snapshots. +.IP "\fB\-\-keep\-daily\fR \fID\fR" +Keep most recent snapshot for \fID\fR distinct days. +.IP "\fB\-\-keep\-weekly\fR \fIW\fR" +Keep most recent snapshot for \fIW\fR distinct calendar weeks. +.IP "\fB\-\-keep\-monthly\fR \fIM\fR" +Keep most recent snapshot for \fIM\fR distinct calendar months. +.IP "\fB\-\-dry\-run\fR" +Simulate pruning plan without deleting files. +.IP "\fB\-\-force\fR" +Confirm actual file deletion. +.RE + +.TP +.B push \fISNAPSHOT_ID\fR \fB\-\-target\fR \fIDEST\fR [\fIOPTIONS\fR] +Transfer an existing local snapshot archive and manifest to a remote directory (local/NFS/SMB mount, SSH/rsync, or alias). + +.TP +.B verify \fISNAPSHOT_ID\fR +Verify SHA-256 cryptographic checksum and tar stream integrity of a snapshot archive. + +.TP +.B completion {\fBbash\fR,\fBzsh\fR} +Output shell autocompletion script to standard output. + +.SH GLOBAL OPTIONS +.TP +.B \-\-json +Format output as machine-readable JSON to standard output. +.TP +.B \-\-verbose +Enable detailed diagnostic and debugging log output. +.TP +.B \-h\fR, \fB\-\-help +Display command usage summary and exit. +.TP +.B \-v\fR, \fB\-\-version +Display version information and exit. + +.SH EXIT STATUS +.TP +.B 0 +Success. +.TP +.B 1 +Generic error or exception. +.TP +.B 2 +Insufficient permissions (root privileges required). +.TP +.B 3 +Pre-flight check failed (missing directories or dependencies). +.TP +.B 4 +Archive corruption or integrity check failure. +.TP +.B 5 +Dry-run simulation completed (no live changes executed). + +.SH FILES +.TP +.I /var/backups/linux-backuper/ +Default directory storing snapshot archives (\fB0700\fR root-only permissions). +.TP +.I /etc/linux-backuper/ +Configuration directory containing custom profiles and remote transport targets. +.TP +.I /var/run/linux-backuper.pid +Lock file preventing concurrent snapshot or restore operations. + +.SH EXAMPLES +.PP +Capture a quick snapshot of system configuration: +.RS +.B sudo linux-backuper snapshot --profile quick +.RE +.PP +Preview changes between a snapshot and the current live system: +.RS +.B sudo linux-backuper diff backup_host_20261009_120000 --unified +.RE +.PP +Perform a dry-run restoration: +.RS +.B sudo linux-backuper restore backup_host_20261009_120000 --dry-run +.RE +.PP +Perform a live restoration (with automated pre-restore safety snapshot): +.RS +.B sudo linux-backuper restore backup_host_20261009_120000 --force +.RE +.PP +Transfer snapshot to remote NAS storage with remote retention: +.RS +.B sudo linux-backuper snapshot --push lain@nas.wired.intra:/volume1/backups --remote-keep-last 7 +.RE +.PP +Install Bash completion: +.RS +.B linux-backuper completion bash | sudo tee /usr/share/bash-completion/completions/linux-backuper > /dev/null +.RE + +.SH AUTHORS +Written and maintained by wiredLAB . +.SH "REPORTING BUGS" +Report bugs to: +.SH "SEE ALSO" +.BR tar (1), +.BR gzip (1), +.BR rsync (1), +.BR ssh (1) diff --git a/packaging/build_packages.py b/packaging/build_packages.py index 6f7df46..6a546dd 100755 --- a/packaging/build_packages.py +++ b/packaging/build_packages.py @@ -10,6 +10,7 @@ Zero mandatory external pip dependencies required. """ import argparse +import gzip import io import os import re @@ -202,6 +203,62 @@ exit 0 ti.mtime = int(time.time()) tar.addfile(ti, io.BytesIO(file_data)) + # Add man page + man_src = os.path.join(repo_root, "man", "linux-backuper.8") + if os.path.isfile(man_src): + add_dir("./usr/share") + add_dir("./usr/share/man") + add_dir("./usr/share/man/man8") + with open(man_src, "rb") as f: + man_raw = f.read() + man_gz = gzip.compress(man_raw) + ti = tarfile.TarInfo("./usr/share/man/man8/linux-backuper.8.gz") + ti.size = len(man_gz) + ti.mode = 0o644 + ti.mtime = int(time.time()) + tar.addfile(ti, io.BytesIO(man_gz)) + + # Add shell completions + bash_comp_src = os.path.join(repo_root, "completions", "bash", "linux-backuper") + if os.path.isfile(bash_comp_src): + add_dir("./usr/share/bash-completion") + add_dir("./usr/share/bash-completion/completions") + with open(bash_comp_src, "rb") as f: + comp_data = f.read() + ti = tarfile.TarInfo("./usr/share/bash-completion/completions/linux-backuper") + ti.size = len(comp_data) + ti.mode = 0o644 + ti.mtime = int(time.time()) + tar.addfile(ti, io.BytesIO(comp_data)) + + zsh_comp_src = os.path.join(repo_root, "completions", "zsh", "_linux-backuper") + if os.path.isfile(zsh_comp_src): + add_dir("./usr/share/zsh") + add_dir("./usr/share/zsh/site-functions") + with open(zsh_comp_src, "rb") as f: + comp_data = f.read() + ti = tarfile.TarInfo("./usr/share/zsh/site-functions/_linux-backuper") + ti.size = len(comp_data) + ti.mode = 0o644 + ti.mtime = int(time.time()) + tar.addfile(ti, io.BytesIO(comp_data)) + + # Add documentation + docs_src = os.path.join(repo_root, "docs") + if os.path.isdir(docs_src): + add_dir("./usr/share/doc") + add_dir("./usr/share/doc/linux-backuper") + for doc_name in ["user-guide.md", "admin-guide.md", "developer-guide.md"]: + doc_path = os.path.join(docs_src, doc_name) + if os.path.isfile(doc_path): + with open(doc_path, "rb") as f: + ddata = f.read() + ti = tarfile.TarInfo(f"./usr/share/doc/linux-backuper/{doc_name}") + ti.size = len(ddata) + ti.mode = 0o644 + ti.mtime = int(time.time()) + tar.addfile(ti, io.BytesIO(ddata)) + data_tar_gz = data_buf.getvalue() # Package into ar archive @@ -281,6 +338,40 @@ def build_tar_package(repo_root: str, out_dir: str, version: str) -> str: ti.mode = 0o644 tar.addfile(ti, io.BytesIO(data)) + # Add man page + man_src = os.path.join(repo_root, "man", "linux-backuper.8") + if os.path.isfile(man_src): + with open(man_src, "rb") as f: + data = f.read() + ti = tarfile.TarInfo(f"{prefix}/man/linux-backuper.8") + ti.size = len(data) + ti.mode = 0o644 + tar.addfile(ti, io.BytesIO(data)) + + # Add completions + for shell, cname in [("bash", "linux-backuper"), ("zsh", "_linux-backuper")]: + c_src = os.path.join(repo_root, "completions", shell, cname) + if os.path.isfile(c_src): + with open(c_src, "rb") as f: + data = f.read() + ti = tarfile.TarInfo(f"{prefix}/completions/{shell}/{cname}") + ti.size = len(data) + ti.mode = 0o644 + tar.addfile(ti, io.BytesIO(data)) + + # Add docs + docs_src = os.path.join(repo_root, "docs") + if os.path.isdir(docs_src): + for doc_name in ["user-guide.md", "admin-guide.md", "developer-guide.md"]: + doc_path = os.path.join(docs_src, doc_name) + if os.path.isfile(doc_path): + with open(doc_path, "rb") as f: + data = f.read() + ti = tarfile.TarInfo(f"{prefix}/docs/{doc_name}") + ti.size = len(data) + ti.mode = 0o644 + tar.addfile(ti, io.BytesIO(data)) + print(f"[SUCCESS] Built binary tarball: {tar_path} ({os.path.getsize(tar_path)} bytes)") return tar_path @@ -327,12 +418,40 @@ find %{{buildroot}}/usr/lib/linux-backuper -name "__pycache__" -type d -exec rm find %{{buildroot}}/usr/lib/linux-backuper -type d -exec chmod 0755 {{}} + find %{{buildroot}}/usr/lib/linux-backuper -type f -exec chmod 0644 {{}} + +if [ -f man/linux-backuper.8 ]; then + mkdir -p %{{buildroot}}%{{_mandir}}/man8 + gzip -c -n man/linux-backuper.8 > %{{buildroot}}%{{_mandir}}/man8/linux-backuper.8.gz + chmod 0644 %{{buildroot}}%{{_mandir}}/man8/linux-backuper.8.gz +fi + +if [ -f completions/bash/linux-backuper ]; then + mkdir -p %{{buildroot}}/usr/share/bash-completion/completions + cp completions/bash/linux-backuper %{{buildroot}}/usr/share/bash-completion/completions/linux-backuper + chmod 0644 %{{buildroot}}/usr/share/bash-completion/completions/linux-backuper +fi + +if [ -f completions/zsh/_linux-backuper ]; then + mkdir -p %{{buildroot}}/usr/share/zsh/site-functions + cp completions/zsh/_linux-backuper %{{buildroot}}/usr/share/zsh/site-functions/_linux-backuper + chmod 0644 %{{buildroot}}/usr/share/zsh/site-functions/_linux-backuper +fi + +if [ -d docs ]; then + mkdir -p %{{buildroot}}/usr/share/doc/linux-backuper + cp docs/*.md %{{buildroot}}/usr/share/doc/linux-backuper/ 2>/dev/null || true + chmod 0644 %{{buildroot}}/usr/share/doc/linux-backuper/* 2>/dev/null || true +fi + %files %defattr(-,root,root,-) /usr/bin/linux-backuper /usr/lib/linux-backuper %dir /etc/linux-backuper %attr(0700,root,root) %dir /var/backups/linux-backuper +%{{_mandir}}/man8/linux-backuper.8* +/usr/share/bash-completion/completions/linux-backuper +/usr/share/zsh/site-functions/_linux-backuper +/usr/share/doc/linux-backuper %changelog * Fri Oct 09 2026 wiredLAB - {version}-1 diff --git a/packaging/install.sh b/packaging/install.sh index b13152e..fd83da3 100755 --- a/packaging/install.sh +++ b/packaging/install.sh @@ -63,6 +63,25 @@ do_install() { cp "${SOURCE_ROOT}/bin/linux-backuper" "${BINDIR}/linux-backuper" chmod 0755 "${BINDIR}/linux-backuper" + # Install man page + if [[ -f "${SOURCE_ROOT}/man/linux-backuper.8" ]]; then + mkdir -p "${PREFIX}/share/man/man8" + cp "${SOURCE_ROOT}/man/linux-backuper.8" "${PREFIX}/share/man/man8/linux-backuper.8" + chmod 0644 "${PREFIX}/share/man/man8/linux-backuper.8" + fi + + # Install completions + if [[ -f "${SOURCE_ROOT}/completions/bash/linux-backuper" ]]; then + mkdir -p "${PREFIX}/share/bash-completion/completions" + cp "${SOURCE_ROOT}/completions/bash/linux-backuper" "${PREFIX}/share/bash-completion/completions/linux-backuper" + chmod 0644 "${PREFIX}/share/bash-completion/completions/linux-backuper" + fi + if [[ -f "${SOURCE_ROOT}/completions/zsh/_linux-backuper" ]]; then + mkdir -p "${PREFIX}/share/zsh/site-functions" + cp "${SOURCE_ROOT}/completions/zsh/_linux-backuper" "${PREFIX}/share/zsh/site-functions/_linux-backuper" + chmod 0644 "${PREFIX}/share/zsh/site-functions/_linux-backuper" + fi + echo "[SUCCESS] linux-backuper installed successfully to ${BINDIR}/linux-backuper" echo "[INFO] Testing installed binary:" "${BINDIR}/linux-backuper" --version || true @@ -77,7 +96,10 @@ do_uninstall() { echo "[INFO] Uninstalling linux-backuper..." rm -f "${BINDIR}/linux-backuper" rm -rf "${LIBDIR}" - echo "[SUCCESS] linux-backuper removed from ${BINDIR} and ${LIBDIR}." + rm -f "${PREFIX}/share/man/man8/linux-backuper.8" + rm -f "${PREFIX}/share/bash-completion/completions/linux-backuper" + rm -f "${PREFIX}/share/zsh/site-functions/_linux-backuper" + echo "[SUCCESS] linux-backuper removed from system." echo "[NOTE] Backup storage at ${BACKUPDIR} and configuration at ${CONFDIR} were preserved." } diff --git a/tests/test_completions.py b/tests/test_completions.py new file mode 100644 index 0000000..f7d3e4d --- /dev/null +++ b/tests/test_completions.py @@ -0,0 +1,59 @@ +"""Unit tests for shell completions and CLI help.""" + +import io +import unittest +from unittest.mock import patch + +from linux_backuper.cli import main +from linux_backuper.core.completions import generate_completion + + +class TestCompletions(unittest.TestCase): + """Test shell autocompletion generator and CLI output.""" + + def test_generate_bash_completion(self): + script = generate_completion("bash") + self.assertIn("_linux_backuper()", script) + self.assertIn("complete -F _linux_backuper linux-backuper", script) + self.assertIn("snapshot list show diff extract restore prune push verify completion", script) + + def test_generate_zsh_completion(self): + script = generate_completion("zsh") + self.assertIn("#compdef linux-backuper", script) + self.assertIn("_linux_backuper()", script) + self.assertIn("snapshot:Capture a new system state snapshot", script) + + def test_generate_invalid_shell(self): + with self.assertRaises(ValueError): + generate_completion("fish") + + def test_cli_completion_subcommand_bash(self): + stdout_buf = io.StringIO() + with patch("sys.stdout", stdout_buf): + code = main(["completion", "bash"]) + self.assertEqual(code, 0) + out = stdout_buf.getvalue() + self.assertIn("complete -F _linux_backuper linux-backuper", out) + + def test_cli_completion_subcommand_zsh(self): + stdout_buf = io.StringIO() + with patch("sys.stdout", stdout_buf): + code = main(["completion", "zsh"]) + self.assertEqual(code, 0) + out = stdout_buf.getvalue() + self.assertIn("#compdef linux-backuper", out) + + def test_cli_help(self): + stdout_buf = io.StringIO() + with patch("sys.stdout", stdout_buf): + with self.assertRaises(SystemExit) as cm: + main(["--help"]) + self.assertEqual(cm.exception.code, 0) + out = stdout_buf.getvalue() + self.assertIn("Enterprise Linux system snapshot", out) + for subcmd in ["snapshot", "list", "show", "diff", "extract", "restore", "prune", "push", "verify", "completion"]: + self.assertIn(subcmd, out) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_packaging.py b/tests/test_packaging.py index 4d051c7..28785ee 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -1,5 +1,4 @@ -"""Unit tests for packaging builder.""" - +import importlib.util import os import shutil import tarfile @@ -7,12 +6,18 @@ import tempfile import unittest from linux_backuper import __version__ -from packaging.build_packages import ( - build_deb_package, - build_tar_package, - generate_rpm_spec, - get_version, -) + +repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +builder_path = os.path.join(repo_root, "packaging", "build_packages.py") + +spec = importlib.util.spec_from_file_location("build_packages", builder_path) +build_packages_mod = importlib.util.module_from_spec(spec) +spec.loader.exec_module(build_packages_mod) + +build_deb_package = build_packages_mod.build_deb_package +build_tar_package = build_packages_mod.build_tar_package +generate_rpm_spec = build_packages_mod.generate_rpm_spec +get_version = build_packages_mod.get_version class TestPackaging(unittest.TestCase): @@ -39,6 +44,9 @@ class TestPackaging(unittest.TestCase): self.assertIn(f"{prefix}/bin/linux-backuper", names) self.assertIn(f"{prefix}/install.sh", names) self.assertIn(f"{prefix}/linux_backuper/cli.py", names) + self.assertIn(f"{prefix}/man/linux-backuper.8", names) + self.assertIn(f"{prefix}/completions/bash/linux-backuper", names) + self.assertIn(f"{prefix}/docs/user-guide.md", names) def test_build_deb_package(self): deb_path = build_deb_package(self.repo_root, self.test_dir, __version__) @@ -91,6 +99,10 @@ class TestPackaging(unittest.TestCase): self.assertIn("./usr/bin/linux-backuper", dnames) self.assertIn("./usr/lib/linux-backuper/linux_backuper/cli.py", dnames) self.assertIn("./var/backups/linux-backuper", dnames) + self.assertIn("./usr/share/man/man8/linux-backuper.8.gz", dnames) + self.assertIn("./usr/share/bash-completion/completions/linux-backuper", dnames) + self.assertIn("./usr/share/zsh/site-functions/_linux-backuper", dnames) + self.assertIn("./usr/share/doc/linux-backuper/user-guide.md", dnames) def test_generate_rpm_spec(self): spec_path = generate_rpm_spec(self.repo_root, self.test_dir, __version__) @@ -101,6 +113,8 @@ class TestPackaging(unittest.TestCase): self.assertIn(f"Version: {__version__}", content) self.assertIn("Requires: python3 >= 3.6", content) self.assertIn("/usr/bin/linux-backuper", content) + self.assertIn("%{_mandir}/man8/linux-backuper.8*", content) + self.assertIn("/usr/share/bash-completion/completions/linux-backuper", content) if __name__ == "__main__":