diff --git a/README.md b/README.md index 299a541..7953859 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # The Kurgan +![The Kurgan's sword](kurgan/assets/sword.png) + One process that runs this PC's backend systems, with one web UI at ****: | Capability | What it does | Package | @@ -55,7 +57,7 @@ icon also pops a balloon tip when something starts to go wrong — a fan group e an AI server reporting an error, or a sensor source starting to fail. What is already wrong when The Kurgan starts is not ballooned; it sits in the tray menu and the UI. -- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. When a sensor source's last read failed — a disconnected Commander PRO, a busy NVML — a pill in the header names it and hover shows the error. +- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. A range selector above the charts switches them to hourly averages for 24 hours, 7 days, 30 days or a year. Those long-term rollups live in `%LOCALAPPDATA%\Kurgan\records-YYYY-MM.jsonl` — one JSON line per hour, about 400 days kept, written best effort (a failing disk stops recording and nothing else notices; `--demo` never records). When a sensor source's last read failed — a disconnected Commander PRO, a busy NVML — a pill in the header names it and hover shows the error. - **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves. - **Lighting**: a mode selector per zone (case fans, RAM, GPU), the zone's status, and the shared chase speed. - **AI**: pick Strata (and its model), llama.cpp or None; requests to either address also pick it. Then see the server's process, model, context size, live request progress and token speeds, and when it will stop if unused; load or unload the model; GPU memory over time; and recent requests. @@ -69,6 +71,7 @@ next start. | --- | --- | | `GET /api/state` | Everything live (what the UI polls), including `telemetry.health`: the sensor sources whose latest read failed, each with its error and age | | `GET /api/history` | The last 10 minutes of telemetry and fan duty | +| `GET /api/records?days=N` | Hourly min/avg/max rollups for the last N days (1-400), oldest first | | `GET /api/config` | Fan profiles and LCD theme thresholds | | `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` | | `POST /api/cooling/profile` | `{"profile": "quiet"\|"balanced"\|"performance"\|"full"}` | @@ -378,13 +381,16 @@ kurgan/ app.py wires the capabilities together; command line; single instance settings.py settings.json: defaults, strict validation, atomic saves, legacy import paths.py, theme.py, tray.py, demo.py (simulated hardware for --demo) - telemetry/ sensors.py (CPU/GPU/system power), readings.py, service.py (sampling + history) + telemetry/ sensors.py (CPU/GPU/system power), readings.py, service.py (sampling + history), + record.py (hourly rollups for the long-term charts) display/ tt_lcd.py (panel HID protocol), renderer.py, service.py (LCD loop), background.png cooling/ profiles.py, control.py (case-fan groups, top-fan curve), board_fans.py (NCT6687D) lighting/ case_fans.py (CORE patterns + shared chase clock), lighting_node.py, memory.py, gpu.py, service.py ai/ config.py, launcher.py (non-elevated child processes in job objects), backends.py (Strata, llama.cpp), service.py (one-at-a-time supervisor), strata_host.py - web/ server.py (API), static/ (index.html, app.js, style.css) + web/ server.py (API), static/ (index.html, app.js, style.css, logo.png, favicon.ico) + assets/ sword.png, hilt.png, kurgan.ico (tray icon); make_assets.py rebuilds them and the + web UI's logo and favicon from The-Kurgan-Sword.png hardware/ hid.py (Windows HID), pawnio/ (signed PawnIO modules, LGPL-2.1) tests/ unittest suites docs/ design references and research notes diff --git a/kurgan/app.py b/kurgan/app.py index f8b7335..820a9c0 100644 --- a/kurgan/app.py +++ b/kurgan/app.py @@ -197,6 +197,11 @@ class Kurgan: self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(), hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load), self.system, args.interval) + self.recorder = None + if not args.demo: # simulated samples must not mix into the real records + from kurgan.telemetry.record import Recorder + self.recorder = Recorder(paths.DATA_DIR) + self.telemetry.subscribe(self.recorder.on_sample) self.display = None if (args.no_lcd or hw) else DisplayService( DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness) @@ -295,12 +300,10 @@ class Kurgan: known = states def _start_tray(self) -> None: - from kurgan.tray import TrayIcon, make_icon + from kurgan.tray import ICON_PATH, TrayIcon try: - icon = make_icon(os.path.join(paths.DATA_DIR, "tray.ico"), - [self.theme.other_color, self.theme.cpu_color, self.theme.gpu_color]) - self.tray = TrayIcon(APP_NAME, icon, on_exit=self.stop.set, + self.tray = TrayIcon(APP_NAME, ICON_PATH, on_exit=self.stop.set, on_open=self.open_ui if self.web else None, status_lines=self.tray_lines) self.tray.start() except Exception: @@ -331,6 +334,8 @@ class Kurgan: deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly for thread in self._threads: thread.join(max(0.1, deadline - time.monotonic())) + if self.recorder is not None: + self.recorder.close() # after the telemetry thread has stopped writing self.lighting.join() self.system.fans.close() @@ -368,6 +373,13 @@ class Kurgan: return {**self.telemetry.history(), "fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}} + def records(self, days: int) -> dict: + from kurgan.telemetry.record import RETENTION_DAYS, load + + if not isinstance(days, int) or not 1 <= days <= RETENTION_DAYS: + raise ValueError(f"days must be a whole number from 1 to {RETENTION_DAYS}") + return load(paths.DATA_DIR, days) + def set_lighting(self, zone: str, mode: str) -> None: self.lighting.set_mode(zone, mode) diff --git a/kurgan/telemetry/record.py b/kurgan/telemetry/record.py new file mode 100644 index 0000000..ff9a7d5 --- /dev/null +++ b/kurgan/telemetry/record.py @@ -0,0 +1,152 @@ +"""Long-term telemetry: hourly min/avg/max per metric, one JSON line per hour. + +The live history in the service keeps ten minutes; this keeps about a year, so the web UI can +draw weeks and months. Files are append-only JSONL in the data dir, one per month +(records-YYYY-MM.jsonl); each line looks like: + + {"hour":1764892800,"n":3600,"cpu_temp":[41.0,55.3,78.0],...} + +Recording is best effort: a failing disk logs once and stops the recorder; nothing else +notices. Restarting within an hour writes a second line for that hour; the reader merges +lines per hour, so that is harmless. +""" + +from __future__ import annotations + +import glob +import json +import logging +import os +import time + +log = logging.getLogger(__name__) + +METRICS = ("cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used") +RETENTION_DAYS = 400 # a little over a year of monthly files +_FILE = "records-%s.jsonl" + + +def _values(sample) -> dict[str, float | None]: + return {"cpu_temp": sample.cpu.temp, "gpu_temp": sample.gpu.temp, + "cpu_load": sample.cpu.load, "gpu_load": sample.gpu.load, + "cpu_w": sample.cpu.power, "gpu_w": sample.gpu.power, + "other_w": sample.power.other, "total_w": sample.power.total, + "vram_used": None if sample.vram is None else sample.vram[0]} + + +class Recorder: + """Subscribed to Telemetry (called once per sample); writes each finished hour to its month file.""" + + def __init__(self, directory: str, retention_days: int = RETENTION_DAYS): + self.directory = directory + self.retention_days = retention_days + self._hour = 0 + self._n = 0 + self._stats: dict[str, list[float]] = {} # metric -> [min, max, sum] + self._stopped = False + self._prune() + + def on_sample(self, sample) -> None: + if self._stopped: + return + try: + hour = int(sample.t // 3600) * 3600 + if hour != self._hour: + self._flush() + self._hour, self._n, self._stats = hour, 0, {} + self._n += 1 + for name, value in _values(sample).items(): + if value is None: + continue + s = self._stats.setdefault(name, [value, value, 0.0]) + s[0], s[1], s[2] = min(s[0], value), max(s[1], value), s[2] + value + except Exception: + self._stopped = True + log.warning("Telemetry recording stopped for this run", exc_info=True) + + def close(self) -> None: + """Write the hour still in progress; a short line is fine, the reader merges per hour.""" + if self._stopped: + return + try: + self._flush() + except Exception: + self._stopped = True + log.warning("Telemetry recording stopped while closing", exc_info=True) + + def _flush(self) -> None: + if not self._hour or not self._n: + return + row = {"hour": self._hour, "n": self._n} + for name in METRICS: + s = self._stats.get(name) + row[name] = [round(s[0], 1), round(s[2] / self._n, 1), round(s[1], 1)] if s else None + month = time.strftime("%Y-%m", time.gmtime(self._hour)) + os.makedirs(self.directory, exist_ok=True) + with open(os.path.join(self.directory, _FILE % month), "a", encoding="utf-8") as f: + f.write(json.dumps(row, separators=(",", ":")) + "\n") + + def _prune(self) -> None: + """Delete month files whose whole month is older than the retention window.""" + # Drop a month file only once its whole month is past the window: it can end up to 31 + # days after the month it is named for starts. + cutoff = time.time() - (self.retention_days + 31) * 86400 + try: + for path in glob.glob(os.path.join(self.directory, _FILE % "*")): + try: + month = os.path.basename(path)[len("records-"):-len(".jsonl")] + when = time.mktime(time.strptime(month, "%Y-%m")) + except ValueError: + continue + if when < cutoff: + os.remove(path) + log.info("Removed telemetry file older than %s days: %s", self.retention_days, path) + except OSError: + log.warning("Couldn't prune old telemetry files", exc_info=True) + + +def load(directory: str, days: int) -> dict: + """Hourly rollups for the last `days` days, oldest first: {"metrics", "rows", "days"}.""" + since = time.time() - days * 86400 + rows: dict[int, dict] = {} + try: + names = sorted(os.listdir(directory)) + except OSError: + names = [] + for name in names: + if not (name.startswith("records-") and name.endswith(".jsonl")): + continue + try: + with open(os.path.join(directory, name), encoding="utf-8") as f: + lines = f.readlines() + except OSError: + log.warning("Couldn't read telemetry file %s", name) + continue + for line in lines: + line = line.strip() + if not line: + continue + try: + row = json.loads(line) + except ValueError: + continue # a torn last line from a crash: skip it + hour = row.get("hour") + if not isinstance(hour, (int, float)) or hour < since: + continue + merged = rows.setdefault(int(hour), {"hour": int(hour), "n": 0}) + n = row.get("n") if isinstance(row.get("n"), int) else 0 + before = merged["n"] + merged["n"] = before + n + for metric in METRICS: + stats = row.get(metric) + if not isinstance(stats, list) or len(stats) != 3: + continue + cur = merged.get(metric) + if cur is None: + merged[metric] = list(stats) + else: + cur[0] = min(cur[0], stats[0]) + cur[2] = max(cur[2], stats[2]) + if before + n: + cur[1] = (cur[1] * before + stats[1] * n) / (before + n) + return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days} \ No newline at end of file diff --git a/kurgan/web/server.py b/kurgan/web/server.py index f96b969..2bd0e12 100644 --- a/kurgan/web/server.py +++ b/kurgan/web/server.py @@ -3,6 +3,7 @@ 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"} @@ -26,6 +27,7 @@ import mimetypes import os import threading from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs from kurgan.web import proxy @@ -105,12 +107,15 @@ def make_handler(app, port: int): def do_GET(self) -> None: if self._proxied() or not self._guard(): return - path = self.path.split("?", 1)[0] + 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"): @@ -119,6 +124,8 @@ def make_handler(app, port: int): 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"}) diff --git a/kurgan/web/static/app.js b/kurgan/web/static/app.js index 02bca3e..2d0565a 100644 --- a/kurgan/web/static/app.js +++ b/kurgan/web/static/app.js @@ -45,6 +45,7 @@ const fmt = { return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`; }, clock: (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }), + stamp: (t) => new Date(t * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }), }; const ICON = { @@ -140,6 +141,7 @@ class Chart { this.xs = []; this.cols = {}; this.markers = []; + this.window = null; // seconds shown; null falls back to the live 10-minute window const legend = this.o.series.length > 1 ? el("div", { class: "legend" }, this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line", style: `background:var(${s.color})` }), s.label))) : null; @@ -164,6 +166,8 @@ class Chart { this.svg.setAttribute("aria-label", title); } + setWindow(seconds) { this.window = seconds; this.draw(); } + setData(xs, cols, markers = []) { this.xs = xs; this.cols = cols; @@ -199,9 +203,10 @@ class Chart { this.svg.replaceChildren(); const xo = this.o.x; let x0, x1; + const span = this.window ?? WINDOW_S; if (xo.type === "time") { x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000; - x0 = x1 - WINDOW_S; + x0 = x1 - span; } else { [x0, x1] = [xo.min, xo.max]; } @@ -226,11 +231,16 @@ class Chart { } this.svg.append(grid); this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) })); - // x ticks - const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks; + // x ticks: five even steps, labelled in minutes, hours or days to suit the span + const ago = (xv) => { + const s = x1 - xv; + return s < 1 ? "now" : span <= 600 ? `−${Math.round(s / 60)} min` + : span <= 172800 ? `−${Math.round(s / 3600)} h` : `−${Math.round(s / 86400)} d`; + }; + const xticks = xo.type === "time" ? [0, 1, 2, 3, 4, 5].map((k) => x1 - span + (span * k) / 5) : xo.ticks; for (const xv of xticks) { const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" }); - t.textContent = xo.type === "time" ? (x1 - xv < 1 ? "now" : `−${Math.round((x1 - xv) / 60)} min`) : xo.fmt(xv); + t.textContent = xo.type === "time" ? ago(xv) : xo.fmt(xv); this.svg.append(t); } // reference lines (e.g. the warn/hot temperatures) @@ -308,7 +318,9 @@ class Chart { this.cross.setAttribute("x1", cx); this.cross.setAttribute("x2", cx); this.cross.setAttribute("visibility", "visible"); - const title = this.o.x.type === "time" ? fmt.clock(this.xs[best]) : this.o.x.fmt(this.xs[best]); + const title = this.o.x.type === "time" + ? ((this.window ?? WINDOW_S) > 7200 ? fmt.stamp(this.xs[best]) : fmt.clock(this.xs[best])) + : this.o.x.fmt(this.xs[best]); const rows = this.o.series.slice().reverse().map((s) => { const v = this.value(s.key, best); return { color: `var(${s.color})`, label: s.label, value: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }; @@ -335,6 +347,7 @@ class Chart { renderTable() { const time = this.o.x.type === "time"; + const stamp = (this.window ?? WINDOW_S) > 7200; const head = el("tr", {}, el("th", { text: time ? "Time" : this.o.x.label }), this.o.series.map((s) => el("th", { class: "r", text: s.label }))); const rows = []; @@ -344,11 +357,12 @@ class Chart { if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s lastT = this.xs[i]; if (!time && this.xs[i] % 5 !== 0) continue; - rows.push(el("tr", {}, el("td", { class: "num", text: time ? fmt.clock(this.xs[i]) : this.o.x.fmt(this.xs[i]) }), + rows.push(el("tr", {}, el("td", { class: "num", text: time ? (stamp ? fmt.stamp(this.xs[i]) : fmt.clock(this.xs[i])) : this.o.x.fmt(this.xs[i]) }), this.o.series.map((s) => { const v = this.value(s.key, i); return el("td", { class: "r", text: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }); }))); } this.tableNode.replaceChildren(el("table", {}, el("caption", { class: "muted", style: "text-align:left;caption-side:top;padding:0 0 6px", - text: time ? "Every 30 seconds, newest first" : "" }), el("thead", {}, head), el("tbody", {}, rows))); + text: time ? ((this.window ?? WINDOW_S) > 600 ? "One row per hour, newest first" : "Every 30 seconds, newest first") : "" }), + el("thead", {}, head), el("tbody", {}, rows))); } stale(on) { this.plot.classList.toggle("stale", on); } @@ -380,6 +394,49 @@ let charts = {}; let built = { profiles: false, groups: "", zones: false, backends: "" }; let strataVariant = null; let profileShown = null; +let rangeDays = 0; // 0 = the live 10-minute view; otherwise days of hourly rollups on the system charts +let rangeToken = 0; +const RANGES = [["10 min", 0], ["24 h", 1], ["7 d", 7], ["30 d", 30], ["1 y", 365]]; + +function buildRange() { + const group = $("chart-range"); + group.replaceChildren(...RANGES.map(([name, days]) => el("label", {}, + el("input", { type: "radio", name: "range", value: String(days), checked: days === 0, + onchange: () => setRange(days) }), + el("span", { text: name })))); +} + +async function setRange(days) { + rangeDays = days; + const token = ++rangeToken; + if (days === 0) { + charts.power.setWindow(null); + charts.temps.setWindow(null); + charts.power.setTitle("Power", `Whole PC, last 10 minutes (DC watts; ${fmt.n0(config.theme.psu_watts)} W supply)`); + charts.temps.setTitle("Temperatures", "Last 10 minutes"); + charts.power.setData(telemetry.t, telemetry.cols); + charts.temps.setData(telemetry.t, telemetry.cols); + return; + } + try { + const data = await api(`/api/records?days=${days}`); + if (token !== rangeToken) return; // another range was picked while this one loaded + const t = [], cols = Object.fromEntries(data.metrics.map((m) => [m, []])); + for (const r of data.rows) { + t.push(r.hour); + for (const m of data.metrics) cols[m].push(r[m] ? r[m][1] : null); // the hourly average + } + const label = days === 1 ? "last 24 hours" : `last ${days} days`; + charts.power.setWindow(days * 86400); + charts.temps.setWindow(days * 86400); + charts.power.setTitle("Power", `Whole PC, ${label}, hourly averages (DC watts; ${fmt.n0(config.theme.psu_watts)} W supply)`); + charts.temps.setTitle("Temperatures", `${label}, hourly averages`); + charts.power.setData(t, cols); + charts.temps.setData(t, cols); + } catch (error) { + if (token === rangeToken) banner("critical", `Couldn't load the long-term history: ${error.message}`); + } +} function buildCharts() { const temps = config.theme; @@ -758,7 +815,7 @@ function render(s) { lastState = s; renderHeader(s); renderSystem(s); - if (telemetry.push(s.telemetry.row)) { + if (telemetry.push(s.telemetry.row) && rangeDays === 0) { // the live series stays fresh even in a long-range view charts.power.setData(telemetry.t, telemetry.cols); charts.temps.setData(telemetry.t, telemetry.cols); } @@ -798,6 +855,7 @@ async function start() { return; } buildCharts(); + buildRange(); charts.power.setData(telemetry.t, telemetry.cols); charts.temps.setData(telemetry.t, telemetry.cols); charts.fans.setData(fanHistory.t, fanHistory.cols); diff --git a/kurgan/web/static/index.html b/kurgan/web/static/index.html index 38b6a79..720882d 100644 --- a/kurgan/web/static/index.html +++ b/kurgan/web/static/index.html @@ -4,14 +4,14 @@ The Kurgan - +
- +

THE KURGAN