The Kurgan 1.0.0: one process for the LCD, fans, lighting, local LLM servers and the web UI
This commit is contained in:
commit
f631386618
71 files changed
+14616
No files matched your search
@@ -0,0 +1,225 @@
|
||||
"""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/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 process runs elevated and controls fans, so 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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
import os
|
||||
import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
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 = self.path.split("?", 1)[0]
|
||||
try:
|
||||
if path == "/api/state":
|
||||
self._json(200, app.state())
|
||||
elif path == "/api/history":
|
||||
self._json(200, app.history())
|
||||
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 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 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()
|
||||
Reference in new issue
Block a user