Files
the_kurgan/kurgan/web/server.py
T
paulandClaude Opus 5.5 eb771656fb Privilege split 6/11: the app reads and drives the hardware through the service
- kurgan/hw/client.py: HardwareClient polls the service's state once a second
  on its own thread, reconnecting (and greeting again) whenever the pipe
  breaks, and sends the app's chase clock with each poll. Profile and RAM
  lighting changes are sent at once: bad values are ValueError before anything
  is sent; an unreachable or refusing service is HardwareUnavailable. A state
  that stops arriving (5 s) or a service loop that stops publishing (15 s)
  counts as unavailable. PipeTransport for the real pipe, LocalTransport (same
  encoding and checks, no pipe) for --demo and tests.
- Telemetry: the CPU package temperature and power (CpuSensors(package=...))
  and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come
  from the service; the app opens neither PawnIO nor the Commander PRO.
  "hardware service" is its own health source, and while it's down the
  missing CPU temperature isn't reported a second time.
- The fan UI, profile buttons and fan history come from the service's state;
  the RAM lighting zone goes through it (LightingService(ram=...)), and the
  case fan and GPU zones stay local. The alert monitor balloons "Hardware
  service unavailable"; the header shows a hardware service pill instead of
  the admin-rights one (and warns if the app itself runs elevated); the tray
  lines read the service's fans. POSTs answer 503 while it's unavailable.
- Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the
  service owns those now.
- settings.json: cooling and lighting.memory are legacy. Old files keep them
  (still validated), nothing reads them, and defaults no longer add them.
- --demo runs the real HardwareService in-process on the demo fakes, with its
  settings in demo-hw-settings.json, through the same client.
- --preview reads the CPU temperature and fan power from the service too.
- Tests: 13 for the client (including a real pipe end to end); the alert,
  lighting, settings and web tests follow the new shapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:41:51 +13:00

238 lines
10 KiB
Python

