20 KiB
20 KiB
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 externaldataclassesdependency required). - Subprocess calls strictly use
stdout=subprocess.PIPE, stderr=subprocess.PIPE(avoiding Python 3.7'scapture_output). - Standard
typinggenerics (typing.Optional,typing.List,typing.Dict,typing.Tuple) with string forward references where applicable. - Zero external pip dependencies; exclusively Python standard library.
- Native Python 3.6 compatibility: models implemented using standard typed classes or
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)
# 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: ...
# 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]: ...
# 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: ...
# 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: ...
# 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: ...
# 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: ...
# 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]: ...
# 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]: ...
# 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]: ...
# 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]: ...
# 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: ...
# 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)
- Dead Lock Detection via
/proc/<PID>orfuser/lsof:- Risk: A lockfile may be empty (contain no PID), or on Debian
/var/lib/dpkg/lock-frontenduses 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/locksmatching inode number, or test whether non-blockingfcntl.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.
- Risk: A lockfile may be empty (contain no PID), or on Debian
- DNF Check-Update Exit Code 100:
- Risk: Standard Linux conventions treat non-zero exit codes as errors. However,
dnf check-updatereturns return code100specifically when updates are available,0when no updates exist, and1on 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
100as normal success with available packages inDnfManager.
- Risk: Standard Linux conventions treat non-zero exit codes as errors. However,
- Major Release Upgrade Non-Interactivity:
- Risk: Tools like Ubuntu's
do-release-upgradeor Debian'sdist-upgradecan prompt during config file diffs (dpkgconffiles: 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=noninteractiveand-o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold", and fordo-release-upgraderequire-f DistUpgradeViewNonInteractive. In interactive mode, let stdin pass through directly to the terminal.
- Risk: Tools like Ubuntu's
- OOM Detection False Alarms:
- Risk: Searching
dmesgor/dev/kmsgfor "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.
- Risk: Searching