llm-host/llmhost/web/server.py
neil e814a2359d install-newt: optional internet access via a Pangolin tunnel, with OIDC sign-in on the dashboard
A plain install is unchanged: LAN-only, dashboard behind the API key. `llmhost install-newt`
is the upgrade path. It installs a pinned, sha256-checked newt as a third user service and
switches the dashboard to an OIDC authorization-code + PKCE sign-in limited to allowed groups
or users. The API still takes the key. Secrets live in 0600 files, never in config.json, a
service file or argv. `llmhost remove-newt` undoes it; setup/update keep it; `logs --newt`
shows the tunnel (and `logs -f` now follows the service it was asked for).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 21:44:09 -08:00

587 lines
27 KiB
Python

"""Dashboard: status, metrics and model switching. Stdlib only.
Serves index.html and a JSON API on cfg["web_port"]. /api/* routes need the API key, or,
when config.json's "dashboard_auth" is set to OIDC, a signed-in session instead (oidc.py).
"""
import hmac
import html
import json
import re
import socket
import threading
import time
import urllib.parse
import urllib.request
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from .. import hfcache, hw, opencode, paths, plan, service
from . import oidc as oidc_mod
HERE = Path(__file__).resolve().parent
SAMPLE_SECONDS = 2
HISTORY_POINTS = 300 # 10 minutes
RUNS_SHOWN = 20 # completed requests in the run summary
# The sampler's own polling shows up in vLLM's access log every 2s; hide it from the log view.
OWN_POLL_RE = re.compile(r'127\.0\.0\.1(:\d+)? - (- \[[^]]*\] )?"GET /(health|metrics|v1/models|llmhost/metrics) '
r'|- INFO - HTTP Request: ')
PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]")
METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$")
# A client that hangs up mid-answer leaves mlx_lm writing to a closed socket, and its
# ThreadingHTTPServer prints a full traceback for it. That's expected (the proxy logs the
# disconnect in one line), so collapse the block instead of letting it bury the log.
DASHES_RE = re.compile(r"^-{20,}\s*$")
EXC_HEAD_RE = re.compile(r"^Exception occurred during processing of request")
DISCONNECT_RE = re.compile(r"^(BrokenPipeError|ConnectionResetError)\b")
MAX_TRACE_LINES = 80
def collapse_disconnects(lines):
"""Replace each mlx_lm traceback that ends in a broken pipe with one line. Any other
traceback is left exactly as it is -- those are worth reading in full.
socketserver brackets each one with a row of dashes, which is what delimits a block
here; a block that never closes (the log was truncated, or is still being written)
is emitted unchanged."""
out, block = [], None
def flush(decide):
nonlocal block
if block is None:
return
if decide and any(DISCONNECT_RE.match(l.split(" - ")[-1].lstrip()) for l in block):
out.append(f" [client disconnected mid-answer; {len(block)} lines of traceback hidden]")
else:
out.extend(block)
block = None
for l in lines:
bare = l.rstrip()
if block is None:
if DASHES_RE.match(bare) or EXC_HEAD_RE.match(bare):
block = [l]
else:
out.append(l)
continue
if DASHES_RE.match(bare):
block.append(l)
flush(True)
continue
block.append(l)
if len(block) > MAX_TRACE_LINES:
flush(False)
flush(False)
return out
def http_get(url, key=None, timeout=2):
req = urllib.request.Request(url)
if key:
req.add_header("Authorization", f"Bearer {key}")
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read().decode()
except Exception:
return None, ""
def run_kv_peak(history, run, now, current):
"""Peak KV % over a finished run's window, from the sampled history. A run shorter
than the sampling interval has no samples, so the reading just after it ended stands
in -- but only while that's fresh: a run picked up later (after a dashboard restart,
say) has nothing to go on, and today's idle reading would claim a peak of 0%."""
window = [q["kv"] for q in history
if q["kv"] is not None and run["start"] <= q["t"] <= run["end"]]
if window:
return max(window)
return current if now - run["end"] <= 2 * SAMPLE_SECONDS else None
def run_phases(r):
"""How long a run spent on each phase, and the rate of each. Time to first token
covers the prompt's prefill (queueing with it, there being nothing finer to measure
from), and what's left of the duration is generation; a rate over the whole duration
would blur the two together.
A run that didn't stream has no first-token mark and so no split: its prompt time is
unknown and its whole duration is charged to generation -- which the table says, by
showing no prompt seconds beside it."""
dur, ttft = r.get("dur") or 0, r.get("ttft")
prompt_s = ttft
gen_s = (dur - ttft) if (ttft is not None and dur > ttft) else dur
return {"prompt_s": prompt_s, "gen_s": gen_s or None,
"prompt_tps": (r["prompt"] / prompt_s) if (prompt_s and r.get("prompt")) else None,
"gen_tps": (r["gen"] / gen_s) if (gen_s and r.get("gen")) else None}
def run_row(r, kv_peak):
"""One finished request as the dashboard's table wants it."""
return {"t": r["end"], "dur": r.get("dur"), "gen": r.get("gen"),
"prompt": r.get("prompt"), "ttft": r.get("ttft"), **run_phases(r),
"kv_peak_pct": kv_peak, "aborted": bool(r.get("aborted"))}
def parse_vllm_metrics(text):
vals = {}
for line in text.splitlines():
m = METRIC_RE.match(line)
if not m:
continue
name, labels, v = m.group(1), m.group(2) or "", m.group(3)
if name.endswith(("_created", "_bucket")) or "position=" in labels or "reason=" in labels or "by_source" in name:
continue
if name == "vllm:engine_sleep_state":
continue
try:
vals[name] = vals.get(name, 0.0) + float(v)
except ValueError:
pass
return {
"running": vals.get("vllm:num_requests_running"),
"waiting": vals.get("vllm:num_requests_waiting"),
"kv": vals.get("vllm:kv_cache_usage_perc"),
"gen_total": vals.get("vllm:generation_tokens_total"),
"prompt_total": vals.get("vllm:prompt_tokens_total"),
"prefix_hits": vals.get("vllm:prefix_cache_hits_total"),
"prefix_queries": vals.get("vllm:prefix_cache_queries_total"),
"spec_accepted": vals.get("vllm:spec_decode_num_accepted_tokens_total"),
"spec_drafted": vals.get("vllm:spec_decode_num_draft_tokens_total"),
"preemptions": vals.get("vllm:num_preemptions_total"),
"ttft_sum": vals.get("vllm:time_to_first_token_seconds_sum"),
"ttft_count": vals.get("vllm:time_to_first_token_seconds_count"),
}
class Sampler:
def __init__(self, cfg, key):
self.cfg = cfg
self.key = key
self.lock = threading.Lock()
self.history = deque(maxlen=HISTORY_POINTS)
self.prev = None
self.state = {}
self.action = None
self._dl_cache = (0, {})
self.last_ttft = None # (time, seconds) of the latest sample with new first tokens
self.baseline = None # counter values at the last stats reset (see reset_stats)
self.stats_since = None
self.runs = deque(maxlen=RUNS_SHOWN)
self._seen_runs = set()
def reload_cfg(self):
self.cfg = paths.load_config() or self.cfg
def downloaded(self):
t, cache = self._dl_cache
if time.time() - t > 30:
cache = {m["repo"]: hfcache.is_downloaded(m["repo"]) for m in self.cfg.get("models", [])}
self._dl_cache = (time.time(), cache)
return cache
def loop(self):
while True:
try:
self.sample()
except Exception as e:
with self.lock:
self.state["sampler_error"] = repr(e)
time.sleep(SAMPLE_SECONDS)
def sample(self):
self.reload_cfg()
cfg = self.cfg
now = time.time()
base = f"http://127.0.0.1:{cfg['api_port']}"
svc_state, uptime = service.state("model")
health, _ = http_get(base + "/health")
served, metrics = None, {}
if health == 200:
st, body = http_get(base + "/v1/models", self.key)
if st == 200:
try:
served = [m["id"] for m in json.loads(body)["data"]]
except (ValueError, KeyError):
pass
# The proxy records each request on either backend; on vLLM the engine's own
# /metrics (on the inner port) has the aggregates, KV usage included.
st, body = http_get(base + "/llmhost/metrics")
try:
proxied = json.loads(body) if st == 200 else {}
except ValueError:
proxied = {}
if cfg["backend"] == "vllm":
st, body = http_get(f"http://127.0.0.1:{cfg['api_port'] + 1}/metrics")
metrics = parse_vllm_metrics(body) if st == 200 else {}
metrics["recent"] = proxied.get("recent") or []
else:
metrics = proxied
active = cfg.get("active")
if svc_state in ("inactive", "failed"):
phase = "failed" if svc_state == "failed" else "stopped"
elif health == 200 and served and active in served:
phase = "ready"
else:
phase = "loading"
gen_rate = prompt_rate = ttft = None
if metrics.get("gen_total") is not None and self.prev:
pt, pm = self.prev
dt = now - pt
if dt > 0 and pm.get("gen_total") is not None:
gen_rate = max(metrics["gen_total"] - pm["gen_total"], 0) / dt
prompt_rate = max((metrics.get("prompt_total") or 0) - (pm.get("prompt_total") or 0), 0) / dt
# Average time to first token of the requests that got their first token since the
# last sample (none: no point, so the chart shows a gap rather than a stale value).
dn = (metrics.get("ttft_count") or 0) - (pm.get("ttft_count") or 0)
if dn > 0:
ttft = max((metrics.get("ttft_sum") or 0) - (pm.get("ttft_sum") or 0), 0) / dn
if ttft is not None:
self.last_ttft = (now, ttft)
self.prev = (now, metrics) if metrics else None
shown = self.since_reset(metrics)
gpu = hw.live_stats(cfg["kind"])
kv = metrics.get("kv")
point = {
"t": now, "gen": gen_rate, "prompt": prompt_rate, "ttft": ttft,
"kv": kv * 100 if kv is not None else None,
"util": gpu["util"] if gpu else None,
"temp": gpu["temp"] if gpu else None,
"power": gpu["power"] if gpu else None,
}
def ratio(a, b):
return shown[a] / shown[b] if shown.get(b) else None
last_log = None
if phase in ("loading", "failed"):
lines = [l for l in service.logs("model", 20) if l.strip() and not OWN_POLL_RE.search(l)]
last_log = lines[-1][-240:] if lines else None
dl = self.downloaded()
models = [{**m, "downloaded": dl.get(m["repo"], False)} for m in cfg.get("models", [])]
reasoning = self.reasoning_state(cfg, active)
with self.lock:
self.history.append(point)
# Peak KV per run is taken from the sampled history over the run's own window;
# the proxy can't do it, since it never sees KV usage (mlx_lm only logs it now and then).
for r in metrics.get("recent") or []:
key = (r.get("start"), r.get("end"))
if key in self._seen_runs or r.get("start") is None:
continue
self._seen_runs.add(key)
self.runs.append(run_row(r, run_kv_peak(self.history, r, now, point["kv"])))
if len(self._seen_runs) > 4 * RUNS_SHOWN:
# The proxy only ever re-offers its own last RECENT_RUNS, so forgetting the
# oldest keys can't resurrect a run we already have.
self._seen_runs = {(r["t"], r["t"]) for r in self.runs} | {
(q.get("start"), q.get("end")) for q in (metrics.get("recent") or [])}
if self.action and phase in ("ready", "stopped", "failed") and now - self.action["t"] > 6:
self.action = None
self.state = {
"time": now, "phase": phase, "service": svc_state, "uptime": uptime,
"host": socket.gethostname(), "backend": cfg["backend"], "kind": cfg["kind"],
"hardware": cfg.get("hardware_name"), "budget_gib": cfg.get("budget_gib"),
"active": active, "served_models": served, "models": models,
"excluded": cfg.get("excluded", []), "gpu": gpu, "last_log": last_log,
"reasoning": reasoning,
"action": self.action,
"metrics": {
"running": shown.get("running"), "waiting": shown.get("waiting"),
"kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate,
"gen_total": shown.get("gen_total"), "prompt_total": shown.get("prompt_total"),
"prefix_hit": ratio("prefix_hits", "prefix_queries"),
"spec_accept": ratio("spec_accepted", "spec_drafted"),
"preemptions": shown.get("preemptions"),
"ttft_last": self.last_ttft[1] if self.last_ttft else None,
"ttft_last_t": self.last_ttft[0] if self.last_ttft else None,
"ttft_avg": ratio("ttft_sum", "ttft_count"),
"ttft_count": shown.get("ttft_count"),
"kv_bytes": shown.get("kv_bytes"),
"kv_seqs": shown.get("kv_seqs"),
"kv_budget_bytes": shown.get("kv_budget_bytes"),
"kv_peak_pct": self.kv_peak_pct(shown),
},
"runs": list(self.runs)[::-1],
"stats_since": self.stats_since,
}
# Counters that run from the model server's start; a stats reset rebases these.
COUNTERS = ("gen_total", "prompt_total", "requests_total", "prefix_hits", "prefix_queries",
"spec_accepted", "spec_drafted", "preemptions", "ttft_sum", "ttft_count")
def since_reset(self, metrics):
"""metrics with the counters taken from the last reset rather than the server's
start. Rates are unaffected: they come from differences between samples."""
base = self.baseline
if not base:
return metrics
if any(metrics.get(k) is not None and base.get(k) is not None and metrics[k] < base[k]
for k in self.COUNTERS):
# The model server restarted since the reset, so its counters already start
# after it. (What came between the reset and the restart is lost.)
self.baseline = base = {}
out = dict(metrics)
for k in self.COUNTERS:
if out.get(k) is not None:
out[k] = out[k] - (base.get(k) or 0)
return out
def kv_peak_pct(self, shown):
"""Peak KV since the model started (MLX reports it); since a reset, the highest
sampled value instead -- the server's own peak can't be rebased."""
if self.stats_since is not None:
vals = [p["kv"] for p in self.history if p["kv"] is not None]
return max(vals) if vals else None
if shown.get("kv_peak_bytes") and shown.get("kv_budget_bytes"):
return shown["kv_peak_bytes"] / shown["kv_budget_bytes"] * 100
return None
def reset_stats(self):
"""Start the Statistics section over: empty the charts, count from now."""
with self.lock:
latest = self.prev[1] if self.prev else {}
self.baseline = {k: latest.get(k) for k in self.COUNTERS}
self.stats_since = time.time()
self.history.clear()
self.last_ttft = None
def clear_runs(self):
"""Empty the Requests table. Runs already seen stay seen, so they don't come back."""
with self.lock:
self.runs.clear()
def reasoning_state(self, cfg, active):
"""What the active model can be told about reasoning, and what it's set to. The
proxy in front of either backend applies it to each chat request."""
choice = next((m for m in cfg.get("models", []) if m["name"] == active), None)
if not choice:
return {"options": [], "value": plan.DEFAULT, "why": None}
entry = next((m for m in paths.load_catalog()["models"] if m["name"] == active), None)
if not entry:
return {"options": [], "value": plan.DEFAULT, "why": None}
if not hfcache.repo_dir(choice["repo"]).exists():
return {"options": [], "value": plan.DEFAULT,
"why": "the model isn't downloaded yet, so its chat template can't be read"}
controls = hfcache.template_controls(choice["repo"])
opts = plan.reasoning_options(entry, choice, controls)
value = (cfg.get("reasoning") or {}).get(active) or plan.DEFAULT
if value not in [v for v, _ in opts]:
value = plan.DEFAULT
why = "" if opts else "this model's chat template exposes no reasoning controls"
return {"options": [{"value": v, "label": l} for v, l in opts], "value": value, "why": why}
def set_reasoning(self, value):
"""Takes effect on the next request -- no restart, so the model stays loaded."""
cfg = paths.load_config()
active = cfg.get("active")
allowed = [o["value"] for o in self.reasoning_state(cfg, active)["options"]]
if value not in allowed:
return False, allowed
cfg.setdefault("reasoning", {})[active] = value
paths.save_config(cfg)
self.cfg = cfg
with self.lock:
if self.state.get("reasoning"):
self.state["reasoning"]["value"] = value
return True, allowed
def snapshot(self):
with self.lock:
s = dict(self.state)
s["history"] = list(self.history)
return s
def control(self, kind, model=None):
if kind == "switch":
cfg = paths.load_config()
cfg["active"] = model
paths.save_config(cfg)
self.cfg = cfg
opencode.sync(cfg) # keep /models' "loaded" marker honest after a dashboard switch
fn = service.restart
else:
fn = {"stop": service.stop, "start": service.start, "restart": service.restart}[kind]
with self.lock:
self.action = {"kind": kind, "model": model, "t": time.time()}
self.history.clear()
self.prev = None
threading.Thread(target=fn, args=("model",), daemon=True).start()
def make_handler(sampler, key, oidc=None):
class Handler(BaseHTTPRequestHandler):
server_version = "llm-host"
def log_message(self, fmt, *args):
pass
def send_json(self, code, obj):
body = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def authed(self):
if oidc:
# Signed in through the provider; the API key isn't accepted here.
if oidc.session(self.headers.get("Cookie", "")) is None:
self.send_json(401, {"error": "unauthorized", "login": "/auth/login"})
return False
if self.command == "POST" and not oidc.same_origin(self.headers):
self.send_json(403, {"error": "cross-origin request refused"})
return False
return True
h = self.headers.get("Authorization", "")
tok = h[7:] if h.startswith("Bearer ") else ""
if hmac.compare_digest(tok.encode(), key.encode()):
return True
self.send_json(401, {"error": "unauthorized"})
return False
def redirect(self, url, cookies=()):
self.send_response(302)
self.send_header("Location", url)
self.send_header("Cache-Control", "no-store")
for c in cookies:
self.send_header("Set-Cookie", c)
self.send_header("Content-Length", "0")
self.end_headers()
def auth_page(self, code, msg):
body = (f"<!doctype html><meta charset=utf-8><meta name=viewport content='width=device-width'>"
f"<title>llm-host sign-in</title><body style='font:15px system-ui;margin:3em auto;"
f"max-width:32em;padding:0 16px'><h2>Couldn't sign you in</h2><p>{html.escape(msg)}</p>"
f"<p><a href='/auth/login'>Try again</a></p>").encode()
self.send_response(code)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/"))
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def on_public_host(self):
"""A session cookie only exists on the public URL's host, so a visit by any
other name (mybox.local:11340) is sent there instead of to a login loop."""
host = (self.headers.get("Host") or "").lower()
return host == urllib.parse.urlsplit(oidc.public_url).netloc.lower()
def auth_get(self, path, query):
if path == "/auth/config":
s = oidc.session(self.headers.get("Cookie", "")) if oidc else None
return self.send_json(200, {"mode": "oidc" if oidc else "key",
"user": s and s["user"], "name": s and s["name"]})
if not oidc:
return self.send_json(404, {"error": "not found"})
if path == "/auth/login":
if not self.on_public_host():
return self.redirect(oidc.public_url + "/auth/login")
try:
url, state = oidc.start()
except oidc_mod.AuthError as e:
return self.auth_page(502, str(e))
return self.redirect(url, [oidc.cookie(oidc_mod.STATE_COOKIE, state, oidc_mod.LOGIN_TTL, "/auth/")])
if path == "/auth/callback":
params = {k: v[0] for k, v in urllib.parse.parse_qs(query).items()}
cookie_state = oidc_mod.parse_cookies(self.headers.get("Cookie", "")).get(oidc_mod.STATE_COOKIE, "")
try:
s = oidc.finish(params, cookie_state)
except oidc_mod.AuthError as e:
return self.auth_page(403, str(e))
print(f"llm-host dashboard: {s['user']} signed in", flush=True)
return self.redirect("/", [oidc.cookie(oidc_mod.SESSION_COOKIE, s["id"], oidc_mod.SESSION_TTL),
oidc.cookie(oidc_mod.STATE_COOKIE, "", 0, "/auth/")])
self.send_json(404, {"error": "not found"})
def do_GET(self):
path, _, query = self.path.partition("?")
if path.startswith("/auth/"):
return self.auth_get(path, query)
if oidc and path in ("/", "/index.html") and not self.on_public_host():
return self.redirect(oidc.public_url + "/")
if path in ("/", "/index.html"):
body = (HERE / "index.html").read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Cache-Control", "no-store")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif path == "/api/status":
if self.authed():
self.send_json(200, sampler.snapshot())
elif path == "/api/logs":
if self.authed():
lines = [l for l in service.logs("model", 1500)
if not PROGRESS_RE.search(l) and not OWN_POLL_RE.search(l)]
self.send_json(200, {"lines": collapse_disconnects(lines)[-80:]})
else:
self.send_json(404, {"error": "not found"})
def do_POST(self):
path = self.path.split("?", 1)[0]
if path == "/auth/logout" and oidc:
if not oidc.same_origin(self.headers):
return self.send_json(403, {"error": "cross-origin request refused"})
oidc.end(self.headers.get("Cookie", ""))
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Set-Cookie", oidc.cookie(oidc_mod.SESSION_COOKIE, "", 0))
self.send_header("Content-Length", "11")
self.end_headers()
self.wfile.write(b'{"ok": true}')
return
if not self.authed():
return
try:
n = int(self.headers.get("Content-Length") or 0)
data = json.loads(self.rfile.read(n) or b"{}") if n else {}
except ValueError:
return self.send_json(400, {"error": "bad json"})
if path == "/api/switch":
name = str(data.get("model", ""))
if name not in {m["name"] for m in sampler.cfg.get("models", [])}:
return self.send_json(400, {"error": f"unknown model {name!r}"})
sampler.control("switch", name)
return self.send_json(202, {"ok": True, "model": name})
if path == "/api/reasoning":
ok, allowed = sampler.set_reasoning(str(data.get("value", "")))
if not ok:
return self.send_json(400, {"error": "unsupported value for this model",
"allowed": allowed})
return self.send_json(200, {"ok": True, "value": data.get("value")})
if path == "/api/stats/reset":
sampler.reset_stats()
return self.send_json(200, {"ok": True})
if path == "/api/runs/clear":
sampler.clear_runs()
return self.send_json(200, {"ok": True})
if path in ("/api/stop", "/api/start", "/api/restart"):
sampler.control(path.rsplit("/", 1)[1])
return self.send_json(202, {"ok": True})
self.send_json(404, {"error": "not found"})
return Handler
def serve():
cfg = paths.load_config()
if not cfg:
raise SystemExit("not set up; run `llmhost setup`")
key = paths.api_key()
sampler = Sampler(cfg, key)
threading.Thread(target=sampler.loop, daemon=True).start()
auth = None
conf = cfg.get("dashboard_auth") or {}
if conf.get("mode") == "oidc":
auth = oidc_mod.OIDC(conf, paths.oidc_secret())
srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key, auth))
how = f"sign-in via {auth.issuer}, at {auth.public_url}" if auth else "API key"
print(f"llm-host dashboard on :{cfg['web_port']} ({how})", flush=True)
srv.serve_forever()