|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +import shutil |
| 6 | +import socket |
| 7 | +from dataclasses import dataclass |
| 8 | +from pathlib import Path |
| 9 | +from typing import TYPE_CHECKING |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from pilot.core.bench import Bench |
| 13 | + |
| 14 | + |
| 15 | +@dataclass |
| 16 | +class DiagnosticCheck: |
| 17 | + group: str |
| 18 | + name: str |
| 19 | + status: str |
| 20 | + detail: str |
| 21 | + hint: str = "" |
| 22 | + |
| 23 | + def to_dict(self) -> dict[str, str]: |
| 24 | + data = {"group": self.group, "name": self.name, "status": self.status, "detail": self.detail} |
| 25 | + if self.hint: |
| 26 | + data["hint"] = self.hint |
| 27 | + return data |
| 28 | + |
| 29 | + |
| 30 | +class DiagnosticRunner: |
| 31 | + def __init__(self, bench: "Bench") -> None: |
| 32 | + self.bench = bench |
| 33 | + |
| 34 | + def run(self) -> list[DiagnosticCheck]: |
| 35 | + checks: list[DiagnosticCheck] = [] |
| 36 | + checks.extend(self._bench_checks()) |
| 37 | + checks.extend(self._configuration_checks()) |
| 38 | + checks.extend(self._site_checks()) |
| 39 | + checks.extend(self._dependency_checks()) |
| 40 | + checks.extend(self._resource_checks()) |
| 41 | + checks.extend(self._process_checks()) |
| 42 | + checks.extend(self._redis_checks()) |
| 43 | + checks.extend(self._database_checks()) |
| 44 | + checks.extend(self._worker_checks()) |
| 45 | + return checks |
| 46 | + |
| 47 | + def _bench_checks(self) -> list[DiagnosticCheck]: |
| 48 | + return [ |
| 49 | + self._path_check("bench", "bench.toml", self.bench.path / "bench.toml", "Run bench new <name>."), |
| 50 | + self._path_check("bench", "python env", self.bench.python, "Run bench init."), |
| 51 | + self._path_check("bench", "apps directory", self.bench.apps_path, "Run bench init."), |
| 52 | + self._path_check("bench", "sites directory", self.bench.sites_path, "Run bench init."), |
| 53 | + self._path_check("bench", "config directory", self.bench.config_path, "Run bench setup config."), |
| 54 | + ] |
| 55 | + |
| 56 | + def _configuration_checks(self) -> list[DiagnosticCheck]: |
| 57 | + checks = [ |
| 58 | + self._path_check("config", "common site config", self.bench.sites_path / "common_site_config.json", "Run bench setup config."), |
| 59 | + self._path_check("config", "procfile", self.bench.config_path / "Procfile", "Run bench setup config."), |
| 60 | + ] |
| 61 | + if self.bench.config.admin.enabled and not self.bench.config.admin.password: |
| 62 | + checks.append(DiagnosticCheck("config", "admin password", "fail", "admin is enabled without a password", "Run bench set-admin-password.")) |
| 63 | + elif self.bench.config.admin.enabled: |
| 64 | + checks.append(DiagnosticCheck("config", "admin password", "ok", "configured")) |
| 65 | + else: |
| 66 | + checks.append(DiagnosticCheck("config", "admin", "warn", "admin UI is disabled")) |
| 67 | + return checks |
| 68 | + |
| 69 | + def _site_checks(self) -> list[DiagnosticCheck]: |
| 70 | + if not self.bench.sites_path.exists(): |
| 71 | + return [DiagnosticCheck("sites", "sites", "fail", f"missing: {self.bench.sites_path}", "Run bench init.")] |
| 72 | + site_dirs = [p for p in sorted(self.bench.sites_path.iterdir()) if (p / "site_config.json").exists()] |
| 73 | + if not site_dirs: |
| 74 | + return [DiagnosticCheck("sites", "sites", "warn", "no sites found", "Create one with bench new-site <name>.")] |
| 75 | + checks = [DiagnosticCheck("sites", "site count", "ok", f"{len(site_dirs)} site(s) found")] |
| 76 | + checks.extend(self._site_config_check(site_dir) for site_dir in site_dirs) |
| 77 | + return checks |
| 78 | + |
| 79 | + def _dependency_checks(self) -> list[DiagnosticCheck]: |
| 80 | + checks = [ |
| 81 | + self._executable_check("dependencies", "redis-server", "redis-server", "Install Redis or run bench init."), |
| 82 | + self._executable_check("dependencies", "node", "node", "Install Node.js or run bench init."), |
| 83 | + ] |
| 84 | + checks.append(self._chromium_check()) |
| 85 | + return checks |
| 86 | + |
| 87 | + def _resource_checks(self) -> list[DiagnosticCheck]: |
| 88 | + return [ |
| 89 | + self._cpu_check(), |
| 90 | + self._disk_check(), |
| 91 | + self._memory_check(), |
| 92 | + ] |
| 93 | + |
| 94 | + def _process_checks(self) -> list[DiagnosticCheck]: |
| 95 | + from pilot.managers.process_manager import ProcessManager |
| 96 | + |
| 97 | + try: |
| 98 | + manager = ProcessManager.detect_running(self.bench) |
| 99 | + workload = manager.is_running() |
| 100 | + admin = manager.is_admin_running() |
| 101 | + except Exception as exc: |
| 102 | + return [DiagnosticCheck("process", "process manager", "fail", str(exc))] |
| 103 | + if workload: |
| 104 | + return [DiagnosticCheck("process", "bench workload", "ok", "workload is running")] |
| 105 | + if admin: |
| 106 | + return [DiagnosticCheck("process", "admin", "warn", "admin is running, workload is stopped", "Run bench start or setup production.")] |
| 107 | + return [DiagnosticCheck("process", "bench workload", "fail", "bench is not running", "Run bench start.")] |
| 108 | + |
| 109 | + def _redis_checks(self) -> list[DiagnosticCheck]: |
| 110 | + redis = self.bench.config.redis |
| 111 | + return [ |
| 112 | + self._port_check("redis", "cache", "127.0.0.1", redis.cache_port), |
| 113 | + self._port_check("redis", "queue", "127.0.0.1", redis.queue_port), |
| 114 | + ] |
| 115 | + |
| 116 | + def _database_checks(self) -> list[DiagnosticCheck]: |
| 117 | + db_type = self.bench.config.db_type |
| 118 | + if db_type == "sqlite": |
| 119 | + return [DiagnosticCheck("database", "sqlite", "skip", "sqlite has no shared database server")] |
| 120 | + if db_type == "postgres": |
| 121 | + pg = self.bench.config.postgres |
| 122 | + return [self._port_check("database", "postgres", pg.host, pg.port)] |
| 123 | + mdb = self.bench.config.mariadb |
| 124 | + if mdb.socket_path: |
| 125 | + return [self._socket_check("database", "mariadb socket", Path(mdb.socket_path))] |
| 126 | + return [self._port_check("database", "mariadb", mdb.host, mdb.port)] |
| 127 | + |
| 128 | + def _worker_checks(self) -> list[DiagnosticCheck]: |
| 129 | + workers = [p for p in self.bench.pids_path.glob("worker*.pid")] if self.bench.pids_path.exists() else [] |
| 130 | + if workers: |
| 131 | + live = sum(1 for path in workers if self._pid_alive(path)) |
| 132 | + status = "ok" if live else "fail" |
| 133 | + return [DiagnosticCheck("workers", "worker pids", status, f"{live}/{len(workers)} worker pid files are live")] |
| 134 | + if self.bench.config.production.use_companion_manager: |
| 135 | + return [DiagnosticCheck("workers", "workers", "skip", "workers run inside the companion web process")] |
| 136 | + return [DiagnosticCheck("workers", "worker pids", "warn", "no worker pid files found", "Start the bench and re-run diagnostics.")] |
| 137 | + |
| 138 | + def _disk_check(self) -> DiagnosticCheck: |
| 139 | + usage = shutil.disk_usage(self.bench.path) |
| 140 | + free_gb = usage.free / 1024**3 |
| 141 | + used_pct = (usage.used / usage.total) * 100 if usage.total else 0 |
| 142 | + detail = f"{free_gb:.1f} GB free, {used_pct:.0f}% used at {self.bench.path}" |
| 143 | + if free_gb < 1: |
| 144 | + return DiagnosticCheck("resources", "disk", "fail", detail, "Free disk space before running migrations or backups.") |
| 145 | + if free_gb < 5: |
| 146 | + return DiagnosticCheck("resources", "disk", "warn", detail, "Keep at least 5 GB free for updates and backups.") |
| 147 | + return DiagnosticCheck("resources", "disk", "ok", detail) |
| 148 | + |
| 149 | + def _cpu_check(self) -> DiagnosticCheck: |
| 150 | + try: |
| 151 | + load_1m = os.getloadavg()[0] |
| 152 | + except (AttributeError, OSError): |
| 153 | + return DiagnosticCheck("resources", "cpu load", "skip", "load average is not available") |
| 154 | + cpu_count = os.cpu_count() or 1 |
| 155 | + detail = f"1m load {load_1m:.2f} across {cpu_count} CPU(s)" |
| 156 | + if load_1m > cpu_count * 2: |
| 157 | + return DiagnosticCheck("resources", "cpu load", "fail", detail, "Server is heavily loaded.") |
| 158 | + if load_1m > cpu_count: |
| 159 | + return DiagnosticCheck("resources", "cpu load", "warn", detail, "CPU pressure may slow requests and jobs.") |
| 160 | + return DiagnosticCheck("resources", "cpu load", "ok", detail) |
| 161 | + |
| 162 | + def _memory_check(self) -> DiagnosticCheck: |
| 163 | + memory = self._linux_memory() |
| 164 | + if not memory: |
| 165 | + return DiagnosticCheck("resources", "memory", "skip", "memory check is only available on Linux") |
| 166 | + available_gb = memory["available"] / 1024**2 |
| 167 | + detail = f"{available_gb:.1f} GB available" |
| 168 | + if available_gb < 0.5: |
| 169 | + return DiagnosticCheck("resources", "memory", "fail", detail, "Free memory or add swap before starting workers.") |
| 170 | + if available_gb < 1: |
| 171 | + return DiagnosticCheck("resources", "memory", "warn", detail, "Low memory can make builds and migrations unreliable.") |
| 172 | + return DiagnosticCheck("resources", "memory", "ok", detail) |
| 173 | + |
| 174 | + def _path_check(self, group: str, name: str, path: Path, hint: str) -> DiagnosticCheck: |
| 175 | + if path.exists(): |
| 176 | + return DiagnosticCheck(group, name, "ok", str(path)) |
| 177 | + return DiagnosticCheck(group, name, "fail", f"missing: {path}", hint) |
| 178 | + |
| 179 | + def _port_check(self, group: str, name: str, host: str, port: int) -> DiagnosticCheck: |
| 180 | + if self._tcp_open(host, port): |
| 181 | + return DiagnosticCheck(group, name, "ok", f"{host}:{port} is reachable") |
| 182 | + return DiagnosticCheck(group, name, "fail", f"{host}:{port} is not reachable") |
| 183 | + |
| 184 | + def _socket_check(self, group: str, name: str, path: Path) -> DiagnosticCheck: |
| 185 | + if path.exists(): |
| 186 | + return DiagnosticCheck(group, name, "ok", str(path)) |
| 187 | + return DiagnosticCheck(group, name, "fail", f"missing: {path}", "Start the database service.") |
| 188 | + |
| 189 | + def _executable_check(self, group: str, name: str, executable: str, hint: str) -> DiagnosticCheck: |
| 190 | + path = shutil.which(executable) |
| 191 | + if path: |
| 192 | + return DiagnosticCheck(group, name, "ok", path) |
| 193 | + return DiagnosticCheck(group, name, "fail", f"{executable} not found in PATH", hint) |
| 194 | + |
| 195 | + def _chromium_check(self) -> DiagnosticCheck: |
| 196 | + candidates = ["chromium", "chromium-browser", "google-chrome", "google-chrome-stable"] |
| 197 | + found = next((path for name in candidates if (path := shutil.which(name))), "") |
| 198 | + if found: |
| 199 | + return DiagnosticCheck("dependencies", "chromium", "ok", found) |
| 200 | + return DiagnosticCheck("dependencies", "chromium", "warn", "not found in PATH", "PDF generation may fail until Chromium is installed.") |
| 201 | + |
| 202 | + def _site_config_check(self, site_dir: Path) -> DiagnosticCheck: |
| 203 | + path = site_dir / "site_config.json" |
| 204 | + try: |
| 205 | + json.loads(path.read_text()) |
| 206 | + except Exception as exc: |
| 207 | + return DiagnosticCheck("sites", site_dir.name, "fail", f"invalid site_config.json: {exc}") |
| 208 | + return DiagnosticCheck("sites", site_dir.name, "ok", "site_config.json is valid") |
| 209 | + |
| 210 | + def _pid_alive(self, path: Path) -> bool: |
| 211 | + try: |
| 212 | + os.kill(int(path.read_text().strip()), 0) |
| 213 | + return True |
| 214 | + except (ValueError, ProcessLookupError, PermissionError, OSError): |
| 215 | + return False |
| 216 | + |
| 217 | + def _linux_memory(self) -> dict[str, int]: |
| 218 | + path = Path("/proc/meminfo") |
| 219 | + if not path.exists(): |
| 220 | + return {} |
| 221 | + fields = {} |
| 222 | + for line in path.read_text().splitlines(): |
| 223 | + key, value = line.split(":", 1) |
| 224 | + fields[key] = int(value.strip().split()[0]) |
| 225 | + return {"available": fields.get("MemAvailable", 0)} |
| 226 | + |
| 227 | + def _tcp_open(self, host: str, port: int) -> bool: |
| 228 | + try: |
| 229 | + with socket.create_connection((host, port), timeout=0.5): |
| 230 | + return True |
| 231 | + except OSError: |
| 232 | + return False |
| 233 | + |
| 234 | + |
| 235 | +class DiagnosticReport: |
| 236 | + def __init__(self, bench_name: str, checks: list[DiagnosticCheck]) -> None: |
| 237 | + self.bench_name = bench_name |
| 238 | + self.checks = checks |
| 239 | + |
| 240 | + @property |
| 241 | + def failed(self) -> bool: |
| 242 | + return any(check.status == "fail" for check in self.checks) |
| 243 | + |
| 244 | + def to_json(self) -> str: |
| 245 | + data = {"bench": self.bench_name, "checks": [check.to_dict() for check in self.checks]} |
| 246 | + return json.dumps(data, indent=2) |
0 commit comments