353 lines
13 KiB
Python
353 lines
13 KiB
Python
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:
|
|
# No PID found in lockfile.
|
|
# In Debian/Ubuntu (/var/lib/dpkg/lock-frontend, /var/lib/dpkg/lock) and RHEL (.rpm.lock),
|
|
# lock files may exist permanently with 0 bytes and are locked via advisory flock().
|
|
# We attempt a non-blocking exclusive flock to check if another process holds it.
|
|
is_held = False
|
|
could_test_flock = False
|
|
try:
|
|
import fcntl
|
|
fd = os.open(str(lock_p), os.O_RDONLY)
|
|
try:
|
|
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
could_test_flock = True
|
|
except (BlockingIOError, IOError, OSError):
|
|
is_held = True
|
|
could_test_flock = True
|
|
finally:
|
|
os.close(fd)
|
|
except PermissionError:
|
|
results.append(
|
|
CheckResult(
|
|
name=f"lock_{lock_p.name}",
|
|
status=CheckStatus.WARN,
|
|
message=f"Cannot inspect lock at {lock_p} (permission denied; run as root)",
|
|
can_remediate=False,
|
|
)
|
|
)
|
|
continue
|
|
except Exception:
|
|
pass
|
|
|
|
if could_test_flock:
|
|
if is_held:
|
|
results.append(
|
|
CheckResult(
|
|
name=f"lock_{lock_p.name}",
|
|
status=CheckStatus.FAIL,
|
|
message=f"Advisory lock actively held by another process at {lock_p}",
|
|
can_remediate=False,
|
|
)
|
|
)
|
|
else:
|
|
results.append(
|
|
CheckResult(
|
|
name=f"lock_{lock_p.name}",
|
|
status=CheckStatus.PASS,
|
|
message=f"No lock active at {lock_p}",
|
|
)
|
|
)
|
|
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",
|
|
)
|
|
)
|
|
|
|
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)
|