|
| 1 | +"""System endpoints: GET /api/v1/health, /schema/incident, /schema/incident/versions. |
| 2 | +
|
| 3 | +Health contract: contracts/path/system.yaml + contracts/schemas/system.yaml |
| 4 | +""" |
| 5 | + |
| 6 | +import shutil |
| 7 | +import time |
| 8 | + |
| 9 | +import requests |
| 10 | +from fastapi import APIRouter |
| 11 | +from fastapi.responses import JSONResponse |
| 12 | +from sqlalchemy import text |
| 13 | + |
| 14 | +from app.api.schemas.system import ( |
| 15 | + ComponentHealth, |
| 16 | + HealthComponents, |
| 17 | + HealthStatus, |
| 18 | + ModelInfo, |
| 19 | +) |
| 20 | +from app.core.config import APP_VERSION, DATA_DIR, OLLAMA_HOST, WHISPER_HOST |
| 21 | +from app.db.database import engine |
| 22 | + |
| 23 | +router = APIRouter(tags=["system"]) |
| 24 | + |
| 25 | +_START_TIME = time.monotonic() |
| 26 | + |
| 27 | +# Tune-able thresholds. _SLOW_MS is patched in tests to trigger degraded |
| 28 | +# without mocking wall-clock time. |
| 29 | +_PROBE_TIMEOUT = 5 |
| 30 | +_SLOW_MS = 5_000 |
| 31 | + |
| 32 | + |
| 33 | +def _check_database() -> ComponentHealth: |
| 34 | + t0 = time.monotonic() |
| 35 | + try: |
| 36 | + with engine.connect() as conn: |
| 37 | + conn.execute(text("SELECT 1")) |
| 38 | + elapsed = int((time.monotonic() - t0) * 1000) |
| 39 | + return ComponentHealth(status="healthy", response_time_ms=elapsed) |
| 40 | + except Exception as exc: |
| 41 | + return ComponentHealth(status="unhealthy", detail=str(exc)) |
| 42 | + |
| 43 | + |
| 44 | +def _check_ollama() -> ComponentHealth: |
| 45 | + t0 = time.monotonic() |
| 46 | + try: |
| 47 | + tags_resp = requests.get(f"{OLLAMA_HOST}/api/tags", timeout=_PROBE_TIMEOUT) |
| 48 | + tags_resp.raise_for_status() |
| 49 | + elapsed = int((time.monotonic() - t0) * 1000) |
| 50 | + |
| 51 | + tags_data = tags_resp.json() |
| 52 | + |
| 53 | + ollama_version: str | None = None |
| 54 | + try: |
| 55 | + ver_resp = requests.get(f"{OLLAMA_HOST}/api/version", timeout=_PROBE_TIMEOUT) |
| 56 | + ver_resp.raise_for_status() |
| 57 | + ollama_version = ver_resp.json().get("version") |
| 58 | + except Exception: |
| 59 | + pass |
| 60 | + |
| 61 | + running_names: set[str] = set() |
| 62 | + model_loaded: str | None = None |
| 63 | + try: |
| 64 | + ps_resp = requests.get(f"{OLLAMA_HOST}/api/ps", timeout=_PROBE_TIMEOUT) |
| 65 | + ps_resp.raise_for_status() |
| 66 | + running = ps_resp.json().get("models", []) |
| 67 | + running_names = {m.get("name", "") for m in running} |
| 68 | + if running: |
| 69 | + model_loaded = running[0].get("name") |
| 70 | + except Exception: |
| 71 | + pass |
| 72 | + |
| 73 | + raw_models = tags_data.get("models", []) |
| 74 | + models_available: list[ModelInfo] = [] |
| 75 | + for m in raw_models: |
| 76 | + name = m.get("name", "") |
| 77 | + size_gb = round(m.get("size", 0) / (1024 ** 3), 2) |
| 78 | + quantization = m.get("details", {}).get("quantization_level") |
| 79 | + models_available.append( |
| 80 | + ModelInfo(name=name, size_gb=size_gb, quantization=quantization, loaded=name in running_names) |
| 81 | + ) |
| 82 | + |
| 83 | + status = "degraded" if elapsed > _SLOW_MS else "healthy" |
| 84 | + |
| 85 | + return ComponentHealth( |
| 86 | + status=status, |
| 87 | + response_time_ms=elapsed, |
| 88 | + model_loaded=model_loaded, |
| 89 | + ollama_version=ollama_version, |
| 90 | + models_available=models_available if models_available else None, |
| 91 | + # current_load is always None — Ollama exposes no queue-depth API; |
| 92 | + # populating it would require fabricating data. |
| 93 | + current_load=None, |
| 94 | + ) |
| 95 | + except requests.exceptions.RequestException as exc: |
| 96 | + return ComponentHealth(status="unhealthy", detail=str(exc)) |
| 97 | + |
| 98 | + |
| 99 | +def _check_whisper() -> ComponentHealth: |
| 100 | + # The onerahmet/openai-whisper-asr-webservice image does not expose /health. |
| 101 | + # Both compose files probe /docs (a FastAPI auto-endpoint always present). |
| 102 | + t0 = time.monotonic() |
| 103 | + try: |
| 104 | + resp = requests.get(f"{WHISPER_HOST}/docs", timeout=_PROBE_TIMEOUT) |
| 105 | + resp.raise_for_status() |
| 106 | + elapsed = int((time.monotonic() - t0) * 1000) |
| 107 | + return ComponentHealth(status="healthy", response_time_ms=elapsed) |
| 108 | + except requests.exceptions.RequestException as exc: |
| 109 | + return ComponentHealth(status="unhealthy", detail=str(exc)) |
| 110 | + |
| 111 | + |
| 112 | +def _check_storage() -> ComponentHealth: |
| 113 | + try: |
| 114 | + usage = shutil.disk_usage(DATA_DIR) |
| 115 | + disk_free_gb = round(usage.free / (1024 ** 3), 2) |
| 116 | + return ComponentHealth(status="healthy", disk_free_gb=disk_free_gb) |
| 117 | + except OSError as exc: |
| 118 | + return ComponentHealth(status="unhealthy", detail=str(exc)) |
| 119 | + |
| 120 | + |
| 121 | +@router.get( |
| 122 | + "/health", |
| 123 | + responses={ |
| 124 | + 200: {"model": HealthStatus, "description": "System healthy or degraded"}, |
| 125 | + 503: {"model": HealthStatus, "description": "System unhealthy, cannot serve requests"}, |
| 126 | + }, |
| 127 | + summary="System health check", |
| 128 | +) |
| 129 | +def get_health(): |
| 130 | + database = _check_database() |
| 131 | + ollama = _check_ollama() |
| 132 | + whisper = _check_whisper() |
| 133 | + storage = _check_storage() |
| 134 | + |
| 135 | + components = HealthComponents( |
| 136 | + database=database, ollama=ollama, whisper=whisper, storage=storage |
| 137 | + ) |
| 138 | + |
| 139 | + statuses = {database.status, ollama.status, whisper.status, storage.status} |
| 140 | + |
| 141 | + if database.status == "unhealthy": |
| 142 | + overall = "unhealthy" |
| 143 | + elif "unhealthy" in statuses or "degraded" in statuses: |
| 144 | + overall = "degraded" |
| 145 | + else: |
| 146 | + overall = "healthy" |
| 147 | + |
| 148 | + body = HealthStatus( |
| 149 | + status=overall, |
| 150 | + version=APP_VERSION, |
| 151 | + uptime_seconds=int(time.monotonic() - _START_TIME), |
| 152 | + components=components, |
| 153 | + ) |
| 154 | + |
| 155 | + http_status = 503 if overall == "unhealthy" else 200 |
| 156 | + return JSONResponse( |
| 157 | + content=body.model_dump(exclude_none=True), |
| 158 | + status_code=http_status, |
| 159 | + ) |
| 160 | + |
| 161 | + |
| 162 | +@router.get("/schema/incident", summary="Get canonical incident JSON Schema") |
| 163 | +def get_schema_incident(): |
| 164 | + # PROVISIONAL: This 501 body shape is not canonical — it will be updated |
| 165 | + # to match the standardized ErrorResponse envelope once #543 lands. |
| 166 | + return JSONResponse( |
| 167 | + status_code=501, |
| 168 | + content={ |
| 169 | + "error_code": "NOT_IMPLEMENTED", |
| 170 | + "message": "Incident schema not yet finalised — see issue #555", |
| 171 | + }, |
| 172 | + ) |
| 173 | + |
| 174 | + |
| 175 | +@router.get("/schema/incident/versions", summary="Get incident schema version history") |
| 176 | +def get_schema_versions(): |
| 177 | + # PROVISIONAL: Same as /schema/incident — shape will align with #543. |
| 178 | + return JSONResponse( |
| 179 | + status_code=501, |
| 180 | + content={ |
| 181 | + "error_code": "NOT_IMPLEMENTED", |
| 182 | + "message": "Schema version history not yet available — see issue #555", |
| 183 | + }, |
| 184 | + ) |
0 commit comments