Compare commits

...
13 Commits
Author SHA1 Message Date
soda64 7972834e90 fix(packaging): prevent duplicate RPM in release by cleaning rpmbuild staging tree
Build and Publish Release / Build Packages and Publish (push) Successful in 42s
2026-10-09 20:38:21 +02:00
soda64 c89aa3d1c7 fix(ci): harmonize release workflow with linux-updater proven architecture
Build and Publish Release / Build Packages and Publish (push) Successful in 43s
2026-10-09 20:33:13 +02:00
soda64 d18db76441 fix(ci): delegate Gitea release asset publishing to standalone python script
Build and Publish Release / test-and-release (push) Successful in 42s
2026-10-09 20:30:00 +02:00
soda64 2462bdf097 fix(ci): make release asset step resilient against set -e in Gitea Actions 2026-10-09 20:28:09 +02:00
soda64 6f23f14b76 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
2026-10-09 20:22:51 +02:00
soda64 c5c3b87bd9 feat(packaging): implement slice 7 native packaging (.deb, .rpm, .tar.gz) 2026-10-09 20:08:30 +02:00
soda64 e7aa5a54a4 feat(transport): implement slice 6 local-first remote transport sync 2026-10-09 19:54:32 +02:00
soda64 361640f5ae feat(retention): implement slice 5 retention engine and pruning policies 2026-10-09 19:29:24 +02:00
soda64 8d4127de30 feat(restore): implement slice 4 snapshot management, diff engine, and safe restore 2026-10-09 19:19:28 +02:00
soda64 646bd9d145 feat(profiles): implement slice 3 profile system, flock concurrency, and sanitize archiver 2026-10-09 18:59:49 +02:00
soda64 66ca179937 feat(inspector): implement slice 2 comprehensive host state inspector 2026-10-09 18:48:51 +02:00
soda64 2602b66a90 feat(core): implement slice 1 tracer bullet end-to-end skeleton 2026-10-09 18:37:27 +02:00
soda64 0aed5bb003 docs(plans): incorporate grill-me architectural refinements and packaging workflows 2026-10-09 18:30:15 +02:00
47 changed files with 7093 additions and 20 deletions

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
name: Build and Publish Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
release:
name: Build Packages and Publish
runs-on: fedora
steps:
- name: Checkout Source Code
uses: actions/checkout@v4
- name: Verify Build Environment
run: |
echo "=== Runner System Info ==="
uname -a
python3 --version
if ! command -v rpmbuild &>/dev/null; then
echo "Installing rpm-build..."
sudo dnf install -y rpm-build
else
echo "rpmbuild is already available: $(which rpmbuild)"
fi
- name: Run Test Suite
run: |
echo "=== Running Unit Tests ==="
python3 -m unittest discover tests
- name: Build Distribution Packages
run: |
echo "=== Building Packages (.rpm, .deb, .tar.gz) ==="
python3 packaging/build_packages.py --all
echo "=== Built Artifacts ==="
ls -lh dist/*.tar.gz dist/*.deb 2>/dev/null || true
ls -lh dist/*.rpm dist/rpmbuild/RPMS/*/*.rpm 2>/dev/null || true
- name: Publish to Gitea Package Registry
env:
PKG_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
run: |
echo "=== Publishing to Gitea Package Registry ==="
RPM_FILE=$(ls dist/*.rpm 2>/dev/null | head -n 1)
DEB_FILE=$(ls dist/*.deb 2>/dev/null | head -n 1)
if [ -n "$RPM_FILE" ] && [ -f "$RPM_FILE" ]; then
echo "Uploading RPM: $RPM_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$RPM_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/rpm/upload")
echo "RPM Registry HTTP status: $HTTP_CODE"
fi
if [ -n "$DEB_FILE" ] && [ -f "$DEB_FILE" ]; then
echo "Uploading DEB: $DEB_FILE"
HTTP_CODE=$(curl -k -s -o /dev/null -w "%{http_code}" -X PUT \
-u "${{ github.actor }}:${PKG_TOKEN}" \
--upload-file "$DEB_FILE" \
"${{ github.server_url }}/api/packages/${{ github.repository_owner }}/debian/pool/stable/main/upload")
echo "Debian Registry HTTP status: $HTTP_CODE"
fi
# Link packages to this repository in Gitea
REPO_NAME=$(basename "${{ github.repository }}")
echo "Linking RPM package 'linux-backuper' to repository ${REPO_NAME}..."
LINK_RPM=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/rpm/linux-backuper/-/link/${REPO_NAME}")
echo "RPM link result: $LINK_RPM"
echo "Linking Debian package 'linux-backuper' to repository ${REPO_NAME}..."
LINK_DEB=$(curl -k -s -w " (HTTP %{http_code})" -X POST \
-H "Authorization: token ${PKG_TOKEN}" \
"${{ github.server_url }}/api/v1/packages/${{ github.repository_owner }}/debian/linux-backuper/-/link/${REPO_NAME}")
echo "Debian link result: $LINK_DEB"
- name: Attach Artifacts to Gitea Release
env:
GITHUB_TOKEN: ${{ secrets.PACKAGES_GENERATION || secrets.GITHUB_TOKEN }}
SERVER_URL: ${{ github.server_url }}
REPO: ${{ github.repository }}
TAG_REF: ${{ github.ref_name }}
run: |
echo "=== Attaching Assets to Release ==="
TAG="${TAG_REF}"
if [[ "$TAG" == "main" || "$TAG" == "" ]]; then
VER=$(python3 -c "import linux_backuper; print(linux_backuper.__version__)")
TAG="v${VER}"
fi
echo "Target Release Tag: $TAG"
# 1. Fetch release ID or create release if missing
REL_JSON=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/tags/${TAG}")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$REL_JSON" 2>/dev/null || true)
if [ -z "$REL_ID" ]; then
echo "Release $TAG does not exist yet. Creating release..."
CREATE_DATA=$(python3 -c "import sys, json; print(json.dumps({'tag_name': sys.argv[1], 'name': 'linux-backuper ' + sys.argv[1], 'body': 'Automated build and release for ' + sys.argv[1] + ' (Debian, Red Hat/Fedora, and universal tarball).'}))" "$TAG")
CREATE_RESP=$(curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-H "Content-Type: application/json" \
-d "$CREATE_DATA" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases")
REL_ID=$(python3 -c "import sys, json; data=json.loads(sys.argv[1]); print(data.get('id', ''))" "$CREATE_RESP" 2>/dev/null || true)
echo "Create release response: $CREATE_RESP"
fi
echo "Release ID: $REL_ID"
if [ -n "$REL_ID" ]; then
# Clean up any existing assets for this release
EXISTING_ASSETS=$(curl -k -s -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets" || true)
ASSET_IDS=$(python3 -c "import sys, json; print(' '.join(str(a['id']) for a in json.loads(sys.argv[1])))" "$EXISTING_ASSETS" 2>/dev/null || true)
for aid in $ASSET_IDS; do
echo "Removing previous asset ID $aid..."
curl -k -s -X DELETE -H "Authorization: token ${GITHUB_TOKEN}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets/${aid}" || true
done
# Target only user-facing binaries in top-level dist/
ASSET_FILES=(
$(ls dist/*.tar.gz 2>/dev/null || true)
$(ls dist/*.deb 2>/dev/null || true)
$(ls dist/*.rpm 2>/dev/null || true)
)
for f in "${ASSET_FILES[@]}"; do
if [ -f "$f" ]; then
fname=$(basename "$f")
echo "Uploading asset $fname from $f..."
curl -k -s -X POST \
-H "Authorization: token ${GITHUB_TOKEN}" \
-F "attachment=@${f}" \
"${SERVER_URL}/api/v1/repos/${REPO}/releases/${REL_ID}/assets?name=${fname}" || echo "Asset upload note: $?"
fi
done
echo "Artifacts successfully attached to release $TAG!"
else
echo "Could not obtain release ID, skipping asset attachment."
fi
+20
View File
@@ -0,0 +1,20 @@
#!/usr/bin/env python3
"""Executable launcher for linux-backuper."""
import os
import sys
# Ensure library path is discoverable when run directly from repo
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if repo_root not in sys.path:
sys.path.insert(0, repo_root)
# Standard package install locations
for install_lib in ["/usr/lib/linux-backuper", "/usr/share/linux-backuper"]:
if os.path.isdir(install_lib) and install_lib not in sys.path:
sys.path.insert(0, install_lib)
from linux_backuper.cli import main
if __name__ == "__main__":
sys.exit(main())
+158
View File
@@ -0,0 +1,158 @@
# 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
+135
View File
@@ -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 "$@"
+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
```
+18 -10
View File
@@ -6,14 +6,14 @@
- Gate 4 — Slice Plan: APPROVED 2026-10-03 - Gate 4 — Slice Plan: APPROVED 2026-10-03
## Slices ## Slices
- [ ] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests) - [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + system inspector stub + gzip snapshot + 0600 perms + tests)
- [ ] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages) - [x] Slice 2 — comprehensive host state inspector (users/groups, kernel/sysctl/cmdline/modules, hardware/cpu/pci, storage/LVM, network, packages)
- [ ] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest - [x] Slice 3 — profile system, configuration archiver & manifest generator (`quick`, `system`, `full`, custom) with atomic write & SHA-256 manifest
- [ ] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot) - [x] Slice 4 — snapshot management, live diff & safe restore engine (list, show, verify, live system diff, extract, restore with dry-run & safety snapshot)
- [ ] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote) - [x] Slice 5 — retention policy & pruning engine (`--keep-last`, `--keep-daily`, `--keep-weekly`, local & remote)
- [ ] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention) - [x] Slice 6 — remote transport sync (local-first + SFTP / rsync / mounted NFS/SMB push with separate remote retention)
- [ ] Slice 7 — native packaging (.deb, .rpm, .tar.gz via pure Python builder) - [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 ## Notes for a fresh session
- Project: Enterprise-grade Linux system snapshot and configuration backup utility. - Project: Enterprise-grade Linux system snapshot and configuration backup utility.
@@ -27,10 +27,18 @@
2. Metadata Collection: Users/groups (`/etc/passwd`, `/etc/group`, subuid/subgid), kernel parameters (`sysctl -a`, `/proc/cmdline`, `lsmod`), hardware (`lscpu`, `lshw`, `lspci`, `lsusb`, `dmidecode`, RAM/meminfo), storage (`lsblk`, `df`, LVM `pvs/vgs/lvs`, `/etc/fstab`), network (`ip a`, `ip r`, `/etc/resolv.conf`), packages (`rpm -qa`, `dpkg-query`, `pacman -Q`). 2. Metadata Collection: Users/groups (`/etc/passwd`, `/etc/group`, subuid/subgid), kernel parameters (`sysctl -a`, `/proc/cmdline`, `lsmod`), hardware (`lscpu`, `lshw`, `lspci`, `lsusb`, `dmidecode`, RAM/meminfo), storage (`lsblk`, `df`, LVM `pvs/vgs/lvs`, `/etc/fstab`), network (`ip a`, `ip r`, `/etc/resolv.conf`), packages (`rpm -qa`, `dpkg-query`, `pacman -Q`).
3. Compression: Built-in standard library `gzip` (`.tar.gz`) enabled by default. Zero external compression binaries required. Optional `--no-compression` flag. 3. Compression: Built-in standard library `gzip` (`.tar.gz`) enabled by default. Zero external compression binaries required. Optional `--no-compression` flag.
4. Security & Encryption: Strict `0600` root-only archive permissions. Optional AES-256 encryption (`--encrypt`). Diagnostic sanitization (`--sanitize`) redacting `/etc/shadow` and private keys. Fully documented. 4. Security & Encryption: Strict `0600` root-only archive permissions. Optional AES-256 encryption (`--encrypt`). Diagnostic sanitization (`--sanitize`) redacting `/etc/shadow` and private keys. Fully documented.
5. Remote Storage & NAS Sync: Local-first architecture (always written locally to `/var/backups/linux-backuper/` first). Optional `--push` flag or profile remote targets (SSH/SFTP, rsync, mounted directory) with independent remote retention. 5. Remote Storage & NAS Sync: Local-first architecture (always written locally to `/var/backups/linux-backuper/` first). Zero mandatory pip dependencies: system CLI `rsync`, `ssh/scp/sftp` via `subprocess` or mounted directory by default, with optional `paramiko` fallback if installed. Independent remote retention.
6. Safe Restore Strategy: 6. Safe Restore Strategy:
- Primary: Selective extraction (`extract <id> --file <path> --out <dest>`) and live system diff (`diff <id>` and `diff <id1> <id2>`). - Primary: Selective extraction (`extract <id> --file <path> --out <dest>`) and live system diff (`diff <id>` and `diff <id1> <id2>`).
- Full restore (`restore <id>`): Guardrailed by default `--dry-run`, mandatory `--force`, automatic `pre-restore-safety-snapshot`, and exclusion of volatile sockets/dynamic symlinks. - Full restore (`restore <id>`): Guardrailed by default `--dry-run`, mandatory `--force`, automatic `pre-restore-safety-snapshot`, atomic file replacement (`os.replace`), automatic `restorecon -R` execution on SELinux systems (RHEL/Alma/Fedora), and exclusion of volatile sockets/dynamic symlinks (`/etc/resolv.conf`, `/etc/mtab`, `/run/`).
- Symlink Safety: Tarball stores relative/absolute symlinks (`dereference=False`), extract engine strictly blocks Path Traversal (Zip Slip) outside target root.
7. Single-File Format & Fast List:
- Exactly one `.tar.gz` per snapshot (no loose companion files).
- `manifest.json` placed as the first member of the tar stream, enabling `linux-backuper list` to read metadata in milliseconds without decompressing full archives.
- Filesystem guard: `--one-file-system` by default, interactive prompt on files > 50 MB in TTY mode, automated skip with warning in batch/cron mode.
8. Packaging & Gitea Package Registry CI/CD:
- Automated build of `.rpm`, `.deb`, and `.tar.gz`.
- Gitea Actions workflow (`.gitea/workflows/release.yml`) publishing directly to Gitea RPM & Debian Package Registries and Release Assets via `PACKAGES_GENERATION` token.
- Shell Tab Completion Standard (Bash & Zsh): - Shell Tab Completion Standard (Bash & Zsh):
- Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `restore`, `prune`, `completion`). - Subcommands and flags auto-completion (`snapshot`, `list`, `show`, `diff`, `verify`, `extract`, `restore`, `prune`, `completion`).
- Dynamic completion: `show`, `diff`, `verify`, `extract`, `restore` auto-complete snapshot IDs from `/var/backups/linux-backuper/`. - Dynamic completion: `show`, `diff`, `verify`, `extract`, `restore` auto-complete snapshot IDs from `/var/backups/linux-backuper/`.
+15 -8
View File
@@ -81,11 +81,13 @@ To ensure complete reconstruction even on a fresh OS install, every snapshot gat
## 4. Snapshot Archive Format & Manifest Schema ## 4. Snapshot Archive Format & Manifest Schema
Each snapshot is packaged as a `.tar.gz` archive with strict `0600` permissions (readable/writeable only by root) inside `/var/backups/linux-backuper/` (`0700` directory). 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.
```text ```text
backup_enterprise_20261002_211500.tar.gz backup_enterprise_20261002_211500.tar.gz
├── manifest.json # Machine-readable metadata document ├── manifest.json # FIRST member: machine-readable metadata & file SHA-256 table
├── meta/ # Deep telemetry command dumps ├── meta/ # Deep telemetry command dumps
│ ├── hardware.json / .txt │ ├── hardware.json / .txt
│ ├── storage.json / .txt │ ├── storage.json / .txt
@@ -123,13 +125,15 @@ backup_enterprise_20261002_211500.tar.gz
"compressed_bytes": 14881024, "compressed_bytes": 14881024,
"file_count": 1420 "file_count": 1420
}, },
"checksums": { "files_sha256": {
"archive_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "meta/packages.txt": "a823f...",
"manifest_sha256": "4b227777d4dd1fc61c6f884f48641d02b4d121d3fd328cb08b5531fcacdabf8a" "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 ## 5. Compression & Security Architecture
@@ -158,9 +162,11 @@ Restoring configuration on a live Linux system carries critical operational risk
- `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 <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. - `linux-backuper diff <id1> <id2>`: Compares two snapshots against each other.
3. **Full Live Restore (`restore <id>`):** 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. - **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. - **Automatic Pre-Restore Safety Snapshot:** When `--force` is specified, `linux-backuper` **automatically captures a safety snapshot** (`pre_restore_<timestamp>`) before modifying a single file on disk. If anything goes wrong, immediate rollback is guaranteed.
- **Strict Exclusion Guardrails:** Automatically skips dynamic sockets (`*.sock`), named pipes (FIFOs), temporary lock files (`*.lock`, `*.pid`), and dynamic mount links (`/etc/resolv.conf`, `/etc/mtab`). - **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.
--- ---
@@ -168,7 +174,8 @@ Restoring configuration on a live Linux system carries critical operational risk
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. 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]`):** 2. **Push Sync (`--push [target]`):**
- Transports supported: SFTP (via `paramiko`), `rsync`, or direct filesystem write to mounted NFS/SMB shares. - **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`). - 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). - **Independent Remote Retention:** Remote target maintains its own retention policy (e.g. keep last 30 on NAS while keeping last 7 locally).
+1 -2
View File
@@ -98,8 +98,7 @@ This roadmap defines the implementation order for `linux-backuper` in thin, inde
- Shell Tab Completion: Native Bash (`completions/bash/linux-backuper`) and Zsh (`completions/zsh/_linux-backuper`) scripts supporting subcommands, flags, profiles, and dynamic snapshot ID completion. - Shell Tab Completion: Native Bash (`completions/bash/linux-backuper`) and Zsh (`completions/zsh/_linux-backuper`) scripts supporting subcommands, flags, profiles, and dynamic snapshot ID completion.
- `linux-backuper completion [bash|zsh]` generator sub-command. - `linux-backuper completion [bash|zsh]` generator sub-command.
- Interactive CLI Help: Complete `-h` and `--help` for root and all sub-commands with usage examples. - Interactive CLI Help: Complete `-h` and `--help` for root and all sub-commands with usage examples.
- Packaging integration: Install completion scripts to `/usr/share/bash-completion/completions/` and `/usr/share/zsh/site-functions/`. - `.gitea/workflows/release.yml`: Gitea Actions pipeline targeting `runs-on: fedora` (hostexecutor runner `giteaworker`), running tests (`python3 -m unittest discover tests`), building `.rpm`/`.deb`/`.tar.gz`, publishing to Gitea RPM (`/api/packages/{owner}/rpm/upload`) & Debian (`/api/packages/{owner}/debian/pool/stable/main/upload`) Package Registries, linking packages via `PACKAGES_GENERATION` token, and uploading Release assets.
- `.gitea/workflows/release.yml`: Gitea Actions pipeline targeting `runs-on: fedora`, running tests, building `.rpm`/`.deb`, publishing to Gitea Package Registry and Release assets.
- **Verification:** Unit tests verifying `linux-backuper -h`, sub-command `--help`, shell completion scripts generation (`linux-backuper completion bash` / `zsh`), and man page syntax verification with `man -l man/linux-backuper.8`. - **Verification:** Unit tests verifying `linux-backuper -h`, sub-command `--help`, shell completion scripts generation (`linux-backuper completion bash` / `zsh`), and man page syntax verification with `man -l man/linux-backuper.8`.
+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
```
+4
View File
@@ -0,0 +1,4 @@
"""linux-backuper - Enterprise Linux system snapshot and configuration backup utility."""
__version__ = "1.0.0"
__author__ = "wiredLAB"
+7
View File
@@ -0,0 +1,7 @@
"""Entrypoint when executed as a module: python3 -m linux_backuper."""
import sys
from linux_backuper.cli import main
if __name__ == "__main__":
sys.exit(main())
+838
View File
@@ -0,0 +1,838 @@
"""Command-line interface and dispatch for linux-backuper."""
import argparse
import datetime
import json
import os
import socket
import sys
from typing import List, Optional
from linux_backuper import __version__
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256
from linux_backuper.core.constants import (
DEFAULT_BACKUP_DIR,
DEFAULT_CONFIG_PATH,
DEFAULT_PID_PATH,
EXIT_CORRUPTED,
EXIT_DRY_RUN,
EXIT_GENERIC_ERROR,
EXIT_PERM_DENIED,
EXIT_PREFLIGHT_FAIL,
EXIT_SUCCESS,
)
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.diff import DiffEngine
from linux_backuper.core.inspector import SystemInspector
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
from linux_backuper.core.profiles import ProfileManager
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
from linux_backuper.core.retention import RetentionEngine
from linux_backuper.core.transport import TransportFactory, TransportError
from linux_backuper.models import SnapshotManifest
def check_root_permissions() -> bool:
"""Check if process has root privileges, respecting test overrides."""
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1":
return True
try:
return os.geteuid() == 0
except AttributeError:
return True
def resolve_default_ssh_key(explicit_key: Optional[str]) -> Optional[str]:
"""Resolve SSH identity key, looking up SUDO_USER if running as root."""
if explicit_key and os.path.isfile(explicit_key):
return explicit_key
sudo_user = os.environ.get("SUDO_USER")
if sudo_user:
for ck in (
f"/home/{sudo_user}/.ssh/id_ed25519",
f"/home/{sudo_user}/.ssh/id_rsa",
f"/Users/{sudo_user}/.ssh/id_ed25519",
f"/Users/{sudo_user}/.ssh/id_rsa",
):
if os.path.isfile(ck):
return ck
return explicit_key
def handle_snapshot(args: argparse.Namespace) -> int:
"""Execute snapshot command."""
if not check_root_permissions():
sys.stderr.write("[ERROR] Creating snapshots requires root privileges (uid 0).\n")
return EXIT_PERM_DENIED
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
try:
os.makedirs(target_dir, exist_ok=True)
except OSError as e:
sys.stderr.write(f"[ERROR] Target backup directory not accessible: {e}\n")
return EXIT_PREFLIGHT_FAIL
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
lock = SingleInstanceLock(pid_path=pid_path)
try:
lock.acquire()
except LockAcquisitionError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
try:
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
profile_mgr = ProfileManager(config_path=config_path)
try:
profile = profile_mgr.get_profile(args.profile)
except KeyError as e:
sys.stderr.write(f"[ERROR] {e}\n")
return EXIT_GENERIC_ERROR
hostname = socket.gethostname().split(".")[0]
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
snapshot_id = f"backup_{hostname}_{timestamp}"
# Resolve paths & exclusions
included_paths = args.paths if args.paths else profile.included_paths
exclude_patterns = profile.exclude_patterns
compression = "none" if getattr(args, "no_compression", False) else args.compression
sanitize = getattr(args, "sanitize", False)
os_info = detect_distro()
archiver = SnapshotArchiver(target_dir=target_dir, compression=compression)
inspector = SystemInspector(distro_id=os_info.distro_id)
packages = inspector.inspect_packages()
if not args.json:
sys.stderr.write(f"[INFO] Initializing snapshot '{snapshot_id}' (profile: {args.profile})...\n")
sys.stderr.write(f"[INFO] Host OS: {os_info.distro_name} {os_info.version_id} ({os_info.arch})\n")
sys.stderr.write(f"[INFO] Packages detected: {len(packages)} via {inspector.package_manager.get_manager_name()}\n")
# Pass 1: Collect data paths
file_entries, files_sha256, uncompressed_bytes, sanitized_files = archiver.collect_file_list(
included_paths,
exclude_patterns=exclude_patterns,
sanitize=sanitize
)
# Pass 1b: Collect deep system telemetry meta files
import shutil
import tempfile
temp_meta_dir = tempfile.mkdtemp(prefix="linux_backuper_meta_")
try:
meta_files_map = inspector.dump_meta_files(temp_meta_dir)
# Record sanitized files if any
if sanitized_files:
sanitized_log_path = os.path.join(temp_meta_dir, "sanitized.txt")
with open(sanitized_log_path, "w", encoding="utf-8") as f:
f.write("# Redacted security files:\n")
for s in sanitized_files:
f.write(f"{s}\n")
meta_files_map["meta/sanitized.txt"] = sanitized_log_path
for rel_path, abs_path in meta_files_map.items():
file_entries.append((abs_path, rel_path))
sha = calculate_file_sha256(abs_path)
files_sha256[rel_path] = sha
uncompressed_bytes += os.path.getsize(abs_path)
# Manifest preparation
manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id=snapshot_id,
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
hostname=socket.gethostname(),
profile=args.profile,
compression=compression,
os=os_info.to_dict(),
package_manager=inspector.package_manager.get_manager_name(),
package_count=len(packages),
included_paths=included_paths,
stats={
"file_count": len(file_entries),
"uncompressed_bytes": uncompressed_bytes,
"compressed_bytes": 0,
"sanitized_count": len(sanitized_files)
},
files_sha256=files_sha256
)
# Pass 2: Create archive with manifest.json as the very first member
archive_path = archiver.create_snapshot_archive(snapshot_id, manifest, file_entries)
finally:
shutil.rmtree(temp_meta_dir, ignore_errors=True)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to create snapshot archive: {e}\n")
return EXIT_GENERIC_ERROR
finally:
lock.release()
# Post-snapshot automatic retention pruning if configured
keep_last = getattr(args, "keep_last", 0) or profile.retention_keep_last
keep_daily = getattr(args, "keep_daily", 0) or profile.retention_keep_daily
keep_weekly = getattr(args, "keep_weekly", 0) or profile.retention_keep_weekly
keep_monthly = getattr(args, "keep_monthly", 0) or profile.retention_keep_monthly
auto_pruned_count = 0
if any([keep_last > 0, keep_daily > 0, keep_weekly > 0, keep_monthly > 0]):
retention = RetentionEngine(
keep_last=keep_last,
keep_daily=keep_daily,
keep_weekly=keep_weekly,
keep_monthly=keep_monthly
)
existing_snaps = archiver.list_snapshots()
_, to_prune = retention.calculate_prune_set(existing_snaps)
if to_prune:
prune_res = retention.execute_prune(to_prune, target_dir=target_dir, dry_run=False, pid_path=pid_path)
auto_pruned_count = len(prune_res)
if not args.json:
sys.stdout.write(f"[INFO] Automatically pruned {auto_pruned_count} old snapshot(s) per retention policy.\n")
# Remote push if requested (--push <target>)
remote_push_result = None
remote_push_error = None
push_target = getattr(args, "push", None)
if push_target:
try:
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
config_data = None
if os.path.isfile(config_path):
try:
with open(config_path, "r", encoding="utf-8") as f:
config_data = json.load(f)
except Exception:
pass
ssh_key = getattr(args, "ssh_key", None)
transport = TransportFactory.get_transport(push_target, config=config_data, ssh_key=ssh_key)
if not args.json:
sys.stdout.write(f"[INFO] Initiating remote transfer to '{push_target}'...\n")
remote_push_result = transport.push(archive_path)
# Remote retention
rem_retention = RetentionEngine(
keep_last=getattr(args, "remote_keep_last", 0) or 0,
keep_daily=getattr(args, "remote_keep_daily", 0) or 0,
keep_weekly=getattr(args, "remote_keep_weekly", 0) or 0,
keep_monthly=getattr(args, "remote_keep_monthly", 0) or 0
)
if rem_retention.is_active():
prune_res = transport.prune_remote(rem_retention)
remote_push_result["remote_pruned"] = prune_res
if not args.json:
sys.stdout.write(f"[INFO] Pruned {len(prune_res)} remote snapshot(s) per retention policy.\n")
if not args.json:
sys.stdout.write(f"[SUCCESS] Remote push completed: {push_target}\n")
except TransportError as e:
remote_push_error = str(e)
sys.stderr.write(f"[WARNING] Local snapshot succeeded, but remote push to '{push_target}' failed: {e}\n")
if args.json:
output_payload = {
"snapshot_id": snapshot_id,
"archive_path": archive_path,
"profile": args.profile,
"files_count": len(file_entries),
"uncompressed_bytes": uncompressed_bytes,
"compressed_bytes": manifest.stats.get("compressed_bytes", 0),
"auto_pruned_count": auto_pruned_count,
"remote_push": remote_push_result,
"remote_push_error": remote_push_error,
"status": "success"
}
print(json.dumps(output_payload, indent=2))
else:
size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f"[SUCCESS] Snapshot created successfully: {archive_path} ({size_mb:.2f} MB, {len(file_entries)} files)\n")
return EXIT_SUCCESS
def handle_list(args: argparse.Namespace) -> int:
"""Execute list command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archiver = SnapshotArchiver(target_dir=target_dir)
try:
snapshots = archiver.list_snapshots()
except PermissionError as e:
sys.stderr.write(f"[ERROR] {e} (try running with sudo).\n")
return EXIT_PERM_DENIED
if args.json:
result = [s.to_dict() for s in snapshots]
print(json.dumps(result, indent=2))
return EXIT_SUCCESS
if not snapshots:
sys.stdout.write(f"No snapshots found in {target_dir}.\n")
return EXIT_SUCCESS
sys.stdout.write(f"{'SNAPSHOT ID':<40} {'PROFILE':<10} {'FILES':<8} {'SIZE (MB)':<10} {'CREATED AT':<25}\n")
sys.stdout.write("-" * 95 + "\n")
for s in snapshots:
size_mb = s.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f"{s.snapshot_id:<40} {s.profile:<10} {s.stats.get('file_count', 0):<8} {size_mb:<10.2f} {s.created_at[:19]:<25}\n")
return EXIT_SUCCESS
def handle_verify(args: argparse.Namespace) -> int:
"""Execute verify command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
snapshot_id = args.snapshot_id
# Resolve filename
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
filename = snapshot_id
else:
candidate_tar = os.path.join(target_dir, f"{snapshot_id}.tar") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar"
candidate_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz") if not os.path.isabs(snapshot_id) else f"{snapshot_id}.tar.gz"
if os.path.exists(candidate_tar) and not os.path.exists(candidate_gz):
filename = f"{snapshot_id}.tar"
else:
filename = f"{snapshot_id}.tar.gz"
archive_path = os.path.join(target_dir, filename) if not os.path.isabs(filename) else filename
is_valid, msg = SnapshotArchiver.verify_archive(archive_path)
if args.json:
print(json.dumps({"snapshot_id": snapshot_id, "valid": is_valid, "message": msg}, indent=2))
else:
if is_valid:
sys.stdout.write(f"[SUCCESS] {msg}: {archive_path}\n")
else:
sys.stderr.write(f"[ERROR] Integrity check failed: {msg}\n")
return EXIT_SUCCESS if is_valid else EXIT_CORRUPTED
def handle_show(args: argparse.Namespace) -> int:
"""Execute show command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
if not os.path.isfile(archive_path):
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
return EXIT_GENERIC_ERROR
try:
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to read manifest: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
payload = manifest.to_dict()
payload["archive_path"] = archive_path
if args.packages:
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
payload["packages_dump"] = pkg_txt.splitlines() if pkg_txt else []
print(json.dumps(payload, indent=2))
return EXIT_SUCCESS
size_mb = manifest.stats.get("compressed_bytes", 0) / (1024 * 1024)
uncomp_mb = manifest.stats.get("uncompressed_bytes", 0) / (1024 * 1024)
os_name = manifest.os.get("distro_name", "Linux")
os_ver = manifest.os.get("version_id", "")
arch = manifest.os.get("arch", "")
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"Snapshot ID: {manifest.snapshot_id}\n")
sys.stdout.write(f"Archive File: {archive_path}\n")
sys.stdout.write(f"Created At: {manifest.created_at}\n")
sys.stdout.write(f"Hostname: {manifest.hostname}\n")
sys.stdout.write(f"Operating System: {os_name} {os_ver} ({arch})\n")
sys.stdout.write(f"Profile: {manifest.profile}\n")
sys.stdout.write(f"Compression: {manifest.compression}\n")
sys.stdout.write(f"File Count: {manifest.stats.get('file_count', 0)}\n")
sys.stdout.write(f"Size on Disk: {size_mb:.2f} MB (uncompressed: {uncomp_mb:.2f} MB)\n")
sys.stdout.write(f"Package Manager: {manifest.package_manager} ({manifest.package_count} packages recorded)\n")
sys.stdout.write(f"Included Paths: {', '.join(manifest.included_paths)}\n")
if manifest.stats.get("sanitized_count"):
sys.stdout.write(f"Sanitized Files: {manifest.stats.get('sanitized_count')} (secrets redacted)\n")
sys.stdout.write("=" * 80 + "\n")
if args.files:
sys.stdout.write("\nArchived files:\n")
for f in sorted(manifest.files_sha256.keys()):
sys.stdout.write(f" {f}\n")
if args.packages:
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
if pkg_txt:
sys.stdout.write("\nArchived packages:\n")
sys.stdout.write(pkg_txt + "\n")
return EXIT_SUCCESS
def handle_diff(args: argparse.Namespace) -> int:
"""Execute diff command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
engine = DiffEngine(target_dir=target_dir)
try:
if args.snapshot_id_2:
result = engine.diff_snapshots(args.snapshot_id, args.snapshot_id_2)
else:
target_root = getattr(args, "target_root", "/") or "/"
result = engine.diff_with_live(args.snapshot_id, target_root=target_root)
except Exception as e:
sys.stderr.write(f"[ERROR] Diff failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps(result, indent=2))
return EXIT_SUCCESS
if result["type"] == "live_vs_snapshot":
sys.stdout.write(f"--- Live System vs Snapshot '{result['snapshot_id']}' ---\n")
files = result["files"]
if files["modified"]:
sys.stdout.write(f"\nModified files on live system ({len(files['modified'])}):\n")
for f in files["modified"]:
sys.stdout.write(f" [M] {f}\n")
if args.unified:
u_diff = engine.generate_unified_file_diff(result["snapshot_id"], f, target_root=result["target_root"])
if u_diff:
sys.stdout.write(u_diff + "\n")
if files["missing_on_live"]:
sys.stdout.write(f"\nMissing files on live system (present in backup) ({len(files['missing_on_live'])}):\n")
for f in files["missing_on_live"]:
sys.stdout.write(f" [-] {f}\n")
if files["added_on_live"]:
sys.stdout.write(f"\nAdded files on live system (not in backup) ({len(files['added_on_live'])}):\n")
for f in files["added_on_live"]:
sys.stdout.write(f" [+] {f}\n")
sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n")
pkgs = result["packages"]
if pkgs["installed_since_backup"]:
sys.stdout.write(f"\nPackages installed since backup ({len(pkgs['installed_since_backup'])}):\n")
for p, v in list(pkgs["installed_since_backup"].items())[:20]:
sys.stdout.write(f" + {p} ({v})\n")
if len(pkgs["installed_since_backup"]) > 20:
sys.stdout.write(f" ... and {len(pkgs['installed_since_backup']) - 20} more\n")
if pkgs["removed_since_backup"]:
sys.stdout.write(f"\nPackages removed since backup ({len(pkgs['removed_since_backup'])}):\n")
for p, v in list(pkgs["removed_since_backup"].items())[:20]:
sys.stdout.write(f" - {p} ({v})\n")
if pkgs["version_changed"]:
sys.stdout.write(f"\nPackages with changed versions ({len(pkgs['version_changed'])}):\n")
for p, ch in list(pkgs["version_changed"].items())[:20]:
sys.stdout.write(f" ~ {p}: {ch['snapshot']} -> {ch['live']}\n")
else:
sys.stdout.write(f"--- Snapshot '{result['snapshot_1']}' vs Snapshot '{result['snapshot_2']}' ---\n")
files = result["files"]
if files["modified"]:
sys.stdout.write(f"\nModified files ({len(files['modified'])}):\n")
for f in files["modified"]:
sys.stdout.write(f" [M] {f}\n")
if files["added"]:
sys.stdout.write(f"\nFiles added in snapshot 2 ({len(files['added'])}):\n")
for f in files["added"]:
sys.stdout.write(f" [+] {f}\n")
if files["removed"]:
sys.stdout.write(f"\nFiles removed in snapshot 2 ({len(files['removed'])}):\n")
for f in files["removed"]:
sys.stdout.write(f" [-] {f}\n")
sys.stdout.write(f"\nUnchanged files: {files['unchanged_count']}\n")
return EXIT_SUCCESS
def handle_extract(args: argparse.Namespace) -> int:
"""Execute extract command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
if not os.path.isfile(archive_path):
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
return EXIT_GENERIC_ERROR
try:
out_path = SnapshotArchiver.extract_file(archive_path, args.file, args.out)
except Exception as e:
sys.stderr.write(f"[ERROR] Extract failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps({
"status": "success",
"snapshot_id": args.snapshot_id,
"file": args.file,
"destination": out_path
}, indent=2))
else:
sys.stdout.write(f"[SUCCESS] Extracted '{args.file}' to '{out_path}'\n")
return EXIT_SUCCESS
def handle_restore(args: argparse.Namespace) -> int:
"""Execute restore command."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
target_root = getattr(args, "target_root", "/") or "/"
force = getattr(args, "force", False)
dry_run = getattr(args, "dry_run", False)
include_fstab = getattr(args, "include_fstab", False)
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
# If live mutation requested, require root unless non-root override
if force and not dry_run and os.geteuid() != 0 and not os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT"):
sys.stderr.write("[ERROR] Restoring files to live system requires root privileges (run with sudo).\n")
return EXIT_PERM_DENIED
engine = SafeRestoreEngine(target_dir=target_dir)
try:
plan = engine.plan_restore(args.snapshot_id, target_root=target_root, include_fstab=include_fstab)
except Exception as e:
sys.stderr.write(f"[ERROR] Failed to plan restore: {e}\n")
return EXIT_GENERIC_ERROR
# If --dry-run or not --force
if dry_run or not force:
if args.json:
out_dict = plan.to_dict()
out_dict["mode"] = "dry-run"
print(json.dumps(out_dict, indent=2))
else:
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"RESTORE EXECUTION PLAN (Dry Run) — Snapshot: {plan.snapshot_id}\n")
sys.stdout.write(f"Target Root: {plan.target_root}\n")
sys.stdout.write("=" * 80 + "\n")
create_items = [i for i in plan.items if i.action == "create"]
modify_items = [i for i in plan.items if i.action == "modify"]
skip_items = [i for i in plan.items if i.action == "skip"]
network_items = [i for i in plan.items if i.is_sensitive_network and i.action in ("create", "modify")]
if network_items:
sys.stdout.write("\n[WARNING] SENSITIVE NETWORK CONFIGURATION DETECTED:\n")
for item in network_items:
sys.stdout.write(f" ! {item.abs_path} will be overwritten\n")
sys.stdout.write(" Restoring network files may impact active network connectivity.\n\n")
if create_items:
sys.stdout.write(f"Files to CREATE ({len(create_items)}):\n")
for item in create_items:
sys.stdout.write(f" [+] {item.abs_path}\n")
if modify_items:
sys.stdout.write(f"\nFiles to MODIFY ({len(modify_items)}):\n")
for item in modify_items:
sys.stdout.write(f" [~] {item.abs_path}\n")
if skip_items:
sys.stdout.write(f"\nFiles to SKIP ({len(skip_items)}):\n")
for item in skip_items:
sys.stdout.write(f" [*] {item.abs_path} ({item.reason})\n")
sys.stdout.write("-" * 80 + "\n")
sys.stdout.write(f"Summary: {len(create_items)} to create, {len(modify_items)} to modify, {len(skip_items)} skipped.\n")
sys.stdout.write("[NOTICE] Dry run completed without modifying filesystem blocks.\n")
sys.stdout.write("[ACTION] Pass --force to execute live restore (automatic safety snapshot will be created).\n")
return EXIT_DRY_RUN
# Live restore with --force
if not args.json:
sys.stdout.write(f"[INFO] Initiating live restore for snapshot '{plan.snapshot_id}'...\n")
sys.stdout.write(f"[INFO] Target root directory: {plan.target_root}\n")
try:
res = engine.execute_restore(plan, force=True, pid_path=pid_path)
except Exception as e:
sys.stderr.write(f"[ERROR] Restore failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps(res, indent=2))
else:
sys.stdout.write(f"[SUCCESS] Safety snapshot created: {res['safety_snapshot_id']}\n")
sys.stdout.write(f"[SUCCESS] Restored {res['restored_count']} files to {plan.target_root}\n")
if res.get("selinux_context_restored"):
sys.stdout.write("[INFO] Restored SELinux security contexts via restorecon.\n")
return EXIT_SUCCESS
def handle_prune(args: argparse.Namespace) -> int:
"""Execute prune command based on retention rules."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
force = getattr(args, "force", False)
dry_run = getattr(args, "dry_run", False) or not force
pid_path = getattr(args, "pid_path", None) or os.environ.get("LINUX_BACKUPER_PID_PATH") or DEFAULT_PID_PATH
# If force delete requested, check root permission
if force and not dry_run and not check_root_permissions():
sys.stderr.write("[ERROR] Pruning snapshots requires root privileges (run with sudo).\n")
return EXIT_PERM_DENIED
archiver = SnapshotArchiver(target_dir=target_dir)
snapshots = archiver.list_snapshots()
retention = RetentionEngine(
keep_last=args.keep_last,
keep_daily=args.keep_daily,
keep_weekly=args.keep_weekly,
keep_monthly=args.keep_monthly
)
if not retention.is_active():
sys.stderr.write("[ERROR] No retention rules specified. Please specify at least one of: --keep-last, --keep-daily, --keep-weekly, --keep-monthly.\n")
return EXIT_GENERIC_ERROR
kept, pruned = retention.calculate_prune_set(snapshots)
results = retention.execute_prune(pruned, target_dir=target_dir, dry_run=dry_run, pid_path=pid_path)
total_freed_bytes = sum(r.get("freed_bytes", 0) for r in results)
freed_mb = total_freed_bytes / (1024 * 1024)
if args.json:
payload = {
"mode": "dry-run" if dry_run else "live",
"total_snapshots": len(snapshots),
"kept_count": len(kept),
"pruned_count": len(pruned),
"freed_bytes": total_freed_bytes,
"kept": [s.snapshot_id for s in kept],
"pruned": results
}
print(json.dumps(payload, indent=2))
return EXIT_SUCCESS
sys.stdout.write("=" * 80 + "\n")
mode_label = "DRY RUN (simulation)" if dry_run else "LIVE PRUNE"
sys.stdout.write(f"RETENTION PRUNE PLAN — {mode_label}\n")
sys.stdout.write(f"Target Directory: {target_dir}\n")
sys.stdout.write(f"Rules: keep-last={args.keep_last}, keep-daily={args.keep_daily}, keep-weekly={args.keep_weekly}, keep-monthly={args.keep_monthly}\n")
sys.stdout.write("=" * 80 + "\n")
sys.stdout.write(f"\nSnapshots to KEEP ({len(kept)}):\n")
for s in kept:
size_mb = s.stats.get("compressed_bytes", 0) / (1024 * 1024)
sys.stdout.write(f" [KEEP] {s.snapshot_id:<45} ({size_mb:.2f} MB, {s.created_at[:19]})\n")
if pruned:
sys.stdout.write(f"\nSnapshots to PRUNE ({len(pruned)}):\n")
for r in results:
mb = r.get("freed_bytes", 0) / (1024 * 1024)
action_tag = "[WOULD DELETE]" if dry_run else "[DELETED]"
sys.stdout.write(f" {action_tag} {r['snapshot_id']:<45} ({mb:.2f} MB freed)\n")
else:
sys.stdout.write("\nNo snapshots qualify for pruning under current retention rules.\n")
sys.stdout.write("-" * 80 + "\n")
sys.stdout.write(f"Summary: Keeping {len(kept)} snapshots, pruning {len(pruned)} snapshots ({freed_mb:.2f} MB disk space).\n")
if dry_run and pruned:
sys.stdout.write("[NOTICE] Dry run completed without deleting files. Pass --force to execute deletion.\n")
elif not dry_run and pruned:
sys.stdout.write(f"[SUCCESS] Successfully pruned {len(pruned)} snapshot(s).\n")
return EXIT_SUCCESS
def handle_push(args: argparse.Namespace) -> int:
"""Execute push command to transfer snapshot to remote destination."""
target_dir = args.target_dir or DEFAULT_BACKUP_DIR
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, args.snapshot_id)
if not os.path.isfile(archive_path):
sys.stderr.write(f"[ERROR] Snapshot archive not found: {archive_path}\n")
return EXIT_GENERIC_ERROR
# Load optional config
config_path = getattr(args, "config", None) or DEFAULT_CONFIG_PATH
config_data = None
if os.path.isfile(config_path):
try:
with open(config_path, "r", encoding="utf-8") as f:
config_data = json.load(f)
except Exception:
pass
try:
ssh_key = getattr(args, "ssh_key", None)
transport = TransportFactory.get_transport(args.target, config=config_data, ssh_key=ssh_key)
if not args.json:
sys.stdout.write(f"[INFO] Transferring snapshot to '{args.target}'...\n")
push_res = transport.push(archive_path)
# Check if remote retention requested
rem_retention = RetentionEngine(
keep_last=getattr(args, "remote_keep_last", 0) or 0,
keep_daily=getattr(args, "remote_keep_daily", 0) or 0,
keep_weekly=getattr(args, "remote_keep_weekly", 0) or 0,
keep_monthly=getattr(args, "remote_keep_monthly", 0) or 0
)
if rem_retention.is_active():
if not args.json:
sys.stdout.write("[INFO] Applying retention policy to remote destination...\n")
prune_res = transport.prune_remote(rem_retention)
push_res["remote_pruned"] = prune_res
except TransportError as e:
sys.stderr.write(f"[ERROR] Transport sync failed: {e}\n")
return EXIT_GENERIC_ERROR
if args.json:
print(json.dumps(push_res, indent=2))
else:
mb = push_res.get("bytes_transferred", 0) / (1024 * 1024)
sys.stdout.write(f"[SUCCESS] Snapshot pushed successfully to '{args.target}' ({mb:.2f} MB transferred, SHA-256 verified).\n")
if "remote_pruned" in push_res:
p_count = len(push_res["remote_pruned"])
sys.stdout.write(f"[INFO] Pruned {p_count} remote snapshot(s) per remote retention policy.\n")
return EXIT_SUCCESS
def build_parser() -> argparse.ArgumentParser:
"""Construct CLI argument parser."""
common_parser = argparse.ArgumentParser(add_help=False)
common_parser.add_argument("--json", action="store_true", help="Output machine-readable JSON to stdout")
common_parser.add_argument("--verbose", action="store_true", help="Enable detailed diagnostic logging")
parser = argparse.ArgumentParser(
prog="linux-backuper",
description="Enterprise Linux system snapshot and configuration backup utility.",
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[common_parser]
)
parser.add_argument("-v", "--version", action="version", version=f"%(prog)s {__version__}")
subparsers = parser.add_subparsers(dest="subcommand", help="Available sub-commands")
# Snapshot command
snap_parser = subparsers.add_parser("snapshot", help="Capture a new system state snapshot", parents=[common_parser])
snap_parser.add_argument("--profile", default="quick", help="Backup profile (default: quick)")
snap_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help=f"Destination directory (default: {DEFAULT_BACKUP_DIR})")
snap_parser.add_argument("--paths", nargs="+", help="Specific directories or files to include in snapshot")
snap_parser.add_argument("--compression", choices=["gzip", "none"], default="gzip", help="Compression algorithm")
snap_parser.add_argument("--no-compression", action="store_true", help="Store plain uncompressed tar archive")
snap_parser.add_argument("--sanitize", action="store_true", help="Redact secrets and private keys for diagnostic export")
snap_parser.add_argument("--config", help=f"Path to JSON configuration file (default: {DEFAULT_CONFIG_PATH})")
snap_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
snap_parser.add_argument("--keep-last", type=int, default=0, help="Prune old backups, keeping N latest snapshots")
snap_parser.add_argument("--keep-daily", type=int, default=0, help="Prune old backups, keeping latest snapshot for D days")
snap_parser.add_argument("--keep-weekly", type=int, default=0, help="Prune old backups, keeping latest snapshot for W weeks")
snap_parser.add_argument("--keep-monthly", type=int, default=0, help="Prune old backups, keeping latest snapshot for M months")
snap_parser.add_argument("--push", help="Transfer snapshot to remote destination after local creation")
snap_parser.add_argument("--ssh-key", help="Private SSH key path for remote authentication")
snap_parser.add_argument("--remote-keep-last", type=int, default=0, help="Remote retention: keep N latest snapshots")
snap_parser.add_argument("--remote-keep-daily", type=int, default=0, help="Remote retention: keep D daily snapshots")
snap_parser.add_argument("--remote-keep-weekly", type=int, default=0, help="Remote retention: keep W weekly snapshots")
snap_parser.add_argument("--remote-keep-monthly", type=int, default=0, help="Remote retention: keep M monthly snapshots")
# List command
list_parser = subparsers.add_parser("list", help="List existing local snapshots", parents=[common_parser])
list_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory to scan for snapshots")
# Show command
show_parser = subparsers.add_parser("show", help="Display details and metadata of a snapshot", parents=[common_parser])
show_parser.add_argument("snapshot_id", help="Snapshot ID or filename to display")
show_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
show_parser.add_argument("--packages", action="store_true", help="List all recorded installed packages")
show_parser.add_argument("--files", action="store_true", help="List all archived file paths")
# Diff command
diff_parser = subparsers.add_parser("diff", help="Compare live system against snapshot, or two snapshots", parents=[common_parser])
diff_parser.add_argument("snapshot_id", help="First snapshot ID (or base snapshot for live diff)")
diff_parser.add_argument("snapshot_id_2", nargs="?", default=None, help="Second snapshot ID (optional, compares two snapshots)")
diff_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots")
diff_parser.add_argument("--target-root", default="/", help="Filesystem root to compare against in live diff (default: /)")
diff_parser.add_argument("--unified", "-u", action="store_true", help="Display unified diff for modified text files")
# Extract command
extract_parser = subparsers.add_parser("extract", help="Selectively extract a single file from a snapshot", parents=[common_parser])
extract_parser.add_argument("snapshot_id", help="Snapshot ID or filename")
extract_parser.add_argument("--file", required=True, help="File path inside snapshot to extract")
extract_parser.add_argument("--out", required=True, help="Destination file or directory path")
extract_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
# Restore command
restore_parser = subparsers.add_parser("restore", help="Restore system configuration from a snapshot", parents=[common_parser])
restore_parser.add_argument("snapshot_id", help="Snapshot ID to restore")
restore_parser.add_argument("--dry-run", action="store_true", help="Display execution plan without modifying filesystem (exit code 5)")
restore_parser.add_argument("--force", action="store_true", help="Execute live restoration (safety snapshot created automatically)")
restore_parser.add_argument("--target-root", default="/", help="Target root directory to restore onto (default: /)")
restore_parser.add_argument("--include-fstab", action="store_true", help="Allow restoring /etc/fstab")
restore_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the snapshot")
restore_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
# Prune command
prune_parser = subparsers.add_parser("prune", help="Prune old snapshots based on retention policies", parents=[common_parser])
prune_parser.add_argument("--keep-last", type=int, default=0, help="Keep N most recent snapshots")
prune_parser.add_argument("--keep-daily", type=int, default=0, help="Keep most recent snapshot for D distinct days")
prune_parser.add_argument("--keep-weekly", type=int, default=0, help="Keep most recent snapshot for W distinct weeks")
prune_parser.add_argument("--keep-monthly", type=int, default=0, help="Keep most recent snapshot for M distinct months")
prune_parser.add_argument("--dry-run", action="store_true", help="Simulate pruning plan without deleting files")
prune_parser.add_argument("--force", action="store_true", help="Confirm deletion of pruned snapshot archives")
prune_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing snapshots")
prune_parser.add_argument("--pid-path", help=f"Path to lockfile PID file (default: {DEFAULT_PID_PATH})")
# Push command
push_parser = subparsers.add_parser("push", help="Push an existing snapshot to remote storage", parents=[common_parser])
push_parser.add_argument("snapshot_id", help="Snapshot ID or archive filename to push")
push_parser.add_argument("--target", required=True, help="Remote destination (e.g. /mnt/nas or user@host:/path or alias)")
push_parser.add_argument("--ssh-key", help="Private SSH key path for authentication")
push_parser.add_argument("--remote-keep-last", type=int, default=0, help="Remote retention: keep N latest snapshots")
push_parser.add_argument("--remote-keep-daily", type=int, default=0, help="Remote retention: keep D daily snapshots")
push_parser.add_argument("--remote-keep-weekly", type=int, default=0, help="Remote retention: keep W weekly snapshots")
push_parser.add_argument("--remote-keep-monthly", type=int, default=0, help="Remote retention: keep M monthly snapshots")
push_parser.add_argument("--target-dir", default=DEFAULT_BACKUP_DIR, help="Directory containing the local snapshot")
push_parser.add_argument("--config", help=f"Path to JSON configuration file (default: {DEFAULT_CONFIG_PATH})")
# Verify command
verify_parser = subparsers.add_parser("verify", help="Verify snapshot cryptographic integrity", parents=[common_parser])
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()
args = parser.parse_args(argv)
if not args.subcommand:
parser.print_help()
return EXIT_SUCCESS
if args.subcommand == "snapshot":
return handle_snapshot(args)
elif args.subcommand == "list":
return handle_list(args)
elif args.subcommand == "show":
return handle_show(args)
elif args.subcommand == "diff":
return handle_diff(args)
elif args.subcommand == "extract":
return handle_extract(args)
elif args.subcommand == "restore":
return handle_restore(args)
elif args.subcommand == "prune":
return handle_prune(args)
elif args.subcommand == "push":
return handle_push(args)
elif args.subcommand == "verify":
return handle_verify(args)
elif args.subcommand == "completion":
return handle_completion(args)
return EXIT_SUCCESS
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
"""Core modules for linux-backuper."""
+429
View File
@@ -0,0 +1,429 @@
"""Archive creation, extraction, and verification using Python standard library."""
import gzip
import hashlib
import json
import os
import stat
import tarfile
import time
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.models import SnapshotManifest
BUFFER_SIZE = 64 * 1024 # 64 KB chunks for hashing and streaming
def calculate_file_sha256(filepath: str) -> str:
"""Calculate SHA-256 checksum of a file."""
hasher = hashlib.sha256()
with open(filepath, "rb") as f:
while chunk := f.read(BUFFER_SIZE):
hasher.update(chunk)
return hasher.hexdigest()
def is_socket_or_fifo(filepath: str) -> bool:
"""Check if path is a UNIX socket, named pipe (FIFO) or character device."""
try:
st = os.lstat(filepath)
return stat.S_ISSOCK(st.st_mode) or stat.S_ISFIFO(st.st_mode)
except OSError:
return False
def is_sanitized_target(filepath: str) -> bool:
"""Check if file contains secrets and must be omitted during sanitized export."""
name = os.path.basename(filepath)
if name in ("shadow", "gshadow", "opasswd", "shadow-", "gshadow-"):
return True
if name.startswith("ssh_host_") and "key" in name and not name.endswith(".pub"):
return True
return False
class SnapshotArchiver:
"""Manages creation, listing, and verification of snapshot archives."""
def __init__(self, target_dir: str, compression: str = "gzip"):
self.target_dir = target_dir
self.compression = "gzip" if compression in ("gz", "gzip") else "none"
def _ensure_target_dir() -> None:
pass
def _ensure_target_dir_inst(self) -> None:
"""Ensure target directory exists with 0700 permissions."""
os.makedirs(self.target_dir, exist_ok=True)
try:
os.chmod(self.target_dir, 0o700)
except OSError:
pass
def collect_file_list(
self,
paths: List[str],
exclude_patterns: Optional[List[str]] = None,
sanitize: bool = False,
one_file_system: bool = True,
max_file_size_mb: int = 50
) -> Tuple[List[Tuple[str, str]], Dict[str, str], int, List[str]]:
"""
Scan paths and compute pre-archive hashes and metadata.
Returns:
- list of (filesystem_abs_path, tar_rel_path)
- dict of {tar_rel_path: sha256_hash}
- total uncompressed bytes
- list of sanitized/redacted relative paths
"""
file_entries: List[Tuple[str, str]] = []
files_sha256: Dict[str, str] = {}
sanitized_files: List[str] = []
total_bytes = 0
exclude_patterns = exclude_patterns or []
for base_path in paths:
abs_base = os.path.abspath(base_path)
if not os.path.exists(abs_base):
continue
try:
base_st = os.lstat(abs_base)
base_dev = base_st.st_dev
except OSError:
continue
if os.path.isfile(abs_base) or os.path.islink(abs_base):
rel_name = os.path.join("data", os.path.basename(abs_base))
if sanitize and is_sanitized_target(abs_base):
sanitized_files.append(rel_name)
continue
if not is_socket_or_fifo(abs_base):
file_entries.append((abs_base, rel_name))
if not os.path.islink(abs_base):
sha = calculate_file_sha256(abs_base)
files_sha256[rel_name] = sha
total_bytes += os.path.getsize(abs_base)
continue
# Directory tree traversal
for root, dirs, files in os.walk(abs_base, followlinks=False):
# Filter subdirectories in place
dirs[:] = [d for d in dirs if not any(p in d for p in exclude_patterns)]
# Check one-file-system boundary for subdirectories
if one_file_system:
allowed_dirs = []
for d in dirs:
dir_path = os.path.join(root, d)
try:
if os.lstat(dir_path).st_dev == base_dev:
allowed_dirs.append(d)
except OSError:
pass
dirs[:] = allowed_dirs
for filename in files:
abs_filepath = os.path.join(root, filename)
if any(p in filename for p in exclude_patterns):
continue
# One file system boundary check
try:
st = os.lstat(abs_filepath)
if one_file_system and st.st_dev != base_dev:
continue
except OSError:
continue
# Large file check (> 50 MB)
if max_file_size_mb > 0 and st.st_size > (max_file_size_mb * 1024 * 1024):
continue
rel_to_base = os.path.relpath(abs_filepath, os.path.dirname(abs_base))
arc_path = os.path.join("data", rel_to_base)
# Diagnostic sanitization check
if sanitize and is_sanitized_target(abs_filepath):
sanitized_files.append(arc_path)
continue
if is_socket_or_fifo(abs_filepath):
continue
file_entries.append((abs_filepath, arc_path))
if not os.path.islink(abs_filepath):
try:
sha = calculate_file_sha256(abs_filepath)
files_sha256[arc_path] = sha
total_bytes += st.st_size
except (OSError, IOError):
pass
return file_entries, files_sha256, total_bytes, sanitized_files
def create_snapshot_archive(
self,
snapshot_id: str,
manifest: SnapshotManifest,
file_entries: List[Tuple[str, str]]
) -> str:
"""
Create atomic .tar.gz archive with manifest.json as the very first member.
Enforces 0600 file permissions.
"""
self._ensure_target_dir_inst()
ext = ".tar.gz" if self.compression == "gzip" else ".tar"
final_archive_path = os.path.join(self.target_dir, f"{snapshot_id}{ext}")
temp_archive_path = os.path.join(self.target_dir, f".{snapshot_id}.tmp{ext}")
# Encode manifest JSON bytes
manifest_dict = manifest.to_dict()
manifest_bytes = json.dumps(manifest_dict, indent=2, sort_keys=True).encode("utf-8")
# Open temp archive for writing with gzip or plain tar
tar_mode = "w:gz" if self.compression == "gzip" else "w:"
with tarfile.open(temp_archive_path, tar_mode) as tar:
# 1. ADD MANIFEST.JSON AS THE VERY FIRST MEMBER
manifest_info = tarfile.TarInfo(name="manifest.json")
manifest_info.size = len(manifest_bytes)
manifest_info.mtime = int(time.time())
manifest_info.mode = 0o600
manifest_info.type = tarfile.REGTYPE
import io
tar.addfile(tarinfo=manifest_info, fileobj=io.BytesIO(manifest_bytes))
# 2. ADD ALL COLLECTED DATA FILES
for abs_path, arc_path in file_entries:
try:
tar.add(abs_path, arcname=arc_path, recursive=False)
except (OSError, IOError):
pass
# Set strict 0600 permissions
try:
os.chmod(temp_archive_path, 0o600)
except OSError:
pass
# Atomic rename to final path
os.replace(temp_archive_path, final_archive_path)
# Update manifest compressed size stat
compressed_size = os.path.getsize(final_archive_path)
manifest.stats["compressed_bytes"] = compressed_size
return final_archive_path
@staticmethod
def read_manifest_from_archive(archive_path: str) -> SnapshotManifest:
"""
Read manifest.json from the first member of the archive stream.
Ultra-fast: avoids decompressing the rest of the archive.
"""
with tarfile.open(archive_path, "r:*") as tar:
first_member = tar.next()
if not first_member or first_member.name != "manifest.json":
# Fallback: scan for manifest.json if not first
member = tar.getmember("manifest.json")
else:
member = first_member
manifest_file = tar.extractfile(member)
if not manifest_file:
raise ValueError(f"Could not read manifest from {archive_path}")
data = json.loads(manifest_file.read().decode("utf-8"))
manifest = SnapshotManifest.from_dict(data)
if manifest.stats.get("compressed_bytes", 0) == 0 and os.path.isfile(archive_path):
manifest.stats["compressed_bytes"] = os.path.getsize(archive_path)
return manifest
@staticmethod
def verify_archive(archive_path: str) -> Tuple[bool, str]:
"""
Verify gzip stream integrity and all file SHA-256 checksums against manifest.json.
Returns (is_valid, error_message).
"""
if not os.path.isfile(archive_path):
return False, f"Archive not found: {archive_path}"
# 1. Check if file is gzip by inspecting header
is_gz = False
try:
with open(archive_path, "rb") as f:
header = f.read(2)
is_gz = (header == b"\x1f\x8b")
except OSError as e:
return False, f"Cannot open archive: {e}"
# If gzipped, verify complete stream integrity
if is_gz:
try:
with gzip.open(archive_path, "rb") as gz:
while gz.read(BUFFER_SIZE):
pass
except Exception as e:
return False, f"Gzip stream corrupted: {e}"
# 2. Manifest and member checksum verification
try:
with tarfile.open(archive_path, "r:*") as tar:
# Read manifest
try:
manifest_member = tar.getmember("manifest.json")
manifest_data = json.loads(tar.extractfile(manifest_member).read().decode("utf-8"))
except Exception as e:
return False, f"Invalid or missing manifest.json: {e}"
expected_hashes: Dict[str, str] = manifest_data.get("files_sha256", {})
for arc_name, expected_sha in expected_hashes.items():
try:
member = tar.getmember(arc_name)
except KeyError:
return False, f"Missing file in archive: {arc_name}"
if member.isreg():
f = tar.extractfile(member)
if not f:
return False, f"Unable to read file: {arc_name}"
hasher = hashlib.sha256()
while chunk := f.read(BUFFER_SIZE):
hasher.update(chunk)
actual_sha = hasher.hexdigest()
if actual_sha != expected_sha:
return False, f"Checksum mismatch for {arc_name}: expected {expected_sha}, got {actual_sha}"
except Exception as e:
return False, f"Tar archive corrupted: {e}"
return True, "Integrity verified successfully"
@staticmethod
def resolve_archive_path(target_dir: str, snapshot_id: str) -> str:
"""Resolve a snapshot ID or filename to full archive path."""
if os.path.isabs(snapshot_id) and os.path.exists(snapshot_id):
return snapshot_id
direct = os.path.join(target_dir, snapshot_id)
if os.path.exists(direct):
return direct
tar_gz = os.path.join(target_dir, f"{snapshot_id}.tar.gz")
if os.path.exists(tar_gz):
return tar_gz
tar_plain = os.path.join(target_dir, f"{snapshot_id}.tar")
if os.path.exists(tar_plain):
return tar_plain
if snapshot_id.endswith(".tar.gz") or snapshot_id.endswith(".tar"):
return direct
return tar_gz
@staticmethod
def read_meta_file(archive_path: str, meta_relative_path: str) -> Optional[str]:
"""Read a metadata text file from the archive (e.g. meta/packages.txt)."""
with tarfile.open(archive_path, "r:*") as tar:
try:
member = tar.getmember(meta_relative_path)
f = tar.extractfile(member)
if f:
return f.read().decode("utf-8", errors="replace")
except KeyError:
return None
return None
@staticmethod
def extract_file(archive_path: str, member_path: str, destination_path: str) -> str:
"""
Extract a single member from the archive to destination_path.
Guards strictly against Zip Slip / path traversal.
Returns final destination path.
"""
dest_abs = os.path.abspath(destination_path)
# If destination is an existing directory, append member filename
if os.path.isdir(dest_abs):
dest_abs = os.path.join(dest_abs, os.path.basename(member_path))
dest_dir = os.path.dirname(dest_abs)
if dest_dir:
os.makedirs(dest_dir, exist_ok=True)
with tarfile.open(archive_path, "r:*") as tar:
# Candidate names inside archive
candidates = [
member_path,
f"data/{member_path.lstrip('/')}",
member_path.lstrip("/"),
f"data{member_path}" if member_path.startswith("/") else f"data/{member_path}"
]
target_member = None
for c in candidates:
try:
target_member = tar.getmember(c)
break
except KeyError:
continue
if not target_member:
clean_target = member_path.strip("/")
for m in tar.getmembers():
if m.name == clean_target or m.name == f"data/{clean_target}":
target_member = m
break
if m.name.endswith(f"/{clean_target}") or m.name.endswith(clean_target):
target_member = m
break
if not target_member:
raise FileNotFoundError(f"File '{member_path}' not found in archive")
if not target_member.isreg():
raise ValueError(f"Member '{target_member.name}' is not a regular file")
f_in = tar.extractfile(target_member)
if not f_in:
raise IOError(f"Could not read member '{target_member.name}'")
tmp_dest = f"{dest_abs}.tmp.{os.getpid()}"
try:
with open(tmp_dest, "wb") as f_out:
while chunk := f_in.read(BUFFER_SIZE):
f_out.write(chunk)
try:
os.chmod(tmp_dest, target_member.mode)
except OSError:
pass
os.replace(tmp_dest, dest_abs)
finally:
if os.path.exists(tmp_dest):
try:
os.unlink(tmp_dest)
except OSError:
pass
return dest_abs
def list_snapshots(self) -> List[SnapshotManifest]:
"""List all valid snapshots in the target directory."""
if not os.path.isdir(self.target_dir):
return []
snapshots: List[SnapshotManifest] = []
try:
entries = sorted(os.listdir(self.target_dir), reverse=True)
except PermissionError:
raise PermissionError(f"Permission denied accessing backup directory: {self.target_dir}")
except OSError:
return []
for filename in entries:
if (filename.endswith(".tar.gz") or filename.endswith(".tar")) and not filename.startswith("."):
filepath = os.path.join(self.target_dir, filename)
try:
manifest = self.read_manifest_from_archive(filepath)
snapshots.append(manifest)
except Exception:
pass
return snapshots
+309
View File
@@ -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")
+18
View File
@@ -0,0 +1,18 @@
"""Constants and exit codes for linux-backuper."""
# Exit Codes
EXIT_SUCCESS = 0
EXIT_GENERIC_ERROR = 1
EXIT_PREFLIGHT_FAIL = 2
EXIT_CORRUPTED = 3
EXIT_PERM_DENIED = 4
EXIT_DRY_RUN = 5
# Default filesystem locations
DEFAULT_BACKUP_DIR = "/var/backups/linux-backuper"
DEFAULT_CONFIG_PATH = "/etc/linux-backuper.json"
DEFAULT_PID_PATH = "/var/run/linux-backuper.pid"
DEFAULT_LOG_DIR = "/var/log/linux-backuper"
# Minimum free disk space in megabytes for preflight check
MIN_FREE_DISK_MB = 1024
+66
View File
@@ -0,0 +1,66 @@
"""Linux distribution and operating system detector."""
import os
import platform
from typing import Dict, Optional
from linux_backuper.models import OsInfo
DEFAULT_OS_RELEASE_PATH = "/etc/os-release"
FALLBACK_OS_RELEASE_PATH = "/usr/lib/os-release"
def parse_os_release(content: str) -> Dict[str, str]:
"""Parse key-value pairs from os-release format string."""
data = {}
for line in content.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
if "=" in line:
key, val = line.split("=", 1)
key = key.strip().lower()
val = val.strip().strip("\"'")
data[key] = val
distro_id = data.get("id", "linux").lower()
distro_name = data.get("name", "Linux")
version_id = data.get("version_id", data.get("build_id", "rolling"))
return {
"id": distro_id,
"name": distro_name,
"version_id": version_id,
"id_like": data.get("id_like", "")
}
def detect_distro(os_release_path: Optional[str] = None) -> OsInfo:
"""Detect current operating system distribution and kernel release."""
content = ""
candidate_paths = [os_release_path] if os_release_path else [DEFAULT_OS_RELEASE_PATH, FALLBACK_OS_RELEASE_PATH]
for path in candidate_paths:
if path and os.path.isfile(path):
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
content = f.read()
break
except (OSError, IOError):
pass
if content:
parsed = parse_os_release(content)
distro_id = parsed["id"]
distro_name = parsed["name"]
version_id = parsed["version_id"]
else:
# Fallback for non-Linux or testing environments
distro_id = platform.system().lower()
distro_name = platform.system()
version_id = platform.release()
return OsInfo(
distro_id=distro_id,
distro_name=distro_name,
version_id=version_id,
kernel=platform.release(),
arch=platform.machine()
)
+248
View File
@@ -0,0 +1,248 @@
"""System and snapshot comparison engine (DiffEngine)."""
import difflib
import hashlib
import os
import tarfile
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, BUFFER_SIZE
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.inspector import SystemInspector
from linux_backuper.models import PackageItem, SnapshotManifest
MAX_DIFF_TEXT_BYTES = 1024 * 1024 # 1 MB threshold for generating unified diffs
class DiffEngine:
"""Computes differences between snapshots, and between live system and snapshot."""
def __init__(self, target_dir: str):
self.target_dir = target_dir
def _resolve_archive(self, snapshot_id: str) -> str:
archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id)
if not os.path.isfile(archive_path):
raise FileNotFoundError(f"Snapshot archive not found: {archive_path}")
return archive_path
@staticmethod
def _parse_packages_txt(content: Optional[str]) -> Dict[str, str]:
"""Parse meta/packages.txt lines into {name: version}."""
packages: Dict[str, str] = {}
if not content:
return packages
for line in content.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split()
if len(parts) >= 2:
packages[parts[0]] = parts[1]
elif len(parts) == 1:
packages[parts[0]] = "unknown"
return packages
def diff_snapshots(self, id1: str, id2: str) -> Dict[str, Any]:
"""
Compare two snapshots.
Returns detailed dictionary of file differences and package differences.
"""
path1 = self._resolve_archive(id1)
path2 = self._resolve_archive(id2)
m1 = SnapshotArchiver.read_manifest_from_archive(path1)
m2 = SnapshotArchiver.read_manifest_from_archive(path2)
hashes1 = {k: v for k, v in m1.files_sha256.items() if k.startswith("data/")}
hashes2 = {k: v for k, v in m2.files_sha256.items() if k.startswith("data/")}
keys1 = set(hashes1.keys())
keys2 = set(hashes2.keys())
added_files = sorted(list(keys2 - keys1))
removed_files = sorted(list(keys1 - keys2))
modified_files = sorted([k for k in (keys1 & keys2) if hashes1[k] != hashes2[k]])
unchanged_files = sorted([k for k in (keys1 & keys2) if hashes1[k] == hashes2[k]])
# Package comparison
pkg_txt1 = SnapshotArchiver.read_meta_file(path1, "meta/packages.txt")
pkg_txt2 = SnapshotArchiver.read_meta_file(path2, "meta/packages.txt")
pkgs1 = self._parse_packages_txt(pkg_txt1)
pkgs2 = self._parse_packages_txt(pkg_txt2)
p_keys1 = set(pkgs1.keys())
p_keys2 = set(pkgs2.keys())
pkgs_added = {p: pkgs2[p] for p in sorted(p_keys2 - p_keys1)}
pkgs_removed = {p: pkgs1[p] for p in sorted(p_keys1 - p_keys2)}
pkgs_changed = {}
for p in sorted(p_keys1 & p_keys2):
if pkgs1[p] != pkgs2[p]:
pkgs_changed[p] = {"old": pkgs1[p], "new": pkgs2[p]}
return {
"type": "snapshot_vs_snapshot",
"snapshot_1": m1.snapshot_id,
"snapshot_2": m2.snapshot_id,
"files": {
"added": added_files,
"removed": removed_files,
"modified": modified_files,
"unchanged_count": len(unchanged_files)
},
"packages": {
"added": pkgs_added,
"removed": pkgs_removed,
"changed": pkgs_changed
}
}
def diff_with_live(self, snapshot_id: str, target_root: str = "/") -> Dict[str, Any]:
"""
Compare live system state against a snapshot.
Checks:
- Files present in snapshot vs live filesystem under target_root
- Files added on live system in snapshot's included paths
- Live packages vs snapshot packages
"""
archive_path = self._resolve_archive(snapshot_id)
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
data_hashes = {k: v for k, v in manifest.files_sha256.items() if k.startswith("data/")}
missing_on_live: List[str] = []
modified_on_live: List[str] = []
unchanged_on_live: List[str] = []
file_diffs: Dict[str, str] = {}
target_root_clean = os.path.abspath(target_root)
for rel_data_path, archived_sha in data_hashes.items():
# rel_data_path is like 'data/etc/hosts'
clean_subpath = rel_data_path[5:].lstrip("/") # 'etc/hosts'
live_abs_path = os.path.join(target_root_clean, clean_subpath)
if not os.path.exists(live_abs_path) and not os.path.islink(live_abs_path):
missing_on_live.append("/" + clean_subpath)
continue
try:
live_sha = calculate_file_sha256(live_abs_path)
except OSError:
modified_on_live.append("/" + clean_subpath)
continue
if live_sha != archived_sha:
modified_on_live.append("/" + clean_subpath)
else:
unchanged_on_live.append("/" + clean_subpath)
# Check for added files on live system within included_paths
added_on_live: List[str] = []
for inc_path in manifest.included_paths:
if inc_path.startswith(target_root_clean):
live_scan_dir = inc_path
else:
live_scan_dir = os.path.join(target_root_clean, inc_path.lstrip("/"))
if not os.path.isdir(live_scan_dir):
continue
for root, _, files in os.walk(live_scan_dir):
for f in files:
full_p = os.path.join(root, f)
rel_to_target = os.path.relpath(full_p, target_root_clean)
archive_key = "data/" + rel_to_target.lstrip("/")
if archive_key not in data_hashes:
candidate_found = any(dk.endswith("/" + rel_to_target.lstrip("/")) for dk in data_hashes)
if not candidate_found:
added_on_live.append("/" + rel_to_target.lstrip("/"))
# Packages diff
pkg_txt = SnapshotArchiver.read_meta_file(archive_path, "meta/packages.txt")
archived_pkgs = self._parse_packages_txt(pkg_txt)
distro_id = manifest.os.get("distro_id", detect_distro().distro_id)
inspector = SystemInspector(distro_id=distro_id)
live_packages = inspector.inspect_packages()
live_pkgs_dict = {p.name: p.version for p in live_packages}
archived_keys = set(archived_pkgs.keys())
live_keys = set(live_pkgs_dict.keys())
pkgs_installed_since = {p: live_pkgs_dict[p] for p in sorted(live_keys - archived_keys)}
pkgs_removed_since = {p: archived_pkgs[p] for p in sorted(archived_keys - live_keys)}
pkgs_version_changed = {}
for p in sorted(archived_keys & live_keys):
if live_pkgs_dict[p] != archived_pkgs[p]:
pkgs_version_changed[p] = {
"snapshot": archived_pkgs[p],
"live": live_pkgs_dict[p]
}
return {
"type": "live_vs_snapshot",
"snapshot_id": manifest.snapshot_id,
"target_root": target_root_clean,
"files": {
"modified": sorted(modified_on_live),
"missing_on_live": sorted(missing_on_live),
"added_on_live": sorted(added_on_live),
"unchanged_count": len(unchanged_on_live)
},
"packages": {
"installed_since_backup": pkgs_installed_since,
"removed_since_backup": pkgs_removed_since,
"version_changed": pkgs_version_changed
}
}
def generate_unified_file_diff(
self,
snapshot_id: str,
file_path: str,
target_root: str = "/"
) -> Optional[str]:
"""
Generate unified diff for a single file between snapshot and live filesystem.
Returns unified diff string, or None if files are binary or identical.
"""
archive_path = self._resolve_archive(snapshot_id)
clean_subpath = file_path.lstrip("/")
archive_member = f"data/{clean_subpath}"
live_path = os.path.join(os.path.abspath(target_root), clean_subpath)
archived_content: Optional[str] = None
with tarfile.open(archive_path, "r:*") as tar:
try:
member = tar.getmember(archive_member)
if member.isreg() and member.size <= MAX_DIFF_TEXT_BYTES:
f = tar.extractfile(member)
if f:
archived_content = f.read().decode("utf-8", errors="replace")
except KeyError:
return None
live_content: Optional[str] = None
if os.path.isfile(live_path):
if os.path.getsize(live_path) <= MAX_DIFF_TEXT_BYTES:
try:
with open(live_path, "r", encoding="utf-8", errors="replace") as f:
live_content = f.read()
except OSError:
pass
if archived_content is None and live_content is None:
return None
archived_lines = archived_content.splitlines(keepends=True) if archived_content is not None else []
live_lines = live_content.splitlines(keepends=True) if live_content is not None else []
diff = list(difflib.unified_diff(
archived_lines,
live_lines,
fromfile=f"snapshot:{snapshot_id}:/{clean_subpath}",
tofile=f"live:/{clean_subpath}"
))
return "".join(diff) if diff else None
+345
View File
@@ -0,0 +1,345 @@
"""System inspector collecting deep host telemetry (hardware, storage, network, kernel, users, packages)."""
import json
import os
import platform
import subprocess
from typing import Any, Dict, List, Optional, Tuple
from linux_backuper.models import NetworkState, PackageItem, StorageState
from linux_backuper.managers.base import BasePackageManager, get_package_manager
class SystemInspector:
"""Collects comprehensive Linux host metadata across diverse distributions."""
def __init__(self, distro_id: str):
self.distro_id = distro_id
self.package_manager: BasePackageManager = get_package_manager(distro_id)
def _run_cmd(self, cmd: List[str]) -> Tuple[int, str]:
"""Safely execute a shell command and return (returncode, stdout)."""
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
return res.returncode, res.stdout
except (OSError, FileNotFoundError):
return 1, ""
def inspect_packages(self) -> List[PackageItem]:
"""Query installed packages using the detected package manager."""
return self.package_manager.list_packages()
def parse_users_and_groups(
self,
passwd_path: str = "/etc/passwd",
group_path: str = "/etc/group",
subuid_path: str = "/etc/subuid",
subgid_path: str = "/etc/subgid"
) -> Dict[str, Any]:
"""Parse Linux user accounts, group memberships, and container subuid/subgid mappings."""
users = []
if os.path.isfile(passwd_path):
try:
with open(passwd_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split(":")
if len(parts) >= 7:
users.append({
"username": parts[0],
"uid": int(parts[2]),
"gid": int(parts[3]),
"gecos": parts[4],
"home": parts[5],
"shell": parts[6]
})
except (OSError, ValueError):
pass
groups = []
if os.path.isfile(group_path):
try:
with open(group_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#"):
continue
parts = line.split(":")
if len(parts) >= 3:
members = parts[3].split(",") if len(parts) > 3 and parts[3] else []
groups.append({
"name": parts[0],
"gid": int(parts[2]),
"members": members
})
except (OSError, ValueError):
pass
subuids = []
if os.path.isfile(subuid_path):
try:
with open(subuid_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.strip().split(":")
if len(parts) == 3:
subuids.append({"user": parts[0], "start_uid": int(parts[1]), "count": int(parts[2])})
except (OSError, ValueError):
pass
subgids = []
if os.path.isfile(subgid_path):
try:
with open(subgid_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
parts = line.strip().split(":")
if len(parts) == 3:
subgids.append({"group": parts[0], "start_gid": int(parts[1]), "count": int(parts[2])})
except (OSError, ValueError):
pass
return {
"users": users,
"groups": groups,
"subuid": subuids,
"subgid": subgids
}
def inspect_storage(self, fstab_path: str = "/etc/fstab") -> StorageState:
"""Inspect storage topology: lsblk block devices, df mounts, LVM, and fstab."""
block_devices = []
rc, out = self._run_cmd(["lsblk", "-J", "-o", "NAME,SIZE,TYPE,MOUNTPOINT,FSTYPE,UUID"])
if rc == 0 and out.strip():
try:
data = json.loads(out)
block_devices = data.get("blockdevices", [])
except json.JSONDecodeError:
pass
if not block_devices:
# Fallback plain lsblk
rc, out = self._run_cmd(["lsblk", "-l", "-o", "NAME,SIZE,TYPE,MOUNTPOINT"])
if rc == 0:
for line in out.splitlines()[1:]:
parts = line.split()
if parts:
block_devices.append({"name": parts[0], "size": parts[1] if len(parts) > 1 else ""})
# Mount points from df -hT
mount_points = []
rc, out = self._run_cmd(["df", "-hT"])
if rc == 0:
lines = out.splitlines()
for line in lines[1:]:
parts = line.split()
if len(parts) >= 7:
mount_points.append({
"device": parts[0],
"fstype": parts[1],
"size": parts[2],
"used": parts[3],
"avail": parts[4],
"percent": parts[5],
"mount": parts[6]
})
# LVM Inspection if tools exist
lvm_pvs, lvm_vgs, lvm_lvs = None, None, None
rc, out = self._run_cmd(["pvs", "--reportformat", "json"])
if rc == 0 and out.strip():
try:
lvm_pvs = json.loads(out).get("report", [{}])[0].get("pv", [])
except (json.JSONDecodeError, IndexError, KeyError):
pass
rc, out = self._run_cmd(["vgs", "--reportformat", "json"])
if rc == 0 and out.strip():
try:
lvm_vgs = json.loads(out).get("report", [{}])[0].get("vg", [])
except (json.JSONDecodeError, IndexError, KeyError):
pass
rc, out = self._run_cmd(["lvs", "--reportformat", "json"])
if rc == 0 and out.strip():
try:
lvm_lvs = json.loads(out).get("report", [{}])[0].get("lv", [])
except (json.JSONDecodeError, IndexError, KeyError):
pass
# Read fstab
fstab_raw = ""
if os.path.isfile(fstab_path):
try:
with open(fstab_path, "r", encoding="utf-8", errors="replace") as f:
fstab_raw = f.read()
except OSError:
pass
return StorageState(
block_devices=block_devices,
mount_points=mount_points,
lvm_pvs=lvm_pvs,
lvm_vgs=lvm_vgs,
lvm_lvs=lvm_lvs,
fstab_raw=fstab_raw
)
def inspect_network(self, resolv_path: str = "/etc/resolv.conf") -> NetworkState:
"""Inspect network interfaces, IP routes, and DNS resolvers."""
interfaces = []
rc, out = self._run_cmd(["ip", "-j", "a"])
if rc == 0 and out.strip():
try:
raw_ifaces = json.loads(out)
for item in raw_ifaces:
interfaces.append({
"name": item.get("ifname", ""),
"flags": item.get("flags", []),
"addresses": [
f"{a.get('local')}/{a.get('prefixlen')}"
for a in item.get("addr_info", []) if "local" in a
]
})
except json.JSONDecodeError:
pass
routes = []
rc, out = self._run_cmd(["ip", "-j", "r"])
if rc == 0 and out.strip():
try:
raw_routes = json.loads(out)
for r in raw_routes:
routes.append({
"dst": r.get("dst", ""),
"gateway": r.get("gateway", ""),
"dev": r.get("dev", "")
})
except json.JSONDecodeError:
pass
dns_servers = []
if os.path.isfile(resolv_path):
try:
with open(resolv_path, "r", encoding="utf-8", errors="replace") as f:
for line in f:
line = line.strip()
if line.startswith("nameserver"):
parts = line.split()
if len(parts) >= 2:
dns_servers.append(parts[1])
except OSError:
pass
return NetworkState(
interfaces=interfaces,
routes=routes,
dns_servers=dns_servers,
hostname=platform.node()
)
def inspect_hardware(self) -> str:
"""Generate hardware overview text."""
lines = []
lines.append(f"System: {platform.system()} {platform.release()} ({platform.machine()})")
lines.append(f"Node: {platform.node()}")
# lscpu
rc, out = self._run_cmd(["lscpu"])
if rc == 0 and out:
lines.append("\n=== CPU Architecture (lscpu) ===")
lines.append(out.strip())
elif os.path.isfile("/proc/cpuinfo"):
try:
with open("/proc/cpuinfo", "r") as f:
lines.append("\n=== /proc/cpuinfo ===")
lines.append(f.read().strip())
except OSError:
pass
# memory info
if os.path.isfile("/proc/meminfo"):
try:
with open("/proc/meminfo", "r") as f:
lines.append("\n=== /proc/meminfo ===")
lines.append(f.read().strip())
except OSError:
pass
return "\n".join(lines)
def inspect_kernel(self) -> str:
"""Generate kernel parameters and loaded modules text."""
lines = []
lines.append(f"Kernel Release: {platform.release()}")
lines.append(f"Kernel Version: {platform.version()}")
if os.path.isfile("/proc/cmdline"):
try:
with open("/proc/cmdline", "r") as f:
lines.append(f"Boot cmdline: {f.read().strip()}")
except OSError:
pass
rc, out = self._run_cmd(["lsmod"])
if rc == 0 and out:
lines.append("\n=== Loaded Modules (lsmod) ===")
lines.append(out.strip())
rc, out = self._run_cmd(["sysctl", "-a"])
if rc == 0 and out:
lines.append("\n=== Kernel Parameters (sysctl -a) ===")
lines.append(out.strip())
return "\n".join(lines)
def dump_meta_files(self, meta_dir: str) -> Dict[str, str]:
"""
Dump all telemetry command outputs and structured JSON into meta_dir.
Returns a mapping of archive relative path to host absolute path.
"""
os.makedirs(meta_dir, exist_ok=True)
files_map: Dict[str, str] = {}
# 1. Packages
packages = self.inspect_packages()
pkg_path = os.path.join(meta_dir, "packages.txt")
with open(pkg_path, "w", encoding="utf-8") as f:
for p in packages:
f.write(f"{p.name}|{p.version}|{p.arch}\n")
files_map["meta/packages.txt"] = pkg_path
# 2. Users and Groups
users_data = self.parse_users_and_groups()
users_path = os.path.join(meta_dir, "users.json")
with open(users_path, "w", encoding="utf-8") as f:
json.dump(users_data, f, indent=2)
files_map["meta/users.json"] = users_path
# 3. Storage
storage_data = self.inspect_storage()
storage_path = os.path.join(meta_dir, "storage.json")
with open(storage_path, "w", encoding="utf-8") as f:
json.dump(storage_data.to_dict(), f, indent=2)
files_map["meta/storage.json"] = storage_path
# 4. Network
network_data = self.inspect_network()
network_path = os.path.join(meta_dir, "network.json")
with open(network_path, "w", encoding="utf-8") as f:
json.dump(network_data.to_dict(), f, indent=2)
files_map["meta/network.json"] = network_path
# 5. Hardware
hw_text = self.inspect_hardware()
hw_path = os.path.join(meta_dir, "hardware.txt")
with open(hw_path, "w", encoding="utf-8") as f:
f.write(hw_text)
files_map["meta/hardware.txt"] = hw_path
# 6. Kernel
kernel_text = self.inspect_kernel()
kernel_path = os.path.join(meta_dir, "kernel.txt")
with open(kernel_path, "w", encoding="utf-8") as f:
f.write(kernel_text)
files_map["meta/kernel.txt"] = kernel_path
return files_map
+76
View File
@@ -0,0 +1,76 @@
"""Concurrency locking using non-blocking fcntl.flock on a PID file."""
import fcntl
import os
from typing import Optional
from linux_backuper.core.constants import DEFAULT_PID_PATH
class LockAcquisitionError(RuntimeError):
"""Raised when another instance of linux-backuper is already executing."""
pass
class SingleInstanceLock:
"""Ensures single-process execution using kernel-level file locks."""
def __init__(self, pid_path: Optional[str] = None):
self.pid_path = pid_path or DEFAULT_PID_PATH
self._fd: Optional[int] = None
def acquire(self) -> bool:
"""Acquire exclusive non-blocking lock. Raises LockAcquisitionError on conflict."""
parent_dir = os.path.dirname(self.pid_path)
if parent_dir:
try:
os.makedirs(parent_dir, exist_ok=True)
except OSError:
pass
try:
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
except PermissionError:
if os.environ.get("LINUX_BACKUPER_ALLOW_NON_ROOT") == "1" or (hasattr(os, "geteuid") and os.geteuid() != 0):
import tempfile
self.pid_path = os.path.join(tempfile.gettempdir(), f"linux-backuper-{os.getpid()}.pid")
self._fd = os.open(self.pid_path, os.O_CREAT | os.O_RDWR, 0o600)
else:
raise
try:
fcntl.flock(self._fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
os.ftruncate(self._fd, 0)
os.write(self._fd, f"{os.getpid()}\n".encode("utf-8"))
return True
except (BlockingIOError, OSError) as e:
if self._fd is not None:
try:
os.close(self._fd)
except OSError:
pass
self._fd = None
raise LockAcquisitionError(
f"Another linux-backuper instance is already running (locked on {self.pid_path}): {e}"
)
def release(self) -> None:
"""Release the file lock and remove the PID file."""
if self._fd is not None:
try:
fcntl.flock(self._fd, fcntl.LOCK_UN)
os.close(self._fd)
except OSError:
pass
self._fd = None
if os.path.isfile(self.pid_path):
try:
os.unlink(self.pid_path)
except OSError:
pass
def __enter__(self) -> "SingleInstanceLock":
self.acquire()
return self
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.release()
+104
View File
@@ -0,0 +1,104 @@
"""Backup profile manager supporting built-in and user-defined custom profiles."""
import json
import os
from typing import Dict, List, Optional
from linux_backuper.core.constants import DEFAULT_CONFIG_PATH
from linux_backuper.models import ProfileConfig
class ProfileManager:
"""Manages built-in profiles (quick, system, full) and custom profiles."""
BUILTIN_PROFILES: Dict[str, ProfileConfig] = {
"quick": ProfileConfig(
name="quick",
description="Default lightweight snapshot of /etc and full host telemetry",
included_paths=["/etc"],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True
),
"system": ProfileConfig(
name="system",
description="System configuration, /boot, systemd units and kernel state",
included_paths=["/etc", "/boot", "/usr/lib/systemd/system"],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True
),
"full": ProfileConfig(
name="full",
description="Complete disaster-recovery profile including cron, NetworkManager and systemd state",
included_paths=[
"/etc", "/boot",
"/var/spool/cron",
"/var/lib/systemd",
"/var/lib/NetworkManager"
],
exclude_patterns=[
"*.sock", "*.fifo", "*.lock", "*.pid",
"/etc/mtab", "/etc/resolv.conf"
],
collect_users=True,
collect_kernel=True,
collect_storage=True,
collect_network=True,
collect_packages=True,
max_journal_mb=50
)
}
def __init__(self, config_path: str = DEFAULT_CONFIG_PATH):
self.config_path = config_path
self._profiles: Dict[str, ProfileConfig] = dict(self.BUILTIN_PROFILES)
self._load_custom_profiles()
def _load_custom_profiles(self) -> None:
"""Load optional user-defined profiles from JSON configuration."""
if not os.path.isfile(self.config_path):
return
try:
with open(self.config_path, "r", encoding="utf-8") as f:
data = json.load(f)
custom_dict = data.get("profiles", {})
for name, cfg in custom_dict.items():
self._profiles[name] = ProfileConfig(
name=name,
description=cfg.get("description", f"Custom profile '{name}'"),
included_paths=cfg.get("included_paths", ["/etc"]),
exclude_patterns=cfg.get("exclude_patterns", ["*.sock", "*.lock"]),
collect_users=cfg.get("collect_users", True),
collect_kernel=cfg.get("collect_kernel", True),
collect_storage=cfg.get("collect_storage", True),
collect_network=cfg.get("collect_network", True),
collect_packages=cfg.get("collect_packages", True),
max_journal_mb=cfg.get("max_journal_mb", 0)
)
except (OSError, json.JSONDecodeError):
pass
def get_profile(self, name: str) -> ProfileConfig:
"""Retrieve profile configuration by name. Raises KeyError if not found."""
if name not in self._profiles:
valid_names = ", ".join(self._profiles.keys())
raise KeyError(f"Unknown backup profile '{name}'. Available profiles: {valid_names}")
return self._profiles[name]
def list_profiles(self) -> List[ProfileConfig]:
"""List all available profiles."""
return list(self._profiles.values())
+317
View File
@@ -0,0 +1,317 @@
"""Safe restore engine with dry-run default, safety snapshots, and atomic write."""
import datetime
import os
import shutil
import socket
import subprocess
import tarfile
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.core.archiver import SnapshotArchiver, calculate_file_sha256, is_socket_or_fifo, BUFFER_SIZE
from linux_backuper.core.constants import EXIT_DRY_RUN, EXIT_SUCCESS, EXIT_GENERIC_ERROR, DEFAULT_BACKUP_DIR
from linux_backuper.core.detector import detect_distro
from linux_backuper.core.lock import SingleInstanceLock
from linux_backuper.models import RestorePlan, RestorePlanItem, SnapshotManifest
EXCLUDED_DYNAMIC_PATHS = {
"/etc/resolv.conf",
"/etc/mtab",
"/etc/adjtime",
"/etc/machine-id"
}
SENSITIVE_NETWORK_PREFIXES = (
"/etc/netplan",
"/etc/sysconfig/network-scripts",
"/etc/network/interfaces",
"/etc/NetworkManager"
)
class DryRunException(Exception):
"""Raised when restore runs in dry-run mode (exit code 5)."""
def __init__(self, plan: RestorePlan):
self.plan = plan
super().__init__("Restore executed in dry-run mode. Pass --force to apply changes.")
class SafeRestoreEngine:
"""Safely restores configuration archives onto the filesystem."""
def __init__(self, target_dir: str = DEFAULT_BACKUP_DIR):
self.target_dir = target_dir
def _resolve_archive(self, snapshot_id: str) -> str:
archive_path = SnapshotArchiver.resolve_archive_path(self.target_dir, snapshot_id)
if not os.path.isfile(archive_path):
raise FileNotFoundError(f"Snapshot archive not found: {archive_path}")
return archive_path
def plan_restore(
self,
snapshot_id: str,
target_root: str = "/",
include_fstab: bool = False
) -> RestorePlan:
"""
Inspect snapshot and construct a detailed RestorePlan against target_root.
Identifies create, modify, and skip actions without mutating the disk.
"""
archive_path = self._resolve_archive(snapshot_id)
manifest = SnapshotArchiver.read_manifest_from_archive(archive_path)
target_root_clean = os.path.abspath(target_root)
plan_items: List[RestorePlanItem] = []
with tarfile.open(archive_path, "r:*") as tar:
for member in tar.getmembers():
if not member.name.startswith("data/"):
continue
clean_subpath = member.name[5:].lstrip("/")
abs_sys_path = "/" + clean_subpath
target_dest_path = os.path.join(target_root_clean, clean_subpath)
# 1. Check excluded dynamic / runtime files
if abs_sys_path in EXCLUDED_DYNAMIC_PATHS:
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="skip",
reason="Excluded dynamic/volatile system file"
))
continue
if abs_sys_path == "/etc/fstab" and not include_fstab:
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="skip",
reason="Protected filesystem table (/etc/fstab). Pass --include-fstab to overwrite"
))
continue
if os.path.exists(target_dest_path) and is_socket_or_fifo(target_dest_path):
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="skip",
reason="Socket or FIFO file on filesystem"
))
continue
# 2. Check sensitive network files
is_net = any(abs_sys_path.startswith(prefix) for prefix in SENSITIVE_NETWORK_PREFIXES)
expected_sha = manifest.files_sha256.get(member.name)
# 3. Check live file state
if not os.path.exists(target_dest_path) and not os.path.islink(target_dest_path):
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="create",
reason="File does not exist on target system",
is_sensitive_network=is_net,
source_sha256=expected_sha,
target_sha256=None
))
else:
if os.path.isfile(target_dest_path):
target_sha = calculate_file_sha256(target_dest_path)
if expected_sha and target_sha == expected_sha:
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="skip",
reason="File content is identical to snapshot",
is_sensitive_network=is_net,
source_sha256=expected_sha,
target_sha256=target_sha
))
else:
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="modify",
reason="File content differs from snapshot",
is_sensitive_network=is_net,
source_sha256=expected_sha,
target_sha256=target_sha
))
else:
plan_items.append(RestorePlanItem(
rel_path=member.name,
abs_path=target_dest_path,
action="modify",
reason="Target exists as non-regular file",
is_sensitive_network=is_net,
source_sha256=expected_sha,
target_sha256=None
))
return RestorePlan(
snapshot_id=manifest.snapshot_id,
target_root=target_root_clean,
items=plan_items,
requires_force=True
)
def create_safety_snapshot(self, target_root: str = "/") -> Tuple[str, str]:
"""
Create a pre-restore safety snapshot of /etc before any file modifications.
Returns (snapshot_id, archive_path).
"""
hostname = socket.gethostname().split(".")[0]
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
safety_id = f"pre_restore_{hostname}_{timestamp}"
etc_path = os.path.join(os.path.abspath(target_root), "etc")
included_paths = [etc_path] if os.path.isdir(etc_path) else ["/etc"]
archiver = SnapshotArchiver(target_dir=self.target_dir, compression="gzip")
file_entries, files_sha256, uncompressed_bytes, _ = archiver.collect_file_list(included_paths)
manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id=safety_id,
created_at=datetime.datetime.now(datetime.timezone.utc).isoformat(),
hostname=socket.gethostname(),
profile="safety_pre_restore",
compression="gzip",
os=detect_distro().to_dict(),
package_manager="none",
package_count=0,
included_paths=included_paths,
stats={
"file_count": len(file_entries),
"uncompressed_bytes": uncompressed_bytes,
"compressed_bytes": 0
},
files_sha256=files_sha256
)
archive_path = archiver.create_snapshot_archive(safety_id, manifest, file_entries)
# Verify safety snapshot integrity immediately
valid, msg = SnapshotArchiver.verify_archive(archive_path)
if not valid:
raise RuntimeError(f"Safety snapshot failed integrity check: {msg}")
return safety_id, archive_path
def execute_restore(
self,
plan: RestorePlan,
force: bool = False,
pid_path: Optional[str] = None
) -> Dict[str, Any]:
"""
Execute file restoration based on RestorePlan.
If force=False: raises DryRunException (exit code 5).
If force=True: creates safety snapshot, atomically restores files, runs restorecon on SELinux.
"""
if not force:
raise DryRunException(plan)
lock = SingleInstanceLock(pid_path=pid_path)
lock.acquire()
restored_files: List[str] = []
restored_dirs: set = set()
safety_id = None
safety_path = None
try:
# 1. Capture unalterable pre-restore safety snapshot
safety_id, safety_path = self.create_safety_snapshot(target_root=plan.target_root)
plan.safety_snapshot_id = safety_id
archive_path = self._resolve_archive(plan.snapshot_id)
with tarfile.open(archive_path, "r:*") as tar:
for item in plan.items:
if item.action not in ("create", "modify"):
continue
# Zip slip security check
dest_abs = os.path.abspath(item.abs_path)
if not dest_abs.startswith(plan.target_root):
raise SecurityError(f"Zip slip path traversal detected: {dest_abs} outside {plan.target_root}")
member = tar.getmember(item.rel_path)
dest_dir = os.path.dirname(dest_abs)
os.makedirs(dest_dir, exist_ok=True)
restored_dirs.add(dest_dir)
if member.isreg():
f_in = tar.extractfile(member)
if not f_in:
continue
tmp_dest = f"{dest_abs}.tmp.{os.getpid()}"
try:
with open(tmp_dest, "wb") as f_out:
while chunk := f_in.read(BUFFER_SIZE):
f_out.write(chunk)
# Apply permissions
try:
os.chmod(tmp_dest, member.mode)
except OSError:
pass
# Apply ownership if root
if os.geteuid() == 0:
try:
os.chown(tmp_dest, member.uid, member.gid)
except OSError:
pass
# Atomic replacement
os.replace(tmp_dest, dest_abs)
restored_files.append(dest_abs)
finally:
if os.path.exists(tmp_dest):
try:
os.unlink(tmp_dest)
except OSError:
pass
elif member.issym():
# Symlink restoration
tmp_link = f"{dest_abs}.tmp.{os.getpid()}"
try:
if os.path.lexists(tmp_link):
os.unlink(tmp_link)
os.symlink(member.linkname, tmp_link)
os.replace(tmp_link, dest_abs)
restored_files.append(dest_abs)
finally:
if os.path.lexists(tmp_link):
try:
os.unlink(tmp_link)
except OSError:
pass
# 2. SELinux context restoration
selinux_restored = False
if os.path.exists("/sys/fs/selinux") and shutil.which("restorecon"):
for d in restored_dirs:
try:
subprocess.run(["restorecon", "-R", d], check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
except Exception:
pass
selinux_restored = True
return {
"status": "success",
"snapshot_id": plan.snapshot_id,
"safety_snapshot_id": safety_id,
"safety_archive_path": safety_path,
"restored_count": len(restored_files),
"restored_files": restored_files,
"selinux_context_restored": selinux_restored
}
finally:
lock.release()
+182
View File
@@ -0,0 +1,182 @@
"""Lifecycle retention and pruning engine for linux-backuper."""
import datetime
import os
import re
from typing import Dict, List, Optional, Set, Tuple, Any
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import DEFAULT_BACKUP_DIR
from linux_backuper.core.lock import SingleInstanceLock
from linux_backuper.models import SnapshotManifest
def parse_snapshot_datetime(manifest: SnapshotManifest) -> datetime.datetime:
"""Parse snapshot creation datetime from manifest or snapshot_id fallback."""
# 1. Try ISO format from manifest.created_at
if manifest.created_at:
try:
# Handle Python 3.6 - 3.10 ISO variations
iso_str = manifest.created_at.replace("Z", "+00:00")
return datetime.datetime.fromisoformat(iso_str)
except (ValueError, AttributeError):
pass
# 2. Try parsing snapshot_id, e.g. backup_hostname_20261009_191639 or pre_restore_hostname_20261009_191644
match = re.search(r"(\d{8})_(\d{6})", manifest.snapshot_id)
if match:
date_part, time_part = match.groups()
try:
dt = datetime.datetime.strptime(f"{date_part}_{time_part}", "%Y%m%d_%H%M%S")
return dt.replace(tzinfo=datetime.timezone.utc)
except ValueError:
pass
# Fallback to epoch
return datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc)
class RetentionEngine:
"""Calculates and executes retention policies (keep-last, keep-daily, keep-weekly, keep-monthly)."""
def __init__(
self,
keep_last: int = 0,
keep_daily: int = 0,
keep_weekly: int = 0,
keep_monthly: int = 0
):
self.keep_last = max(0, keep_last)
self.keep_daily = max(0, keep_daily)
self.keep_weekly = max(0, keep_weekly)
self.keep_monthly = max(0, keep_monthly)
def is_active(self) -> bool:
"""Returns True if at least one retention policy rule is configured (> 0)."""
return any([
self.keep_last > 0,
self.keep_daily > 0,
self.keep_weekly > 0,
self.keep_monthly > 0
])
def calculate_prune_set(
self,
snapshots: List[SnapshotManifest]
) -> Tuple[List[SnapshotManifest], List[SnapshotManifest]]:
"""
Evaluate snapshots against retention rules.
Returns:
- kept_snapshots: list of snapshots to preserve (sorted newest to oldest)
- pruned_snapshots: list of snapshots to delete (sorted oldest to newest)
"""
if not snapshots or not self.is_active():
return snapshots, []
# Sort snapshots descending (newest first)
sorted_snaps = sorted(
snapshots,
key=lambda s: parse_snapshot_datetime(s),
reverse=True
)
kept_ids: Set[str] = set()
# 1. Rule: keep-last N
if self.keep_last > 0:
for s in sorted_snaps[:self.keep_last]:
kept_ids.add(s.snapshot_id)
# 2. Rule: keep-daily D (newest snapshot per distinct day)
if self.keep_daily > 0:
seen_days: Dict[Tuple[int, int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
day_key = (dt.year, dt.month, dt.day)
if day_key not in seen_days:
if len(seen_days) < self.keep_daily:
seen_days[day_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
# 3. Rule: keep-weekly W (newest snapshot per ISO week)
if self.keep_weekly > 0:
seen_weeks: Dict[Tuple[int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
iso_year, iso_week, _ = dt.isocalendar()
week_key = (iso_year, iso_week)
if week_key not in seen_weeks:
if len(seen_weeks) < self.keep_weekly:
seen_weeks[week_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
# 4. Rule: keep-monthly M (newest snapshot per calendar month)
if self.keep_monthly > 0:
seen_months: Dict[Tuple[int, int], str] = {}
for s in sorted_snaps:
dt = parse_snapshot_datetime(s)
month_key = (dt.year, dt.month)
if month_key not in seen_months:
if len(seen_months) < self.keep_monthly:
seen_months[month_key] = s.snapshot_id
kept_ids.add(s.snapshot_id)
kept = [s for s in sorted_snaps if s.snapshot_id in kept_ids]
pruned = [s for s in reversed(sorted_snaps) if s.snapshot_id not in kept_ids]
return kept, pruned
def execute_prune(
self,
prune_list: List[SnapshotManifest],
target_dir: str = DEFAULT_BACKUP_DIR,
dry_run: bool = False,
pid_path: Optional[str] = None
) -> List[Dict[str, Any]]:
"""
Delete pruned snapshot archives from target_dir.
If dry_run is True, simulates deletion without removing files.
"""
if not dry_run:
lock = SingleInstanceLock(pid_path=pid_path)
lock.acquire()
results: List[Dict[str, Any]] = []
try:
for snap in prune_list:
archive_path = SnapshotArchiver.resolve_archive_path(target_dir, snap.snapshot_id)
size_bytes = 0
file_exists = os.path.isfile(archive_path)
if file_exists:
try:
size_bytes = os.path.getsize(archive_path)
except OSError:
pass
if dry_run:
results.append({
"snapshot_id": snap.snapshot_id,
"archive_path": archive_path,
"freed_bytes": size_bytes,
"action": "would_delete"
})
else:
if file_exists:
try:
os.unlink(archive_path)
status = "deleted"
except OSError as e:
status = f"error: {e}"
else:
status = "file_not_found"
results.append({
"snapshot_id": snap.snapshot_id,
"archive_path": archive_path,
"freed_bytes": size_bytes,
"action": status
})
finally:
if not dry_run:
lock.release()
return results
+292
View File
@@ -0,0 +1,292 @@
"""Remote transport engine supporting local directory/NFS/SMB mounts and SSH/SCP/rsync."""
import json
import os
import re
import shutil
import subprocess
import tarfile
from typing import Dict, List, Optional, Tuple, Any
from linux_backuper.core.archiver import calculate_file_sha256, SnapshotArchiver, BUFFER_SIZE
from linux_backuper.core.retention import RetentionEngine, parse_snapshot_datetime
from linux_backuper.models import SnapshotManifest
class TransportError(Exception):
"""Raised when transport operation fails."""
pass
class BaseTransport:
"""Base interface for snapshot transport backends."""
def push(self, local_archive_path: str) -> Dict[str, Any]:
"""Transfer archive to destination. Returns result metadata."""
raise NotImplementedError
def list_remote(self) -> List[SnapshotManifest]:
"""List snapshots available at destination."""
raise NotImplementedError
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
"""Apply retention policy to remote destination."""
raise NotImplementedError
class LocalPathTransport(BaseTransport):
"""Transport backend for local directories and mounted NFS/SMB shares."""
def __init__(self, target_dir: str):
self.target_dir = os.path.abspath(target_dir)
def push(self, local_archive_path: str) -> Dict[str, Any]:
if not os.path.isfile(local_archive_path):
raise TransportError(f"Source archive does not exist: {local_archive_path}")
os.makedirs(self.target_dir, exist_ok=True)
filename = os.path.basename(local_archive_path)
dest_final = os.path.join(self.target_dir, filename)
dest_tmp = f"{dest_final}.tmp.{os.getpid()}"
source_sha = calculate_file_sha256(local_archive_path)
source_size = os.path.getsize(local_archive_path)
# Atomic copy: copy to .tmp, verify sha256, then replace
try:
with open(local_archive_path, "rb") as f_in, open(dest_tmp, "wb") as f_out:
while chunk := f_in.read(BUFFER_SIZE):
f_out.write(chunk)
# Strict 0600 permissions
try:
os.chmod(dest_tmp, 0o600)
except OSError:
pass
dest_sha = calculate_file_sha256(dest_tmp)
if dest_sha != source_sha:
raise TransportError(f"Checksum mismatch after copying to {dest_tmp}: {dest_sha} != {source_sha}")
os.replace(dest_tmp, dest_final)
finally:
if os.path.exists(dest_tmp):
try:
os.unlink(dest_tmp)
except OSError:
pass
return {
"status": "success",
"transport": "local_mount",
"source_path": local_archive_path,
"destination_path": dest_final,
"bytes_transferred": source_size,
"sha256": source_sha
}
def list_remote(self) -> List[SnapshotManifest]:
archiver = SnapshotArchiver(target_dir=self.target_dir)
return archiver.list_snapshots()
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
snaps = self.list_remote()
_, to_prune = retention.calculate_prune_set(snaps)
return retention.execute_prune(to_prune, target_dir=self.target_dir, dry_run=False)
class SshTransport(BaseTransport):
"""Transport backend for remote servers via SSH/SCP/rsync."""
def __init__(self, target_spec: str, ssh_key: Optional[str] = None, port: int = 22):
self.raw_spec = target_spec
self.ssh_key = ssh_key
self.port = port
self.user, self.host, self.remote_dir = self._parse_target_spec(target_spec)
def _parse_target_spec(self, spec: str) -> Tuple[Optional[str], str, str]:
# Forms: user@host:/path or host:/path or ssh://user@host[:port]/path
clean = spec
if clean.startswith("ssh://"):
clean = clean[6:]
if "/" in clean:
host_part, path_part = clean.split("/", 1)
remote_path = "/" + path_part
else:
host_part, remote_path = clean, "/var/backups"
if ":" in host_part:
host_part, port_str = host_part.split(":", 1)
try:
self.port = int(port_str)
except ValueError:
pass
if "@" in host_part:
user, host = host_part.split("@", 1)
else:
user, host = None, host_part
return user, host, remote_path
# Standard scp user@host:/path
if ":" in clean:
host_part, remote_path = clean.split(":", 1)
if "@" in host_part:
user, host = host_part.split("@", 1)
else:
user, host = None, host_part
return user, host, remote_path
raise TransportError(f"Invalid SSH target spec: {spec}. Expected user@host:/path or ssh://user@host/path")
def _build_ssh_cmd(self, remote_command: str) -> List[str]:
cmd = ["ssh", "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no", "-p", str(self.port)]
if self.ssh_key:
cmd.extend(["-i", self.ssh_key])
target = f"{self.user}@{self.host}" if self.user else self.host
cmd.extend([target, remote_command])
return cmd
def push(self, local_archive_path: str) -> Dict[str, Any]:
if not os.path.isfile(local_archive_path):
raise TransportError(f"Source archive does not exist: {local_archive_path}")
source_sha = calculate_file_sha256(local_archive_path)
source_size = os.path.getsize(local_archive_path)
filename = os.path.basename(local_archive_path)
# 1. Ensure remote directory exists
mkdir_cmd = self._build_ssh_cmd(f"mkdir -p {self.remote_dir}")
res = subprocess.run(mkdir_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if res.returncode != 0:
raise TransportError(f"Failed to create remote directory {self.remote_dir}: {res.stderr.strip()}")
remote_tmp = f"{self.remote_dir}/{filename}.tmp.{os.getpid()}"
remote_final = f"{self.remote_dir}/{filename}"
target_dest = f"{self.user}@{self.host}:{remote_tmp}" if self.user else f"{self.host}:{remote_tmp}"
# 2. Transfer using rsync if available, else scp
if shutil.which("rsync"):
ssh_opt = f"ssh -o BatchMode=yes -o StrictHostKeyChecking=no -p {self.port}"
if self.ssh_key:
ssh_opt += f" -i {self.ssh_key}"
transfer_cmd = ["rsync", "-avz", "--partial", "-e", ssh_opt, local_archive_path, target_dest]
else:
scp_cmd = ["scp", "-P", str(self.port), "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=no"]
if self.ssh_key:
scp_cmd.extend(["-i", self.ssh_key])
scp_cmd.extend([local_archive_path, target_dest])
transfer_cmd = scp_cmd
res = subprocess.run(transfer_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if res.returncode != 0:
raise TransportError(f"Transfer to {target_dest} failed: {res.stderr.strip()}")
# 3. Verify remote SHA-256 and atomically move to final path
verify_and_mv = (
f"if command -v sha256sum >/dev/null 2>&1; then "
f" rsha=$(sha256sum {remote_tmp} | cut -d' ' -f1); "
f" if [ \"$rsha\" != \"{source_sha}\" ]; then rm -f {remote_tmp}; exit 2; fi; "
f"fi; "
f"mv {remote_tmp} {remote_final} && chmod 0600 {remote_final}"
)
mv_cmd = self._build_ssh_cmd(verify_and_mv)
res = subprocess.run(mv_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if res.returncode != 0:
raise TransportError(f"Remote integrity verification or rename failed on {self.host}: {res.stderr.strip()}")
return {
"status": "success",
"transport": "ssh",
"source_path": local_archive_path,
"destination_target": f"{self.host}:{remote_final}",
"bytes_transferred": source_size,
"sha256": source_sha
}
def list_remote(self) -> List[SnapshotManifest]:
"""Query remote directory for snapshot files."""
list_cmd = self._build_ssh_cmd(f"ls -1 {self.remote_dir}/*.tar.gz {self.remote_dir}/*.tar 2>/dev/null || true")
res = subprocess.run(list_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if res.returncode != 0:
return []
remote_files = [line.strip() for line in res.stdout.splitlines() if line.strip()]
manifests: List[SnapshotManifest] = []
for rf in remote_files:
fname = os.path.basename(rf)
# Create synthetic manifest parsed from filename
snap_id = fname
for ext in (".tar.gz", ".tar"):
if snap_id.endswith(ext):
snap_id = snap_id[:-len(ext)]
break
m = SnapshotManifest(
schema_version="1.0",
snapshot_id=snap_id,
created_at="",
hostname="",
profile="remote",
compression="gzip" if rf.endswith(".gz") else "none",
os={},
package_manager="none",
package_count=0,
included_paths=[],
stats={},
files_sha256={}
)
manifests.append(m)
return manifests
def prune_remote(self, retention: RetentionEngine) -> List[Dict[str, Any]]:
snaps = self.list_remote()
_, to_prune = retention.calculate_prune_set(snaps)
results: List[Dict[str, Any]] = []
for s in to_prune:
target_rm = f"{self.remote_dir}/{s.snapshot_id}.tar.gz"
target_rm_plain = f"{self.remote_dir}/{s.snapshot_id}.tar"
rm_cmd = self._build_ssh_cmd(f"rm -f {target_rm} {target_rm_plain}")
res = subprocess.run(rm_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
status = "deleted" if res.returncode == 0 else f"error: {res.stderr.strip()}"
results.append({
"snapshot_id": s.snapshot_id,
"remote_path": target_rm,
"action": status
})
return results
class TransportFactory:
"""Factory to instantiate transport backends based on destination string or config."""
@staticmethod
def get_transport(
target_spec: str,
config: Optional[Dict[str, Any]] = None,
ssh_key: Optional[str] = None
) -> BaseTransport:
# 1. Check if target_spec is an alias in config['remotes']
if config and "remotes" in config and target_spec in config["remotes"]:
remote_cfg = config["remotes"][target_spec]
t_type = remote_cfg.get("type", "ssh")
if t_type == "local" or t_type == "mount":
return LocalPathTransport(remote_cfg["path"])
elif t_type in ("ssh", "rsync", "sftp"):
host = remote_cfg["host"]
user = remote_cfg.get("user")
path = remote_cfg.get("path", "/var/backups")
port = remote_cfg.get("port", 22)
key = remote_cfg.get("key") or ssh_key
spec = f"{user}@{host}:{path}" if user else f"{host}:{path}"
return SshTransport(spec, ssh_key=key, port=port)
# 2. Local directory or mounted NFS/SMB share
if target_spec.startswith("/") or target_spec.startswith("./") or target_spec.startswith("../"):
return LocalPathTransport(target_spec)
# 3. SSH specification: user@host:/path or ssh://...
if ":" in target_spec:
return SshTransport(target_spec, ssh_key=ssh_key)
# Default fallback: treat as local path
return LocalPathTransport(target_spec)
+1
View File
@@ -0,0 +1 @@
"""Package manager adapters for multi-distro Linux environments."""
+50
View File
@@ -0,0 +1,50 @@
"""Base class and factory for package manager adapters."""
import shutil
from abc import ABC, abstractmethod
from typing import List
from linux_backuper.models import PackageItem
class BasePackageManager(ABC):
"""Abstract interface for Linux package manager inspectors."""
@abstractmethod
def get_manager_name(self) -> str:
"""Return the canonical name of the package manager (e.g. rpm, dpkg, pacman)."""
pass
@abstractmethod
def list_packages(self) -> List[PackageItem]:
"""Query and parse all installed packages on the system."""
pass
def is_available(self) -> bool:
"""Check if the package manager binary exists on the system."""
return shutil.which(self.get_manager_name()) is not None
def get_package_manager(distro_id: str) -> BasePackageManager:
"""Return appropriate package manager adapter based on distro_id or system binaries."""
from linux_backuper.managers.rpm import RpmPackageManager
from linux_backuper.managers.dpkg import DpkgPackageManager
from linux_backuper.managers.pacman import PacmanPackageManager
distro_id = (distro_id or "").lower()
if distro_id in ("rhel", "almalinux", "rocky", "centos", "fedora", "amzn"):
return RpmPackageManager()
elif distro_id in ("debian", "ubuntu", "raspbian", "pop", "linuxmint"):
return DpkgPackageManager()
elif distro_id in ("arch", "manjaro", "endeavouros"):
return PacmanPackageManager()
# Fallback by probing available binaries on PATH
if shutil.which("rpm"):
return RpmPackageManager()
elif shutil.which("dpkg-query"):
return DpkgPackageManager()
elif shutil.which("pacman"):
return PacmanPackageManager()
# Generic fallback
return DpkgPackageManager()
+38
View File
@@ -0,0 +1,38 @@
"""DPKG package manager adapter (Debian, Ubuntu)."""
import subprocess
from typing import List
from linux_backuper.models import PackageItem
from linux_backuper.managers.base import BasePackageManager
class DpkgPackageManager(BasePackageManager):
"""Inspector for DPKG-based Linux distributions."""
def get_manager_name(self) -> str:
return "dpkg-query"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via dpkg-query."""
cmd = ["dpkg-query", "-W", "-f=${Package}|${Version}|${Architecture}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
line = line.strip()
if not line:
continue
parts = line.split("|")
if len(parts) >= 2:
name = parts[0]
version = parts[1]
arch = parts[2] if len(parts) > 2 else ""
packages.append(PackageItem(name=name, version=version, arch=arch))
packages.sort(key=lambda p: p.name)
return packages
+37
View File
@@ -0,0 +1,37 @@
"""Pacman package manager adapter (Arch Linux)."""
import subprocess
from typing import List
from linux_backuper.models import PackageItem
from linux_backuper.managers.base import BasePackageManager
class PacmanPackageManager(BasePackageManager):
"""Inspector for Pacman-based Linux distributions (Arch Linux)."""
def get_manager_name(self) -> str:
return "pacman"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via pacman -Q."""
cmd = ["pacman", "-Q"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
line = line.strip()
if not line:
continue
parts = line.split(None, 1)
if len(parts) >= 2:
name = parts[0]
version = parts[1]
packages.append(PackageItem(name=name, version=version, arch=""))
packages.sort(key=lambda p: p.name)
return packages
+38
View File
@@ -0,0 +1,38 @@
"""RPM package manager adapter (RHEL, AlmaLinux, Rocky, CentOS, Fedora)."""
import subprocess
from typing import List
from linux_backuper.models import PackageItem
from linux_backuper.managers.base import BasePackageManager
class RpmPackageManager(BasePackageManager):
"""Inspector for RPM-based Linux distributions."""
def get_manager_name(self) -> str:
return "rpm"
def list_packages(self) -> List[PackageItem]:
"""List installed packages via rpm query."""
cmd = ["rpm", "-qa", "--qf", "%{NAME}|%{VERSION}-%{RELEASE}|%{ARCH}\n"]
try:
res = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=False)
if res.returncode != 0:
return []
except (OSError, FileNotFoundError):
return []
packages: List[PackageItem] = []
for line in res.stdout.splitlines():
line = line.strip()
if not line or line.startswith("("):
continue
parts = line.split("|")
if len(parts) >= 2:
name = parts[0]
version = parts[1]
arch = parts[2] if len(parts) > 2 else ""
packages.append(PackageItem(name=name, version=version, arch=arch))
packages.sort(key=lambda p: p.name)
return packages
+156
View File
@@ -0,0 +1,156 @@
"""Data transfer objects and models for linux-backuper."""
from dataclasses import dataclass, asdict, field
from typing import Dict, List, Optional, Any
@dataclass
class OsInfo:
distro_id: str
distro_name: str
version_id: str
kernel: str
arch: str
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "OsInfo":
return cls(
distro_id=data.get("distro_id", "unknown"),
distro_name=data.get("distro_name", "Unknown Linux"),
version_id=data.get("version_id", "0"),
kernel=data.get("kernel", ""),
arch=data.get("arch", "")
)
@dataclass
class PackageItem:
name: str
version: str
arch: str
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "PackageItem":
return cls(
name=data["name"],
version=data["version"],
arch=data.get("arch", "")
)
@dataclass
class ProfileConfig:
name: str
description: str
included_paths: List[str]
exclude_patterns: List[str] = field(default_factory=list)
collect_users: bool = True
collect_kernel: bool = True
collect_storage: bool = True
collect_network: bool = True
collect_packages: bool = True
max_journal_mb: int = 0
retention_keep_last: int = 0
retention_keep_daily: int = 0
retention_keep_weekly: int = 0
retention_keep_monthly: int = 0
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class StorageState:
block_devices: List[Dict[str, Any]] = field(default_factory=list)
mount_points: List[Dict[str, Any]] = field(default_factory=list)
lvm_pvs: Optional[List[Dict[str, Any]]] = None
lvm_vgs: Optional[List[Dict[str, Any]]] = None
lvm_lvs: Optional[List[Dict[str, Any]]] = None
fstab_raw: str = ""
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class NetworkState:
interfaces: List[Dict[str, Any]] = field(default_factory=list)
routes: List[Dict[str, Any]] = field(default_factory=list)
dns_servers: List[str] = field(default_factory=list)
hostname: str = ""
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class SnapshotManifest:
schema_version: str
snapshot_id: str
created_at: str
hostname: str
profile: str
compression: str
os: Dict[str, Any]
package_manager: str
package_count: int
included_paths: List[str]
stats: Dict[str, Any]
files_sha256: Dict[str, str] = field(default_factory=dict)
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "SnapshotManifest":
return cls(
schema_version=data.get("schema_version", "1.0"),
snapshot_id=data["snapshot_id"],
created_at=data["created_at"],
hostname=data["hostname"],
profile=data.get("profile", "quick"),
compression=data.get("compression", "gzip"),
os=data.get("os", {}),
package_manager=data.get("package_manager", "none"),
package_count=data.get("package_count", 0),
included_paths=data.get("included_paths", []),
stats=data.get("stats", {}),
files_sha256=data.get("files_sha256", {})
)
@dataclass
class RestorePlanItem:
rel_path: str
abs_path: str
action: str # "create", "modify", "skip"
reason: Optional[str] = None
is_sensitive_network: bool = False
source_sha256: Optional[str] = None
target_sha256: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
return asdict(self)
@dataclass
class RestorePlan:
snapshot_id: str
target_root: str
items: List[RestorePlanItem] = field(default_factory=list)
safety_snapshot_id: Optional[str] = None
requires_force: bool = True
def to_dict(self) -> Dict[str, Any]:
return {
"snapshot_id": self.snapshot_id,
"target_root": self.target_root,
"items": [item.to_dict() for item in self.items],
"safety_snapshot_id": self.safety_snapshot_id,
"requires_force": self.requires_force,
"summary": {
"create_count": sum(1 for i in self.items if i.action == "create"),
"modify_count": sum(1 for i in self.items if i.action == "modify"),
"skip_count": sum(1 for i in self.items if i.action == "skip"),
"sensitive_network_count": sum(1 for i in self.items if i.is_sensitive_network)
}
}
+201
View File
@@ -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_<timestamp>\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 <lain@wired.intra>.
.SH "REPORTING BUGS"
Report bugs to: <https://gitea.wired.synology.me/soda64/linux-backuper/issues>
.SH "SEE ALSO"
.BR tar (1),
.BR gzip (1),
.BR rsync (1),
.BR ssh (1)
+550
View File
@@ -0,0 +1,550 @@
#!/usr/bin/env python3
"""Enterprise package builder for linux-backuper.
Builds:
1. Pure Python Debian package (.deb) using standard ar / tar.gz formats.
2. RPM package (.rpm) via spec generation and rpmbuild (when available).
3. Universal binary distribution (.tar.gz) with standalone install.sh.
Zero mandatory external pip dependencies required.
"""
import argparse
import gzip
import io
import os
import re
import shutil
import subprocess
import sys
import tarfile
import time
def get_version(repo_root: str) -> str:
"""Extract version from linux_backuper/__init__.py."""
init_path = os.path.join(repo_root, "linux_backuper", "__init__.py")
with open(init_path, "r", encoding="utf-8") as f:
content = f.read()
match = re.search(r'__version__\s*=\s*["\']([^"\']+)["\']', content)
if not match:
raise ValueError("Could not find __version__ in linux_backuper/__init__.py")
return match.group(1)
def create_ar_archive(target_path: str, members: list):
"""Create a standard UNIX ar archive (Debian .deb package format).
members is a list of tuples: (name: str, content: bytes, mode: int)
"""
with open(target_path, "wb") as out:
# 8-byte ar magic header
out.write(b"!<arch>\n")
for name, data, mode in members:
# Entry header format:
# 0..15 (16) Name
# 16..27 (12) Timestamp
# 28..33 (6) Owner UID
# 34..39 (6) Owner GID
# 40..47 (8) File mode (octal)
# 48..57 (10) File size (decimal)
# 58..59 (2) Trailer `\x60\n`
name_bytes = name.encode("ascii").ljust(16)
timestamp_bytes = str(int(time.time())).encode("ascii").ljust(12)
uid_bytes = b"0 "
gid_bytes = b"0 "
mode_bytes = f"{mode:o}".encode("ascii").ljust(8)
size_bytes = str(len(data)).encode("ascii").ljust(10)
trailer = b"`\n"
header = (
name_bytes
+ timestamp_bytes
+ uid_bytes
+ gid_bytes
+ mode_bytes
+ size_bytes
+ trailer
)
if len(header) != 60:
raise ValueError(f"Malformed ar header length: {len(header)}")
out.write(header)
out.write(data)
# ar entries are padded with \n if size is odd
if len(data) % 2 != 0:
out.write(b"\n")
def build_deb_package(repo_root: str, out_dir: str, version: str) -> str:
"""Build a standard Debian .deb package in pure Python."""
deb_filename = f"linux-backuper_{version}_all.deb"
deb_path = os.path.join(out_dir, deb_filename)
os.makedirs(out_dir, exist_ok=True)
# 1. debian-binary member
debian_binary = b"2.0\n"
# 2. control.tar.gz member
control_content = f"""Package: linux-backuper
Version: {version}
Section: admin
Priority: optional
Architecture: all
Depends: python3 (>= 3.6)
Recommends: rsync, openssh-client
Maintainer: wiredLAB <lain@wired.intra>
Description: Enterprise Linux system snapshot and configuration backup utility.
linux-backuper creates reliable, verifiable, and restorable system configuration
and state snapshots across Debian, Ubuntu, RHEL, AlmaLinux, Fedora, and Arch Linux.
Features include zero mandatory external pip dependencies, fast metadata indexing,
live system diffing, dry-run safety restore, time-bucket retention pruning, and
local-first remote synchronization.
"""
postinst_script = """#!/bin/sh
set -e
mkdir -p /var/backups/linux-backuper /etc/linux-backuper
chmod 0700 /var/backups/linux-backuper
exit 0
"""
prerm_script = """#!/bin/sh
set -e
exit 0
"""
control_buf = io.BytesIO()
with tarfile.open(fileobj=control_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar:
# ./
ti = tarfile.TarInfo("./")
ti.type = tarfile.DIRTYPE
ti.mode = 0o755
ti.mtime = int(time.time())
tar.addfile(ti)
# ./control
data = control_content.encode("utf-8")
ti = tarfile.TarInfo("./control")
ti.size = len(data)
ti.mode = 0o644
ti.mtime = int(time.time())
tar.addfile(ti, io.BytesIO(data))
# ./postinst
data = postinst_script.encode("utf-8")
ti = tarfile.TarInfo("./postinst")
ti.size = len(data)
ti.mode = 0o755
ti.mtime = int(time.time())
tar.addfile(ti, io.BytesIO(data))
# ./prerm
data = prerm_script.encode("utf-8")
ti = tarfile.TarInfo("./prerm")
ti.size = len(data)
ti.mode = 0o755
ti.mtime = int(time.time())
tar.addfile(ti, io.BytesIO(data))
control_tar_gz = control_buf.getvalue()
# 3. data.tar.gz member
data_buf = io.BytesIO()
with tarfile.open(fileobj=data_buf, mode="w:gz", format=tarfile.PAX_FORMAT) as tar:
def add_dir(path: str, mode: int = 0o755):
ti = tarfile.TarInfo(path)
ti.type = tarfile.DIRTYPE
ti.mode = mode
ti.mtime = int(time.time())
tar.addfile(ti)
# Base directories
add_dir("./usr")
add_dir("./usr/bin")
add_dir("./usr/lib")
add_dir("./usr/lib/linux-backuper")
add_dir("./etc")
add_dir("./etc/linux-backuper")
add_dir("./var")
add_dir("./var/backups")
add_dir("./var/backups/linux-backuper", mode=0o700)
# Add executable /usr/bin/linux-backuper
bin_src = os.path.join(repo_root, "bin", "linux-backuper")
with open(bin_src, "rb") as f:
bin_data = f.read()
ti = tarfile.TarInfo("./usr/bin/linux-backuper")
ti.size = len(bin_data)
ti.mode = 0o755
ti.mtime = int(time.time())
tar.addfile(ti, io.BytesIO(bin_data))
# Add python library files to /usr/lib/linux-backuper/linux_backuper
lib_src_root = os.path.join(repo_root, "linux_backuper")
for root, dirs, files in os.walk(lib_src_root):
dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")]
rel_dir = os.path.relpath(root, repo_root)
tar_dir = f"./usr/lib/linux-backuper/{rel_dir}".replace("\\", "/")
add_dir(tar_dir)
for file in sorted(files):
if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__":
continue
file_src = os.path.join(root, file)
tar_file = f"{tar_dir}/{file}"
with open(file_src, "rb") as f:
file_data = f.read()
ti = tarfile.TarInfo(tar_file)
ti.size = len(file_data)
ti.mode = 0o644
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
members = [
("debian-binary", debian_binary, 0o644),
("control.tar.gz", control_tar_gz, 0o644),
("data.tar.gz", data_tar_gz, 0o644),
]
create_ar_archive(deb_path, members)
print(f"[SUCCESS] Built Debian package: {deb_path} ({os.path.getsize(deb_path)} bytes)")
return deb_path
def build_tar_package(repo_root: str, out_dir: str, version: str) -> str:
"""Build universal binary tarball distribution."""
tar_filename = f"linux-backuper-{version}.tar.gz"
tar_path = os.path.join(out_dir, tar_filename)
os.makedirs(out_dir, exist_ok=True)
prefix = f"linux-backuper-{version}"
with tarfile.open(tar_path, "w:gz", format=tarfile.PAX_FORMAT) as tar:
# Add root dir
ti = tarfile.TarInfo(prefix)
ti.type = tarfile.DIRTYPE
ti.mode = 0o755
tar.addfile(ti)
# Add install script
install_src = os.path.join(repo_root, "packaging", "install.sh")
if os.path.isfile(install_src):
with open(install_src, "rb") as f:
data = f.read()
ti = tarfile.TarInfo(f"{prefix}/install.sh")
ti.size = len(data)
ti.mode = 0o755
tar.addfile(ti, io.BytesIO(data))
# Add bin launcher
bin_src = os.path.join(repo_root, "bin", "linux-backuper")
with open(bin_src, "rb") as f:
data = f.read()
ti = tarfile.TarInfo(f"{prefix}/bin/linux-backuper")
ti.size = len(data)
ti.mode = 0o755
tar.addfile(ti, io.BytesIO(data))
# Add README
readme_src = os.path.join(repo_root, "README.md")
if os.path.isfile(readme_src):
with open(readme_src, "rb") as f:
data = f.read()
ti = tarfile.TarInfo(f"{prefix}/README.md")
ti.size = len(data)
ti.mode = 0o644
tar.addfile(ti, io.BytesIO(data))
# Add python library
lib_src_root = os.path.join(repo_root, "linux_backuper")
for root, dirs, files in os.walk(lib_src_root):
dirs[:] = [d for d in dirs if d != "__pycache__" and not d.startswith("._")]
rel_dir = os.path.relpath(root, repo_root)
tar_dir = f"{prefix}/{rel_dir}".replace("\\", "/")
ti = tarfile.TarInfo(tar_dir)
ti.type = tarfile.DIRTYPE
ti.mode = 0o755
tar.addfile(ti)
for file in sorted(files):
if file.startswith("._") or file.endswith(".pyc") or file == "__pycache__":
continue
file_src = os.path.join(root, file)
tar_file = f"{tar_dir}/{file}"
with open(file_src, "rb") as f:
data = f.read()
ti = tarfile.TarInfo(tar_file)
ti.size = len(data)
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
def generate_rpm_spec(repo_root: str, out_dir: str, version: str) -> str:
"""Generate standard RPM .spec file for building .rpm packages."""
spec_content = f"""Name: linux-backuper
Version: {version}
Release: 1%{{?dist}}
Summary: Enterprise Linux system snapshot and configuration backup utility
License: MIT
URL: https://gitea.wired.synology.me/soda64/linux-backuper
Source0: linux-backuper-%{{version}}.tar.gz
BuildArch: noarch
Requires: python3 >= 3.6
Recommends: rsync, openssh-clients
%description
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 features fast manifest indexing, live system diffing,
safe restore with dry-run protection, time-bucket pruning, and local-first
remote storage synchronization.
%prep
%setup -q
%build
# Pure python, no compile step needed
%install
rm -rf %{{buildroot}}
mkdir -p %{{buildroot}}/usr/bin
mkdir -p %{{buildroot}}/usr/lib/linux-backuper/linux_backuper
mkdir -p %{{buildroot}}/etc/linux-backuper
mkdir -p %{{buildroot}}/var/backups/linux-backuper
cp -r bin/linux-backuper %{{buildroot}}/usr/bin/linux-backuper
chmod 0755 %{{buildroot}}/usr/bin/linux-backuper
cp -r linux_backuper/* %{{buildroot}}/usr/lib/linux-backuper/linux_backuper/
find %{{buildroot}}/usr/lib/linux-backuper -name "._*" -delete
find %{{buildroot}}/usr/lib/linux-backuper -name "__pycache__" -type d -exec rm -rf {{}} + 2>/dev/null || true
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 <lain@wired.intra> - {version}-1
- Initial release of linux-backuper.
"""
spec_path = os.path.join(out_dir, "linux-backuper.spec")
with open(spec_path, "w", encoding="utf-8") as f:
f.write(spec_content)
print(f"[SUCCESS] Generated RPM spec: {spec_path}")
return spec_path
def build_rpm_package(repo_root: str, out_dir: str, version: str) -> str:
"""Build RPM package using rpmbuild if available."""
spec_path = generate_rpm_spec(repo_root, out_dir, version)
rpmbuild_bin = shutil.which("rpmbuild")
if not rpmbuild_bin:
print("[WARNING] 'rpmbuild' binary not found on this system. RPM spec was generated, but .rpm build skipped.")
return spec_path
# Build source tarball required by rpmbuild
tar_path = build_tar_package(repo_root, out_dir, version)
# Set up isolated rpmbuild directory structure inside out_dir/rpmbuild
rpmbuild_dir = os.path.abspath(os.path.join(out_dir, "rpmbuild"))
for d in ["BUILD", "RPMS", "SOURCES", "SPECS", "SRPMS"]:
os.makedirs(os.path.join(rpmbuild_dir, d), exist_ok=True)
# Copy source tarball to SOURCES and spec to SPECS
shutil.copy2(tar_path, os.path.join(rpmbuild_dir, "SOURCES"))
rpm_spec_in_tree = os.path.join(rpmbuild_dir, "SPECS", "linux-backuper.spec")
shutil.copy2(spec_path, rpm_spec_in_tree)
cmd = [
rpmbuild_bin,
"-bb",
f"--define=_topdir {rpmbuild_dir}",
rpm_spec_in_tree,
]
print(f"[INFO] Running rpmbuild: {' '.join(cmd)}")
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
print(f"[ERROR] rpmbuild failed:\n{result.stderr}", file=sys.stderr)
raise RuntimeError("rpmbuild execution failed")
# Locate generated rpm and copy to out_dir
rpms_found = []
for root, _, files in os.walk(os.path.join(rpmbuild_dir, "RPMS")):
for f in files:
if f.endswith(".rpm"):
full_rpm = os.path.join(root, f)
target_rpm = os.path.join(out_dir, f)
shutil.copy2(full_rpm, target_rpm)
rpms_found.append(target_rpm)
if not rpms_found:
raise RuntimeError("rpmbuild succeeded but no .rpm file was found in RPMS")
# Clean up temporary rpmbuild staging tree so out_dir contains only final artifacts
shutil.rmtree(rpmbuild_dir, ignore_errors=True)
print(f"[SUCCESS] Built RPM package: {rpms_found[0]} ({os.path.getsize(rpms_found[0])} bytes)")
return rpms_found[0]
def main():
parser = argparse.ArgumentParser(description="Package builder for linux-backuper")
parser.add_argument("--deb", action="store_true", help="Build Debian .deb package")
parser.add_argument("--rpm", action="store_true", help="Build RPM .rpm package / spec")
parser.add_argument("--tar", action="store_true", help="Build universal .tar.gz package")
parser.add_argument("--all", action="store_true", help="Build all package types (default)")
parser.add_argument("--out-dir", default="dist", help="Output directory (default: dist)")
args = parser.parse_args()
repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
version = get_version(repo_root)
out_dir = os.path.abspath(args.out_dir)
build_all = args.all or (not args.deb and not args.rpm and not args.tar)
print(f"[INFO] Building packages for linux-backuper v{version} into {out_dir}")
if build_all or args.tar:
build_tar_package(repo_root, out_dir, version)
if build_all or args.deb:
build_deb_package(repo_root, out_dir, version)
if build_all or args.rpm:
build_rpm_package(repo_root, out_dir, version)
if __name__ == "__main__":
main()
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env bash
# linux-backuper generic tarball installer
set -euo pipefail
PREFIX="${PREFIX:-/usr}"
BINDIR="${PREFIX}/bin"
LIBDIR="${PREFIX}/lib/linux-backuper"
CONFDIR="/etc/linux-backuper"
BACKUPDIR="/var/backups/linux-backuper"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SOURCE_ROOT="${SCRIPT_DIR}/.."
if [[ ! -d "${SOURCE_ROOT}/linux_backuper" ]]; then
# In case run from inside extracted tarball where install.sh is at root
if [[ -d "${SCRIPT_DIR}/linux_backuper" ]]; then
SOURCE_ROOT="${SCRIPT_DIR}"
fi
fi
usage() {
cat <<EOF
Usage: $0 [OPTION]
Options:
--install Install linux-backuper to system (default)
--uninstall Remove linux-backuper from system
-h, --help Show this help message
EOF
}
check_python() {
if ! command -v python3 >/dev/null 2>&1; then
echo "[ERROR] python3 is required but not installed." >&2
exit 1
fi
PYTHON_VER="$(python3 -c 'import sys; print(f"{sys.version_info.major}.{sys.version_info.minor}")')"
PYTHON_MAJOR="$(echo "$PYTHON_VER" | cut -d. -f1)"
PYTHON_MINOR="$(echo "$PYTHON_VER" | cut -d. -f2)"
if [[ "$PYTHON_MAJOR" -lt 3 ]] || [[ "$PYTHON_MAJOR" -eq 3 && "$PYTHON_MINOR" -lt 6 ]]; then
echo "[ERROR] Python >= 3.6 required (found $PYTHON_VER)." >&2
exit 1
fi
}
do_install() {
if [[ $EUID -ne 0 ]]; then
echo "[ERROR] Installation requires root privileges. Please run with sudo." >&2
exit 1
fi
check_python
echo "[INFO] Installing linux-backuper..."
mkdir -p "${BINDIR}" "${LIBDIR}" "${CONFDIR}" "${BACKUPDIR}"
chmod 0700 "${BACKUPDIR}"
# Install library files
cp -r "${SOURCE_ROOT}/linux_backuper" "${LIBDIR}/"
find "${LIBDIR}" -type d -exec chmod 0755 {} +
find "${LIBDIR}" -type f -exec chmod 0644 {} +
# Install launcher
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
}
do_uninstall() {
if [[ $EUID -ne 0 ]]; then
echo "[ERROR] Uninstallation requires root privileges. Please run with sudo." >&2
exit 1
fi
echo "[INFO] Uninstalling linux-backuper..."
rm -f "${BINDIR}/linux-backuper"
rm -rf "${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."
}
ACTION="install"
while [[ $# -gt 0 ]]; do
case "$1" in
--install)
ACTION="install"
shift
;;
--uninstall)
ACTION="uninstall"
shift
;;
-h|--help)
usage
exit 0
;;
*)
echo "[ERROR] Unknown option: $1" >&2
usage
exit 1
;;
esac
done
if [[ "$ACTION" == "install" ]]; then
do_install
elif [[ "$ACTION" == "uninstall" ]]; then
do_uninstall
fi
+116
View File
@@ -0,0 +1,116 @@
#!/usr/bin/env python3
"""Helper script to create Gitea release and upload package assets.
Uses only Python standard library (urllib, json, os, sys).
"""
import json
import os
import sys
import urllib.error
import urllib.request
def make_request(url: str, method: str = "GET", data: bytes = None, headers: dict = None):
req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
try:
with urllib.request.urlopen(req) as resp:
content = resp.read()
return resp.status, content
except urllib.error.HTTPError as e:
return e.code, e.read()
def main():
server_url = os.environ.get("GITHUB_SERVER_URL", "").rstrip("/")
owner = os.environ.get("GITHUB_REPOSITORY_OWNER", "")
repo = os.environ.get("GITHUB_REPOSITORY", "").split("/")[-1]
token = os.environ.get("GITEA_TOKEN", "")
ref = os.environ.get("GITHUB_REF", "")
if not ref.startswith("refs/tags/v"):
print(f"[INFO] Ref '{ref}' is not a release tag (refs/tags/v*). Skipping release publishing.")
return 0
tag_name = ref.replace("refs/tags/", "")
api_url = f"{server_url}/api/v1/repos/{owner}/{repo}"
auth_headers = {"Authorization": f"token {token}"}
print(f"[INFO] Publishing release for tag '{tag_name}' to {api_url}")
# 1. Get or create release
status, body = make_request(f"{api_url}/releases/tags/{tag_name}", headers=auth_headers)
rel_id = None
if status == 200:
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[INFO] Existing release found (ID: {rel_id})")
else:
print(f"[INFO] Creating new release for tag {tag_name}...")
payload = json.dumps({
"tag_name": tag_name,
"name": f"linux-backuper {tag_name}",
"body": f"Automated release of linux-backuper {tag_name}.\n\nArtifacts:\n- Native Debian package (.deb)\n- Native Red Hat / Fedora package (.rpm)\n- Universal standalone archive (.tar.gz)",
"draft": False,
"prerelease": False,
}).encode("utf-8")
headers = dict(auth_headers)
headers["Content-Type"] = "application/json"
status, body = make_request(f"{api_url}/releases", method="POST", data=payload, headers=headers)
if status in (200, 201):
data = json.loads(body.decode("utf-8"))
rel_id = data.get("id")
print(f"[SUCCESS] Created release (ID: {rel_id})")
else:
print(f"[ERROR] Failed to create release: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
# 2. Get existing assets
status, body = make_request(f"{api_url}/releases/{rel_id}/assets", headers=auth_headers)
existing_assets = {}
if status == 200:
for a in json.loads(body.decode("utf-8")):
existing_assets[a.get("name")] = a.get("id")
# 3. Upload assets from dist directory
dist_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dist")
if not os.path.isdir(dist_dir):
print(f"[ERROR] Dist directory not found at {dist_dir}", file=sys.stderr)
return 1
asset_files = [f for f in os.listdir(dist_dir) if f.endswith((".tar.gz", ".deb", ".rpm")) and not f.startswith(".")]
for fname in sorted(asset_files):
fpath = os.path.join(dist_dir, fname)
if not os.path.isfile(fpath):
continue
# If asset exists, delete old one first
if fname in existing_assets:
asset_id = existing_assets[fname]
print(f"[INFO] Deleting existing asset {fname} (ID: {asset_id})...")
make_request(f"{api_url}/releases/{rel_id}/assets/{asset_id}", method="DELETE", headers=auth_headers)
print(f"[INFO] Uploading asset: {fname} ({os.path.getsize(fpath)} bytes)...")
with open(fpath, "rb") as f:
data = f.read()
headers = dict(auth_headers)
headers["Content-Type"] = "application/octet-stream"
status, body = make_request(
f"{api_url}/releases/{rel_id}/assets?name={fname}",
method="POST",
data=data,
headers=headers
)
if status in (200, 201):
print(f"[SUCCESS] Uploaded {fname}")
else:
print(f"[ERROR] Failed to upload {fname}: HTTP {status} - {body.decode('utf-8', errors='replace')}", file=sys.stderr)
return 1
print("[SUCCESS] All release assets uploaded successfully.")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
# tests/__init__.py
+300
View File
@@ -0,0 +1,300 @@
import io
import json
import os
import stat
import sys
import tarfile
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.cli import main
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_CORRUPTED, EXIT_DRY_RUN
class TestCliTracerBullet(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_linux_backuper_")
self.backup_dir = os.path.join(self.temp_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
# Mock etc directory with dummy file
self.mock_etc = os.path.join(self.temp_dir, "etc")
os.makedirs(self.mock_etc, exist_ok=True)
with open(os.path.join(self.mock_etc, "hostname"), "w") as f:
f.write("test-host.local\n")
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
f.write("key=value\n")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_version_flag(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with self.assertRaises(SystemExit) as cm:
main(["--version"])
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
self.assertIn("1.0.0", stdout.getvalue())
def test_help_flag(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
with self.assertRaises(SystemExit) as cm:
main(["--help"])
self.assertEqual(cm.exception.code, EXIT_SUCCESS)
self.assertIn("linux-backuper", stdout.getvalue())
self.assertIn("snapshot", stdout.getvalue())
def test_snapshot_tracer_bullet_creates_archive(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--profile", "quick",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
output_data = json.loads(stdout.getvalue().strip())
self.assertIn("snapshot_id", output_data)
self.assertIn("archive_path", output_data)
archive_path = output_data["archive_path"]
self.assertTrue(os.path.exists(archive_path))
# Check file permissions (0600 on POSIX)
file_mode = stat.S_IMODE(os.stat(archive_path).st_mode)
self.assertEqual(file_mode, 0o600)
# Verify tar members: manifest.json MUST be the very first member
with tarfile.open(archive_path, "r:gz") as tar:
members = tar.getmembers()
self.assertGreater(len(members), 0)
self.assertEqual(members[0].name, "manifest.json")
# Extract manifest and verify structure
manifest_file = tar.extractfile(members[0])
manifest = json.loads(manifest_file.read().decode("utf-8"))
self.assertEqual(manifest["snapshot_id"], output_data["snapshot_id"])
self.assertEqual(manifest["profile"], "quick")
self.assertIn("os", manifest)
self.assertIn("files_sha256", manifest)
def test_list_command(self):
# First create a snapshot
with patch("sys.stdout", io.StringIO()), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc])
# Now test listing
stdout = io.StringIO()
with patch("sys.stdout", stdout):
exit_code = main(["list", "--target-dir", self.backup_dir, "--json"])
self.assertEqual(exit_code, EXIT_SUCCESS)
listed = json.loads(stdout.getvalue().strip())
self.assertEqual(len(listed), 1)
self.assertIn("snapshot_id", listed[0])
self.assertEqual(listed[0]["profile"], "quick")
def test_verify_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_data = json.loads(stdout.getvalue().strip())
snap_id = snap_data["snapshot_id"]
# Verify should succeed on untouched archive
with patch("sys.stdout", io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
# Corrupt archive CRC
archive_path = snap_data["archive_path"]
with open(archive_path, "r+b") as f:
f.seek(-4, os.SEEK_END)
f.write(b"\x00\x00\x00\x00")
# Verify should detect corruption and return EXIT_CORRUPTED (3)
with patch("sys.stdout", io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_CORRUPTED)
def test_snapshot_sanitize_redacts_secrets(self):
# Create sensitive files in mock_etc
shadow_path = os.path.join(self.mock_etc, "shadow")
with open(shadow_path, "w") as f:
f.write("root:$6$secretpasswordhash:19000:0:99999:7:::\n")
ssh_key_path = os.path.join(self.mock_etc, "ssh_host_ed25519_key")
with open(ssh_key_path, "w") as f:
f.write("-----BEGIN OPENSSH PRIVATE KEY-----\nsecret\n-----END OPENSSH PRIVATE KEY-----\n")
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--sanitize",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
with tarfile.open(archive_path, "r:gz") as tar:
names = tar.getnames()
# Sensitive files must NOT be in archive data/
self.assertFalse(any("data" in n and "shadow" in n for n in names))
self.assertFalse(any("data" in n and "ssh_host_ed25519_key" in n for n in names))
# meta/sanitized.txt must exist and list them
self.assertIn("meta/sanitized.txt", names)
sanitized_log = tar.extractfile("meta/sanitized.txt").read().decode("utf-8")
self.assertIn("shadow", sanitized_log)
self.assertIn("ssh_host_ed25519_key", sanitized_log)
def test_snapshot_no_compression(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", self.mock_etc,
"--no-compression",
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
snap_data = json.loads(stdout.getvalue().strip())
archive_path = snap_data["archive_path"]
self.assertTrue(archive_path.endswith(".tar"))
# Verify it is openable as uncompressed tar
with tarfile.open(archive_path, "r:") as tar:
self.assertEqual(tar.getmembers()[0].name, "manifest.json")
# Verify command works on uncompressed tar
snap_id = snap_data["snapshot_id"]
with patch("sys.stdout", io.StringIO()):
exit_code = main(["verify", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
def test_show_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Text mode
stdout_show = io.StringIO()
with patch("sys.stdout", stdout_show):
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir])
self.assertEqual(exit_code, EXIT_SUCCESS)
self.assertIn("Snapshot ID:", stdout_show.getvalue())
self.assertIn(snap_id, stdout_show.getvalue())
# JSON mode
stdout_json = io.StringIO()
with patch("sys.stdout", stdout_json):
exit_code = main(["show", snap_id, "--target-dir", self.backup_dir, "--json"])
self.assertEqual(exit_code, EXIT_SUCCESS)
data = json.loads(stdout_json.getvalue().strip())
self.assertEqual(data["snapshot_id"], snap_id)
def test_extract_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
dest_file = os.path.join(self.temp_dir, "extracted_hostname.txt")
# Extract filename
sample_path = [f for f in os.listdir(self.mock_etc) if f == "hostname"][0]
exit_code = main([
"extract", snap_id,
"--file", sample_path,
"--out", dest_file,
"--target-dir", self.backup_dir
])
self.assertEqual(exit_code, EXIT_SUCCESS)
self.assertTrue(os.path.isfile(dest_file))
with open(dest_file, "r") as f:
self.assertEqual(f.read(), "test-host.local\n")
def test_diff_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Modify sample.conf on mock etc
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
f.write("key=modified_value\n")
# Test live diff
stdout_diff = io.StringIO()
with patch("sys.stdout", stdout_diff):
exit_code = main([
"diff", snap_id,
"--target-dir", self.backup_dir,
"--target-root", self.temp_dir,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
diff_data = json.loads(stdout_diff.getvalue().strip())
self.assertEqual(diff_data["type"], "live_vs_snapshot")
self.assertTrue(any("sample.conf" in f for f in diff_data["files"]["modified"]))
def test_restore_dry_run_exits_with_code_5(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Default restore (no --force) must return EXIT_DRY_RUN (5)
stdout_restore = io.StringIO()
with patch("sys.stdout", stdout_restore):
exit_code = main([
"restore", snap_id,
"--target-dir", self.backup_dir,
"--target-root", self.temp_dir
])
self.assertEqual(exit_code, EXIT_DRY_RUN)
self.assertIn("RESTORE EXECUTION PLAN (Dry Run)", stdout_restore.getvalue())
def test_restore_force_executes_successfully(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
main(["snapshot", "--target-dir", self.backup_dir, "--paths", self.mock_etc, "--json"])
snap_id = json.loads(stdout.getvalue().strip())["snapshot_id"]
# Alter sample.conf
with open(os.path.join(self.mock_etc, "sample.conf"), "w") as f:
f.write("key=tampered_value\n")
# Restore with --force and non-root test override
pid_file = os.path.join(self.temp_dir, "restore_test.pid")
stdout_restore = io.StringIO()
with patch("sys.stdout", stdout_restore), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"restore", snap_id,
"--force",
"--target-dir", self.backup_dir,
"--target-root", self.temp_dir,
"--pid-path", pid_file,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
res = json.loads(stdout_restore.getvalue().strip())
self.assertEqual(res["status"], "success")
self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_"))
# Check sample.conf restored
with open(os.path.join(self.mock_etc, "sample.conf"), "r") as f:
self.assertEqual(f.read(), "key=value\n")
if __name__ == "__main__":
unittest.main()
+59
View File
@@ -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()
+80
View File
@@ -0,0 +1,80 @@
import os
import tempfile
import unittest
from linux_backuper.core.detector import detect_distro, parse_os_release
from linux_backuper.models import OsInfo
class TestOsDetector(unittest.TestCase):
def test_parse_almalinux_9(self):
content = """NAME="AlmaLinux"
VERSION="9.4 (Seafoam)"
ID="almalinux"
ID_LIKE="rhel centos fedora"
VERSION_ID="9.4"
PRETTY_NAME="AlmaLinux 9.4 (Seafoam)"
"""
info = parse_os_release(content)
self.assertEqual(info["id"], "almalinux")
self.assertEqual(info["name"], "AlmaLinux")
self.assertEqual(info["version_id"], "9.4")
def test_parse_debian_12(self):
content = """PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
NAME="Debian GNU/Linux"
VERSION_ID="12"
VERSION="12 (bookworm)"
VERSION_CODENAME=bookworm
ID=debian
"""
info = parse_os_release(content)
self.assertEqual(info["id"], "debian")
self.assertEqual(info["name"], "Debian GNU/Linux")
self.assertEqual(info["version_id"], "12")
def test_parse_ubuntu_2204(self):
content = """NAME="Ubuntu"
VERSION="22.04.4 LTS (Jammy Jellyfish)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 22.04.4 LTS"
VERSION_ID="22.04"
"""
info = parse_os_release(content)
self.assertEqual(info["id"], "ubuntu")
self.assertEqual(info["name"], "Ubuntu")
self.assertEqual(info["version_id"], "22.04")
def test_parse_arch(self):
content = """NAME="Arch Linux"
PRETTY_NAME="Arch Linux"
ID=arch
BUILD_ID=rolling
"""
info = parse_os_release(content)
self.assertEqual(info["id"], "arch")
self.assertEqual(info["name"], "Arch Linux")
self.assertEqual(info["version_id"], "rolling")
def test_detect_distro_with_custom_file(self):
with tempfile.NamedTemporaryFile("w+", delete=False) as f:
f.write("""NAME="Fedora Linux"
VERSION="40 (Cloud Edition)"
ID=fedora
VERSION_ID="40"
""")
temp_path = f.name
try:
os_info = detect_distro(os_release_path=temp_path)
self.assertIsInstance(os_info, OsInfo)
self.assertEqual(os_info.distro_id, "fedora")
self.assertEqual(os_info.distro_name, "Fedora Linux")
self.assertEqual(os_info.version_id, "40")
self.assertTrue(len(os_info.arch) > 0)
self.assertTrue(len(os_info.kernel) > 0)
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
if __name__ == "__main__":
unittest.main()
+140
View File
@@ -0,0 +1,140 @@
"""Unit tests for DiffEngine."""
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.diff import DiffEngine
from linux_backuper.models import SnapshotManifest
class TestDiffEngine(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_diff_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
self.mock_root = os.path.join(self.test_dir, "root")
self.mock_etc = os.path.join(self.mock_root, "etc")
os.makedirs(self.mock_etc, exist_ok=True)
# File A
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
f.write("127.0.0.1 localhost\n")
# File B
with open(os.path.join(self.mock_etc, "issue"), "w") as f:
f.write("Test Linux\n")
# Snapshot 1
archiver = SnapshotArchiver(target_dir=self.backup_dir)
entries1, sha1, bytes1, _ = archiver.collect_file_list([self.mock_etc])
# Write fake meta/packages.txt into archive
temp_meta = os.path.join(self.test_dir, "meta1")
os.makedirs(temp_meta, exist_ok=True)
pkg_file1 = os.path.join(temp_meta, "packages.txt")
with open(pkg_file1, "w") as f:
f.write("bash 5.1.0\ncoreutils 8.32\ncurl 7.74.0\n")
entries1.append((pkg_file1, "meta/packages.txt"))
sha1["meta/packages.txt"] = "dummy"
m1 = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap1",
created_at="2026-10-01T12:00:00Z",
hostname="host1",
profile="quick",
compression="gzip",
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
package_manager="dpkg",
package_count=3,
included_paths=[self.mock_etc],
stats={"file_count": len(entries1), "uncompressed_bytes": bytes1, "compressed_bytes": 0},
files_sha256=sha1
)
self.archive1 = archiver.create_snapshot_archive("snap1", m1, entries1)
# Modify file A, delete file B, add file C for Snapshot 2
with open(os.path.join(self.mock_etc, "hosts"), "w") as f:
f.write("127.0.0.1 localhost\n192.168.1.1 router\n")
os.remove(os.path.join(self.mock_etc, "issue"))
with open(os.path.join(self.mock_etc, "resolv.conf"), "w") as f:
f.write("nameserver 1.1.1.1\n")
entries2, sha2, bytes2, _ = archiver.collect_file_list([self.mock_etc])
temp_meta2 = os.path.join(self.test_dir, "meta2")
os.makedirs(temp_meta2, exist_ok=True)
pkg_file2 = os.path.join(temp_meta2, "packages.txt")
with open(pkg_file2, "w") as f:
f.write("bash 5.2.0\ncoreutils 8.32\nwget 1.21\n") # bash upgraded, curl removed, wget added
entries2.append((pkg_file2, "meta/packages.txt"))
sha2["meta/packages.txt"] = "dummy2"
m2 = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap2",
created_at="2026-10-02T12:00:00Z",
hostname="host1",
profile="quick",
compression="gzip",
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
package_manager="dpkg",
package_count=3,
included_paths=[self.mock_etc],
stats={"file_count": len(entries2), "uncompressed_bytes": bytes2, "compressed_bytes": 0},
files_sha256=sha2
)
self.archive2 = archiver.create_snapshot_archive("snap2", m2, entries2)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_diff_snapshots(self):
engine = DiffEngine(target_dir=self.backup_dir)
res = engine.diff_snapshots("snap1", "snap2")
self.assertEqual(res["type"], "snapshot_vs_snapshot")
self.assertEqual(res["snapshot_1"], "snap1")
self.assertEqual(res["snapshot_2"], "snap2")
files = res["files"]
# hosts is modified
self.assertTrue(any("hosts" in f for f in files["modified"]))
# resolv.conf is added
self.assertTrue(any("resolv.conf" in f for f in files["added"]))
# issue is removed
self.assertTrue(any("issue" in f for f in files["removed"]))
# Check packages
pkgs = res["packages"]
self.assertIn("wget", pkgs["added"])
self.assertIn("curl", pkgs["removed"])
self.assertIn("bash", pkgs["changed"])
self.assertEqual(pkgs["changed"]["bash"]["old"], "5.1.0")
self.assertEqual(pkgs["changed"]["bash"]["new"], "5.2.0")
def test_diff_with_live(self):
engine = DiffEngine(target_dir=self.backup_dir)
# Compare live mock_root against snap1
# Currently mock_root has modified hosts, deleted issue, added resolv.conf
res = engine.diff_with_live("snap1", target_root=self.mock_root)
self.assertEqual(res["type"], "live_vs_snapshot")
files = res["files"]
self.assertTrue(any("hosts" in f for f in files["modified"]))
self.assertTrue(any("issue" in f for f in files["missing_on_live"]))
self.assertTrue(any("resolv.conf" in f for f in files["added_on_live"]))
def test_generate_unified_file_diff(self):
engine = DiffEngine(target_dir=self.backup_dir)
diff_text = engine.generate_unified_file_diff("snap1", "etc/hosts", target_root=self.mock_root)
self.assertIsNotNone(diff_text)
self.assertIn("+192.168.1.1 router", diff_text)
if __name__ == "__main__":
unittest.main()
+188
View File
@@ -0,0 +1,188 @@
import json
import os
import tempfile
import unittest
from unittest.mock import patch, MagicMock
from linux_backuper.models import PackageItem, StorageState, NetworkState
from linux_backuper.managers.base import BasePackageManager
from linux_backuper.managers.rpm import RpmPackageManager
from linux_backuper.managers.dpkg import DpkgPackageManager
from linux_backuper.managers.pacman import PacmanPackageManager
from linux_backuper.core.inspector import SystemInspector
class TestPackageManagerAdapters(unittest.TestCase):
def test_rpm_parser(self):
sample_output = """bash|5.1.8-9.el9|x86_64
coreutils|8.32-35.el9|x86_64
systemd|252-32.el9_4.6|x86_64
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = RpmPackageManager()
packages = mgr.list_packages()
self.assertEqual(len(packages), 3)
self.assertEqual(packages[0].name, "bash")
self.assertEqual(packages[0].version, "5.1.8-9.el9")
self.assertEqual(packages[0].arch, "x86_64")
def test_dpkg_parser(self):
sample_output = """adduser|3.134ubuntu1|all
apt|2.4.12|amd64
systemd|249.11-0ubuntu3.12|amd64
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = DpkgPackageManager()
packages = mgr.list_packages()
self.assertEqual(len(packages), 3)
self.assertEqual(packages[1].name, "apt")
self.assertEqual(packages[1].version, "2.4.12")
self.assertEqual(packages[1].arch, "amd64")
def test_pacman_parser(self):
sample_output = """bash 5.2.026-2
coreutils 9.5-1
systemd 255.7-1
"""
with patch("subprocess.run") as mock_run:
mock_run.return_value = MagicMock(returncode=0, stdout=sample_output, stderr="")
mgr = PacmanPackageManager()
packages = mgr.list_packages()
self.assertEqual(len(packages), 3)
self.assertEqual(packages[0].name, "bash")
self.assertEqual(packages[0].version, "5.2.026-2")
class TestSystemInspector(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_inspector_")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_inspect_users_and_groups_parsing(self):
passwd_content = """root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
soda64:x:1000:1000:Soda User:/home/soda64:/bin/zsh
"""
group_content = """root:x:0:
wheel:x:10:soda64
soda64:x:1000:
"""
passwd_file = os.path.join(self.temp_dir, "passwd")
group_file = os.path.join(self.temp_dir, "group")
with open(passwd_file, "w") as f:
f.write(passwd_content)
with open(group_file, "w") as f:
f.write(group_content)
inspector = SystemInspector(distro_id="almalinux")
users_info = inspector.parse_users_and_groups(passwd_path=passwd_file, group_path=group_file)
self.assertEqual(len(users_info["users"]), 3)
self.assertEqual(users_info["users"][0]["username"], "root")
self.assertEqual(users_info["users"][0]["uid"], 0)
self.assertEqual(users_info["users"][2]["shell"], "/bin/zsh")
self.assertEqual(len(users_info["groups"]), 3)
self.assertEqual(users_info["groups"][1]["name"], "wheel")
def test_inspect_storage_json_parsing(self):
sample_lsblk_json = json.dumps({
"blockdevices": [
{"name": "sda", "size": "50G", "type": "disk", "children": [
{"name": "sda1", "size": "1G", "type": "part", "mountpoint": "/boot"},
{"name": "sda2", "size": "49G", "type": "part", "mountpoint": "/"}
]}
]
})
sample_df_output = """Filesystem Type Size Used Avail Use% Mounted on
/dev/sda2 ext4 48G 12G 34G 27% /
/dev/sda1 ext4 976M 142M 767M 16% /boot
"""
with patch("subprocess.run") as mock_run:
def side_effect(cmd, *args, **kwargs):
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
if "lsblk" in cmd_str:
return MagicMock(returncode=0, stdout=sample_lsblk_json, stderr="")
if "df" in cmd_str:
return MagicMock(returncode=0, stdout=sample_df_output, stderr="")
return MagicMock(returncode=1, stdout="", stderr="not found")
mock_run.side_effect = side_effect
inspector = SystemInspector(distro_id="debian")
storage_state = inspector.inspect_storage()
self.assertIsInstance(storage_state, StorageState)
self.assertEqual(len(storage_state.block_devices), 1)
self.assertEqual(storage_state.block_devices[0]["name"], "sda")
self.assertEqual(len(storage_state.mount_points), 2)
self.assertEqual(storage_state.mount_points[0]["mount"], "/")
def test_inspect_network_parsing(self):
sample_ip_a = json.dumps([
{
"ifname": "eth0",
"flags": ["UP", "LOWER_UP"],
"addr_info": [
{"family": "inet", "local": "192.168.10.55", "prefixlen": 24}
]
}
])
sample_ip_r = json.dumps([
{"dst": "default", "gateway": "192.168.10.1", "dev": "eth0"}
])
sample_resolv = "nameserver 192.168.10.1\nnameserver 1.1.1.1\n"
resolv_path = os.path.join(self.temp_dir, "resolv.conf")
with open(resolv_path, "w") as f:
f.write(sample_resolv)
with patch("subprocess.run") as mock_run:
def side_effect(cmd, *args, **kwargs):
cmd_str = " ".join(cmd) if isinstance(cmd, list) else cmd
if "ip -j a" in cmd_str or "ip" in cmd_str and "a" in cmd_str:
return MagicMock(returncode=0, stdout=sample_ip_a, stderr="")
if "ip -j r" in cmd_str or "ip" in cmd_str and "r" in cmd_str:
return MagicMock(returncode=0, stdout=sample_ip_r, stderr="")
return MagicMock(returncode=1, stdout="", stderr="")
mock_run.side_effect = side_effect
inspector = SystemInspector(distro_id="almalinux")
net_state = inspector.inspect_network(resolv_path=resolv_path)
self.assertIsInstance(net_state, NetworkState)
self.assertEqual(len(net_state.interfaces), 1)
self.assertEqual(net_state.interfaces[0]["name"], "eth0")
self.assertEqual(len(net_state.routes), 1)
self.assertEqual(net_state.routes[0]["gateway"], "192.168.10.1")
self.assertEqual(net_state.dns_servers, ["192.168.10.1", "1.1.1.1"])
def test_dump_meta_files(self):
inspector = SystemInspector(distro_id="almalinux")
with patch.object(inspector, "inspect_packages", return_value=[
PackageItem(name="bash", version="5.1.8", arch="x86_64")
]):
meta_dir = os.path.join(self.temp_dir, "meta")
files_map = inspector.dump_meta_files(meta_dir)
self.assertIn("meta/packages.txt", files_map)
self.assertIn("meta/users.json", files_map)
self.assertIn("meta/storage.json", files_map)
self.assertIn("meta/network.json", files_map)
self.assertIn("meta/kernel.txt", files_map)
self.assertIn("meta/hardware.txt", files_map)
# Check that files actually exist on disk
for rel_path, abs_path in files_map.items():
self.assertTrue(os.path.isfile(abs_path), f"File {abs_path} was not created")
# Check content of packages.txt
with open(files_map["meta/packages.txt"], "r") as f:
content = f.read()
self.assertIn("bash|5.1.8|x86_64", content)
if __name__ == "__main__":
unittest.main()
+51
View File
@@ -0,0 +1,51 @@
import os
import tempfile
import unittest
from linux_backuper.core.lock import SingleInstanceLock, LockAcquisitionError
class TestSingleInstanceLock(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_lock_")
self.pid_path = os.path.join(self.temp_dir, "test.pid")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_lock_acquire_and_release(self):
lock1 = SingleInstanceLock(pid_path=self.pid_path)
self.assertTrue(lock1.acquire())
self.assertTrue(os.path.isfile(self.pid_path))
with open(self.pid_path, "r") as f:
pid = int(f.read().strip())
self.assertEqual(pid, os.getpid())
# Second lock attempt must fail
lock2 = SingleInstanceLock(pid_path=self.pid_path)
with self.assertRaises(LockAcquisitionError):
lock2.acquire()
# Release first lock
lock1.release()
# Now lock2 should succeed
self.assertTrue(lock2.acquire())
lock2.release()
def test_lock_context_manager(self):
with SingleInstanceLock(pid_path=self.pid_path):
self.assertTrue(os.path.isfile(self.pid_path))
# Nested lock should fail
lock2 = SingleInstanceLock(pid_path=self.pid_path)
with self.assertRaises(LockAcquisitionError):
lock2.acquire()
# After context exit, lock file is unlinked or released
lock3 = SingleInstanceLock(pid_path=self.pid_path)
self.assertTrue(lock3.acquire())
lock3.release()
if __name__ == "__main__":
unittest.main()
+121
View File
@@ -0,0 +1,121 @@
import importlib.util
import os
import shutil
import tarfile
import tempfile
import unittest
from linux_backuper import __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):
"""Test Debian, RPM, and tar.gz package building."""
def setUp(self):
self.repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
self.test_dir = tempfile.mkdtemp(prefix="test_packaging_")
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_get_version(self):
v = get_version(self.repo_root)
self.assertEqual(v, __version__)
def test_build_tar_package(self):
tar_path = build_tar_package(self.repo_root, self.test_dir, __version__)
self.assertTrue(os.path.isfile(tar_path))
with tarfile.open(tar_path, "r:gz") as tar:
names = tar.getnames()
prefix = f"linux-backuper-{__version__}"
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__)
self.assertTrue(os.path.isfile(deb_path))
with open(deb_path, "rb") as f:
header = f.read(8)
self.assertEqual(header, b"!<arch>\n")
# Read first member header (debian-binary)
m1_hdr = f.read(60)
self.assertTrue(m1_hdr.startswith(b"debian-binary"))
m1_data = f.read(4)
self.assertEqual(m1_data, b"2.0\n")
# Read second member header (control.tar.gz)
m2_hdr = f.read(60)
self.assertTrue(m2_hdr.startswith(b"control.tar.gz"))
m2_size = int(m2_hdr[48:58].strip())
m2_data = f.read(m2_size)
if m2_size % 2 != 0:
f.read(1) # padding
# Verify control.tar.gz content
control_tar_path = os.path.join(self.test_dir, "control.tar.gz")
with open(control_tar_path, "wb") as cf:
cf.write(m2_data)
with tarfile.open(control_tar_path, "r:gz") as ctar:
cnames = ctar.getnames()
self.assertIn("./control", cnames)
control_file = ctar.extractfile("./control")
self.assertIsNotNone(control_file)
control_text = control_file.read().decode("utf-8")
self.assertIn("Package: linux-backuper", control_text)
self.assertIn(f"Version: {__version__}", control_text)
# Read third member header (data.tar.gz)
m3_hdr = f.read(60)
self.assertTrue(m3_hdr.startswith(b"data.tar.gz"))
m3_size = int(m3_hdr[48:58].strip())
m3_data = f.read(m3_size)
data_tar_path = os.path.join(self.test_dir, "data.tar.gz")
with open(data_tar_path, "wb") as df:
df.write(m3_data)
with tarfile.open(data_tar_path, "r:gz") as dtar:
dnames = dtar.getnames()
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__)
self.assertTrue(os.path.isfile(spec_path))
with open(spec_path, "r", encoding="utf-8") as f:
content = f.read()
self.assertIn("Name: linux-backuper", content)
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__":
unittest.main()
+74
View File
@@ -0,0 +1,74 @@
import json
import os
import tempfile
import unittest
from linux_backuper.core.profiles import ProfileManager
from linux_backuper.models import ProfileConfig
class TestProfileManager(unittest.TestCase):
def setUp(self):
self.temp_dir = tempfile.mkdtemp(prefix="test_profiles_")
def tearDown(self):
import shutil
shutil.rmtree(self.temp_dir, ignore_errors=True)
def test_builtin_profiles_exist(self):
mgr = ProfileManager()
profiles = mgr.list_profiles()
names = [p.name for p in profiles]
self.assertIn("quick", names)
self.assertIn("system", names)
self.assertIn("full", names)
def test_quick_profile_paths(self):
mgr = ProfileManager()
quick = mgr.get_profile("quick")
self.assertEqual(quick.name, "quick")
self.assertIn("/etc", quick.included_paths)
self.assertNotIn("/boot", quick.included_paths)
def test_system_profile_paths(self):
mgr = ProfileManager()
system = mgr.get_profile("system")
self.assertIn("/etc", system.included_paths)
self.assertIn("/boot", system.included_paths)
def test_full_profile_paths(self):
mgr = ProfileManager()
full = mgr.get_profile("full")
self.assertIn("/etc", full.included_paths)
self.assertIn("/boot", full.included_paths)
self.assertIn("/var/spool/cron", full.included_paths)
self.assertIn("/var/lib/systemd", full.included_paths)
def test_custom_profile_from_config(self):
config_path = os.path.join(self.temp_dir, "linux-backuper.json")
custom_data = {
"profiles": {
"custom_web": {
"description": "Web server custom profile",
"included_paths": ["/etc", "/var/www/html"],
"exclude_patterns": ["*.log", "*.tmp"],
"collect_packages": True
}
}
}
with open(config_path, "w") as f:
json.dump(custom_data, f)
mgr = ProfileManager(config_path=config_path)
p = mgr.get_profile("custom_web")
self.assertEqual(p.name, "custom_web")
self.assertIn("/var/www/html", p.included_paths)
self.assertIn("*.log", p.exclude_patterns)
def test_unknown_profile_raises_key_error(self):
mgr = ProfileManager()
with self.assertRaises(KeyError):
mgr.get_profile("non_existent_profile_xyz")
if __name__ == "__main__":
unittest.main()
+131
View File
@@ -0,0 +1,131 @@
"""Unit tests for SafeRestoreEngine."""
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.restore import SafeRestoreEngine, DryRunException
from linux_backuper.models import SnapshotManifest
class TestSafeRestoreEngine(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_restore_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
self.mock_root = os.path.join(self.test_dir, "root")
self.mock_etc = os.path.join(self.mock_root, "etc")
os.makedirs(self.mock_etc, exist_ok=True)
# Create files to back up
self.hosts_path = os.path.join(self.mock_etc, "hosts")
with open(self.hosts_path, "w") as f:
f.write("127.0.0.1 localhost\n")
self.resolv_path = os.path.join(self.mock_etc, "resolv.conf")
with open(self.resolv_path, "w") as f:
f.write("nameserver 8.8.8.8\n")
self.fstab_path = os.path.join(self.mock_etc, "fstab")
with open(self.fstab_path, "w") as f:
f.write("/dev/sda1 / ext4 defaults 0 1\n")
# Create netplan file (sensitive network)
self.netplan_dir = os.path.join(self.mock_etc, "netplan")
os.makedirs(self.netplan_dir, exist_ok=True)
self.net_cfg = os.path.join(self.netplan_dir, "01-netcfg.yaml")
with open(self.net_cfg, "w") as f:
f.write("network: {version: 2}\n")
# Create base snapshot
archiver = SnapshotArchiver(target_dir=self.backup_dir)
entries, sha, uncompressed, _ = archiver.collect_file_list([self.mock_etc])
m = SnapshotManifest(
schema_version="1.0",
snapshot_id="test_snap",
created_at="2026-10-01T12:00:00Z",
hostname="host1",
profile="quick",
compression="gzip",
os={"distro_id": "debian", "distro_name": "Debian", "version_id": "12", "kernel": "6.1", "arch": "x86_64"},
package_manager="dpkg",
package_count=0,
included_paths=[self.mock_etc],
stats={"file_count": len(entries), "uncompressed_bytes": uncompressed, "compressed_bytes": 0},
files_sha256=sha
)
self.archive_path = archiver.create_snapshot_archive("test_snap", m, entries)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_plan_restore_skips_dynamic_and_fstab(self):
engine = SafeRestoreEngine(target_dir=self.backup_dir)
plan = engine.plan_restore("test_snap", target_root=self.mock_root, include_fstab=False)
actions_by_path = {item.rel_path: item for item in plan.items}
# resolv.conf must be skipped (dynamic system file)
resolv_item = [item for item in plan.items if "resolv.conf" in item.rel_path][0]
self.assertEqual(resolv_item.action, "skip")
self.assertIn("volatile", resolv_item.reason.lower())
# fstab must be skipped unless include_fstab is set
fstab_item = [item for item in plan.items if "fstab" in item.rel_path][0]
self.assertEqual(fstab_item.action, "skip")
self.assertIn("fstab", fstab_item.reason.lower())
# netplan must be flagged as sensitive network
net_item = [item for item in plan.items if "01-netcfg.yaml" in item.rel_path][0]
self.assertTrue(net_item.is_sensitive_network)
def test_dry_run_raises_and_modifies_nothing(self):
# Modify hosts on mock_root
with open(self.hosts_path, "w") as f:
f.write("corrupted hosts content\n")
engine = SafeRestoreEngine(target_dir=self.backup_dir)
plan = engine.plan_restore("test_snap", target_root=self.mock_root)
with self.assertRaises(DryRunException):
engine.execute_restore(plan, force=False)
# Verify hosts content was NOT modified
with open(self.hosts_path, "r") as f:
self.assertEqual(f.read(), "corrupted hosts content\n")
def test_execute_restore_with_force_creates_safety_snapshot_and_restores(self):
# Corrupt hosts
with open(self.hosts_path, "w") as f:
f.write("corrupted content\n")
# Delete netplan config
os.remove(self.net_cfg)
engine = SafeRestoreEngine(target_dir=self.backup_dir)
plan = engine.plan_restore("test_snap", target_root=self.mock_root)
# Allow non-root flock fallback
pid_file = os.path.join(self.test_dir, "test.pid")
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
res = engine.execute_restore(plan, force=True, pid_path=pid_file)
self.assertEqual(res["status"], "success")
self.assertTrue(res["safety_snapshot_id"].startswith("pre_restore_"))
self.assertTrue(os.path.isfile(res["safety_archive_path"]))
# Verify hosts restored
with open(self.hosts_path, "r") as f:
self.assertEqual(f.read(), "127.0.0.1 localhost\n")
# Verify netplan recreated
self.assertTrue(os.path.isfile(self.net_cfg))
with open(self.net_cfg, "r") as f:
self.assertEqual(f.read(), "network: {version: 2}\n")
if __name__ == "__main__":
unittest.main()
+195
View File
@@ -0,0 +1,195 @@
"""Unit tests for RetentionEngine and lifecycle pruning."""
import datetime
import io
import json
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR
from linux_backuper.core.retention import RetentionEngine, parse_snapshot_datetime
from linux_backuper.models import SnapshotManifest
class TestRetentionEngine(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_retention_")
self.backup_dir = os.path.join(self.test_dir, "backups")
os.makedirs(self.backup_dir, exist_ok=True)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def _create_synthetic_manifest(self, snap_id: str, dt_str: str) -> SnapshotManifest:
return SnapshotManifest(
schema_version="1.0",
snapshot_id=snap_id,
created_at=dt_str,
hostname="testhost",
profile="quick",
compression="gzip",
os={},
package_manager="dpkg",
package_count=0,
included_paths=["/etc"],
stats={"file_count": 10, "uncompressed_bytes": 1000, "compressed_bytes": 500},
files_sha256={}
)
def test_keep_last(self):
# 5 snapshots
snaps = [
self._create_synthetic_manifest(f"snap_{i}", f"2026-10-0{i+1}T10:00:00Z")
for i in range(5)
]
retention = RetentionEngine(keep_last=2)
kept, pruned = retention.calculate_prune_set(snaps)
self.assertEqual(len(kept), 2)
self.assertEqual(len(pruned), 3)
self.assertEqual([s.snapshot_id for s in kept], ["snap_4", "snap_3"])
self.assertEqual([s.snapshot_id for s in pruned], ["snap_0", "snap_1", "snap_2"])
def test_keep_daily(self):
# Multiple snapshots on same days
snaps = [
# Day 1: 3 snapshots
self._create_synthetic_manifest("d1_1", "2026-10-01T08:00:00Z"),
self._create_synthetic_manifest("d1_2", "2026-10-01T12:00:00Z"),
self._create_synthetic_manifest("d1_3", "2026-10-01T20:00:00Z"),
# Day 2: 2 snapshots
self._create_synthetic_manifest("d2_1", "2026-10-02T10:00:00Z"),
self._create_synthetic_manifest("d2_2", "2026-10-02T22:00:00Z"),
# Day 3: 1 snapshot
self._create_synthetic_manifest("d3_1", "2026-10-03T15:00:00Z"),
]
# Keep 2 daily
retention = RetentionEngine(keep_daily=2)
kept, pruned = retention.calculate_prune_set(snaps)
# Should keep newest of Day 3 (d3_1) and newest of Day 2 (d2_2)
kept_ids = [s.snapshot_id for s in kept]
self.assertEqual(len(kept_ids), 2)
self.assertIn("d3_1", kept_ids)
self.assertIn("d2_2", kept_ids)
self.assertEqual(len(pruned), 4)
def test_keep_weekly_and_monthly(self):
snaps = [
# Month 1, Week 1
self._create_synthetic_manifest("m1_w1", "2026-08-03T10:00:00Z"),
# Month 1, Week 2
self._create_synthetic_manifest("m1_w2", "2026-08-10T10:00:00Z"),
# Month 2, Week 1
self._create_synthetic_manifest("m2_w1", "2026-09-07T10:00:00Z"),
# Month 2, Week 2
self._create_synthetic_manifest("m2_w2", "2026-09-14T10:00:00Z"),
# Month 3, Week 1
self._create_synthetic_manifest("m3_w1", "2026-10-05T10:00:00Z"),
]
# Keep 1 monthly
retention = RetentionEngine(keep_monthly=1)
kept, pruned = retention.calculate_prune_set(snaps)
self.assertEqual(len(kept), 1)
self.assertEqual(kept[0].snapshot_id, "m3_w1")
def test_execute_prune_dry_run_vs_live(self):
archiver = SnapshotArchiver(target_dir=self.backup_dir)
# Create 3 real tiny snapshot archives on disk
snap_ids = []
manifests = []
for i in range(3):
s_id = f"snap_real_{i}"
snap_ids.append(s_id)
dummy_file = os.path.join(self.test_dir, f"file_{i}.txt")
with open(dummy_file, "w") as f:
f.write(f"content {i}\n")
entries, sha, uncomp, _ = archiver.collect_file_list([dummy_file])
m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z")
m.files_sha256 = sha
archiver.create_snapshot_archive(s_id, m, entries)
manifests.append(m)
# Verify all 3 exist
for s_id in snap_ids:
path = SnapshotArchiver.resolve_archive_path(self.backup_dir, s_id)
self.assertTrue(os.path.isfile(path))
retention = RetentionEngine(keep_last=1)
kept, pruned = retention.calculate_prune_set(manifests)
self.assertEqual(len(pruned), 2)
# Test dry-run: files must NOT be deleted
pid_file = os.path.join(self.test_dir, "test.pid")
results = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=True, pid_path=pid_file)
self.assertEqual(len(results), 2)
for r in results:
self.assertEqual(r["action"], "would_delete")
self.assertTrue(os.path.isfile(r["archive_path"]))
# Test live prune: files MUST be deleted
with patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
results_live = retention.execute_prune(pruned, target_dir=self.backup_dir, dry_run=False, pid_path=pid_file)
self.assertEqual(len(results_live), 2)
for r in results_live:
self.assertEqual(r["action"], "deleted")
self.assertFalse(os.path.isfile(r["archive_path"]))
# Kept archive must still exist
kept_path = SnapshotArchiver.resolve_archive_path(self.backup_dir, kept[0].snapshot_id)
self.assertTrue(os.path.isfile(kept_path))
def test_cli_prune_command(self):
archiver = SnapshotArchiver(target_dir=self.backup_dir)
# Create 2 archives
for i in range(2):
s_id = f"cli_snap_{i}"
f_path = os.path.join(self.test_dir, f"f_{i}.txt")
with open(f_path, "w") as f:
f.write(f"val {i}")
entries, sha, uncomp, _ = archiver.collect_file_list([f_path])
m = self._create_synthetic_manifest(s_id, f"2026-10-0{i+1}T12:00:00Z")
m.files_sha256 = sha
archiver.create_snapshot_archive(s_id, m, entries)
# 1. Prune without rules -> error
stdout = io.StringIO()
with patch("sys.stderr", stdout):
code = main(["prune", "--target-dir", self.backup_dir])
self.assertEqual(code, EXIT_GENERIC_ERROR)
# 2. Prune dry-run (default without --force)
stdout_dry = io.StringIO()
with patch("sys.stdout", stdout_dry):
code = main(["prune", "--keep-last", "1", "--target-dir", self.backup_dir, "--json"])
self.assertEqual(code, EXIT_SUCCESS)
data = json.loads(stdout_dry.getvalue().strip())
self.assertEqual(data["mode"], "dry-run")
self.assertEqual(data["kept_count"], 1)
self.assertEqual(data["pruned_count"], 1)
# 3. Prune with --force
pid_file = os.path.join(self.test_dir, "prune_test.pid")
stdout_live = io.StringIO()
with patch("sys.stdout", stdout_live), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
code = main([
"prune",
"--keep-last", "1",
"--force",
"--target-dir", self.backup_dir,
"--pid-path", pid_file,
"--json"
])
self.assertEqual(code, EXIT_SUCCESS)
data_live = json.loads(stdout_live.getvalue().strip())
self.assertEqual(data_live["mode"], "live")
self.assertEqual(data_live["pruned"][0]["action"], "deleted")
if __name__ == "__main__":
unittest.main()
+161
View File
@@ -0,0 +1,161 @@
"""Unit tests for RemoteTransport and push command."""
import io
import json
import os
import shutil
import tempfile
import unittest
from unittest.mock import patch, MagicMock
from linux_backuper.cli import main
from linux_backuper.core.archiver import SnapshotArchiver
from linux_backuper.core.constants import EXIT_SUCCESS, EXIT_GENERIC_ERROR
from linux_backuper.core.retention import RetentionEngine
from linux_backuper.core.transport import (
LocalPathTransport,
SshTransport,
TransportFactory,
TransportError
)
from linux_backuper.models import SnapshotManifest
class TestRemoteTransport(unittest.TestCase):
def setUp(self):
self.test_dir = tempfile.mkdtemp(prefix="test_transport_")
self.backup_dir = os.path.join(self.test_dir, "local_backups")
self.remote_dir = os.path.join(self.test_dir, "remote_nas")
os.makedirs(self.backup_dir, exist_ok=True)
os.makedirs(self.remote_dir, exist_ok=True)
# Create a mock snapshot locally
self.archiver = SnapshotArchiver(target_dir=self.backup_dir)
dummy_f = os.path.join(self.test_dir, "sample.txt")
with open(dummy_f, "w") as f:
f.write("hello transport\n")
entries, sha, uncomp, _ = self.archiver.collect_file_list([dummy_f])
self.manifest = SnapshotManifest(
schema_version="1.0",
snapshot_id="snap_transport_1",
created_at="2026-10-09T12:00:00Z",
hostname="host1",
profile="quick",
compression="gzip",
os={},
package_manager="none",
package_count=0,
included_paths=[dummy_f],
stats={"file_count": 1, "uncompressed_bytes": uncomp, "compressed_bytes": 0},
files_sha256=sha
)
self.archive_path = self.archiver.create_snapshot_archive("snap_transport_1", self.manifest, entries)
def tearDown(self):
shutil.rmtree(self.test_dir, ignore_errors=True)
def test_local_path_transport_push_and_verify(self):
transport = LocalPathTransport(self.remote_dir)
res = transport.push(self.archive_path)
self.assertEqual(res["status"], "success")
self.assertEqual(res["transport"], "local_mount")
dest_path = res["destination_path"]
self.assertTrue(os.path.isfile(dest_path))
self.assertEqual(os.path.basename(dest_path), os.path.basename(self.archive_path))
# Check strict permissions (0600)
mode = os.stat(dest_path).st_mode & 0o777
self.assertEqual(mode, 0o600)
def test_local_path_transport_remote_prune(self):
transport = LocalPathTransport(self.remote_dir)
# Push first archive
transport.push(self.archive_path)
# Create second archive and push
m2 = SnapshotManifest.from_dict(self.manifest.to_dict())
m2.snapshot_id = "snap_transport_2"
m2.created_at = "2026-10-09T14:00:00Z"
arc2 = self.archiver.create_snapshot_archive("snap_transport_2", m2, [(os.path.join(self.test_dir, "sample.txt"), "data/sample.txt")])
transport.push(arc2)
# 2 archives on remote
self.assertEqual(len(transport.list_remote()), 2)
# Prune remote with keep-last 1
retention = RetentionEngine(keep_last=1)
pruned_results = transport.prune_remote(retention)
self.assertEqual(len(pruned_results), 1)
self.assertEqual(pruned_results[0]["action"], "deleted")
self.assertEqual(len(transport.list_remote()), 1)
self.assertEqual(transport.list_remote()[0].snapshot_id, "snap_transport_2")
def test_transport_factory_parsing(self):
# Local dir
t1 = TransportFactory.get_transport("/mnt/nas/backups")
self.assertIsInstance(t1, LocalPathTransport)
# SSH
t2 = TransportFactory.get_transport("backupuser@nas.local:/volume1/backups")
self.assertIsInstance(t2, SshTransport)
self.assertEqual(t2.user, "backupuser")
self.assertEqual(t2.host, "nas.local")
self.assertEqual(t2.remote_dir, "/volume1/backups")
# Config alias
cfg = {
"remotes": {
"mynas": {
"type": "ssh",
"host": "192.168.1.100",
"user": "admin",
"path": "/backups"
}
}
}
t3 = TransportFactory.get_transport("mynas", config=cfg)
self.assertIsInstance(t3, SshTransport)
self.assertEqual(t3.host, "192.168.1.100")
def test_cli_push_command(self):
stdout = io.StringIO()
with patch("sys.stdout", stdout):
exit_code = main([
"push", "snap_transport_1",
"--target", self.remote_dir,
"--target-dir", self.backup_dir,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
res = json.loads(stdout.getvalue().strip())
self.assertEqual(res["status"], "success")
# Archive exists on remote
expected_remote = os.path.join(self.remote_dir, os.path.basename(self.archive_path))
self.assertTrue(os.path.isfile(expected_remote))
def test_cli_snapshot_auto_push(self):
dummy_f = os.path.join(self.test_dir, "auto.txt")
with open(dummy_f, "w") as f:
f.write("auto push test\n")
stdout = io.StringIO()
with patch("sys.stdout", stdout), patch.dict(os.environ, {"LINUX_BACKUPER_ALLOW_NON_ROOT": "1"}):
exit_code = main([
"snapshot",
"--target-dir", self.backup_dir,
"--paths", dummy_f,
"--push", self.remote_dir,
"--json"
])
self.assertEqual(exit_code, EXIT_SUCCESS)
res = json.loads(stdout.getvalue().strip())
self.assertEqual(res["status"], "success")
self.assertIsNotNone(res["remote_push"])
self.assertEqual(res["remote_push"]["status"], "success")
if __name__ == "__main__":
unittest.main()