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
@@ -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
|
||||
Reference in new issue
Block a user