Files

9.9 KiB

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:

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

@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:

{
  "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)