feat: implement slice 1 tracer bullet (cli entrypoint, distro detector, and test suite)

This commit is contained in:
soda64 committed 2026-10-02 10:05:39 +02:00
commit 63c6cc846b
16 files changed
+1317

No files matched your search

@@ -0,0 +1,20 @@
# Status: linux-system-updater
- Gate 1 — Spec & Product: APPROVED 2026-10-02
- Gate 2 — Architecture: APPROVED 2026-10-02
- Gate 3 — Program Design: APPROVED 2026-10-02
- Gate 4 — Slice Plan: APPROVED 2026-10-02
## Slices
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
- [ ] Slice 2 — pre-flight health & auto-remediation engine
- [ ] Slice 3 — package managers (apt, dnf, pacman) & routine updates
- [ ] Slice 4 — major release upgrade & configuration engine
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
- [ ] Slice 6 — documentation (man page, README, user/admin/developer guides)
## Notes for a fresh session
- Project: Multi-distribution Linux system updater in Python.
- Process: Software Factory 4-gate workflow.
- All 4 Gates APPROVED on 2026-10-02.
- Scope: Debian/Ubuntu, RHEL 8/9/Fedora, Arch Linux. Pre-flight health checks with auto-remediation. Routine update + major release-upgrade. Selective package updates (--packages) + target release upgrade (--target-release). Pure Python standard library (compatible with Python >= 3.6). Packaging for .tar.gz, .deb, and .rpm. MAN page (Section 8) + user, admin, developer documentation.
@@ -0,0 +1,19 @@
# Product Spec: linux-system-updater
## Problem Statement
System administrators and engineers managing diverse Linux installations often face fragile, distribution-dependent upgrade procedures. Running package updates on an unhealthy machine can leave systems in an unbootable or corrupted state if disk space on `/boot` or `/var` runs out, memory is exhausted, or stale package locks block the process. Furthermore, administering updates across Debian/Ubuntu, RHEL/Fedora, and Arch requires remembering disparate commands, flags, and major-version upgrade workflows, leading to accidental mistakes during maintenance windows.
## Measurable Success Criteria
1. **Distribution Compatibility**: 100% automated detection and update execution across the three primary families: Debian/Ubuntu, RHEL/Fedora/Rocky/Alma/CentOS, and Arch Linux.
2. **Pre-flight Health Safety**: Zero updates allowed to begin if `/boot` has less than 250 MB free, `/var` has less than 1 GB free, or available RAM is below 300 MB without successful remediation.
3. **Auto-Remediation Success**: Automatically recovers from low `/var` cache space and dead package manager lockfiles in 100% of detected safe cases before aborting.
4. **Zero External Dependencies**: Operates entirely using the standard runtime available out-of-the-box on clean Linux installs without requiring external package installations.
5. **Operational Modes**: Flawlessly supports both fully unattended automation (CLI flags or configuration file without blocking prompts) and an interactive review mode with clear progress and post-update reboot notices.
6. **Selective Package Updates**: Allows updating either the full system or an explicit subset of packages via `--packages`.
7. **Targeted Release Upgrade**: Supports upgrading to a specific target OS release version via `--target-release` on supported platforms (Debian, Ubuntu, RHEL/Fedora).
## Announcement / User Story
Linux System Updater is a single, bulletproof CLI tool designed to safely inspect, heal, and update your Linux systems. Before changing a single package, it verifies your system health—ensuring sufficient `/boot` and `/var` storage, checking memory headroom, and clearing stale locks. It supports both routine package maintenance and major operating system version upgrades across Debian, RHEL, and Arch families. Whether run interactively during maintenance or silently via automation timers, it guarantees your systems update safely with clear reporting and reboot notifications.
## UI Screens & Mockups
No UI (CLI-only tool). The terminal interface provides structured textual diagnostics, clear pre-flight check tables, interactive confirmation prompts, and unattended execution modes.
@@ -0,0 +1,259 @@
# Architecture: linux-system-updater
## System Fit
`linux-system-updater` is a standalone, dependency-free Python 3 CLI tool designed to run directly on Linux hosts (Debian/Ubuntu, RHEL/Fedora/CentOS/Rocky/Alma, Arch Linux/Manjaro). It relies strictly on Python's standard library (`sys`, `os`, `platform`, `subprocess`, `shutil`, `json`, `argparse`, `pathlib`, `logging`, `typing`, `re`) so it can execute out-of-the-box on bare-metal systems, cloud VMs, and containers without running `pip install`.
```
+------------------------------------+
| CLI Interface & Args |
+-----------------+------------------+
|
v
+------------------------------------+
| Config Loader (/etc & CLI) |
+-----------------+------------------+
|
v
+------------------------------------+
| Distro Family Detector |
| (/etc/os-release) |
+-----------------+------------------+
|
v
+------------------------------------+
| Pre-flight Health Engine |
| (Disk, RAM, OOM, Locks, AC Power) |
+-----------------+------------------+
|
(if issues & auto-heal)
v
+------------------------------------+
| Auto-Remediation Unit |
| (Cache cleanup, Dead lock removal) |
+-----------------+------------------+
|
v
+------------------------------------+
| Package Manager Orchestrator |
+--------+--------+---------+--------+
| | |
+---------------+ | +---------------+
v v v
+---------------+ +---------------+ +---------------+
| APT Manager | | DNF Manager | | Pacman Manager|
| (Debian/Ubuntu| | (RHEL/Fedora) | | (Arch/Manjaro)|
+---------------+ +---------------+ +---------------+
```
## Endpoints / Contracts
### Abstract Package Manager Contract (`PackageManager`)
Every distribution family implements the uniform `PackageManager` interface:
```python
class PackageManager(ABC):
@property
@abstractmethod
def name(self) -> str:
"""Returns the identifier of the package manager (e.g., 'apt', 'dnf', 'pacman')."""
pass
@abstractmethod
def refresh_repositories(self) -> bool:
"""Synchronizes package repositories (e.g., apt update, dnf check-update, pacman -Sy)."""
pass
@abstractmethod
def check_updates(self) -> List[PackageUpdate]:
"""Lists available package updates without modifying the system."""
pass
@abstractmethod
def apply_updates(
self,
packages: Optional[List[str]] = None,
dry_run: bool = False,
non_interactive: bool = False
) -> CommandResult:
"""Performs package upgrade (full or selective) (e.g., apt-get upgrade / install, dnf upgrade, pacman -Su / -S)."""
pass
@abstractmethod
def release_upgrade(self, target_release: Optional[str] = None, non_interactive: bool = False) -> CommandResult:
"""Executes major OS distribution upgrade to latest or target_release."""
pass
@abstractmethod
def clean_cache(self) -> CommandResult:
"""Cleans downloaded package cache to recover space."""
pass
@abstractmethod
def autoremove(self) -> CommandResult:
"""Removes orphan/unneeded packages."""
pass
@abstractmethod
def is_reboot_required(self) -> RebootStatus:
"""Determines whether a kernel or core library update requires a system reboot."""
pass
@abstractmethod
def get_lock_files(self) -> List[Path]:
"""Returns distribution-specific lockfile paths for pre-flight checking."""
pass
```
### CLI Interface Contract
Subcommands and options:
- `update` (default action): Runs pre-flight health checks $\rightarrow$ auto-remediates if needed $\rightarrow$ checks updates $\rightarrow$ confirms (if interactive) $\rightarrow$ executes update $\rightarrow$ reports reboot status.
- `check`: Runs health checks and lists available package updates without modifying system state (`--dry-run`).
- `release-upgrade`: Executes a major distribution release upgrade with additional confirmation gates and safety warnings.
- `clean`: Runs cache cleanup and autoremove.
- `health`: Standalone execution of pre-flight checks and diagnostics only.
Global CLI Flags:
- `-y`, `--yes`, `--non-interactive`: Bypasses all interactive confirmation prompts (for cron/automation).
- `-c`, `--config <path>`: Specifies custom JSON configuration file path.
- `--no-remediation`: Disables automatic remediation of failed pre-flight checks.
- `--skip-preflight`: Skips pre-flight health checks (requires explicit flag).
- `-v`, `--verbose`: Enables detailed logging and full subprocess command output.
- `--json`: Outputs machine-readable JSON status (ideal for monitoring, Zabbix, or automation agents).
Exit Codes:
- `0`: Success, no reboot required.
- `1`: Error encountered (health check failed and unrecovered, command failure).
- `2`: Success, but system reboot is required.
- `3`: Operation aborted by user at interactive prompt.
## Data Models & Persistence
### In-Memory Models
```python
@dataclass(frozen=True)
class DistroInfo:
family: str # 'debian', 'rhel', 'arch', 'unknown'
distro_id: str # 'ubuntu', 'debian', 'fedora', 'rocky', 'arch', etc.
version_id: str # '24.04', '9.4', 'rolling'
pretty_name: str # 'Ubuntu 24.04.1 LTS'
@dataclass
class CheckResult:
name: str
passed: bool
message: str
can_remediate: bool
remediation_action: Optional[str] = None
@dataclass
class PreflightReport:
passed: bool
results: List[CheckResult]
remediations_performed: List[str]
@dataclass(frozen=True)
class PackageUpdate:
package: str
current_version: str
new_version: str
repo: Optional[str] = None
@dataclass
class RebootStatus:
required: bool
reason: str
```
### Configuration Schema (`/etc/linux-updater.json`)
Persistent JSON configuration for sysadmins and systemd timers:
```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_file": "/var/log/linux-updater.log",
"verbose": false
}
}
```
## Call Flow
### Primary `update` Happy Path
```
User / Timer Invocation
|
v
1. Parse CLI flags & merge with /etc/linux-updater.json (defaults fallback)
|
v
2. Privilege Verification (euid == 0 check for modifying operations)
|
v
3. Distro Detection (parse /etc/os-release, resolve to Apt/Dnf/PacmanManager)
|
v
4. Run Pre-flight Health Checks:
├── Disk Check: statvfs on /boot, /var, /
├── Lock Check: inspect lockfiles & verify if holder PID is alive (/proc/<pid>)
├── Memory & OOM: /proc/meminfo MemAvailable & dmesg OOM killer warnings
├── AC Power: /sys/class/power_supply/*/status (skip if no battery)
└── Pending Reboot: check /var/run/reboot-required or needs-restarting
|
v
5. Pre-flight Decision:
├── If all checks pass -> proceed to step 6.
└── If checks fail & auto_remediate=True:
├── Cache space low -> clean package cache
├── Dead lockfile found -> remove stale lockfile
└── Re-run checks. If still failing -> ABORT with exit code 1.
|
v
6. Refresh Repositories & Query Available Updates
|
v
7. Confirmation Gate:
├── If non_interactive or --yes -> auto-proceed.
└── If interactive -> display table of updates and prompt [Y/n].
|
v
8. Apply Updates:
└── Stream subprocess output with live progress and logging.
|
v
9. Post-Execution:
├── Optional autoremove / clean (if configured)
├── Evaluate RebootStatus
└── Print summary and exit (code 0 or 2 if reboot required).
```
### `release-upgrade` Call Flow
1. Run pre-flight health checks with stricter thresholds (e.g. min 5 GB `/var`, min 500 MB `/boot`).
2. Warn user prominently that major OS upgrade is starting; require explicit typed confirmation unless `--yes` is passed.
3. Delegate to native distro release upgrade tool:
- Ubuntu: `do-release-upgrade`
- Debian: guided repository sources update + `apt-get dist-upgrade`
- Fedora: `dnf system-upgrade download` and report reboot command `dnf system-upgrade reboot`.
- Arch Linux: inform user that Arch is rolling, proceed with full rolling upgrade `pacman -Syu`.
## External Integrations & Configuration
- **System Binaries**: `apt-get`, `dpkg`, `do-release-upgrade`, `dnf`, `rpm`, `pacman`, `uname`.
- **Kernel / Proc Interfaces**:
- `/etc/os-release`, `/usr/lib/os-release`
- `/proc/meminfo` (`MemAvailable`, `MemTotal`)
- `/proc/<pid>/status` (detecting alive vs zombie/stale lock processes)
- `/dev/kmsg` or `dmesg` (OOM kill events)
- `/sys/class/power_supply/` (battery capacity and charging status)
- **Environment Variables**:
- `DEBIAN_FRONTEND=noninteractive` (when running in unattended mode on Debian/Ubuntu)
- `LINUX_UPDATER_CONFIG` (override default config path)
@@ -0,0 +1,441 @@
# Program Design: linux-system-updater
## Target Runtime & Compatibility
- **Target Baseline**: **Python >= 3.6**
- **RHEL 8 / Rocky 8 / CentOS 8**: Ships natively with **Python 3.6.8** as system python3.
- **RHEL 9 / Rocky 9 / AlmaLinux 9**: Ships natively with **Python 3.9.x**.
- **Debian 13 (Trixie)**: Ships natively with **Python 3.12 / 3.13**.
- **Arch Linux**: Latest rolling Python (3.12+).
- **Syntax and Typing Guardrails**:
- Native Python 3.6 compatibility: models implemented using standard typed classes or `typing.NamedTuple` (no external `dataclasses` dependency required).
- Subprocess calls strictly use `stdout=subprocess.PIPE, stderr=subprocess.PIPE` (avoiding Python 3.7's `capture_output`).
- Standard `typing` generics (`typing.Optional`, `typing.List`, `typing.Dict`, `typing.Tuple`) with string forward references where applicable.
- Zero external pip dependencies; exclusively Python standard library.
## Files
| File Path | Rationale |
|-----------|-----------|
| `linux_updater/__init__.py` | Package initialization and version definition. |
| `linux_updater/__main__.py` | Package execution entry point (`python3 -m linux_updater`). |
| `linux_updater/cli.py` | Argument parsing, user prompts, orchestration, and exit code handling. |
| `linux_updater/config.py` | Configuration dataclass, default values, and JSON loading logic. |
| `linux_updater/models.py` | Domain dataclasses and enumerations used across modules. |
| `linux_updater/core/__init__.py` | Core subsystem initialization. |
| `linux_updater/core/runner.py` | Subprocess execution wrapper with logging, streaming, and error capture. |
| `linux_updater/core/detector.py` | Linux distribution family identification from `/etc/os-release`. |
| `linux_updater/core/health.py` | Pre-flight health checks (disk, locks, RAM/OOM, battery, pending reboot). |
| `linux_updater/core/remediation.py` | Safe automatic repairs (package cache cleanup, dead lockfile removal). |
| `linux_updater/managers/__init__.py` | Package managers subsystem initialization. |
| `linux_updater/managers/base.py` | Abstract `PackageManager` base class. |
| `linux_updater/managers/apt.py` | Debian/Ubuntu implementation (`apt-get`, `dpkg`, `do-release-upgrade`). |
| `linux_updater/managers/dnf.py` | RHEL/Fedora/Rocky implementation (`dnf`/`yum`, `system-upgrade`). |
| `linux_updater/managers/pacman.py` | Arch Linux implementation (`pacman` rolling release). |
| `packaging/build_packages.py` | Standalone Python builder for .tar.gz, .deb, and .rpm distributions. |
| `packaging/deb/control.template` | Debian control file template for .deb package generation. |
| `packaging/rpm/linux-updater.spec` | RPM spec file template for .rpm package generation. |
| `tests/test_detector.py` | Unit tests for distribution detection with various `/etc/os-release` mocks. |
| `tests/test_health.py` | Unit tests for health checks (disk space, alive vs dead locks, RAM, OOM). |
| `tests/test_remediation.py` | Unit tests for auto-remediation actions. |
| `tests/test_managers.py` | Unit tests for package manager command generation and output parsing. |
| `tests/test_cli.py` | Integration tests for CLI arguments, non-interactive mode, and exit codes. |
| `tests/test_packaging.py` | Unit and generation tests for .tar.gz, .deb, and .rpm artifacts. |
| `man/linux-updater.8` | Standard Section 8 troff/groff manual page for system administrators. |
| `README.md` | Project overview, feature matrix, installation quickstart, and basic usage. |
| `docs/user-guide.md` | End-user manual: interactive CLI workflow, options, interpreting outputs. |
| `docs/admin-guide.md` | System administration guide: cron/systemd automation, JSON config, pre-flight tuning. |
| `docs/developer-guide.md` | Developer manual: architecture, adding new package managers, running tests and packaging. |
---
## Types & Signatures (No Function Bodies)
```python
# linux_updater/models.py
from enum import Enum
from pathlib import Path
from typing import List, Optional, Dict, Any, NamedTuple
class DistroFamily(str, Enum):
DEBIAN = "debian"
RHEL = "rhel"
ARCH = "arch"
UNKNOWN = "unknown"
class CheckStatus(str, Enum):
PASS = "PASS"
WARN = "WARN"
FAIL = "FAIL"
class DistroInfo(NamedTuple):
family: DistroFamily
distro_id: str
version_id: str
pretty_name: str
class CheckResult:
def __init__(
self,
name: str,
status: CheckStatus,
message: str,
can_remediate: bool,
remediation_id: Optional[str] = None
) -> None: ...
class PreflightReport:
def __init__(
self,
passed: bool,
results: List[CheckResult],
remediations_performed: List[str]
) -> None: ...
class PackageUpdate(NamedTuple):
package: str
current_version: str
new_version: str
repo: Optional[str] = None
class CommandResult:
def __init__(
self,
return_code: int,
stdout: str,
stderr: str,
success: bool
) -> None: ...
class RebootStatus:
def __init__(self, required: bool, reason: str) -> None: ...
```
```python
# linux_updater/config.py
from pathlib import Path
from typing import Optional, Dict, Any
class UpdaterConfig:
def __init__(
self,
min_boot_mb: int = 250,
min_var_mb: int = 1024,
min_root_mb: int = 1024,
min_ram_mb: int = 300,
auto_remediate: bool = True,
non_interactive: bool = False,
check_ac_power: bool = True,
clean_after_update: bool = False,
log_file: Optional[Path] = Path("/var/log/linux-updater.log"),
verbose: bool = False,
) -> None: ...
@classmethod
def load(cls, config_path: Optional[Path] = None) -> "UpdaterConfig": ...
def to_dict(self) -> Dict[str, Any]: ...
```
```python
# linux_updater/core/runner.py
from pathlib import Path
from typing import List, Optional
from linux_updater.models import CommandResult
class CommandRunner:
def __init__(self, verbose: bool = False, log_file: Optional[Path] = None): ...
def run(self, cmd: List[str], check: bool = False, env: Optional[dict] = None) -> CommandResult: ...
def stream_run(self, cmd: List[str], env: Optional[dict] = None) -> CommandResult: ...
```
```python
# linux_updater/core/detector.py
from pathlib import Path
from linux_updater.models import DistroInfo
class DistroDetector:
def __init__(self, os_release_path: Path = Path("/etc/os-release")): ...
def detect(self) -> DistroInfo: ...
```
```python
# linux_updater/core/health.py
from pathlib import Path
from typing import List
from linux_updater.models import CheckResult, PreflightReport
from linux_updater.config import UpdaterConfig
from linux_updater.managers.base import PackageManager
class HealthChecker:
def __init__(self, config: UpdaterConfig, manager: PackageManager): ...
def check_disk_space(self) -> List[CheckResult]: ...
def check_locks(self) -> List[CheckResult]: ...
def check_memory_and_oom(self) -> List[CheckResult]: ...
def check_power(self) -> List[CheckResult]: ...
def check_pending_reboot(self) -> List[CheckResult]: ...
def run_all_checks(self) -> PreflightReport: ...
```
```python
# linux_updater/core/remediation.py
from typing import List
from linux_updater.models import CheckResult
from linux_updater.managers.base import PackageManager
class RemediationEngine:
def __init__(self, manager: PackageManager): ...
def can_remediate(self, check: CheckResult) -> bool: ...
def remediate(self, check: CheckResult) -> bool: ...
def clean_cache(self) -> bool: ...
def remove_stale_lock(self, lock_path: str) -> bool: ...
```
```python
# linux_updater/managers/base.py
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Optional
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
from linux_updater.core.runner import CommandRunner
class PackageManager(ABC):
def __init__(self, runner: CommandRunner): ...
@property
@abstractmethod
def name(self) -> str: ...
@abstractmethod
def refresh_repositories(self) -> CommandResult: ...
@abstractmethod
def check_updates(self) -> List[PackageUpdate]: ...
@abstractmethod
def apply_updates(self, packages: Optional[List[str]] = None, dry_run: bool = False, non_interactive: bool = False) -> CommandResult: ...
@abstractmethod
def release_upgrade(self, target_release: Optional[str] = None, non_interactive: bool = False) -> CommandResult: ...
@abstractmethod
def clean_cache(self) -> CommandResult: ...
@abstractmethod
def autoremove(self) -> CommandResult: ...
@abstractmethod
def is_reboot_required(self) -> RebootStatus: ...
@abstractmethod
def get_lock_files(self) -> List[Path]: ...
```
```python
# linux_updater/managers/apt.py
from typing import List, Optional
from pathlib import Path
from linux_updater.managers.base import PackageManager
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
class AptManager(PackageManager):
@property
def name(self) -> str: ...
def refresh_repositories(self) -> CommandResult: ...
def check_updates(self) -> List[PackageUpdate]: ...
def apply_updates(self, packages: Optional[List[str]] = None, dry_run: bool = False, non_interactive: bool = False) -> CommandResult: ...
def release_upgrade(self, target_release: Optional[str] = None, non_interactive: bool = False) -> CommandResult: ...
def clean_cache(self) -> CommandResult: ...
def autoremove(self) -> CommandResult: ...
def is_reboot_required(self) -> RebootStatus: ...
def get_lock_files(self) -> List[Path]: ...
```
```python
# linux_updater/managers/dnf.py
from typing import List, Optional
from pathlib import Path
from linux_updater.managers.base import PackageManager
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
class DnfManager(PackageManager):
@property
def name(self) -> str: ...
def refresh_repositories(self) -> CommandResult: ...
def check_updates(self) -> List[PackageUpdate]: ...
def apply_updates(self, packages: Optional[List[str]] = None, dry_run: bool = False, non_interactive: bool = False) -> CommandResult: ...
def release_upgrade(self, target_release: Optional[str] = None, non_interactive: bool = False) -> CommandResult: ...
def clean_cache(self) -> CommandResult: ...
def autoremove(self) -> CommandResult: ...
def is_reboot_required(self) -> RebootStatus: ...
def get_lock_files(self) -> List[Path]: ...
```
```python
# linux_updater/managers/pacman.py
from typing import List, Optional
from pathlib import Path
from linux_updater.managers.base import PackageManager
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
class PacmanManager(PackageManager):
@property
def name(self) -> str: ...
def refresh_repositories(self) -> CommandResult: ...
def check_updates(self) -> List[PackageUpdate]: ...
def apply_updates(self, packages: Optional[List[str]] = None, dry_run: bool = False, non_interactive: bool = False) -> CommandResult: ...
def release_upgrade(self, target_release: Optional[str] = None, non_interactive: bool = False) -> CommandResult: ...
def clean_cache(self) -> CommandResult: ...
def autoremove(self) -> CommandResult: ...
def is_reboot_required(self) -> RebootStatus: ...
def get_lock_files(self) -> List[Path]: ...
```
```python
# linux_updater/cli.py
from typing import List, Optional
from linux_updater.config import UpdaterConfig
from linux_updater.managers.base import PackageManager
def parse_args(args: Optional[List[str]] = None) -> argparse.Namespace: ...
def get_manager(family: str, runner: CommandRunner) -> PackageManager: ...
def main(args: Optional[List[str]] = None) -> int: ...
```
```python
# packaging/build_packages.py
from pathlib import Path
from typing import List, Optional
class PackageBuilder:
def __init__(self, source_root: Path, dist_root: Path, version: str): ...
def build_tarball(self) -> Path: ...
def build_deb(self) -> Path: ...
def build_rpm(self) -> Path: ...
def build_all(self) -> List[Path]: ...
```
---
## Call Stack Trace
Main `update` workflow:
```
main()
│
├── parse_args()
├── UpdaterConfig.load(config_path)
├── CommandRunner(verbose, log_file)
│
├── DistroDetector.detect()
│ └── reads /etc/os-release
│
├── get_manager(family, runner) -> AptManager / DnfManager / PacmanManager
│
├── HealthChecker(config, manager).run_all_checks()
│ ├── check_disk_space() (statvfs /boot, /var, /)
│ ├── check_locks() (inspect manager.get_lock_files() + /proc/<pid>)
│ ├── check_memory_and_oom() (/proc/meminfo & dmesg)
│ ├── check_power() (/sys/class/power_supply)
│ └── check_pending_reboot() (manager.is_reboot_required())
│
├── [If checks FAIL]:
│ └── RemediationEngine.remediate()
│ ├── clean_cache()
│ ├── remove_stale_lock()
│ └── HealthChecker.run_all_checks() (re-verify)
│
├── manager.refresh_repositories()
├── manager.check_updates() -> List[PackageUpdate]
│
├── [If interactive & not --yes]:
│ └── prompt_user_confirmation()
│
├── manager.apply_updates(dry_run, non_interactive)
│
├── [If config.clean_after_update]:
│ └── manager.autoremove()
│
├── manager.is_reboot_required()
│
└── output_summary() -> return exit_code (0 or 2)
```
---
## Test Plan & Invariants
| Test Module | Test Name | Key Assertions / Invariants |
|-------------|-----------|-----------------------------|
| `test_detector.py` | `test_detect_ubuntu_lts` | Returns `DistroFamily.DEBIAN`, id `ubuntu`, version `24.04`. |
| `test_detector.py` | `test_detect_debian_bookworm` | Returns `DistroFamily.DEBIAN`, id `debian`, version `12`. |
| `test_detector.py` | `test_detect_fedora` | Returns `DistroFamily.RHEL`, id `fedora`. |
| `test_detector.py` | `test_detect_rocky` | Returns `DistroFamily.RHEL`, id `rocky`. |
| `test_detector.py` | `test_detect_arch` | Returns `DistroFamily.ARCH`, id `arch`. |
| `test_detector.py` | `test_detect_missing_os_release` | Handles missing file gracefully, returns `DistroFamily.UNKNOWN`. |
| `test_health.py` | `test_disk_check_sufficient_space` | Passes when `/boot` > 250MB, `/var` > 1GB, `/` > 1GB. |
| `test_health.py` | `test_disk_check_low_boot_space` | Fails when `/boot` free < 250MB with `can_remediate=False`. |
| `test_health.py` | `test_disk_check_low_var_space` | Fails when `/var` free < 1GB with `can_remediate=True`. |
| `test_health.py` | `test_lock_check_no_locks` | Passes when no lockfiles exist. |
| `test_health.py` | `test_lock_check_active_pid` | Fails when lockfile exists and PID is alive (`can_remediate=False`). |
| `test_health.py` | `test_lock_check_dead_pid` | Fails when lockfile exists and PID is dead (`can_remediate=True`). |
| `test_health.py` | `test_memory_check_low_ram` | Fails/Warns when `MemAvailable` < 300MB. |
| `test_health.py` | `test_power_check_on_ac` | Passes when AC adapter is connected. |
| `test_health.py` | `test_power_check_low_battery_unplugged` | Fails/Warns when discharging and battery < 20%. |
| `test_remediation.py`| `test_remediate_low_var_calls_clean_cache` | Calls `manager.clean_cache()` on low `/var` error. |
| `test_remediation.py`| `test_remediate_stale_lock_removes_file` | Deletes stale lockfile when holding PID is dead. |
| `test_remediation.py`| `test_remediate_does_not_touch_active_lock` | Refuses to delete lockfile if process is still running. |
| `test_managers.py` | `test_apt_check_updates_parsing` | Correctly parses `apt-get -s upgrade` simulation output into `PackageUpdate` objects. |
| `test_managers.py` | `test_apt_apply_updates_command` | Generates `apt-get upgrade -y` with `DEBIAN_FRONTEND=noninteractive`. |
| `test_managers.py` | `test_dnf_check_updates_parsing` | Correctly parses `dnf check-update` output (exit code 100). |
| `test_managers.py` | `test_pacman_check_updates_parsing` | Correctly parses `checkupdates` / `pacman -Qu` output. |
| `test_managers.py` | `test_reboot_required_detection` | Detects `/var/run/reboot-required` on Debian and `needs-restarting -r` on RHEL. |
| `test_cli.py` | `test_cli_dry_run_does_not_modify` | Runs in `--dry-run` mode without calling apply_updates. |
| `test_cli.py` | `test_cli_non_interactive_no_prompt` | Runs to completion without blocking on `stdin`. |
| `test_cli.py` | `test_cli_exit_code_reboot_required` | Returns exit code 2 when reboot is pending after update. |
| `test_cli.py` | `test_cli_exit_code_health_failure` | Returns exit code 1 when unrecoverable health check fails. |
| `test_packaging.py` | `test_build_tarball_creates_valid_archive` | Generates valid .tar.gz containing executable and modules. |
| `test_packaging.py` | `test_build_deb_structure_and_control` | Generates valid .deb tree with DEBIAN/control and /usr/bin symlink. |
| `test_packaging.py` | `test_build_rpm_spec_validity` | Generates valid .spec file with correct tags, files, and install macros. |
---
## Least Confident Decisions (Adversarial Check)
1. **Dead Lock Detection via `/proc/<PID>` or `fuser` / `lsof`**:
- *Risk*: A lockfile may be empty (contain no PID), or on Debian `/var/lib/dpkg/lock-frontend` uses advisory file locking (`fcntl` / `flock`) without writing a PID into the file!
- *Failure Mode*: If we assume the lockfile contains a text PID, reading it yields empty string, and we might falsely declare it "dead" or fail to identify the owner.
- *Remedy / Mitigation*: On Linux, check advisory locks via `/proc/locks` matching inode number, or test whether non-blocking `fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)` succeeds. If we can acquire the lock non-blockingly, no active process holds it. If an active process holds it, we inspect the PID holding the lock from `/proc/locks`.
2. **DNF Check-Update Exit Code 100**:
- *Risk*: Standard Linux conventions treat non-zero exit codes as errors. However, `dnf check-update` returns return code `100` specifically when updates are available, `0` when no updates exist, and `1` on error.
- *Failure Mode*: A generic `subprocess.run(check=True)` crashes on code 100, falsely claiming failure when updates are found.
- *Remedy / Mitigation*: Explicitly handle exit code `100` as normal success with available packages in `DnfManager`.
3. **Major Release Upgrade Non-Interactivity**:
- *Risk*: Tools like Ubuntu's `do-release-upgrade` or Debian's `dist-upgrade` can prompt during config file diffs (`dpkg` conffiles: keep existing vs overwrite). If run unattended without appropriate flags, they hang indefinitely waiting for stdin.
- *Failure Mode*: Cron or automated runner hangs forever on a conffile prompt.
- *Remedy / Mitigation*: In unattended mode, enforce `DEBIAN_FRONTEND=noninteractive` and `-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold"`, and for `do-release-upgrade` require `-f DistUpgradeViewNonInteractive`. In interactive mode, let stdin pass through directly to the terminal.
4. **OOM Detection False Alarms**:
- *Risk*: Searching `dmesg` or `/dev/kmsg` for "Out of memory" might catch an OOM event from 3 months ago when the system was under stress, unnecessarily blocking today's update.
- *Failure Mode*: A healthy system is blocked from updating due to an old log message.
- *Remedy / Mitigation*: Correlate kernel message timestamps against `/proc/uptime`. Only flag OOM killer incidents that occurred recently (e.g. within the last 1 hour), and treat it as a warning (`WARN`) rather than a fatal blocker unless available RAM is also critically low.
@@ -0,0 +1,38 @@
# Vertical Slice Plan: linux-system-updater
- **Slice 1 (Tracer Bullet):** Minimal end-to-end wire.
- Creates basic package layout `linux_updater/` (`__init__.py`, `__main__.py`, `models.py`, `cli.py`, `core/detector.py`, stub `managers/base.py`).
- Implements distro detection from `/etc/os-release` and basic CLI dispatch.
- Runs and verifies immediately via `python3 -m linux_updater --help` and initial test suite (`test_detector.py`).
- **Slice 2 (Pre-flight Health & Auto-Remediation):**
- Implements `core/health.py`: disk space checks (`/boot`, `/var`, `/`), active/stale lock detection (`/proc/locks` & `fcntl`), memory/OOM warnings, and AC power status.
- Implements `core/remediation.py`: safe cache cleanup and stale lock removal.
- Fully verified via unit test suite (`test_health.py` and `test_remediation.py`).
- **Slice 3 (Package Managers & Routine Updates):**
- Implements `core/runner.py` for subprocess execution (Python 3.6+ compatible).
- Implements `AptManager` (Debian/Ubuntu), `DnfManager` (RHEL 8/9/Fedora/Rocky), and `PacmanManager` (Arch Linux).
- Implements repo refresh, update simulation/parsing, full or selective package installation (`--packages`), autoremove, and reboot required checks.
- Integrates interactive prompt and `--yes` / `--non-interactive` mode.
- Verified via `test_managers.py` against mock outputs.
- **Slice 4 (Major Release Upgrade & Configuration Engine):**
- Implements `release-upgrade` subcommand with distro-specific drivers (`do-release-upgrade`, `dnf system-upgrade`, Arch rolling notice) and `--target-release` flag.
- Implements `config.py` loading `/etc/linux-updater.json` with CLI flag overrides.
- Implements structured `--json` output and strict exit codes (`0` clean, `1` error, `2` reboot required, `3` user abort).
- Verified via `test_cli.py`.
- **Slice 5 (Packaging & Distribution - .tar.gz, .deb, .rpm):**
- Implements `packaging/build_packages.py` in pure Python standard library.
- Adds Debian packaging templates (`control.template`) and RPM spec (`linux-updater.spec`).
- Adds standalone tarball builder with `install.sh`.
- Integrates installation of man page and default configuration into package trees.
- Verified via `test_packaging.py` generating valid archive artifacts.
- **Slice 6 (Documentation & MAN Pages):**
- Implements `man/linux-updater.8` (standard Section 8 troff/groff manual page for system administrators).
- Implements `README.md` (project overview, feature matrix, installation quickstart, and basic usage).
- Implements `docs/user-guide.md` (end-user manual: interactive CLI workflow, options, interpreting outputs).
- Implements `docs/admin-guide.md` (system administration guide: cron/systemd automation, JSON config, pre-flight tuning).
- Implements `docs/developer-guide.md` (developer manual: architecture, adding new package managers, running tests and packaging).