|
| 1 | +"""Safe aggregate host resource metrics for the WebUI VPS panel (#693). |
| 2 | +
|
| 3 | +The browser only needs coarse CPU/RAM/disk usage. Keep this module intentionally |
| 4 | +small and dependency-free: no process lists, command strings, user identities, |
| 5 | +environment variables, or filesystem topology leave the server. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import shutil |
| 11 | +import time |
| 12 | +from datetime import datetime, timezone |
| 13 | +from pathlib import Path |
| 14 | +from typing import Any |
| 15 | + |
| 16 | + |
| 17 | +_PROC_STAT = Path("/proc/stat") |
| 18 | +_PROC_MEMINFO = Path("/proc/meminfo") |
| 19 | +_CPU_SAMPLE_SECONDS = 0.05 |
| 20 | + |
| 21 | + |
| 22 | +def _checked_at() -> str: |
| 23 | + return datetime.now(timezone.utc).isoformat() |
| 24 | + |
| 25 | + |
| 26 | +def _clamp_percent(value: Any) -> float: |
| 27 | + try: |
| 28 | + numeric = float(value) |
| 29 | + except (TypeError, ValueError): |
| 30 | + return 0.0 |
| 31 | + if numeric < 0: |
| 32 | + numeric = 0.0 |
| 33 | + if numeric > 100: |
| 34 | + numeric = 100.0 |
| 35 | + return round(numeric, 1) |
| 36 | + |
| 37 | + |
| 38 | +def _read_proc_stat_cpu() -> tuple[int, int]: |
| 39 | + """Return (idle_ticks, total_ticks) from Linux /proc/stat.""" |
| 40 | + with _PROC_STAT.open("r", encoding="utf-8") as handle: |
| 41 | + first = handle.readline().strip().split() |
| 42 | + if not first or first[0] != "cpu": |
| 43 | + raise RuntimeError("proc_stat_unavailable") |
| 44 | + values = [int(part) for part in first[1:]] |
| 45 | + if len(values) < 4: |
| 46 | + raise RuntimeError("proc_stat_unavailable") |
| 47 | + idle = values[3] + (values[4] if len(values) > 4 else 0) |
| 48 | + total = sum(values) |
| 49 | + if total <= 0: |
| 50 | + raise RuntimeError("proc_stat_unavailable") |
| 51 | + return idle, total |
| 52 | + |
| 53 | + |
| 54 | +def _cpu_delta_percent(start: tuple[int, int], end: tuple[int, int]) -> float: |
| 55 | + idle_delta = end[0] - start[0] |
| 56 | + total_delta = end[1] - start[1] |
| 57 | + if total_delta <= 0: |
| 58 | + return 0.0 |
| 59 | + busy_delta = max(0, total_delta - max(0, idle_delta)) |
| 60 | + return _clamp_percent((busy_delta / total_delta) * 100.0) |
| 61 | + |
| 62 | + |
| 63 | +def _cpu_percent() -> float: |
| 64 | + """Sample aggregate CPU usage without psutil. |
| 65 | +
|
| 66 | + A short local sample avoids storing cross-request state and returns a stable |
| 67 | + percentage on the first poll. Unsupported platforms raise a safe error code. |
| 68 | + """ |
| 69 | + start = _read_proc_stat_cpu() |
| 70 | + time.sleep(_CPU_SAMPLE_SECONDS) |
| 71 | + end = _read_proc_stat_cpu() |
| 72 | + return _cpu_delta_percent(start, end) |
| 73 | + |
| 74 | + |
| 75 | +def _read_meminfo_kib() -> dict[str, int]: |
| 76 | + data: dict[str, int] = {} |
| 77 | + with _PROC_MEMINFO.open("r", encoding="utf-8") as handle: |
| 78 | + for line in handle: |
| 79 | + key, _, rest = line.partition(":") |
| 80 | + if not key or not rest: |
| 81 | + continue |
| 82 | + parts = rest.strip().split() |
| 83 | + if not parts: |
| 84 | + continue |
| 85 | + try: |
| 86 | + data[key] = int(parts[0]) |
| 87 | + except ValueError: |
| 88 | + continue |
| 89 | + return data |
| 90 | + |
| 91 | + |
| 92 | +def _memory_usage() -> dict[str, int | float]: |
| 93 | + meminfo = _read_meminfo_kib() |
| 94 | + total = int(meminfo.get("MemTotal") or 0) * 1024 |
| 95 | + if total <= 0: |
| 96 | + raise RuntimeError("meminfo_unavailable") |
| 97 | + available_kib = meminfo.get("MemAvailable") |
| 98 | + if available_kib is None: |
| 99 | + available_kib = ( |
| 100 | + meminfo.get("MemFree", 0) |
| 101 | + + meminfo.get("Buffers", 0) |
| 102 | + + meminfo.get("Cached", 0) |
| 103 | + + meminfo.get("SReclaimable", 0) |
| 104 | + - meminfo.get("Shmem", 0) |
| 105 | + ) |
| 106 | + available = max(0, int(available_kib) * 1024) |
| 107 | + used = max(0, min(total, total - available)) |
| 108 | + return { |
| 109 | + "used_bytes": used, |
| 110 | + "total_bytes": total, |
| 111 | + "percent": _clamp_percent((used / total) * 100.0), |
| 112 | + } |
| 113 | + |
| 114 | + |
| 115 | +def _disk_usage() -> dict[str, int | float]: |
| 116 | + usage = shutil.disk_usage("/") |
| 117 | + total = int(usage.total) |
| 118 | + if total <= 0: |
| 119 | + raise RuntimeError("disk_unavailable") |
| 120 | + used = int(usage.used) |
| 121 | + return { |
| 122 | + "used_bytes": used, |
| 123 | + "total_bytes": total, |
| 124 | + "percent": _clamp_percent((used / total) * 100.0), |
| 125 | + } |
| 126 | + |
| 127 | + |
| 128 | +def _safe_error(metric: str, exc: Exception) -> dict[str, str]: |
| 129 | + # Keep this intentionally coarse. Exception messages can contain local paths |
| 130 | + # on unusual platforms; the browser only needs a safe unavailable reason. |
| 131 | + return {"metric": metric, "code": type(exc).__name__} |
| 132 | + |
| 133 | + |
| 134 | +def build_system_health_payload() -> dict[str, Any]: |
| 135 | + metrics: dict[str, Any] = {"cpu": None, "memory": None, "disk": None} |
| 136 | + errors: list[dict[str, str]] = [] |
| 137 | + |
| 138 | + collectors = { |
| 139 | + "cpu": _cpu_percent, |
| 140 | + "memory": _memory_usage, |
| 141 | + "disk": _disk_usage, |
| 142 | + } |
| 143 | + for name, collect in collectors.items(): |
| 144 | + try: |
| 145 | + value = collect() |
| 146 | + if name == "cpu": |
| 147 | + metrics[name] = {"percent": _clamp_percent(value)} |
| 148 | + else: |
| 149 | + metrics[name] = { |
| 150 | + "used_bytes": max(0, int(value["used_bytes"])), |
| 151 | + "total_bytes": max(0, int(value["total_bytes"])), |
| 152 | + "percent": _clamp_percent(value["percent"]), |
| 153 | + } |
| 154 | + except Exception as exc: |
| 155 | + errors.append(_safe_error(name, exc)) |
| 156 | + |
| 157 | + available = any(metrics[name] is not None for name in metrics) |
| 158 | + status = "ok" if available and not errors else "partial" if available else "unavailable" |
| 159 | + return { |
| 160 | + "status": status, |
| 161 | + "available": available, |
| 162 | + "checked_at": _checked_at(), |
| 163 | + "cpu": metrics["cpu"], |
| 164 | + "memory": metrics["memory"], |
| 165 | + "disk": metrics["disk"], |
| 166 | + "errors": errors, |
| 167 | + } |
0 commit comments