Long-term telemetry: hourly rollups in JSONL, a range selector in the UI

- telemetry/record.py: a Recorder subscribed to Telemetry keeps min/avg/max
  per metric for the current hour and appends each finished hour as one JSON
  line to records-YYYY-MM.jsonl in the data dir (~400 days kept; whole months
  older than that are pruned on start). Best effort by design: a failing disk
  logs once and stops recording; nothing else notices. load() merges lines per
  hour (a restart re-writes the current hour; torn last lines are skipped).
- app.py: the recorder runs unless --demo (simulated samples must not mix into
  real records) and flushes the open hour in close(), after the telemetry
  thread has stopped. records(days) validates 1..400.
- Web: GET /api/records?days=N (bad values answer 400 with the reason).
- UI: a range selector above the power/temperature charts switches them
  between the live 10 minutes and hourly averages for 24 h / 7 d / 30 d /
  1 y; the chart window, tick labels (min/h/d), tooltips and table captions
  adapt to the span. Live samples keep accumulating behind a long-range view,
  so switching back is instant.
- Tests: test_record.py (5) and a /api/records case in test_web.py; README
  updated (API table, System section, layout).
This commit is contained in:
paul committed 2026-12-05 18:04:57 +13:00
1 parent ba39016d52
commit f717f7a82f
8 files changed
+371 -18

No files matched your search

