feat: implement slice 1 tracer bullet (cli entrypoint, distro detector, and test suite)
This commit is contained in:
commit
63c6cc846b
16 files changed
+1317
No files matched your search
+11
@@ -0,0 +1,11 @@
|
|||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
*.so
|
||||||
|
.pytest_cache/
|
||||||
|
.coverage
|
||||||
|
htmlcov/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg-info/
|
||||||
|
.eggs/
|
||||||
@@ -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).
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
"""Linux System Updater - Multi-distribution system updater and health checker."""
|
||||||
|
|
||||||
|
__version__ = "1.0.0"
|
||||||
|
__author__ = "Test Factory"
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import sys
|
||||||
|
from linux_updater.cli import main
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1,135 @@
|
|||||||
|
import argparse
|
||||||
|
import sys
|
||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from linux_updater import __version__
|
||||||
|
from linux_updater.core.detector import DistroDetector
|
||||||
|
from linux_updater.models import DistroFamily
|
||||||
|
|
||||||
|
|
||||||
|
def create_parser() -> argparse.ArgumentParser:
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
prog="linux-updater",
|
||||||
|
description="Unified, safe multi-distribution Linux system updater and health inspector.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-v", "--version",
|
||||||
|
action="version",
|
||||||
|
version=f"%(prog)s {__version__}",
|
||||||
|
help="Show program's version number and exit.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-c", "--config",
|
||||||
|
type=str,
|
||||||
|
default="/etc/linux-updater.json",
|
||||||
|
help="Path to JSON configuration file.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-y", "--yes", "--non-interactive",
|
||||||
|
dest="non_interactive",
|
||||||
|
action="store_true",
|
||||||
|
help="Run without interactive confirmation prompts (ideal for cron and automation).",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
help="Simulate execution without modifying system state.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--no-remediation",
|
||||||
|
action="store_true",
|
||||||
|
help="Disable automatic remediation of failed pre-flight health checks.",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--skip-preflight",
|
||||||
|
action="store_true",
|
||||||
|
help="Skip pre-flight health checks (not recommended).",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--json",
|
||||||
|
action="store_true",
|
||||||
|
help="Output structured JSON results.",
|
||||||
|
)
|
||||||
|
|
||||||
|
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
||||||
|
|
||||||
|
# Subcommand: update
|
||||||
|
update_parser = subparsers.add_parser(
|
||||||
|
"update",
|
||||||
|
help="Inspect health, auto-remediate safe issues, and apply package updates.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
update_parser.add_argument(
|
||||||
|
"--packages",
|
||||||
|
nargs="+",
|
||||||
|
metavar="PACKAGE",
|
||||||
|
help="Selectively update only the specified package(s) instead of the entire system.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: check
|
||||||
|
subparsers.add_parser(
|
||||||
|
"check",
|
||||||
|
help="Check system health and list available updates without making modifications.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: release-upgrade
|
||||||
|
release_parser = subparsers.add_parser(
|
||||||
|
"release-upgrade",
|
||||||
|
help="Perform a major distribution release upgrade with additional safety guardrails.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
release_parser.add_argument(
|
||||||
|
"-t", "--target-release",
|
||||||
|
type=str,
|
||||||
|
help="Specify the target distribution version number/codename (e.g. 24.04, 41).",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: clean
|
||||||
|
clean_parser = subparsers.add_parser(
|
||||||
|
"clean",
|
||||||
|
help="Clean downloaded package cache and remove orphaned packages.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
clean_parser.add_argument(
|
||||||
|
"--all",
|
||||||
|
action="store_true",
|
||||||
|
help="Clean both package cache and autoremove unused dependencies.",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Subcommand: health
|
||||||
|
subparsers.add_parser(
|
||||||
|
"health",
|
||||||
|
help="Run only the pre-flight health diagnostic checks.",
|
||||||
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
)
|
||||||
|
|
||||||
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv: Optional[List[str]] = None) -> int:
|
||||||
|
parser = create_parser()
|
||||||
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
|
# If no subcommand provided, default to update or show help if no args given
|
||||||
|
if args.command is None:
|
||||||
|
args.command = "update"
|
||||||
|
|
||||||
|
detector = DistroDetector()
|
||||||
|
distro = detector.detect()
|
||||||
|
|
||||||
|
if not args.json:
|
||||||
|
print(f"Linux System Updater v{__version__}")
|
||||||
|
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
||||||
|
|
||||||
|
if distro.family == DistroFamily.UNKNOWN:
|
||||||
|
if not args.json:
|
||||||
|
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main())
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Core subsystem
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from typing import Dict, Optional
|
||||||
|
from linux_updater.models import DistroFamily, DistroInfo
|
||||||
|
|
||||||
|
|
||||||
|
class DistroDetector:
|
||||||
|
def __init__(self, os_release_path: Optional[Path] = None) -> None:
|
||||||
|
if os_release_path is not None:
|
||||||
|
self.os_release_path = os_release_path
|
||||||
|
else:
|
||||||
|
default_p = Path("/etc/os-release")
|
||||||
|
fallback_p = Path("/usr/lib/os-release")
|
||||||
|
self.os_release_path = default_p if default_p.exists() else fallback_p
|
||||||
|
|
||||||
|
def _parse_os_release(self) -> Dict[str, str]:
|
||||||
|
data: Dict[str, str] = {}
|
||||||
|
if not self.os_release_path.exists():
|
||||||
|
return data
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(str(self.os_release_path), "r", encoding="utf-8", errors="replace") as f:
|
||||||
|
for line in f:
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or "=" not in line:
|
||||||
|
continue
|
||||||
|
key, val = line.split("=", 1)
|
||||||
|
key = key.strip()
|
||||||
|
val = val.strip()
|
||||||
|
# Strip surrounding quotes if present
|
||||||
|
if len(val) >= 2 and (
|
||||||
|
(val.startswith('"') and val.endswith('"'))
|
||||||
|
or (val.startswith("'") and val.endswith("'"))
|
||||||
|
):
|
||||||
|
val = val[1:-1]
|
||||||
|
data[key] = val
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
return data
|
||||||
|
|
||||||
|
def detect(self) -> DistroInfo:
|
||||||
|
data = self._parse_os_release()
|
||||||
|
if not data:
|
||||||
|
return DistroInfo(
|
||||||
|
family=DistroFamily.UNKNOWN,
|
||||||
|
distro_id="unknown",
|
||||||
|
version_id="unknown",
|
||||||
|
pretty_name="Unknown Linux System",
|
||||||
|
)
|
||||||
|
|
||||||
|
distro_id = data.get("ID", "").lower().strip()
|
||||||
|
id_like = data.get("ID_LIKE", "").lower().strip().split()
|
||||||
|
version_id = data.get("VERSION_ID", data.get("BUILD_ID", "rolling")).strip()
|
||||||
|
pretty_name = data.get("PRETTY_NAME", data.get("NAME", distro_id)).strip()
|
||||||
|
|
||||||
|
family = self._resolve_family(distro_id, id_like)
|
||||||
|
|
||||||
|
return DistroInfo(
|
||||||
|
family=family,
|
||||||
|
distro_id=distro_id,
|
||||||
|
version_id=version_id,
|
||||||
|
pretty_name=pretty_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _resolve_family(self, distro_id: str, id_like: list) -> DistroFamily:
|
||||||
|
debian_ids = {"debian", "ubuntu", "linuxmint", "pop", "elementary", "kali", "raspbian"}
|
||||||
|
rhel_ids = {"rhel", "fedora", "centos", "rocky", "almalinux", "ol", "amzn"}
|
||||||
|
arch_ids = {"arch", "manjaro", "endeavouros", "garuda", "artix"}
|
||||||
|
|
||||||
|
if distro_id in debian_ids:
|
||||||
|
return DistroFamily.DEBIAN
|
||||||
|
if distro_id in rhel_ids:
|
||||||
|
return DistroFamily.RHEL
|
||||||
|
if distro_id in arch_ids:
|
||||||
|
return DistroFamily.ARCH
|
||||||
|
|
||||||
|
# Check ID_LIKE
|
||||||
|
for like in id_like:
|
||||||
|
if like in debian_ids:
|
||||||
|
return DistroFamily.DEBIAN
|
||||||
|
if like in rhel_ids:
|
||||||
|
return DistroFamily.RHEL
|
||||||
|
if like in arch_ids:
|
||||||
|
return DistroFamily.ARCH
|
||||||
|
|
||||||
|
return DistroFamily.UNKNOWN
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Package managers subsystem
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
from abc import ABC, abstractmethod
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import List, Optional
|
||||||
|
from linux_updater.models import PackageUpdate, CommandResult, RebootStatus
|
||||||
|
|
||||||
|
|
||||||
|
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) -> CommandResult:
|
||||||
|
"""Synchronizes repository metadata."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def check_updates(self) -> List[PackageUpdate]:
|
||||||
|
"""Lists available package updates."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def apply_updates(
|
||||||
|
self,
|
||||||
|
packages: Optional[List[str]] = None,
|
||||||
|
dry_run: bool = False,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
"""Applies package updates."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def release_upgrade(
|
||||||
|
self,
|
||||||
|
target_release: Optional[str] = None,
|
||||||
|
non_interactive: bool = False,
|
||||||
|
) -> CommandResult:
|
||||||
|
"""Executes a major OS distribution upgrade."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def clean_cache(self) -> CommandResult:
|
||||||
|
"""Cleans downloaded package cache."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def autoremove(self) -> CommandResult:
|
||||||
|
"""Removes unneeded dependency packages."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def is_reboot_required(self) -> RebootStatus:
|
||||||
|
"""Detects whether a system reboot is required."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
@abstractmethod
|
||||||
|
def get_lock_files(self) -> List[Path]:
|
||||||
|
"""Returns paths of lockfiles used by this manager."""
|
||||||
|
pass
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
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 = False,
|
||||||
|
remediation_id: Optional[str] = None,
|
||||||
|
) -> None:
|
||||||
|
self.name = name
|
||||||
|
self.status = status
|
||||||
|
self.message = message
|
||||||
|
self.can_remediate = can_remediate
|
||||||
|
self.remediation_id = remediation_id
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"name": self.name,
|
||||||
|
"status": self.status.value,
|
||||||
|
"message": self.message,
|
||||||
|
"can_remediate": self.can_remediate,
|
||||||
|
"remediation_id": self.remediation_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"CheckResult(name={self.name!r}, status={self.status!r}, message={self.message!r})"
|
||||||
|
|
||||||
|
|
||||||
|
class PreflightReport:
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
passed: bool,
|
||||||
|
results: List[CheckResult],
|
||||||
|
remediations_performed: Optional[List[str]] = None,
|
||||||
|
) -> None:
|
||||||
|
self.passed = passed
|
||||||
|
self.results = results
|
||||||
|
self.remediations_performed = remediations_performed or []
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"passed": self.passed,
|
||||||
|
"results": [r.to_dict() for r in self.results],
|
||||||
|
"remediations_performed": self.remediations_performed,
|
||||||
|
}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"PreflightReport(passed={self.passed!r}, results_count={len(self.results)})"
|
||||||
|
|
||||||
|
|
||||||
|
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:
|
||||||
|
self.return_code = return_code
|
||||||
|
self.stdout = stdout
|
||||||
|
self.stderr = stderr
|
||||||
|
self.success = success
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"return_code": self.return_code,
|
||||||
|
"stdout": self.stdout,
|
||||||
|
"stderr": self.stderr,
|
||||||
|
"success": self.success,
|
||||||
|
}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"CommandResult(return_code={self.return_code}, success={self.success})"
|
||||||
|
|
||||||
|
|
||||||
|
class RebootStatus:
|
||||||
|
def __init__(self, required: bool, reason: str = "") -> None:
|
||||||
|
self.required = required
|
||||||
|
self.reason = reason
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"required": self.required,
|
||||||
|
"reason": self.reason,
|
||||||
|
}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return f"RebootStatus(required={self.required!r}, reason={self.reason!r})"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Package marker for tests
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
import unittest
|
||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from linux_updater.models import DistroFamily, DistroInfo
|
||||||
|
from linux_updater.core.detector import DistroDetector
|
||||||
|
|
||||||
|
|
||||||
|
class TestDistroDetector(unittest.TestCase):
|
||||||
|
def _create_os_release(self, content: str) -> Path:
|
||||||
|
t = tempfile.NamedTemporaryFile("w", delete=False)
|
||||||
|
t.write(content)
|
||||||
|
t.close()
|
||||||
|
return Path(t.name)
|
||||||
|
|
||||||
|
def test_detect_ubuntu(self):
|
||||||
|
content = """NAME="Ubuntu"
|
||||||
|
VERSION="24.04.1 LTS (Noble Numbat)"
|
||||||
|
ID=ubuntu
|
||||||
|
ID_LIKE=debian
|
||||||
|
PRETTY_NAME="Ubuntu 24.04.1 LTS"
|
||||||
|
VERSION_ID="24.04"
|
||||||
|
"""
|
||||||
|
p = self._create_os_release(content)
|
||||||
|
try:
|
||||||
|
detector = DistroDetector(os_release_path=p)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.DEBIAN)
|
||||||
|
self.assertEqual(info.distro_id, "ubuntu")
|
||||||
|
self.assertEqual(info.version_id, "24.04")
|
||||||
|
self.assertEqual(info.pretty_name, "Ubuntu 24.04.1 LTS")
|
||||||
|
finally:
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
def test_detect_debian(self):
|
||||||
|
content = """PRETTY_NAME="Debian GNU/Linux 12 (bookworm)"
|
||||||
|
NAME="Debian GNU/Linux"
|
||||||
|
VERSION_ID="12"
|
||||||
|
VERSION="12 (bookworm)"
|
||||||
|
VERSION_CODENAME=bookworm
|
||||||
|
ID=debian
|
||||||
|
"""
|
||||||
|
p = self._create_os_release(content)
|
||||||
|
try:
|
||||||
|
detector = DistroDetector(os_release_path=p)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.DEBIAN)
|
||||||
|
self.assertEqual(info.distro_id, "debian")
|
||||||
|
self.assertEqual(info.version_id, "12")
|
||||||
|
finally:
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
def test_detect_fedora(self):
|
||||||
|
content = """NAME="Fedora Linux"
|
||||||
|
VERSION="40 (Workstation Edition)"
|
||||||
|
ID=fedora
|
||||||
|
VERSION_ID="40"
|
||||||
|
PRETTY_NAME="Fedora Linux 40 (Workstation Edition)"
|
||||||
|
"""
|
||||||
|
p = self._create_os_release(content)
|
||||||
|
try:
|
||||||
|
detector = DistroDetector(os_release_path=p)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.RHEL)
|
||||||
|
self.assertEqual(info.distro_id, "fedora")
|
||||||
|
self.assertEqual(info.version_id, "40")
|
||||||
|
finally:
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
def test_detect_rocky_rhel_family(self):
|
||||||
|
content = """NAME="Rocky Linux"
|
||||||
|
VERSION="9.4 (Blue Onyx)"
|
||||||
|
ID="rocky"
|
||||||
|
ID_LIKE="rhel centos fedora"
|
||||||
|
VERSION_ID="9.4"
|
||||||
|
PRETTY_NAME="Rocky Linux 9.4 (Blue Onyx)"
|
||||||
|
"""
|
||||||
|
p = self._create_os_release(content)
|
||||||
|
try:
|
||||||
|
detector = DistroDetector(os_release_path=p)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.RHEL)
|
||||||
|
self.assertEqual(info.distro_id, "rocky")
|
||||||
|
self.assertEqual(info.version_id, "9.4")
|
||||||
|
finally:
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
def test_detect_arch(self):
|
||||||
|
content = """NAME="Arch Linux"
|
||||||
|
PRETTY_NAME="Arch Linux"
|
||||||
|
ID=arch
|
||||||
|
BUILD_ID=rolling
|
||||||
|
"""
|
||||||
|
p = self._create_os_release(content)
|
||||||
|
try:
|
||||||
|
detector = DistroDetector(os_release_path=p)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.ARCH)
|
||||||
|
self.assertEqual(info.distro_id, "arch")
|
||||||
|
self.assertEqual(info.version_id, "rolling")
|
||||||
|
finally:
|
||||||
|
p.unlink()
|
||||||
|
|
||||||
|
def test_detect_missing_os_release(self):
|
||||||
|
non_existent = Path("/tmp/non_existent_os_release_12345")
|
||||||
|
if non_existent.exists():
|
||||||
|
non_existent.unlink()
|
||||||
|
detector = DistroDetector(os_release_path=non_existent)
|
||||||
|
info = detector.detect()
|
||||||
|
self.assertEqual(info.family, DistroFamily.UNKNOWN)
|
||||||
|
self.assertEqual(info.distro_id, "unknown")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user