feat(docs): implement slice 8 documentation triad, man page, completions and Gitea Actions CI/CD
Build and Publish Release / test-and-release (push) Failing after 48s

This commit is contained in:
soda64 committed 2026-10-09 20:22:51 +02:00
1 parent c5c3b87bd9
commit 6f23f14b76
14 files changed
+1730 -10

No files matched your search

+212
View File
@@ -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 <<EOF > "$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/`. |
+153
View File
@@ -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
```
+1 -1
View File
@@ -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.
+177
View File
@@ -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_<timestamp>` 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
```