+9 -3
View File
@@ -1,5 +1,7 @@
# The Kurgan # The Kurgan
![The Kurgan's sword](kurgan/assets/sword.png)
One process that runs this PC's backend systems, with one web UI at **<http://127.0.0.1:8080/>**: One process that runs this PC's backend systems, with one web UI at **<http://127.0.0.1:8080/>**:
| Capability | What it does | Package | | 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 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. 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. - **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. - **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. - **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/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/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 | | `GET /api/config` | Fan profiles and LCD theme thresholds |
| `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` | | `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` |
| `POST /api/cooling/profile` | `{"profile": "quiet"\|"balanced"\|"performance"\|"full"}` | | `POST /api/cooling/profile` | `{"profile": "quiet"\|"balanced"\|"performance"\|"full"}` |
@@ -378,13 +381,16 @@ kurgan/
app.py wires the capabilities together; command line; single instance app.py wires the capabilities together; command line; single instance
settings.py settings.json: defaults, strict validation, atomic saves, legacy import settings.py settings.json: defaults, strict validation, atomic saves, legacy import
paths.py, theme.py, tray.py, demo.py (simulated hardware for --demo) 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 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) 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 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), 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 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) hardware/ hid.py (Windows HID), pawnio/ (signed PawnIO modules, LGPL-2.1)
tests/ unittest suites tests/ unittest suites
docs/ design references and research notes docs/ design references and research notes
+16 -4
View File
@@ -197,6 +197,11 @@ class Kurgan:
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(), self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(),
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load), hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
self.system, args.interval) 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( self.display = None if (args.no_lcd or hw) else DisplayService(
DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness) DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness)
@@ -295,12 +300,10 @@ class Kurgan:
known = states known = states
def _start_tray(self) -> None: def _start_tray(self) -> None:
from kurgan.tray import TrayIcon, make_icon from kurgan.tray import ICON_PATH, TrayIcon
try: try:
icon = make_icon(os.path.join(paths.DATA_DIR, "tray.ico"), self.tray = TrayIcon(APP_NAME, ICON_PATH, on_exit=self.stop.set,
[self.theme.other_color, self.theme.cpu_color, self.theme.gpu_color])
self.tray = TrayIcon(APP_NAME, icon, on_exit=self.stop.set,
on_open=self.open_ui if self.web else None, status_lines=self.tray_lines) on_open=self.open_ui if self.web else None, status_lines=self.tray_lines)
self.tray.start() self.tray.start()
except Exception: except Exception:
@@ -331,6 +334,8 @@ class Kurgan:
deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly
for thread in self._threads: for thread in self._threads:
thread.join(max(0.1, deadline - time.monotonic())) 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.lighting.join()
self.system.fans.close() self.system.fans.close()
@@ -368,6 +373,13 @@ class Kurgan:
return {**self.telemetry.history(), return {**self.telemetry.history(),
"fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_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: def set_lighting(self, zone: str, mode: str) -> None:
self.lighting.set_mode(zone, mode) self.lighting.set_mode(zone, mode)
+152
View File
@@ -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}
+8 -1
View File
@@ -3,6 +3,7 @@
GET / the UI (static/index.html) GET / the UI (static/index.html)
GET /api/state everything live, polled by the UI once a second 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/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) GET /api/config fan profiles, lighting zones and AI backends (static)
POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...} POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...}
POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"} POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"}
@@ -26,6 +27,7 @@ import mimetypes
import os import os
import threading import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from kurgan.web import proxy from kurgan.web import proxy
@@ -105,12 +107,15 @@ def make_handler(app, port: int):
def do_GET(self) -> None: def do_GET(self) -> None:
if self._proxied() or not self._guard(): if self._proxied() or not self._guard():
return return
path = self.path.split("?", 1)[0] path, _, query = self.path.partition("?")
try: try:
if path == "/api/state": if path == "/api/state":
self._json(200, app.state()) self._json(200, app.state())
elif path == "/api/history": elif path == "/api/history":
self._json(200, app.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": elif path == "/api/config":
self._json(200, app.config()) self._json(200, app.config())
elif path in ("/", "/index.html"): elif path in ("/", "/index.html"):
@@ -119,6 +124,8 @@ def make_handler(app, port: int):
self._static(path[len("/static/"):]) self._static(path[len("/static/"):])
else: else:
self._json(404, {"error": "not found"}) self._json(404, {"error": "not found"})
except ValueError as e:
self._json(400, {"error": str(e)})
except Exception: except Exception:
log.exception("GET %s failed", path) log.exception("GET %s failed", path)
self._json(500, {"error": "internal error; see kurgan.log"}) self._json(500, {"error": "internal error; see kurgan.log"})
+66 -8
View File
@@ -45,6 +45,7 @@ const fmt = {
return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`; 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" }), 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 = { const ICON = {
@@ -140,6 +141,7 @@ class Chart {
this.xs = []; this.xs = [];
this.cols = {}; this.cols = {};
this.markers = []; 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" }, 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", this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line",
style: `background:var(${s.color})` }), s.label))) : null; style: `background:var(${s.color})` }), s.label))) : null;
@@ -164,6 +166,8 @@ class Chart {
this.svg.setAttribute("aria-label", title); this.svg.setAttribute("aria-label", title);
} }
setWindow(seconds) { this.window = seconds; this.draw(); }
setData(xs, cols, markers = []) { setData(xs, cols, markers = []) {
this.xs = xs; this.xs = xs;
this.cols = cols; this.cols = cols;
@@ -199,9 +203,10 @@ class Chart {
this.svg.replaceChildren(); this.svg.replaceChildren();
const xo = this.o.x; const xo = this.o.x;
let x0, x1; let x0, x1;
const span = this.window ?? WINDOW_S;
if (xo.type === "time") { if (xo.type === "time") {
x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000; x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000;
x0 = x1 - WINDOW_S; x0 = x1 - span;
} else { } else {
[x0, x1] = [xo.min, xo.max]; [x0, x1] = [xo.min, xo.max];
} }
@@ -226,11 +231,16 @@ class Chart {
} }
this.svg.append(grid); this.svg.append(grid);
this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) })); this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) }));
// x ticks // x ticks: five even steps, labelled in minutes, hours or days to suit the span
const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks; 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) { for (const xv of xticks) {
const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" }); 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); this.svg.append(t);
} }
// reference lines (e.g. the warn/hot temperatures) // reference lines (e.g. the warn/hot temperatures)
@@ -308,7 +318,9 @@ class Chart {
this.cross.setAttribute("x1", cx); this.cross.setAttribute("x1", cx);
this.cross.setAttribute("x2", cx); this.cross.setAttribute("x2", cx);
this.cross.setAttribute("visibility", "visible"); 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 rows = this.o.series.slice().reverse().map((s) => {
const v = this.value(s.key, best); 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}` }; 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() { renderTable() {
const time = this.o.x.type === "time"; 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 }), 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 }))); this.o.series.map((s) => el("th", { class: "r", text: s.label })));
const rows = []; const rows = [];
@@ -344,11 +357,12 @@ class Chart {
if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s
lastT = this.xs[i]; lastT = this.xs[i];
if (!time && this.xs[i] % 5 !== 0) continue; 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.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", 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); } stale(on) { this.plot.classList.toggle("stale", on); }
@@ -380,6 +394,49 @@ let charts = {};
let built = { profiles: false, groups: "", zones: false, backends: "" }; let built = { profiles: false, groups: "", zones: false, backends: "" };
let strataVariant = null; let strataVariant = null;
let profileShown = 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() { function buildCharts() {
const temps = config.theme; const temps = config.theme;
@@ -758,7 +815,7 @@ function render(s) {
lastState = s; lastState = s;
renderHeader(s); renderHeader(s);
renderSystem(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.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols); charts.temps.setData(telemetry.t, telemetry.cols);
} }
@@ -798,6 +855,7 @@ async function start() {
return; return;
} }
buildCharts(); buildCharts();
buildRange();
charts.power.setData(telemetry.t, telemetry.cols); charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols); charts.temps.setData(telemetry.t, telemetry.cols);
charts.fans.setData(fanHistory.t, fanHistory.cols); charts.fans.setData(fanHistory.t, fanHistory.cols);
+5 -2
View File
@@ -4,14 +4,14 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Kurgan</title> <title>The Kurgan</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml"> <link rel="icon" href="/static/favicon.ico" sizes="16x16 32x32 48x48">
<link rel="stylesheet" href="/static/style.css"> <link rel="stylesheet" href="/static/style.css">
<script src="/static/app.js" defer></script> <script src="/static/app.js" defer></script>
</head> </head>
<body> <body>
<header class="masthead"> <header class="masthead">
<div class="brand"> <div class="brand">
<svg viewBox="0 0 32 32" aria-hidden="true"><use href="/static/favicon.svg#tank"/></svg> <img src="/static/logo.png" alt="" width="90" height="40">
<h1>THE KURGAN</h1> <h1>THE KURGAN</h1>
</div> </div>
<nav aria-label="Sections"> <nav aria-label="Sections">
@@ -51,6 +51,9 @@
<div class="detail" id="lcd-detail">&nbsp;</div> <div class="detail" id="lcd-detail">&nbsp;</div>
</div> </div>
</div> </div>
<div class="row" style="justify-content:flex-end;margin:0 0 10px">
<div class="seg" role="radiogroup" aria-label="Chart range" id="chart-range"></div>
</div>
<div class="grid2"> <div class="grid2">
<figure class="card chart" id="chart-power"></figure> <figure class="card chart" id="chart-power"></figure>
<figure class="card chart" id="chart-temps"></figure> <figure class="card chart" id="chart-temps"></figure>
+96
View File
@@ -0,0 +1,96 @@
import json
import os
import tempfile
import time
import unittest
from kurgan.telemetry.readings import PowerReadings, Readings
from kurgan.telemetry.record import Recorder, load
from kurgan.telemetry.service import Sample
HOUR = 1764892800 # any hour boundary; 1764892800 % 3600 == 0
def sample(t, cpu_temp=50.0, gpu_temp=None, vram=None, cpu_w=30.0, gpu_w=80.0, other_w=20.0):
return Sample(1, t, Readings(temp=cpu_temp, power=cpu_w), Readings(temp=gpu_temp, power=gpu_w),
PowerReadings(cpu=cpu_w, gpu=gpu_w, other=other_w), vram)
def written(directory):
rows = []
for name in sorted(os.listdir(directory)):
with open(os.path.join(directory, name), encoding="utf-8") as f:
rows += [json.loads(line) for line in f if line.strip()]
return rows
class RecorderTest(unittest.TestCase):
def test_an_hour_is_written_when_it_ends(self):
with tempfile.TemporaryDirectory() as d:
rec = Recorder(d)
rec.on_sample(sample(HOUR + 1))
rec.on_sample(sample(HOUR + 3599, cpu_temp=70.0))
rec.on_sample(sample(HOUR + 3600, cpu_temp=40.0)) # the new hour flushes the old one
rec.close() # ... and closing writes the hour still in progress
month = time.strftime("%Y-%m", time.gmtime(HOUR))
self.assertEqual(os.listdir(d), [f"records-{month}.jsonl"])
rows = written(d)
self.assertEqual(len(rows), 2)
first, second = rows
self.assertEqual((first["hour"], first["n"]), (HOUR, 2))
self.assertEqual(first["cpu_temp"], [50.0, 60.0, 70.0]) # min, avg, max
self.assertEqual(first["total_w"], [130.0, 130.0, 130.0]) # 30 + 80 + 20 W every sample
self.assertIsNone(first["gpu_temp"]) # a metric no sample carried stays null ...
self.assertIsNone(first["vram_used"])
self.assertEqual((second["hour"], second["n"], second["cpu_temp"]), (HOUR + 3600, 1, [40.0, 40.0, 40.0]))
def test_a_failing_disk_stops_recording_quietly(self):
with tempfile.TemporaryDirectory() as d:
blocked = os.path.join(d, "blocked")
open(blocked, "w").close()
rec = Recorder(blocked) # the "directory" is a file: every write fails
with self.assertLogs("kurgan.telemetry.record", level="WARNING") as logs:
rec.on_sample(sample(HOUR))
rec.on_sample(sample(HOUR + 3600)) # the hour boundary is where the write fails
rec.on_sample(sample(HOUR + 7200)) # already stopped: nothing happens, nothing raised
rec.close()
self.assertTrue(rec._stopped)
self.assertEqual(len(logs.output), 1)
def test_pruning_removes_months_older_than_the_retention(self):
with tempfile.TemporaryDirectory() as d:
old = os.path.join(d, "records-2020-01.jsonl")
current = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime())}.jsonl")
open(old, "w").close()
open(current, "w").close()
Recorder(d, retention_days=400)
self.assertFalse(os.path.exists(old))
self.assertTrue(os.path.exists(current))
class LoadTest(unittest.TestCase):
def test_load_merges_restarts_and_skips_junk(self):
h = int(time.time() // 3600) * 3600
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime(h))}.jsonl")
with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps({"hour": h, "n": 100, "cpu_temp": [40.0, 50.0, 60.0], "total_w": None}) + "\n")
f.write(json.dumps({"hour": h, "n": 300, "cpu_temp": [30.0, 40.0, 80.0]}) + "\n") # a restart re-wrote this hour
f.write(json.dumps({"hour": h - 5 * 86400, "n": 3600, "cpu_temp": [10.0, 20.0, 30.0]}) + "\n") # outside the window
f.write("{torn\n") # the last line of a crashed run
data = load(d, days=1)
self.assertEqual(data["days"], 1)
self.assertEqual(data["metrics"][0], "cpu_temp")
self.assertEqual(len(data["rows"]), 1)
row = data["rows"][0]
self.assertEqual((row["hour"], row["n"]), (h, 400))
self.assertEqual(row["cpu_temp"], [30.0, 42.5, 80.0]) # min, sample-weighted avg, max
self.assertIsNone(row.get("total_w"))
def test_load_without_a_directory_is_empty(self):
data = load(os.path.join(tempfile.gettempdir(), "kurgan-no-such-records-dir"), 7)
self.assertEqual(data["rows"], [])
if __name__ == "__main__":
unittest.main()
+19
View File
@@ -35,6 +35,12 @@ class FakeApp:
def ai_model(self, action): def ai_model(self, action):
self.calls.append(("model", action)) self.calls.append(("model", action))
def records(self, days):
self.calls.append(("records", days))
if not 1 <= days <= 400:
raise ValueError("days must be a whole number from 1 to 400")
return {"metrics": [], "rows": [], "days": days}
def free_port() -> int: def free_port() -> int:
with socket.socket() as s: with socket.socket() as s:
@@ -127,6 +133,19 @@ class WebServerTest(unittest.TestCase):
self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"}) self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"})
self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")]) self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")])
def test_records_serves_the_long_term_rollups(self):
status, _, body = self.request("GET", "/api/records") # no days: the default week
self.assertEqual((status, json.loads(body)["days"]), (200, 7))
status, _, body = self.request("GET", "/api/records?days=30")
self.assertEqual((status, json.loads(body)["days"]), (200, 30))
self.assertEqual(self.app.calls, [("records", 7), ("records", 30)])
for path in ("/api/records?days=abc", "/api/records?days=0", "/api/records?days=-3",
"/api/records?days=401", "/api/records?days=1.5"):
with self.subTest(path=path):
status, _, raw = self.request("GET", path)
self.assertEqual(status, 400)
self.assertIn("whole number", json.loads(raw)["error"])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()