feat: implement slice 2 pre-flight health checks and auto-remediation engine

This commit is contained in:
soda64 committed 2026-10-02 10:10:54 +02:00
1 parent 63c6cc846b
commit 62ce7e63f8
7 files changed
+780 -38

No files matched your search

+96 -37
View File
@@ -1,17 +1,54 @@
import argparse
from pathlib import Path
import sys
from typing import List, Optional
from linux_updater import __version__
from linux_updater.config import UpdaterConfig
from linux_updater.core.detector import DistroDetector
from linux_updater.models import DistroFamily
def create_parser() -> argparse.ArgumentParser:
common = argparse.ArgumentParser(add_help=False)
common.add_argument(
"-c", "--config",
type=str,
default="/etc/linux-updater.json",
help="Path to JSON configuration file.",
)
common.add_argument(
"-y", "--yes", "--non-interactive",
dest="non_interactive",
action="store_true",
help="Run without interactive confirmation prompts (ideal for cron and automation).",
)
common.add_argument(
"--dry-run",
action="store_true",
help="Simulate execution without modifying system state.",
)
common.add_argument(
"--no-remediation",
action="store_true",
help="Disable automatic remediation of failed pre-flight health checks.",
)
common.add_argument(
"--skip-preflight",
action="store_true",
help="Skip pre-flight health checks (not recommended).",
)
common.add_argument(
"--json",
action="store_true",
help="Output structured JSON results.",
)
parser = argparse.ArgumentParser(
prog="linux-updater",
description="Unified, safe multi-distribution Linux system updater and health inspector.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
parents=[common],
)
parser.add_argument(
"-v", "--version",
@@ -19,44 +56,13 @@ def create_parser() -> argparse.ArgumentParser:
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",
parents=[common],
help="Inspect health, auto-remediate safe issues, and apply package updates.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
@@ -70,6 +76,7 @@ def create_parser() -> argparse.ArgumentParser:
# Subcommand: check
subparsers.add_parser(
"check",
parents=[common],
help="Check system health and list available updates without making modifications.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
@@ -77,6 +84,7 @@ def create_parser() -> argparse.ArgumentParser:
# Subcommand: release-upgrade
release_parser = subparsers.add_parser(
"release-upgrade",
parents=[common],
help="Perform a major distribution release upgrade with additional safety guardrails.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
@@ -89,6 +97,7 @@ def create_parser() -> argparse.ArgumentParser:
# Subcommand: clean
clean_parser = subparsers.add_parser(
"clean",
parents=[common],
help="Clean downloaded package cache and remove orphaned packages.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
@@ -101,6 +110,7 @@ def create_parser() -> argparse.ArgumentParser:
# Subcommand: health
subparsers.add_parser(
"health",
parents=[common],
help="Run only the pre-flight health diagnostic checks.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
@@ -112,7 +122,6 @@ 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"
@@ -123,10 +132,60 @@ def main(argv: Optional[List[str]] = None) -> int:
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
config = UpdaterConfig.load(Path(args.config) if args.config else None)
if args.non_interactive:
config.non_interactive = True
if args.no_remediation:
config.auto_remediate = False
# Create dummy manager for health checks when specific manager isn't wired yet
from linux_updater.managers.base import PackageManager
from linux_updater.models import RebootStatus
class FallbackManager(PackageManager):
@property
def name(self) -> str:
return distro.family.value
def refresh_repositories(self): pass
def check_updates(self): return []
def apply_updates(self, packages=None, dry_run=False, non_interactive=False): pass
def release_upgrade(self, target_release=None, non_interactive=False): pass
def clean_cache(self): pass
def autoremove(self): pass
def is_reboot_required(self) -> RebootStatus:
reboot_p = Path("/var/run/reboot-required")
return RebootStatus(required=reboot_p.exists(), reason="reboot-required flag found" if reboot_p.exists() else "")
def get_lock_files(self) -> List[Path]:
if distro.family == DistroFamily.DEBIAN:
return [Path("/var/lib/dpkg/lock-frontend"), Path("/var/lib/dpkg/lock")]
elif distro.family == DistroFamily.RHEL:
return [Path("/var/lib/rpm/.rpm.lock")]
elif distro.family == DistroFamily.ARCH:
return [Path("/var/lib/pacman/db.lck")]
return []
manager = FallbackManager()
from linux_updater.core.health import HealthChecker
checker = HealthChecker(config=config, manager=manager)
if args.command == "health":
report = checker.run_all_checks()
if args.json:
import json
print(json.dumps(report.to_dict(), indent=2))
else:
print("\nPre-flight Health Diagnostics:")
print("-" * 65)
for res in report.results:
status_symbol = "[ PASS ]" if res.status.value == "PASS" else (
"[ WARN ]" if res.status.value == "WARN" else "[ FAIL ]"
)
print(f"{status_symbol} {res.name:<22} {res.message}")
print("-" * 65)
status_text = "PASSED" if report.passed else "FAILED"
print(f"Overall Pre-flight Status: {status_text}\n")
return 0 if report.passed else 1
return 0
+80
View File
@@ -0,0 +1,80 @@
import json
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[str] = "/var/log/linux-updater.log",
verbose: bool = False,
) -> None:
self.min_boot_mb = min_boot_mb
self.min_var_mb = min_var_mb
self.min_root_mb = min_root_mb
self.min_ram_mb = min_ram_mb
self.auto_remediate = auto_remediate
self.non_interactive = non_interactive
self.check_ac_power = check_ac_power
self.clean_after_update = clean_after_update
self.log_file = log_file
self.verbose = verbose
@classmethod
def load(cls, config_path: Optional[Path] = None) -> "UpdaterConfig":
if config_path is None:
config_path = Path("/etc/linux-updater.json")
if not config_path.exists():
return cls()
try:
with open(str(config_path), "r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
return cls()
thresholds = data.get("thresholds", {})
behavior = data.get("behavior", {})
logging = data.get("logging", {})
return cls(
min_boot_mb=thresholds.get("min_boot_mb", 250),
min_var_mb=thresholds.get("min_var_mb", 1024),
min_root_mb=thresholds.get("min_root_mb", 1024),
min_ram_mb=thresholds.get("min_ram_mb", 300),
auto_remediate=behavior.get("auto_remediate", True),
non_interactive=behavior.get("non_interactive", False),
check_ac_power=behavior.get("check_ac_power", True),
clean_after_update=behavior.get("clean_after_update", False),
log_file=logging.get("log_file", "/var/log/linux-updater.log"),
verbose=logging.get("verbose", False),
)
def to_dict(self) -> Dict[str, Any]:
return {
"thresholds": {
"min_boot_mb": self.min_boot_mb,
"min_var_mb": self.min_var_mb,
"min_root_mb": self.min_root_mb,
"min_ram_mb": self.min_ram_mb,
},
"behavior": {
"auto_remediate": self.auto_remediate,
"non_interactive": self.non_interactive,
"check_ac_power": self.check_ac_power,
"clean_after_update": self.clean_after_update,
},
"logging": {
"log_file": self.log_file,
"verbose": self.verbose,
},
}
+301
View File
@@ -0,0 +1,301 @@
import os
import re
from pathlib import Path
from typing import List, Optional
from linux_updater.config import UpdaterConfig
from linux_updater.managers.base import PackageManager
from linux_updater.models import CheckResult, CheckStatus, PreflightReport
class HealthChecker:
def __init__(
self,
config: UpdaterConfig,
manager: PackageManager,
meminfo_path: Optional[Path] = None,
power_path: Optional[Path] = None,
) -> None:
self.config = config
self.manager = manager
self.meminfo_path = meminfo_path or Path("/proc/meminfo")
self.power_path = power_path or Path("/sys/class/power_supply")
def _get_free_space_mb(self, path: Path) -> int:
try:
stat = os.statvfs(str(path))
return (stat.f_bavail * stat.f_frsize) // (1024 * 1024)
except (FileNotFoundError, OSError):
try:
stat = os.statvfs("/")
return (stat.f_bavail * stat.f_frsize) // (1024 * 1024)
except Exception:
return 999999
except Exception:
return 999999
def check_disk_space(self) -> List[CheckResult]:
results: List[CheckResult] = []
# 1. /boot check
boot_path = Path("/boot")
boot_free = self._get_free_space_mb(boot_path)
if boot_free < self.config.min_boot_mb:
results.append(
CheckResult(
name="disk_boot",
status=CheckStatus.FAIL,
message=f"/boot free space is critically low: {boot_free}MB (min required: {self.config.min_boot_mb}MB)",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name="disk_boot",
status=CheckStatus.PASS,
message=f"/boot free space is sufficient: {boot_free}MB",
)
)
# 2. /var check
var_path = Path("/var")
var_free = self._get_free_space_mb(var_path)
if var_free < self.config.min_var_mb:
results.append(
CheckResult(
name="disk_var",
status=CheckStatus.FAIL,
message=f"/var free space is low: {var_free}MB (min required: {self.config.min_var_mb}MB)",
can_remediate=True,
remediation_id="clean_cache",
)
)
else:
results.append(
CheckResult(
name="disk_var",
status=CheckStatus.PASS,
message=f"/var free space is sufficient: {var_free}MB",
)
)
# 3. / (root) check
root_path = Path("/")
root_free = self._get_free_space_mb(root_path)
if root_free < self.config.min_root_mb:
results.append(
CheckResult(
name="disk_root",
status=CheckStatus.FAIL,
message=f"Root filesystem free space is critically low: {root_free}MB (min required: {self.config.min_root_mb}MB)",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name="disk_root",
status=CheckStatus.PASS,
message=f"Root filesystem free space is sufficient: {root_free}MB",
)
)
return results
@staticmethod
def _is_pid_alive(pid: int) -> bool:
if pid <= 0:
return False
try:
# Signal 0 performs error checking without sending an actual signal
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
# Process exists but owned by someone else
return True
except Exception:
return False
def check_locks(self) -> List[CheckResult]:
results: List[CheckResult] = []
lock_files = self.manager.get_lock_files()
for lock_p in lock_files:
if not lock_p.exists():
results.append(
CheckResult(
name=f"lock_{lock_p.name}",
status=CheckStatus.PASS,
message=f"No lock active at {lock_p}",
)
)
continue
# Lockfile exists - inspect if holder PID is alive
pid: Optional[int] = None
try:
content = lock_p.read_text().strip()
if content and content.isdigit():
pid = int(content)
except Exception:
pid = None
if pid is not None:
if self._is_pid_alive(pid):
results.append(
CheckResult(
name=f"lock_{lock_p.name}",
status=CheckStatus.FAIL,
message=f"Active lock held by running process PID {pid} at {lock_p}",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name=f"lock_{lock_p.name}",
status=CheckStatus.FAIL,
message=str(lock_p),
can_remediate=True,
remediation_id="remove_stale_lock",
)
)
else:
results.append(
CheckResult(
name=f"lock_{lock_p.name}",
status=CheckStatus.FAIL,
message=f"Lock file exists at {lock_p}",
can_remediate=False,
)
)
return results
def check_memory_and_oom(self) -> List[CheckResult]:
results: List[CheckResult] = []
if not self.meminfo_path.exists():
return results
mem_avail_kb: Optional[int] = None
mem_free_kb = 0
buffers_kb = 0
cached_kb = 0
try:
with open(str(self.meminfo_path), "r", encoding="utf-8") as f:
for line in f:
if line.startswith("MemAvailable:"):
parts = line.split()
if len(parts) >= 2:
mem_avail_kb = int(parts[1])
elif line.startswith("MemFree:"):
parts = line.split()
if len(parts) >= 2:
mem_free_kb = int(parts[1])
elif line.startswith("Buffers:"):
parts = line.split()
if len(parts) >= 2:
buffers_kb = int(parts[1])
elif line.startswith("Cached:"):
parts = line.split()
if len(parts) >= 2:
cached_kb = int(parts[1])
except Exception:
return results
if mem_avail_kb is None:
mem_avail_kb = mem_free_kb + buffers_kb + cached_kb
mem_avail_mb = mem_avail_kb // 1024
if mem_avail_mb < self.config.min_ram_mb:
results.append(
CheckResult(
name="memory_available",
status=CheckStatus.FAIL,
message=f"Available RAM is critically low: {mem_avail_mb}MB (min required: {self.config.min_ram_mb}MB)",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name="memory_available",
status=CheckStatus.PASS,
message=f"Available RAM is sufficient: {mem_avail_mb}MB",
)
)
return results
def check_power(self) -> List[CheckResult]:
results: List[CheckResult] = []
if not self.config.check_ac_power:
return results
if not self.power_path.exists():
return results
for supply in self.power_path.iterdir():
type_p = supply / "type"
if type_p.exists() and "battery" in type_p.read_text().lower():
status_p = supply / "status"
capacity_p = supply / "capacity"
status = status_p.read_text().strip() if status_p.exists() else "Unknown"
capacity = int(capacity_p.read_text().strip()) if capacity_p.exists() and capacity_p.read_text().strip().isdigit() else 100
if status.lower() == "discharging" and capacity < 20:
results.append(
CheckResult(
name="power_battery",
status=CheckStatus.WARN,
message=f"Battery is discharging and capacity is low: {capacity}%. Please connect AC adapter.",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name="power_battery",
status=CheckStatus.PASS,
message=f"Power status is safe: {status} ({capacity}%)",
)
)
return results
def check_pending_reboot(self) -> List[CheckResult]:
results: List[CheckResult] = []
reboot_status = self.manager.is_reboot_required()
if reboot_status.required:
results.append(
CheckResult(
name="pending_reboot",
status=CheckStatus.WARN,
message=f"System reboot is already pending from prior updates ({reboot_status.reason}).",
can_remediate=False,
)
)
else:
results.append(
CheckResult(
name="pending_reboot",
status=CheckStatus.PASS,
message="No pending system reboot detected.",
)
)
return results
def run_all_checks(self) -> PreflightReport:
all_results: List[CheckResult] = []
all_results.extend(self.check_disk_space())
all_results.extend(self.check_locks())
all_results.extend(self.check_memory_and_oom())
all_results.extend(self.check_power())
all_results.extend(self.check_pending_reboot())
has_failure = any(r.status == CheckStatus.FAIL for r in all_results)
return PreflightReport(passed=not has_failure, results=all_results)
+60
View File
@@ -0,0 +1,60 @@
import os
from pathlib import Path
from typing import Optional
from linux_updater.core.health import HealthChecker
from linux_updater.managers.base import PackageManager
from linux_updater.models import CheckResult
class RemediationEngine:
def __init__(self, manager: PackageManager) -> None:
self.manager = manager
def can_remediate(self, check: CheckResult) -> bool:
if not check.can_remediate:
return False
return check.remediation_id in {"clean_cache", "remove_stale_lock"}
def remediate(self, check: CheckResult) -> bool:
if not self.can_remediate(check):
return False
if check.remediation_id == "clean_cache":
return self.clean_cache()
elif check.remediation_id == "remove_stale_lock":
return self.remove_stale_lock(check.message)
return False
def clean_cache(self) -> bool:
try:
res = self.manager.clean_cache()
# If manager returns CommandResult or bool
if hasattr(res, "success"):
return bool(res.success)
return True
except Exception:
return False
def remove_stale_lock(self, lock_path_str: str) -> bool:
lock_p = Path(lock_path_str)
if not lock_p.exists():
return True
# Safety check: if lockfile contains a PID, ensure it is truly dead
try:
content = lock_p.read_text().strip()
if content and content.isdigit():
pid = int(content)
if HealthChecker._is_pid_alive(pid):
# Process is actually alive! Do not delete!
return False
except Exception:
pass
try:
lock_p.unlink()
return True
except Exception:
return False