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

+8 -1
View File
@@ -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"})
+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`;
},
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);
+5 -2
View File
@@ -4,14 +4,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<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">
<script src="/static/app.js" defer></script>
</head>
<body>
<header class="masthead">
<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>
</div>
<nav aria-label="Sections">
@@ -51,6 +51,9 @@
<div class="detail" id="lcd-detail">&nbsp;</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">
<figure class="card chart" id="chart-power"></figure>
<figure class="card chart" id="chart-temps"></figure>