"""The web UI and its JSON API, served on 127.0.0.1 only.
GET / the UI (static/index.html)
GET /api/state everything live, polled by the UI once a second
GET /api/history the last 10 minutes of telemetry (fetched once; the UI appends from /api/state)
GET /api/records?days=N hourly min/avg/max rollups for the last N days (long-term telemetry)
GET /api/config fan profiles, lighting zones and AI backends (static)
POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...}
POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"}
POST /api/ai/active {"backend": "strata"|"llama"|null, "variant": "q5"|"iq3" (Strata only, optional)}
POST /api/ai/model {"action": "load"|"unload"}
* /strata/... /llama/... the LLM servers, started on demand (kurgan/web/proxy.py)
The fan profile and the RAM lighting are passed on to the hardware service, which answers
503 here while it can't be reached. Requests are guarded: the Host header must name this server
(blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header, which a page on
another site can't send without a CORS preflight that this server never answers. There is no
other authentication: anything already running on this PC as you can use the API (as it could
use the hardware service's pipe directly).
"""
from __future__ import annotations
import json
import logging
import mimetypes
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from kurgan.hw.protocol import Unavailable
from kurgan.web import proxy
log = logging.getLogger(__name__)
STATIC_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static")
MAX_BODY = 16 * 1024
class ApiError(Exception):
def __init__(self, message: str, status: int = 400):
super().__init__(message)
self.status = status
def make_handler(app, port: int):
hosts = {f"127.0.0.1:{port}", f"localhost:{port}"}
origins = {f"http://{h}" for h in hosts}
posts = {
"/api/lighting": lambda b: app.set_lighting(_text(b, "zone"), _text(b, "mode")),
"/api/cooling/profile": lambda b: app.set_fan_profile(_text(b, "profile")),
"/api/ai/active": lambda b: app.set_ai(_optional_text(b, "backend"), _optional_text(b, "variant")),
"/api/ai/model": lambda b: app.ai_model(_text(b, "action")),
}
class Handler(BaseHTTPRequestHandler):
server_version = "Kurgan"
sys_version = ""
def log_message(self, fmt, *args) -> None:
log.debug("%s %s", self.address_string(), fmt % args)
def _send(self, status: int, body: bytes, content_type: str = "application/json",
cache: str = "no-store") -> None:
self.send_response(status)
self.send_header("Content-Type", content_type)
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", cache)
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("X-Frame-Options", "DENY")
self.end_headers()
if self.command != "HEAD":
self.wfile.write(body)
def _json(self, status: int, data) -> None:
self._send(status, json.dumps(data, separators=(",", ":")).encode())
def _guard(self) -> bool:
if self.headers.get("Host") not in hosts:
self._json(403, {"error": "forbidden host"})
return False
return True
def _proxied(self) -> bool:
"""Hand /strata/... and /llama/... to the LLM servers; True if it did."""
if proxy.match(self.path) is None:
return False
try:
proxy.handle(self, getattr(app, "ai", None), hosts, origins)
except Exception:
log.exception("%s %s failed", self.command, self.path)
self.close_connection = True
return True
def _other(self) -> None:
if self._proxied():
return
self._read_body()
if self._guard():
self._json(405, {"error": "method not allowed"})
do_PUT = do_DELETE = do_PATCH = do_OPTIONS = _other
def do_HEAD(self) -> None:
if not self._proxied() and self._guard():
self._json(405, {"error": "method not allowed"})
def do_GET(self) -> None:
if self._proxied() or not self._guard():
return
path, _, query = self.path.partition("?")
try:
if path == "/api/state":
self._json(200, app.state())
elif path == "/api/history":
self._json(200, app.history())
elif path == "/api/records":
raw = parse_qs(query).get("days", ["7"])[0]
self._json(200, app.records(int(raw) if raw.isdigit() else -1))
elif path == "/api/config":
self._json(200, app.config())
elif path in ("/", "/index.html"):
self._static("index.html")
elif path.startswith("/static/"):
self._static(path[len("/static/"):])
else:
self._json(404, {"error": "not found"})
except ValueError as e:
self._json(400, {"error": str(e)})
except Exception:
log.exception("GET %s failed", path)
self._json(500, {"error": "internal error; see kurgan.log"})
def _static(self, name: str) -> None:
if name not in os.listdir(STATIC_DIR): # no paths, no traversal: only files in static/
self._json(404, {"error": "not found"})
return
with open(os.path.join(STATIC_DIR, name), "rb") as f:
body = f.read()
kind = mimetypes.guess_type(name)[0] or "application/octet-stream"
if kind.startswith("text/") or kind in ("application/javascript", "image/svg+xml"):
kind += "; charset=utf-8"
self._send(200, body, kind, cache="no-cache")
def _read_body(self) -> bytes | None:
"""The request body, or None if missing or oversized. Read before any answer: closing a
socket with unread data resets the connection on Windows, and the client would see a
dropped connection instead of the error."""
try:
length = int(self.headers.get("Content-Length", "0"))
except ValueError:
self.close_connection = True
return None
if 0 < length <= MAX_BODY:
return self.rfile.read(length)
remaining = min(max(length, 0), 1024 * 1024) # drain a modest oversized body; beyond that, give up
while remaining > 0:
chunk = self.rfile.read(min(remaining, 65536))
if not chunk:
break
remaining -= len(chunk)
self.close_connection = True
return None
def do_POST(self) -> None:
if self._proxied():
return
raw = self._read_body()
if not self._guard():
return
origin = self.headers.get("Origin")
if self.headers.get("X-Kurgan") != "1" or (origin is not None and origin not in origins):
self._json(403, {"error": "forbidden"})
return
if not self.headers.get("Content-Type", "").startswith("application/json"):
self._json(415, {"error": "send application/json"})
return
action = posts.get(self.path)
if action is None:
self._json(404, {"error": "not found"})
return
try:
if raw is None:
raise ApiError("missing or oversized body")
body = json.loads(raw)
if not isinstance(body, dict):
raise ApiError("body must be a JSON object")
action(body)
self._json(200, app.state())
except (ApiError, ValueError) as e:
status = e.status if isinstance(e, ApiError) else 400
self._json(status, {"error": str(e)})
except Unavailable as e: # the hardware service: unreachable, or can't do it now
log.warning("POST %s: %s", self.path, e)
self._json(503, {"error": f"Hardware service unavailable: {e}"})
except OSError as e:
log.warning("POST %s failed: %s", self.path, e)
self._json(500, {"error": f"Couldn't save the setting: {e}"})
except Exception:
log.exception("POST %s failed", self.path)
self._json(500, {"error": "internal error; see kurgan.log"})
return Handler
def _text(body: dict, key: str) -> str:
value = body.get(key)
if not isinstance(value, str) or not value:
raise ApiError(f"{key} is required")
return value
def _optional_text(body: dict, key: str) -> str | None:
value = body.get(key)
if value is not None and not isinstance(value, str):
raise ApiError(f"{key} must be a string or null")
return value
class WebServer:
def __init__(self, app, port: int):
self.port = port
self.url = f"http://127.0.0.1:{port}/"
self.httpd = ThreadingHTTPServer(("127.0.0.1", port), make_handler(app, port))
self.httpd.daemon_threads = True
self._thread: threading.Thread | None = None
def start(self) -> None:
self._thread = threading.Thread(target=self.httpd.serve_forever, kwargs={"poll_interval": 0.5},
name="web", daemon=True)
self._thread.start()
log.info("Web UI at %s", self.url)
def close(self) -> None:
self.httpd.shutdown()
self.httpd.server_close()