"""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. """ import hmac import json import re import socket import threading import time import urllib.request from collections import deque from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from .. import hfcache, hw, paths, service HERE = Path(__file__).resolve().parent SAMPLE_SECONDS = 2 HISTORY_POINTS = 300 # 10 minutes # 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) ') PROGRESS_RE = re.compile(r"\d+(\.\d+)?(it/s|s/it)\]") METRIC_RE = re.compile(r"^(vllm:[a-z_]+)(\{[^}]*\})?\s+([0-9.eE+-]+|NaN)$") 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 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"), } 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, {}) 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 if cfg["backend"] == "vllm": st, body = http_get(base + "/metrics") metrics = parse_vllm_metrics(body) if st == 200 else {} else: st, body = http_get(base + "/llmhost/metrics") try: metrics = json.loads(body) if st == 200 else {} except ValueError: metrics = {} 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 = 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 self.prev = (now, metrics) if metrics else None gpu = hw.live_stats(cfg["kind"]) kv = metrics.get("kv") point = { "t": now, "gen": gen_rate, "prompt": prompt_rate, "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 metrics[a] / metrics[b] if metrics.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", [])] with self.lock: self.history.append(point) 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, "action": self.action, "metrics": { "running": metrics.get("running"), "waiting": metrics.get("waiting"), "kv_pct": point["kv"], "gen_tps": gen_rate, "prompt_tps": prompt_rate, "gen_total": metrics.get("gen_total"), "prompt_total": metrics.get("prompt_total"), "prefix_hit": ratio("prefix_hits", "prefix_queries"), "spec_accept": ratio("spec_accepted", "spec_drafted"), "preemptions": metrics.get("preemptions"), }, } 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 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): 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): 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 do_GET(self): path = self.path.split("?", 1)[0] 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": lines[-80:]}) else: self.send_json(404, {"error": "not found"}) def do_POST(self): path = self.path.split("?", 1)[0] 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 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() srv = ThreadingHTTPServer(("0.0.0.0", cfg["web_port"]), make_handler(sampler, key)) print(f"llm-host dashboard on :{cfg['web_port']}", flush=True) srv.serve_forever()