Files
2026-10-09 20:22:51 +02:00

154 lines
6.7 KiB
Markdown

# 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
```