Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)

This commit is contained in:
Thomas Karner committed 2026-09-20 23:49:40 +02:00
1 parent 3694cdf207
commit 8a51e3d95e
38 files changed
+2442 -21

No files matched your search

Whitespace-only changes.
+82
View File
@@ -0,0 +1,82 @@
"""Health.
Two endpoints on purpose:
* ``/api/v1/health`` always answers 200 with detail, because the WebUI banner
wants to *render* a degraded system, not fail to load.
* ``/healthz`` answers 503 when the database is unreachable, because that is
what a proxy or a monitor should act on.
"""
from __future__ import annotations
import shutil
import time
from typing import Any
from fastapi import APIRouter, Response
from sqlalchemy import func, select, text
from ... import __version__
from ...config import get_settings
from ...db import SessionLocal
from ...models import BackupRun, Capture, Device
router = APIRouter()
# Mounted at the root, not under /api/v1: proxies and monitors expect /healthz
# where it has always been.
root_router = APIRouter()
_STARTED = time.monotonic()
def _db_probe() -> tuple[bool, str | None, dict[str, Any]]:
facts: dict[str, Any] = {}
try:
with SessionLocal() as s:
s.execute(text("SELECT 1"))
facts["devices"] = s.scalar(select(func.count()).select_from(Device))
facts["captures"] = s.scalar(select(func.count()).select_from(Capture))
last_backup = s.scalar(select(func.max(BackupRun.finished_at)))
facts["last_backup_at"] = last_backup.isoformat() if last_backup else None
return True, None, facts
except Exception as exc: # noqa: BLE001 - the point is to report, not raise
return False, f"{type(exc).__name__}: {exc}", facts
def _disk() -> dict[str, Any]:
settings = get_settings()
try:
usage = shutil.disk_usage(settings.image_root)
except OSError:
# Not yet created, or not mounted. Both are real conditions to report.
return {"available": False, "path": str(settings.image_root)}
return {
"available": True,
"path": str(settings.image_root),
"total_bytes": usage.total,
"free_bytes": usage.free,
"used_pct": round(100 * usage.used / usage.total, 1) if usage.total else None,
}
@router.get("/health", summary="System health, always 200")
def health() -> dict[str, Any]:
db_ok, db_error, facts = _db_probe()
settings = get_settings()
return {
"status": "ok" if db_ok else "degraded",
"version": __version__,
"uptime_s": round(time.monotonic() - _STARTED, 1),
"database": {"ok": db_ok, "error": db_error, **facts},
"disk": _disk(),
"enroll_secret_configured": settings.enroll_secret_is_set,
}
@root_router.get("/healthz", include_in_schema=False)
def healthz(response: Response) -> dict[str, str]:
db_ok, _, _ = _db_probe()
if not db_ok:
response.status_code = 503
return {"status": "unavailable"}
return {"status": "ok"}