docs: add MAN page (section 8), README, user guide, admin guide, and developer guide

This commit is contained in:
soda64 committed 2026-10-02 12:37:13 +02:00
1 parent e1a99d7e6f
commit 507a3fd310
10 files changed
+835 -1

No files matched your search

+192
View File
@@ -0,0 +1,192 @@
# Linux System Updater: Administrator Guide
This guide covers enterprise deployment, automated scheduling, monitoring, log management, and configuration tuning for `linux-updater`.
---
## 1. Automated Execution (Cron & Systemd)
For automated maintenance windows, run `linux-updater` non-interactively using the `-y` (`--non-interactive`) flag.
### A. Systemd Service & Timer (Recommended)
Create `/etc/systemd/system/linux-updater.service`:
```ini
[Unit]
Description=Automated Safe Linux System Updater
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/bin/linux-updater -y update
StandardOutput=journal
StandardError=journal
```
Create `/etc/systemd/system/linux-updater.timer`:
```ini
[Unit]
Description=Weekly automated system update
[Timer]
OnCalendar=Sun *-*-* 03:00:00
Persistent=true
RandomizedDelaySec=1800
[Install]
WantedBy=timers.target
```
Enable and activate the timer:
```bash
sudo systemctl daemon-reload
sudo systemctl enable --now linux-updater.timer
sudo systemctl list-timers linux-updater.timer
```
### B. Standard Cron Job
Alternatively, add an entry to `/etc/cron.d/linux-updater`:
```cron
# Run every Sunday at 03:30 AM
30 3 * * 0 root /usr/bin/linux-updater -y update > /dev/null 2>&1
```
---
## 2. Configuration Reference (`/etc/linux-updater.json`)
The default configuration file `/etc/linux-updater.json` governs health check thresholds and update behaviors:
```json
{
"thresholds": {
"min_boot_mb": 250,
"min_var_mb": 1024,
"min_root_mb": 1024,
"min_ram_mb": 300
},
"behavior": {
"auto_remediate": true,
"non_interactive": false,
"check_ac_power": true,
"clean_after_update": false
},
"logging": {
"log_dir": "/var/log/linux-updater",
"log_file": null,
"verbose": false
}
}
```
### Threshold Parameters
- `min_boot_mb`: Minimum required free space in `/boot`. Prevents failed kernel installations. Defaults to 250 MB.
- `min_var_mb`: Minimum required free space in `/var`. If space drops below this, auto-remediation triggers a cache purge. Defaults to 1024 MB (1 GB).
- `min_root_mb`: Minimum free space on root `/`. Defaults to 1024 MB.
- `min_ram_mb`: Available RAM threshold in `/proc/meminfo`. Protects against OOM killer crashing package scripts. Defaults to 300 MB.
### Behavior Parameters
- `auto_remediate`: When `true`, automatically clears package cache if `/var` is low and unlinks stale locks if the holder PID is dead.
- `non_interactive`: Default non-interactive state. (Overridden by CLI `-y`).
- `check_ac_power`: Inspects `/sys/class/power_supply` and warns/halts if running on battery power.
- `clean_after_update`: If `true`, runs `autoremove` automatically after successful updates.
---
## 3. Monitoring & Structured JSON Integration
`linux-updater` includes native `--json` output for direct consumption by monitoring agents (Zabbix, Wazuh, Prometheus node exporter textfile collector).
### Health Monitoring Check
```bash
linux-updater health --json
```
**JSON Output:**
```json
{
"passed": true,
"results": [
{
"name": "disk_boot",
"status": "PASS",
"message": "/boot free space is sufficient: 1042MB",
"can_remediate": false,
"remediation_id": null
},
{
"name": "disk_var",
"status": "PASS",
"message": "/var free space is sufficient: 42100MB",
"can_remediate": false,
"remediation_id": null
},
{
"name": "memory_available",
"status": "PASS",
"message": "Available RAM is sufficient: 7850MB",
"can_remediate": false,
"remediation_id": null
},
{
"name": "pending_reboot",
"status": "PASS",
"message": "No pending system reboot detected.",
"can_remediate": false,
"remediation_id": null
}
],
"remediations_performed": []
}
```
### Exit Code Handling in Automation Scripts
In shell scripts, handle the four deterministic exit codes:
```bash
#!/bin/bash
linux-updater -y update
STATUS=$?
case $STATUS in
0)
echo "Updates succeeded cleanly. No reboot required."
;;
1)
echo "Update or health check failed! Raising alert." >&2
exit 1
;;
2)
echo "Updates applied successfully. System reboot required!"
# Optional automated reboot:
# /sbin/reboot
;;
3)
echo "Operation aborted by user."
;;
esac
```
---
## 4. Log Management & Logrotate
By default, logs are written to `/var/log/linux-updater/` with:
- Timestamped files: `linux-updater-YYYYMMDD-HHMMSS.log`
- Symlink to latest run: `/var/log/linux-updater/latest.log`
To manage historical logs and compress older runs, configure `/etc/logrotate.d/linux-updater`:
```text
/var/log/linux-updater/*.log {
weekly
rotate 12
compress
missingok
notifempty
create 0640 root root
}
```
+154
View File
@@ -0,0 +1,154 @@
# Linux System Updater: Developer Guide
This guide provides technical specifications, architectural details, and developer workflows for contributing to `linux-updater`.
---
## 1. Architectural Overview
`linux-updater` follows a clean separation of concerns:
```text
linux_updater/
├── __init__.py # Package version definition
├── __main__.py # CLI invocation entrypoint (python3 -m linux_updater)
├── cli.py # Argument parsing, formatting, execution controller
├── config.py # JSON configuration loader & default thresholds
├── models.py # Core data transfer objects (DistroInfo, CheckResult, etc.)
├── core/
│ ├── detector.py # Distro detection via /etc/os-release parsing
│ ├── health.py # Pre-flight health diagnostics & lock checking
│ ├── remediation.py # Automated remediation actions (cache, stale locks)
│ └── runner.py # Subprocess runner with timestamped file logging
└── managers/
├── __init__.py # get_manager() factory
├── base.py # PackageManager abstract base class interface
├── apt.py # Debian/Ubuntu (APT) driver
├── dnf.py # RHEL/Fedora/CentOS/AlmaLinux/Rocky (DNF) driver
└── pacman.py # Arch Linux (Pacman) driver
```
---
## 2. Hard Constraints & Coding Standards
1. **Python >= 3.6 Standard Library Baseline:**
- **NO** external `pip` dependencies. Zero third-party packages allowed.
- **NO** `dataclasses` (introduced in Python 3.7). Use standard classes or `NamedTuple`.
- **NO** `subprocess.run(capture_output=True)` (introduced in Python 3.7). Use `stdout=subprocess.PIPE, stderr=subprocess.PIPE`.
- **NO** modern union operators like `int | None` (introduced in Python 3.10). Use `Optional[int]`.
2. **Deterministic Return Codes:**
- Always map execution outcomes to standard exit codes (`0` clean, `1` error, `2` reboot required, `3` user abort).
3. **Container-First Verification:**
- All tests against actual package managers and distributions MUST be run inside clean Podman containers, never on the host system.
---
## 3. Implementing a New Package Manager Driver
To add support for a new package manager (e.g. `zypper` for openSUSE or `apk` for Alpine):
1. **Subclass `PackageManager`** in `linux_updater/managers/<name>.py`:
```python
from pathlib import Path
from typing import List, Optional
from linux_updater.managers.base import PackageManager
from linux_updater.models import CommandResult, PackageUpdate, RebootStatus
class ZypperManager(PackageManager):
@property
def name(self) -> str:
return "zypper"
def refresh_repositories(self) -> CommandResult:
return self.runner.run(["zypper", "refresh"])
def check_updates(self) -> List[PackageUpdate]:
# Parse 'zypper list-updates'
...
def apply_updates(self, packages=None, dry_run=False, non_interactive=False) -> CommandResult:
cmd = ["zypper", "update"]
if dry_run:
cmd.append("--dry-run")
if non_interactive:
cmd.append("-y")
if packages:
cmd.extend(packages)
return self.runner.run(cmd)
def release_upgrade(self, target_release=None, dry_run=False, non_interactive=False) -> CommandResult:
cmd = ["zypper", "dup"]
if dry_run:
cmd.append("--dry-run")
if non_interactive:
cmd.append("-y")
return self.runner.run(cmd)
def clean_cache(self) -> CommandResult:
return self.runner.run(["zypper", "clean", "-a"])
def autoremove(self) -> CommandResult:
return self.runner.run(["zypper", "rm", "-u"])
def is_reboot_required(self) -> RebootStatus:
res = self.runner.run(["zypper", "needs-rebooting"])
return RebootStatus(required=(res.return_code != 0))
def get_lock_files(self) -> List[Path]:
return [Path("/var/run/zypp.pid")]
```
2. **Register in `linux_updater/managers/__init__.py`:**
```python
def get_manager(family: str, runner: Optional[CommandRunner] = None) -> PackageManager:
...
elif family == "suse":
return ZypperManager(runner=runner)
```
3. **Add Distro Mapping in `linux_updater/models.py` and `core/detector.py`:**
Ensure `/etc/os-release` `ID` or `ID_LIKE` values map to the new family.
---
## 4. Testing & Quality Assurance
### Local Unit Tests
Unit tests use mocks and run locally with Python's built-in `unittest` runner:
```bash
python3 -m unittest discover tests
```
### Container Integration Tests (Podman)
Automated multi-distro container integration testing is orchestrated by `tests/containers/run_tests.sh`:
```bash
# Test all distributions (Debian 12, Ubuntu 22.04, Fedora 40, AlmaLinux 8):
./tests/containers/run_tests.sh all
# Test a single distribution:
./tests/containers/run_tests.sh debian
./tests/containers/run_tests.sh ubuntu
./tests/containers/run_tests.sh fedora
./tests/containers/run_tests.sh almalinux8
```
The script automatically mounts `/workspace:Z`, builds `.deb` or `.rpm` packages from source, installs the package inside the container, verifies the binary, runs health checks, tests routine update (dry-run), tests release-upgrade (dry-run), and verifies `/var/log/linux-updater/` logging.
---
## 5. Building Distribution Packages
Run the pure Python builder script:
```bash
python3 packaging/build_packages.py
```
Generated artifacts:
- `dist/linux-updater-1.0.0.tar.gz`: Standalone distribution archive containing `install.sh`.
- `dist/linux-updater_1.0.0_all.deb`: Native Debian/Ubuntu binary package.
- `dist/rpm/RPMS/noarch/linux-updater-1.0.0-1.*.noarch.rpm`: Native RPM package.
+1 -1
View File
@@ -11,7 +11,7 @@
- [x] Slice 3 — package managers (apt, dnf, pacman) & routine updates
- [x] Slice 4 — major release upgrade & configuration engine
- [x] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
- [ ] Slice 6 — documentation (man page, README, user/admin/developer guides)
- [x] Slice 6 — documentation (man page, README, user/admin/developer guides)
## Notes for a fresh session
- Project: Multi-distribution Linux system updater in Python.
+153
View File
@@ -0,0 +1,153 @@
# Linux System Updater: User Guide
Welcome to the **Linux System Updater** (`linux-updater`) User Guide. This guide covers how to safely inspect and update your Linux workstation or server using `linux-updater`.
---
## 1. Overview & Philosophy
Updating a Linux system can occasionally fail due to preventable conditions:
- `/boot` partition running out of inodes or disk space during kernel installation.
- Leftover package manager lock files from crashed background processes.
- Memory exhaustion causing package compilers or post-install scripts to fail.
- Sudden laptop power loss during critical package unpacking.
`linux-updater` acts as an intelligent safety wrapper around your system's native package manager (`apt`, `dnf`, or `pacman`). Before making any modifications, it verifies that the system is in a healthy, safe state to upgrade.
---
## 2. Interactive CLI Workflow
### Checking System Health (`health`)
To run a fast pre-flight diagnostic without checking for updates or altering system state:
```bash
linux-updater health
```
**Example Output:**
```text
Linux System Updater v1.0.0
Detected System: Ubuntu 24.04.1 LTS (Family: debian)
Pre-flight Health Diagnostics:
-----------------------------------------------------------------
[ PASS ] disk_boot /boot free space is sufficient: 1042MB
[ PASS ] disk_var /var free space is sufficient: 42100MB
[ PASS ] disk_root Root filesystem free space is sufficient: 42100MB
[ PASS ] lock_lock-frontend No lock active at /var/lib/dpkg/lock-frontend
[ PASS ] lock_lock No lock active at /var/lib/dpkg/lock
[ PASS ] lock_lock No lock active at /var/lib/apt/lists/lock
[ PASS ] memory_available Available RAM is sufficient: 7850MB
[ PASS ] pending_reboot No pending system reboot detected.
-----------------------------------------------------------------
Overall Pre-flight Status: PASSED
```
### Checking for Available Updates (`check`)
To see which packages have upgrades available without installing anything:
```bash
linux-updater check
```
**Example Output:**
```text
Linux System Updater v1.0.0
Detected System: Fedora Linux 40 (Family: rhel)
Checking available updates...
Available Updates (3):
-----------------------------------------------------------------
• openssl.x86_64 1:3.0.7-27 -> 1:3.0.7-28 (baseos)
• nginx.x86_64 1.24.0-1 -> 1.24.0-2 (updates)
• curl.x86_64 8.2.1-1 -> 8.2.1-2 (updates)
-----------------------------------------------------------------
Run 'linux-updater update' to apply updates.
```
### Applying Routine System Updates (`update`)
To apply routine package upgrades interactively:
```bash
sudo linux-updater update
```
1. **Pre-flight Checks:** Checks `/boot`, `/var`, `/`, locks, RAM, and power.
2. **Review:** Shows list of available updates.
3. **Confirmation:** Prompts `Proceed with updates? [Y/n]: `
4. **Execution:** Runs native package upgrade transaction.
5. **Reboot Notice:** Warns if a kernel or core library update requires a reboot.
### Selective Package Updates (`--packages`)
If you only want to upgrade specific software (e.g. security patches for OpenSSL and Nginx) without touching the rest of the operating system:
```bash
sudo linux-updater update --packages openssl nginx
```
### Simulation / Dry Run (`--dry-run`)
To simulate the complete update transaction without changing package states:
```bash
linux-updater update --dry-run
```
---
## 3. Major Distribution Release Upgrade (`release-upgrade`)
A major distribution upgrade transitions your system from one release version to the next (e.g., Ubuntu 22.04 LTS to 24.04 LTS, Debian 12 to 13, Fedora 40 to 41, or AlmaLinux 8 to 9).
Because major upgrades modify thousands of core system packages, `linux-updater` introduces strict safety gates:
```bash
# Simulate upgrade first:
linux-updater release-upgrade --dry-run -t 41
# Execute real upgrade:
sudo linux-updater release-upgrade -t 41
```
**Safety Banner:**
```text
=================================================================
WARNING: MAJOR DISTRIBUTION RELEASE UPGRADE
=================================================================
Target Release: 41
This operation performs a major upgrade of core system components.
Ensure you have a recent system backup or snapshot before proceeding.
=================================================================
Are you absolutely sure you want to proceed with upgrade to 41? [y/N]:
```
---
## 4. System Cleanup (`clean`)
To recover disk space occupied by old downloaded package files:
```bash
# Clean package download cache:
sudo linux-updater clean
# Clean cache AND remove orphaned dependencies:
sudo linux-updater clean --all
```
---
## 5. Reading System Logs
All execution logs are recorded in `/var/log/linux-updater/`:
```bash
# View the log from the most recent run:
cat /var/log/linux-updater/latest.log
# List historical execution logs:
ls -lh /var/log/linux-updater/
```
Each log line includes timestamped records of commands executed, exit codes, and diagnostics.