feat: implement slice 2 pre-flight health checks and auto-remediation engine
This commit is contained in:
1 parent
63c6cc846b
commit
62ce7e63f8
7 files changed
+780
-38
No files matched your search
@@ -7,7 +7,7 @@
|
|||||||
|
|
||||||
## Slices
|
## Slices
|
||||||
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
|
- [x] Slice 1 — tracer bullet: minimal end-to-end wire (CLI + detector + tests)
|
||||||
- [ ] Slice 2 — pre-flight health & auto-remediation engine
|
- [x] Slice 2 — pre-flight health & auto-remediation engine
|
||||||
- [ ] Slice 3 — package managers (apt, dnf, pacman) & routine updates
|
- [ ] Slice 3 — package managers (apt, dnf, pacman) & routine updates
|
||||||
- [ ] Slice 4 — major release upgrade & configuration engine
|
- [ ] Slice 4 — major release upgrade & configuration engine
|
||||||
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
- [ ] Slice 5 — packaging & distribution (.tar.gz, .deb, .rpm)
|
||||||
|
|||||||
+96
-37
@@ -1,17 +1,54 @@
|
|||||||
import argparse
|
import argparse
|
||||||
|
from pathlib import Path
|
||||||
import sys
|
import sys
|
||||||
from typing import List, Optional
|
from typing import List, Optional
|
||||||
|
|
||||||
from linux_updater import __version__
|
from linux_updater import __version__
|
||||||
|
from linux_updater.config import UpdaterConfig
|
||||||
from linux_updater.core.detector import DistroDetector
|
from linux_updater.core.detector import DistroDetector
|
||||||
from linux_updater.models import DistroFamily
|
from linux_updater.models import DistroFamily
|
||||||
|
|
||||||
|
|
||||||
def create_parser() -> argparse.ArgumentParser:
|
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(
|
parser = argparse.ArgumentParser(
|
||||||
prog="linux-updater",
|
prog="linux-updater",
|
||||||
description="Unified, safe multi-distribution Linux system updater and health inspector.",
|
description="Unified, safe multi-distribution Linux system updater and health inspector.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
|
parents=[common],
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"-v", "--version",
|
"-v", "--version",
|
||||||
@@ -19,44 +56,13 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
version=f"%(prog)s {__version__}",
|
version=f"%(prog)s {__version__}",
|
||||||
help="Show program's version number and exit.",
|
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")
|
subparsers = parser.add_subparsers(dest="command", help="Available subcommands")
|
||||||
|
|
||||||
# Subcommand: update
|
# Subcommand: update
|
||||||
update_parser = subparsers.add_parser(
|
update_parser = subparsers.add_parser(
|
||||||
"update",
|
"update",
|
||||||
|
parents=[common],
|
||||||
help="Inspect health, auto-remediate safe issues, and apply package updates.",
|
help="Inspect health, auto-remediate safe issues, and apply package updates.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
)
|
)
|
||||||
@@ -70,6 +76,7 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
# Subcommand: check
|
# Subcommand: check
|
||||||
subparsers.add_parser(
|
subparsers.add_parser(
|
||||||
"check",
|
"check",
|
||||||
|
parents=[common],
|
||||||
help="Check system health and list available updates without making modifications.",
|
help="Check system health and list available updates without making modifications.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
)
|
)
|
||||||
@@ -77,6 +84,7 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
# Subcommand: release-upgrade
|
# Subcommand: release-upgrade
|
||||||
release_parser = subparsers.add_parser(
|
release_parser = subparsers.add_parser(
|
||||||
"release-upgrade",
|
"release-upgrade",
|
||||||
|
parents=[common],
|
||||||
help="Perform a major distribution release upgrade with additional safety guardrails.",
|
help="Perform a major distribution release upgrade with additional safety guardrails.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
)
|
)
|
||||||
@@ -89,6 +97,7 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
# Subcommand: clean
|
# Subcommand: clean
|
||||||
clean_parser = subparsers.add_parser(
|
clean_parser = subparsers.add_parser(
|
||||||
"clean",
|
"clean",
|
||||||
|
parents=[common],
|
||||||
help="Clean downloaded package cache and remove orphaned packages.",
|
help="Clean downloaded package cache and remove orphaned packages.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
)
|
)
|
||||||
@@ -101,6 +110,7 @@ def create_parser() -> argparse.ArgumentParser:
|
|||||||
# Subcommand: health
|
# Subcommand: health
|
||||||
subparsers.add_parser(
|
subparsers.add_parser(
|
||||||
"health",
|
"health",
|
||||||
|
parents=[common],
|
||||||
help="Run only the pre-flight health diagnostic checks.",
|
help="Run only the pre-flight health diagnostic checks.",
|
||||||
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
||||||
)
|
)
|
||||||
@@ -112,7 +122,6 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
parser = create_parser()
|
parser = create_parser()
|
||||||
args = parser.parse_args(argv)
|
args = parser.parse_args(argv)
|
||||||
|
|
||||||
# If no subcommand provided, default to update or show help if no args given
|
|
||||||
if args.command is None:
|
if args.command is None:
|
||||||
args.command = "update"
|
args.command = "update"
|
||||||
|
|
||||||
@@ -123,10 +132,60 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|||||||
print(f"Linux System Updater v{__version__}")
|
print(f"Linux System Updater v{__version__}")
|
||||||
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
print(f"Detected System: {distro.pretty_name} (Family: {distro.family.value})")
|
||||||
|
|
||||||
if distro.family == DistroFamily.UNKNOWN:
|
config = UpdaterConfig.load(Path(args.config) if args.config else None)
|
||||||
if not args.json:
|
if args.non_interactive:
|
||||||
print(f"Error: Unsupported or unrecognized Linux distribution: {distro.distro_id}", file=sys.stderr)
|
config.non_interactive = True
|
||||||
return 1
|
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
|
return 0
|
||||||
|
|
||||||
|
|||||||
@@ -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,
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
@@ -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
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch, MagicMock
|
||||||
|
|
||||||
|
from linux_updater.models import CheckStatus, DistroFamily, DistroInfo, RebootStatus
|
||||||
|
from linux_updater.config import UpdaterConfig
|
||||||
|
from linux_updater.managers.base import PackageManager
|
||||||
|
from linux_updater.core.health import HealthChecker
|
||||||
|
|
||||||
|
|
||||||
|
class DummyManager(PackageManager):
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
return "dummy"
|
||||||
|
|
||||||
|
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:
|
||||||
|
return RebootStatus(required=False)
|
||||||
|
|
||||||
|
def get_lock_files(self):
|
||||||
|
return [Path("/tmp/test_dummy.lock")]
|
||||||
|
|
||||||
|
|
||||||
|
class TestHealthChecker(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.config = UpdaterConfig(
|
||||||
|
min_boot_mb=250,
|
||||||
|
min_var_mb=1024,
|
||||||
|
min_root_mb=1024,
|
||||||
|
min_ram_mb=300,
|
||||||
|
)
|
||||||
|
self.manager = DummyManager()
|
||||||
|
self.checker = HealthChecker(config=self.config, manager=self.manager)
|
||||||
|
|
||||||
|
@patch("os.statvfs")
|
||||||
|
def test_disk_space_sufficient(self, mock_statvfs):
|
||||||
|
mock_stat = MagicMock()
|
||||||
|
mock_stat.f_bavail = 10 * 1024 * 1024
|
||||||
|
mock_stat.f_frsize = 1024
|
||||||
|
mock_statvfs.return_value = mock_stat
|
||||||
|
|
||||||
|
results = self.checker.check_disk_space()
|
||||||
|
for r in results:
|
||||||
|
self.assertEqual(r.status, CheckStatus.PASS)
|
||||||
|
|
||||||
|
@patch("os.statvfs")
|
||||||
|
def test_disk_space_low_boot(self, mock_statvfs):
|
||||||
|
def stat_side_effect(path):
|
||||||
|
mock_stat = MagicMock()
|
||||||
|
mock_stat.f_frsize = 1024
|
||||||
|
if str(path).rstrip("/") == "/boot":
|
||||||
|
mock_stat.f_bavail = 100 * 1024 # 100 MB (< 250 MB)
|
||||||
|
else:
|
||||||
|
mock_stat.f_bavail = 5 * 1024 * 1024 # 5 GB
|
||||||
|
return mock_stat
|
||||||
|
|
||||||
|
mock_statvfs.side_effect = stat_side_effect
|
||||||
|
results = self.checker.check_disk_space()
|
||||||
|
boot_res = next(r for r in results if r.name == "disk_boot")
|
||||||
|
self.assertEqual(boot_res.status, CheckStatus.FAIL)
|
||||||
|
self.assertFalse(boot_res.can_remediate)
|
||||||
|
|
||||||
|
@patch("os.statvfs")
|
||||||
|
def test_disk_space_low_var_can_remediate(self, mock_statvfs):
|
||||||
|
def stat_side_effect(path):
|
||||||
|
mock_stat = MagicMock()
|
||||||
|
mock_stat.f_frsize = 1024
|
||||||
|
if str(path).rstrip("/") == "/var":
|
||||||
|
mock_stat.f_bavail = 500 * 1024 # 500 MB (< 1024 MB)
|
||||||
|
else:
|
||||||
|
mock_stat.f_bavail = 5 * 1024 * 1024 # 5 GB
|
||||||
|
return mock_stat
|
||||||
|
|
||||||
|
mock_statvfs.side_effect = stat_side_effect
|
||||||
|
results = self.checker.check_disk_space()
|
||||||
|
var_res = next(r for r in results if r.name == "disk_var")
|
||||||
|
self.assertEqual(var_res.status, CheckStatus.FAIL)
|
||||||
|
self.assertTrue(var_res.can_remediate)
|
||||||
|
self.assertEqual(var_res.remediation_id, "clean_cache")
|
||||||
|
|
||||||
|
def test_locks_no_lockfiles(self):
|
||||||
|
if Path("/tmp/test_dummy.lock").exists():
|
||||||
|
Path("/tmp/test_dummy.lock").unlink()
|
||||||
|
results = self.checker.check_locks()
|
||||||
|
self.assertEqual(len(results), 1)
|
||||||
|
self.assertEqual(results[0].status, CheckStatus.PASS)
|
||||||
|
|
||||||
|
@patch("linux_updater.core.health.HealthChecker._is_pid_alive")
|
||||||
|
def test_locks_active_process(self, mock_pid_alive):
|
||||||
|
lock_p = Path("/tmp/test_dummy.lock")
|
||||||
|
lock_p.write_text("12345\n")
|
||||||
|
mock_pid_alive.return_value = True
|
||||||
|
try:
|
||||||
|
results = self.checker.check_locks()
|
||||||
|
self.assertEqual(len(results), 1)
|
||||||
|
self.assertEqual(results[0].status, CheckStatus.FAIL)
|
||||||
|
self.assertFalse(results[0].can_remediate)
|
||||||
|
finally:
|
||||||
|
if lock_p.exists():
|
||||||
|
lock_p.unlink()
|
||||||
|
|
||||||
|
@patch("linux_updater.core.health.HealthChecker._is_pid_alive")
|
||||||
|
def test_locks_dead_stale_process(self, mock_pid_alive):
|
||||||
|
lock_p = Path("/tmp/test_dummy.lock")
|
||||||
|
lock_p.write_text("99999\n")
|
||||||
|
mock_pid_alive.return_value = False
|
||||||
|
try:
|
||||||
|
results = self.checker.check_locks()
|
||||||
|
self.assertEqual(len(results), 1)
|
||||||
|
self.assertEqual(results[0].status, CheckStatus.FAIL)
|
||||||
|
self.assertTrue(results[0].can_remediate)
|
||||||
|
self.assertEqual(results[0].remediation_id, "remove_stale_lock")
|
||||||
|
finally:
|
||||||
|
if lock_p.exists():
|
||||||
|
lock_p.unlink()
|
||||||
|
|
||||||
|
def test_memory_sufficient(self):
|
||||||
|
meminfo = """MemTotal: 8147284 kB
|
||||||
|
MemFree: 2145124 kB
|
||||||
|
MemAvailable: 5123456 kB
|
||||||
|
Buffers: 345124 kB
|
||||||
|
Cached: 2567890 kB
|
||||||
|
"""
|
||||||
|
with tempfile.NamedTemporaryFile("w", delete=False) as t:
|
||||||
|
t.write(meminfo)
|
||||||
|
t_path = Path(t.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
checker = HealthChecker(config=self.config, manager=self.manager, meminfo_path=t_path)
|
||||||
|
results = checker.check_memory_and_oom()
|
||||||
|
mem_res = next(r for r in results if r.name == "memory_available")
|
||||||
|
self.assertEqual(mem_res.status, CheckStatus.PASS)
|
||||||
|
finally:
|
||||||
|
if t_path.exists():
|
||||||
|
t_path.unlink()
|
||||||
|
|
||||||
|
def test_memory_low_ram(self):
|
||||||
|
meminfo = """MemTotal: 8147284 kB
|
||||||
|
MemFree: 100124 kB
|
||||||
|
MemAvailable: 153600 kB
|
||||||
|
"""
|
||||||
|
with tempfile.NamedTemporaryFile("w", delete=False) as t:
|
||||||
|
t.write(meminfo)
|
||||||
|
t_path = Path(t.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
checker = HealthChecker(config=self.config, manager=self.manager, meminfo_path=t_path)
|
||||||
|
results = checker.check_memory_and_oom()
|
||||||
|
mem_res = next(r for r in results if r.name == "memory_available")
|
||||||
|
self.assertEqual(mem_res.status, CheckStatus.FAIL)
|
||||||
|
finally:
|
||||||
|
if t_path.exists():
|
||||||
|
t_path.unlink()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
|
||||||
|
from linux_updater.models import CheckResult, CheckStatus
|
||||||
|
from linux_updater.core.remediation import RemediationEngine
|
||||||
|
|
||||||
|
|
||||||
|
class TestRemediationEngine(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.mock_manager = MagicMock()
|
||||||
|
self.engine = RemediationEngine(manager=self.mock_manager)
|
||||||
|
|
||||||
|
def test_can_remediate_clean_cache(self):
|
||||||
|
check = CheckResult(
|
||||||
|
name="disk_var",
|
||||||
|
status=CheckStatus.FAIL,
|
||||||
|
message="Low disk space",
|
||||||
|
can_remediate=True,
|
||||||
|
remediation_id="clean_cache",
|
||||||
|
)
|
||||||
|
self.assertTrue(self.engine.can_remediate(check))
|
||||||
|
|
||||||
|
def test_remediate_clean_cache_calls_manager(self):
|
||||||
|
check = CheckResult(
|
||||||
|
name="disk_var",
|
||||||
|
status=CheckStatus.FAIL,
|
||||||
|
message="Low disk space",
|
||||||
|
can_remediate=True,
|
||||||
|
remediation_id="clean_cache",
|
||||||
|
)
|
||||||
|
success = self.engine.remediate(check)
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.mock_manager.clean_cache.assert_called_once()
|
||||||
|
|
||||||
|
def test_remediate_stale_lock_deletes_file(self):
|
||||||
|
lock_p = Path("/tmp/test_remediate_stale.lock")
|
||||||
|
lock_p.write_text("99999\n")
|
||||||
|
check = CheckResult(
|
||||||
|
name="lock_check",
|
||||||
|
status=CheckStatus.FAIL,
|
||||||
|
message=str(lock_p),
|
||||||
|
can_remediate=True,
|
||||||
|
remediation_id="remove_stale_lock",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
success = self.engine.remediate(check)
|
||||||
|
self.assertTrue(success)
|
||||||
|
self.assertFalse(lock_p.exists())
|
||||||
|
finally:
|
||||||
|
if lock_p.exists():
|
||||||
|
lock_p.unlink()
|
||||||
|
|
||||||
|
def test_remediate_refuses_non_remediable(self):
|
||||||
|
check = CheckResult(
|
||||||
|
name="disk_boot",
|
||||||
|
status=CheckStatus.FAIL,
|
||||||
|
message="/boot is full",
|
||||||
|
can_remediate=False,
|
||||||
|
)
|
||||||
|
self.assertFalse(self.engine.can_remediate(check))
|
||||||
|
self.assertFalse(self.engine.remediate(check))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user