Add optional query statistics
Off by default (stats in jarl.yaml). When enabled, Jarl adds a loopback statistics channel and a response log to named's configuration (merged into existing logging/statistics-channels statements) and switches response logging with rndc responselog, because the responselog option only counts when named starts. jarld polls named's counters every minute and tails the response log (resuming after restarts and across rotation). It stores aggregates, never individual queries, in a separate SQLite database: per-minute, hourly and daily counters (queries, result codes, record types, views, zones, cache hits, upstream latency, DNSSEC) and hourly/daily top lists (names, clients, NXDOMAIN and SERVFAIL names, refused clients), each with its own retention. Clients can be anonymized or excluded. - Web UI: Statistics page with KPI tiles, queries and failed answers over time, a weekday x hour heatmap, top lists and breakdowns; SVG charts with hover/keyboard readouts, a table view and light/dark palettes validated for colour-vision deficiency. - CLI: jarl stats status|summary|top|timeline|heatmap|breakdown. - API: /api/v1/stats/*, behind a new "stats" permission resource. - jarld brings named's configuration up to date with jarl.yaml at startup (engine.SyncConfig), never overwriting hand-edited files. - resync now refuses to overwrite drifted files without force, as documented. - tmpfiles.d creates /var/log/named (allowed by named's AppArmor profile on Debian 13 and Ubuntu). - The e2e harness runs named with -f like the Debian unit. - docs/stats.md, plus API, CLI, configuration, permissions and README updates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
0795a1001e
commit
3b7bee67f8
44 files changed
+4163
-42
No files matched your search
@@ -14,6 +14,7 @@ import * as audit from "./pages/audit.js";
|
||||
import * as users from "./pages/users.js";
|
||||
import * as account from "./pages/account.js";
|
||||
import * as search from "./pages/search.js";
|
||||
import * as stats from "./pages/stats.js";
|
||||
|
||||
const routes = [
|
||||
{ pattern: /^$/, page: dashboard, nav: "dashboard" },
|
||||
@@ -30,10 +31,12 @@ const routes = [
|
||||
{ pattern: /^users$/, page: users, nav: "users" },
|
||||
{ pattern: /^account$/, page: account, nav: "account" },
|
||||
{ pattern: /^search$/, page: search, nav: "" },
|
||||
{ pattern: /^stats$/, page: stats, nav: "stats" },
|
||||
];
|
||||
|
||||
const navItems = [
|
||||
["dashboard", "#/", "Dashboard"],
|
||||
["stats", "#/stats", "Statistics"],
|
||||
["zones", "#/zones", "Zones"],
|
||||
["views", "#/views", "Views"],
|
||||
["acls", "#/acls", "ACLs"],
|
||||
|
||||
@@ -0,0 +1,333 @@
|
||||
// Small SVG charts for the statistics page: a line/area chart with a
|
||||
// crosshair tooltip, a weekday x hour heatmap, and bar lists. No library;
|
||||
// colors come from CSS custom properties (--series-N, --heat-N) so light
|
||||
// and dark themes are handled in style.css. All text is inserted as text,
|
||||
// never as markup.
|
||||
import { h } from "./ui.js";
|
||||
|
||||
const NS = "http://www.w3.org/2000/svg";
|
||||
|
||||
function svg(tag, attrs, ...children) {
|
||||
const el = document.createElementNS(NS, tag);
|
||||
for (const [k, v] of Object.entries(attrs || {})) {
|
||||
if (v !== undefined && v !== null && v !== false) el.setAttribute(k, v);
|
||||
}
|
||||
for (const c of children.flat(Infinity)) {
|
||||
if (c === null || c === undefined || c === false) continue;
|
||||
el.append(c instanceof Node ? c : document.createTextNode(String(c)));
|
||||
}
|
||||
return el;
|
||||
}
|
||||
|
||||
// compact formats a count: 1,234 / 12.9K / 4.2M.
|
||||
export function compact(n) {
|
||||
const a = Math.abs(n);
|
||||
if (a >= 1e9) return (n / 1e9).toFixed(a >= 1e10 ? 0 : 1).replace(/\.0$/, "") + "B";
|
||||
if (a >= 1e6) return (n / 1e6).toFixed(a >= 1e7 ? 0 : 1).replace(/\.0$/, "") + "M";
|
||||
if (a >= 1e4) return (n / 1e3).toFixed(a >= 1e5 ? 0 : 1).replace(/\.0$/, "") + "K";
|
||||
return Math.round(n).toLocaleString();
|
||||
}
|
||||
|
||||
// niceTicks returns 0..max in clean steps (1, 2 or 5 x 10^k), at most n+1 ticks.
|
||||
export function niceTicks(max, n = 4) {
|
||||
if (max <= 0) return [0, 1];
|
||||
const raw = max / n;
|
||||
const mag = Math.pow(10, Math.floor(Math.log10(raw)));
|
||||
const step = [1, 2, 5, 10].map((m) => m * mag).find((s) => s >= raw);
|
||||
const ticks = [];
|
||||
for (let v = 0; v < max + step * 0.999; v += step) ticks.push(Math.round(v * 1e6) / 1e6);
|
||||
return ticks;
|
||||
}
|
||||
|
||||
const MIN = 60, HOUR = 3600, DAY = 86400;
|
||||
const tickSteps = [5 * MIN, 10 * MIN, 15 * MIN, 30 * MIN, HOUR, 2 * HOUR, 3 * HOUR, 6 * HOUR, 12 * HOUR, DAY, 2 * DAY, 7 * DAY, 14 * DAY, 30 * DAY];
|
||||
|
||||
// timeTicks picks local-time-aligned ticks between t0 and t1 (Unix seconds).
|
||||
function timeTicks(t0, t1, maxTicks) {
|
||||
const span = t1 - t0;
|
||||
const step = tickSteps.find((s) => span / s <= maxTicks) || 30 * DAY;
|
||||
const out = [];
|
||||
const d = new Date(t0 * 1000);
|
||||
if (step >= DAY) {
|
||||
d.setHours(0, 0, 0, 0);
|
||||
} else {
|
||||
d.setSeconds(0, 0);
|
||||
const mins = d.getHours() * 60 + d.getMinutes();
|
||||
const stepMin = step / 60;
|
||||
d.setHours(0, Math.floor(mins / stepMin) * stepMin, 0, 0);
|
||||
}
|
||||
for (let t = d.getTime() / 1000; t <= t1; ) {
|
||||
if (t >= t0) out.push(t);
|
||||
if (step >= DAY) {
|
||||
const nd = new Date(t * 1000);
|
||||
nd.setDate(nd.getDate() + step / DAY);
|
||||
t = nd.getTime() / 1000;
|
||||
} else t += step;
|
||||
}
|
||||
return { ticks: out, step };
|
||||
}
|
||||
|
||||
const weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
function tickLabel(t, step) {
|
||||
const d = new Date(t * 1000);
|
||||
if (step >= DAY) return step >= 7 * DAY ? months[d.getMonth()] + " " + d.getDate() : weekdays[d.getDay()] + " " + d.getDate();
|
||||
const hm = pad(d.getHours()) + ":" + pad(d.getMinutes());
|
||||
return d.getHours() === 0 && d.getMinutes() === 0 ? weekdays[d.getDay()] + " " + d.getDate() : hm;
|
||||
}
|
||||
|
||||
// longTime describes a bucket for tooltips and tables.
|
||||
export function bucketLabel(t, stepSecs) {
|
||||
const d = new Date(t * 1000);
|
||||
const day = weekdays[d.getDay()] + " " + d.getDate() + " " + months[d.getMonth()];
|
||||
if (stepSecs >= DAY) return day;
|
||||
const end = new Date((t + stepSecs) * 1000);
|
||||
const hm = (x) => pad(x.getHours()) + ":" + pad(x.getMinutes());
|
||||
return day + ", " + hm(d) + (stepSecs > MIN ? "–" + hm(end) : "");
|
||||
}
|
||||
|
||||
export const stepSeconds = { "1m": MIN, "5m": 5 * MIN, "15m": 15 * MIN, "1h": HOUR, "6h": 6 * HOUR, "1d": DAY };
|
||||
|
||||
// tooltip is one floating readout per chart.
|
||||
function tooltip() {
|
||||
const el = h("div", { class: "chart-tip", role: "status" });
|
||||
el.hidden = true;
|
||||
return el;
|
||||
}
|
||||
|
||||
// chartCard wraps a chart with its title and a table-view toggle (the
|
||||
// accessible twin of every chart).
|
||||
export function chartCard(title, subtitle, chart, tableView, opts = {}) {
|
||||
const body = h("div", { class: "chart-body" }, chart);
|
||||
const tableBox = h("div", { class: "chart-table" }, tableView);
|
||||
tableBox.hidden = true;
|
||||
const toggle = h("button", { class: "small link", type: "button", "aria-pressed": "false" }, "Table");
|
||||
toggle.addEventListener("click", () => {
|
||||
const showTable = tableBox.hidden;
|
||||
tableBox.hidden = !showTable;
|
||||
body.hidden = showTable;
|
||||
toggle.textContent = showTable ? "Chart" : "Table";
|
||||
toggle.setAttribute("aria-pressed", String(showTable));
|
||||
});
|
||||
return h("figure", { class: "panel chart-card" + (opts.wide ? " wide" : "") },
|
||||
h("figcaption", { class: "chart-head" },
|
||||
h("div", { class: "grow" }, h("h2", null, title), subtitle ? h("div", { class: "muted small" }, subtitle) : null),
|
||||
opts.legend || null,
|
||||
tableView ? toggle : null),
|
||||
body, tableBox);
|
||||
}
|
||||
|
||||
// legend lists series with a short line key (the mark the series uses).
|
||||
export function legend(series) {
|
||||
return h("ul", { class: "chart-legend" }, series.map((s) =>
|
||||
h("li", null, h("span", { class: "key line s" + s.slot }), s.label)));
|
||||
}
|
||||
|
||||
// lineChart draws series over time. series: [{label, values, slot}] (slot
|
||||
// = categorical color 1..3); times: bucket starts (Unix seconds); step in
|
||||
// seconds. With area, the first series gets a 10% wash under its line.
|
||||
export function lineChart({ series, times, step, area = false, height = 220, endLabels = true }) {
|
||||
const root = h("div", { class: "chart", tabindex: "0", "aria-label": series.map((s) => s.label).join(", ") + " over time" });
|
||||
const tip = tooltip();
|
||||
root.append(tip);
|
||||
let width = 0, focusIdx = -1, geom = null;
|
||||
|
||||
function draw() {
|
||||
const w = root.clientWidth;
|
||||
if (!w || w === width) return;
|
||||
width = w;
|
||||
root.querySelector("svg")?.remove();
|
||||
const max = Math.max(1, ...series.flatMap((s) => s.values));
|
||||
const yTicks = niceTicks(max, 4);
|
||||
const yMax = yTicks[yTicks.length - 1];
|
||||
const labelW = Math.max(...yTicks.map((t) => compact(t).length)) * 7 + 10;
|
||||
const endW = endLabels && series.length > 1 && series.length <= 4 ? Math.max(...series.map((s) => s.label.length)) * 7 + 12 : 8;
|
||||
const m = { top: 10, right: endW, bottom: 24, left: labelW };
|
||||
const pw = Math.max(40, w - m.left - m.right), ph = height - m.top - m.bottom;
|
||||
const t0 = times[0], t1 = times[times.length - 1] + step;
|
||||
const x = (t) => m.left + ((t - t0) / Math.max(1, t1 - t0)) * pw;
|
||||
const cx = (i) => x(times[i] + step / 2); // the middle of a bucket
|
||||
const y = (v) => m.top + ph - (v / yMax) * ph;
|
||||
const s = svg("svg", { width: w, height, viewBox: `0 0 ${w} ${height}`, role: "img", "aria-hidden": "true" });
|
||||
// Grid and axes.
|
||||
for (const t of yTicks) {
|
||||
s.append(svg("line", { class: t === 0 ? "axis" : "grid", x1: m.left, x2: m.left + pw, y1: y(t), y2: y(t) }));
|
||||
s.append(svg("text", { class: "tick", x: m.left - 6, y: y(t) + 4, "text-anchor": "end" }, compact(t)));
|
||||
}
|
||||
const { ticks, step: tstep } = timeTicks(t0, t1, Math.max(2, Math.floor(pw / 90)));
|
||||
for (const t of ticks) {
|
||||
s.append(svg("text", { class: "tick", x: x(t), y: height - 6, "text-anchor": "middle" }, tickLabel(t, tstep)));
|
||||
}
|
||||
// Series.
|
||||
series.forEach((sr, k) => {
|
||||
const pts = sr.values.map((v, i) => [cx(i), y(v)]);
|
||||
const d = pts.map((p, i) => (i ? "L" : "M") + p[0].toFixed(1) + " " + p[1].toFixed(1)).join("");
|
||||
if (area && k === 0 && pts.length) {
|
||||
s.append(svg("path", { class: "area s" + sr.slot, d: d + `L${pts[pts.length - 1][0].toFixed(1)} ${y(0)}L${pts[0][0].toFixed(1)} ${y(0)}Z` }));
|
||||
}
|
||||
s.append(svg("path", { class: "line s" + sr.slot, d }));
|
||||
if (pts.length === 1) s.append(svg("circle", { class: "dot s" + sr.slot, cx: pts[0][0], cy: pts[0][1], r: 4 }));
|
||||
});
|
||||
// Direct end labels when there is room and they don't collide.
|
||||
if (m.right > 8) {
|
||||
const ends = series.map((sr) => ({ label: sr.label, y: y(sr.values[sr.values.length - 1] || 0) })).sort((a, b) => a.y - b.y);
|
||||
if (ends.every((e, i) => i === 0 || e.y - ends[i - 1].y >= 13)) {
|
||||
for (const e of ends) s.append(svg("text", { class: "end-label", x: m.left + pw + 6, y: e.y + 4 }, e.label));
|
||||
}
|
||||
}
|
||||
// Crosshair (drawn on hover/focus).
|
||||
const cross = svg("line", { class: "crosshair", y1: m.top, y2: m.top + ph, visibility: "hidden" });
|
||||
const dots = series.map((sr) => svg("circle", { class: "dot s" + sr.slot, r: 4, visibility: "hidden" }));
|
||||
s.append(cross, ...dots);
|
||||
// The hit area is the whole plot: readers aim at a time, not a line.
|
||||
const hit = svg("rect", { class: "hit", x: m.left, y: m.top, width: pw, height: ph });
|
||||
s.append(hit);
|
||||
root.prepend(s);
|
||||
geom = { cx, y, m, pw, ph, cross, dots, hit };
|
||||
hit.addEventListener("pointermove", (e) => {
|
||||
const r = s.getBoundingClientRect();
|
||||
const px = e.clientX - r.left;
|
||||
const i = Math.round(((px - m.left) / pw) * (times.length) - 0.5);
|
||||
show(Math.max(0, Math.min(times.length - 1, i)));
|
||||
});
|
||||
hit.addEventListener("pointerleave", hide);
|
||||
if (focusIdx >= 0) show(focusIdx);
|
||||
}
|
||||
|
||||
function show(i) {
|
||||
if (!geom) return;
|
||||
focusIdx = i;
|
||||
const xpos = geom.cx(i);
|
||||
geom.cross.setAttribute("x1", xpos);
|
||||
geom.cross.setAttribute("x2", xpos);
|
||||
geom.cross.setAttribute("visibility", "visible");
|
||||
series.forEach((sr, k) => {
|
||||
geom.dots[k].setAttribute("cx", xpos);
|
||||
geom.dots[k].setAttribute("cy", geom.y(sr.values[i]));
|
||||
geom.dots[k].setAttribute("visibility", "visible");
|
||||
});
|
||||
tip.replaceChildren(
|
||||
h("div", { class: "tip-head" }, bucketLabel(times[i], step)),
|
||||
...series.map((sr) => h("div", { class: "tip-row" },
|
||||
h("span", { class: "key line s" + sr.slot }), h("strong", null, sr.values[i].toLocaleString()), " ", h("span", { class: "muted" }, sr.label))));
|
||||
tip.hidden = false;
|
||||
// Keep the readout inside the chart, on the far side of the pointer.
|
||||
const left = xpos > root.clientWidth / 2 ? xpos - tip.offsetWidth - 12 : xpos + 12;
|
||||
tip.style.left = Math.max(0, left) + "px";
|
||||
tip.style.top = geom.m.top + "px";
|
||||
}
|
||||
|
||||
function hide() {
|
||||
if (!geom) return;
|
||||
geom.cross.setAttribute("visibility", "hidden");
|
||||
geom.dots.forEach((d) => d.setAttribute("visibility", "hidden"));
|
||||
tip.hidden = true;
|
||||
focusIdx = -1;
|
||||
}
|
||||
|
||||
// Keyboard: arrows move the crosshair, as hover does.
|
||||
root.addEventListener("focus", () => show(focusIdx >= 0 ? focusIdx : times.length - 1));
|
||||
root.addEventListener("blur", hide);
|
||||
root.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
show(Math.max(0, Math.min(times.length - 1, (focusIdx < 0 ? times.length - 1 : focusIdx) + (e.key === "ArrowLeft" ? -1 : 1))));
|
||||
}
|
||||
});
|
||||
new ResizeObserver(draw).observe(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
// timeTable is the table view of a line chart (busiest buckets first is
|
||||
// not useful here: keep time order, newest first).
|
||||
export function timeTable(series, times, step) {
|
||||
const rows = times.map((t, i) => ({ t, i })).reverse();
|
||||
return h("div", { class: "table-wrap scroll" }, h("table", null,
|
||||
h("thead", null, h("tr", null, h("th", null, "Time"), series.map((s) => h("th", { class: "num" }, s.label)))),
|
||||
h("tbody", null, rows.map((r) => h("tr", null, h("td", null, bucketLabel(r.t, step)),
|
||||
series.map((s) => h("td", { class: "num" }, s.values[r.i].toLocaleString())))))));
|
||||
}
|
||||
|
||||
// heatmap draws average activity by weekday (rows, Monday first) and hour
|
||||
// (columns) with a sequential one-hue ramp; cells without data stay empty.
|
||||
export function heatmap(hm, unit) {
|
||||
const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
|
||||
let peak = 0;
|
||||
hm.avg.forEach((row) => row.forEach((v) => { peak = Math.max(peak, v); }));
|
||||
const steps = 7;
|
||||
const level = (v) => (peak <= 0 ? 0 : Math.min(steps - 1, Math.floor((v / peak) * steps)));
|
||||
const tip = tooltip();
|
||||
const grid = h("div", { class: "heatmap", role: "grid", "aria-label": "Average " + unit + " per hour by weekday and hour of day" });
|
||||
grid.append(h("div", { class: "hm-corner" }));
|
||||
for (let hr = 0; hr < 24; hr++) grid.append(h("div", { class: "hm-col" }, hr % 3 === 0 ? pad(hr) : ""));
|
||||
days.forEach((day, d) => {
|
||||
grid.append(h("div", { class: "hm-row" }, day));
|
||||
for (let hr = 0; hr < 24; hr++) {
|
||||
const v = hm.avg[d][hr];
|
||||
const n = hm.samples[d][hr];
|
||||
const text = v < 0 ? day + " " + pad(hr) + ":00 – no data" :
|
||||
day + " " + pad(hr) + ":00 – " + Math.round(v).toLocaleString() + " " + unit + " per hour (average of " + n + (n === 1 ? " hour)" : " hours)");
|
||||
const cell = h("div", { class: "hm-cell " + (v < 0 ? "empty" : "heat-" + level(v)), tabindex: "-1", "aria-label": text });
|
||||
const showTip = () => {
|
||||
tip.textContent = text;
|
||||
tip.hidden = false;
|
||||
const r = cell.getBoundingClientRect(), pr = grid.getBoundingClientRect();
|
||||
tip.style.left = Math.max(0, Math.min(pr.width - tip.offsetWidth, r.left - pr.left - tip.offsetWidth / 2 + r.width / 2)) + "px";
|
||||
tip.style.top = (r.bottom - pr.top + 6) + "px";
|
||||
};
|
||||
cell.addEventListener("pointerenter", showTip);
|
||||
cell.addEventListener("focus", showTip);
|
||||
cell.addEventListener("pointerleave", () => { tip.hidden = true; });
|
||||
cell.addEventListener("blur", () => { tip.hidden = true; });
|
||||
grid.append(cell);
|
||||
}
|
||||
});
|
||||
// Arrow keys move between cells.
|
||||
grid.tabIndex = 0;
|
||||
let cur = -1;
|
||||
const cells = () => [...grid.querySelectorAll(".hm-cell")];
|
||||
grid.addEventListener("keydown", (e) => {
|
||||
const delta = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -24, ArrowDown: 24 }[e.key];
|
||||
if (delta === undefined) return;
|
||||
e.preventDefault();
|
||||
cur = Math.max(0, Math.min(7 * 24 - 1, (cur < 0 ? 0 : cur) + delta));
|
||||
cells()[cur].focus();
|
||||
});
|
||||
const scale = h("div", { class: "hm-scale" },
|
||||
h("span", { class: "muted small" }, "0"),
|
||||
Array.from({ length: steps }, (_, i) => h("span", { class: "hm-swatch heat-" + i })),
|
||||
h("span", { class: "muted small" }, compact(peak) + " " + unit + "/hour"),
|
||||
h("span", { class: "hm-swatch empty" }), h("span", { class: "muted small" }, "no data"));
|
||||
return h("div", { class: "heatmap-wrap" }, grid, tip, scale);
|
||||
}
|
||||
|
||||
export function heatmapTable(hm, unit) {
|
||||
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
|
||||
return h("div", { class: "table-wrap scroll" }, h("table", null,
|
||||
h("thead", null, h("tr", null, h("th", null, "Hour"), days.map((d) => h("th", { class: "num" }, d)))),
|
||||
h("tbody", null, Array.from({ length: 24 }, (_, hr) => h("tr", null, h("td", null, pad(hr) + ":00"),
|
||||
days.map((_, d) => h("td", { class: "num" }, hm.avg[d][hr] < 0 ? "–" : Math.round(hm.avg[d][hr]).toLocaleString())))))),
|
||||
h("div", { class: "muted small" }, "Average " + unit + " per hour."));
|
||||
}
|
||||
|
||||
// barList shows ranked entries as labelled horizontal bars in one hue
|
||||
// (one series: no legend, the title names it). Values are always printed,
|
||||
// so the list is its own table view.
|
||||
export function barList(entries, { total, label = (k) => k, empty = "No data yet.", href } = {}) {
|
||||
if (!entries.length) return h("div", { class: "empty" }, empty);
|
||||
// Entries may be in a natural order (e.g. latency buckets), not by size.
|
||||
const peak = Math.max(1, ...entries.map((e) => e.count));
|
||||
const sum = total || entries.reduce((a, e) => a + e.count, 0);
|
||||
return h("ol", { class: "bar-list" }, entries.map((e) => {
|
||||
const share = sum ? (e.count / sum) * 100 : 0;
|
||||
const name = label(e.key);
|
||||
const link = href ? href(e.key) : null;
|
||||
return h("li", { title: name + ": " + e.count.toLocaleString() + " (" + share.toFixed(1) + "%)" },
|
||||
h("div", { class: "bar-text" },
|
||||
link ? h("a", { href: link, class: "bar-label" }, name) : h("span", { class: "bar-label" }, name),
|
||||
h("span", { class: "bar-value" }, compact(e.count), h("span", { class: "muted" }, " · " + share.toFixed(share < 10 ? 1 : 0) + "%"))),
|
||||
h("div", { class: "bar-track" }, h("div", { class: "bar-fill", style: { width: Math.max(0.5, (e.count / peak) * 100) + "%" } })));
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { h, mount, fmtTime, errorBox } from "../ui.js";
|
||||
import { get } from "../api.js";
|
||||
import { lineChart, chartCard, legend, timeTable, heatmap, heatmapTable, barList, compact, stepSeconds } from "../charts.js";
|
||||
|
||||
const ranges = [["1h", "1 hour"], ["6h", "6 hours"], ["24h", "24 hours"], ["7d", "7 days"], ["30d", "30 days"], ["90d", "90 days"]];
|
||||
const rangeSecs = { "1h": 3600, "6h": 6 * 3600, "24h": 86400, "7d": 7 * 86400, "30d": 30 * 86400, "90d": 90 * 86400 };
|
||||
|
||||
// Failed answers keep the same color whatever the range: color follows
|
||||
// the result code, never its rank.
|
||||
const failures = [
|
||||
{ key: "rcode:NXDOMAIN", label: "NXDOMAIN", slot: 1 },
|
||||
{ key: "rcode:SERVFAIL", label: "SERVFAIL", slot: 2 },
|
||||
{ key: "rcode:REFUSED", label: "REFUSED", slot: 3 },
|
||||
];
|
||||
|
||||
const rttOrder = ["<10ms", "10-100ms", "100-500ms", "500-800ms", "800-1600ms", ">1600ms"];
|
||||
|
||||
let generation = 0;
|
||||
|
||||
export async function render(el, params, query) {
|
||||
const gen = ++generation;
|
||||
const want = query && query.get ? query.get("since") : null;
|
||||
const since = rangeSecs[want] ? want : "24h";
|
||||
const status = await get("/stats/status");
|
||||
const head = h("div", { class: "page-head" },
|
||||
h("div", { class: "grow" }, h("h1", null, "Statistics"),
|
||||
h("div", { class: "muted" }, status.enabled
|
||||
? "From named's counters" + (status.query_log ? " and response log" : "") + " · data since " + (status.first_data ? fmtTime(status.first_data) : "–") +
|
||||
" · kept: minutes " + status.retention.minute + ", hours " + status.retention.hour + ", days " + status.retention.day
|
||||
: "Query statistics are off")));
|
||||
if (!status.enabled) {
|
||||
mount(el, head, disabledPanel());
|
||||
return;
|
||||
}
|
||||
const heatSince = rangeSecs[since] < 7 * 86400 ? "7d" : since;
|
||||
let data;
|
||||
try {
|
||||
data = await loadAll(since, heatSince, status.query_log);
|
||||
} catch (e) {
|
||||
mount(el, head, errorBox(e));
|
||||
return;
|
||||
}
|
||||
if (gen !== generation) return; // the user moved on
|
||||
const { summary: s, heat } = data;
|
||||
// The newest bucket is still filling up; drawing it would look like a
|
||||
// sudden drop in traffic.
|
||||
const timeline = complete(data.timeline), errors = complete(data.errors);
|
||||
const step = stepSeconds[timeline.step];
|
||||
const parts = [head, filterRow(since)];
|
||||
for (const w of status.warnings || []) parts.push(h("div", { class: "msg warn" }, w));
|
||||
|
||||
// Headline numbers.
|
||||
const rangeLabel = "in the last " + ranges.find((r) => r[0] === since)[1];
|
||||
parts.push(h("div", { class: "cards" },
|
||||
tile("Queries", compact(s.queries), rangeLabel),
|
||||
tile("Per second", s.avg_qps < 10 ? s.avg_qps.toFixed(2) : Math.round(s.avg_qps).toLocaleString(), "on average"),
|
||||
s.peak ? tile("Busiest " + s.peak.per, compact(s.peak.queries), fmtTime(s.peak.time)) : null,
|
||||
s.nxdomain_ratio != null ? tile("NXDOMAIN", pct(s.nxdomain_ratio), "of queries named no existing name") : null,
|
||||
s.cache_hit_ratio != null ? tile("Cache hits", pct(s.cache_hit_ratio), "of recursive queries answered from cache") : null));
|
||||
|
||||
// Volume over time: one series, so no legend box; the title names it.
|
||||
const q = timeline.series.find((x) => x.key === "queries") || { values: timeline.times.map(() => 0) };
|
||||
const qSeries = [{ label: "Queries", values: q.values, slot: 1 }];
|
||||
parts.push(chartCard("Queries", "per " + stepName(timeline.step) + ", " + rangeLabel,
|
||||
lineChart({ series: qSeries, times: timeline.times, step, area: true }), timeTable(qSeries, timeline.times, step), { wide: true }));
|
||||
|
||||
// Failed answers: three fixed series, legend plus end labels.
|
||||
const fSeries = failures.map((f) => ({ ...f, values: (errors.series.find((x) => x.key === f.key) || { values: errors.times.map(() => 0) }).values }));
|
||||
const anyFailures = fSeries.some((f) => f.values.some((v) => v > 0));
|
||||
parts.push(chartCard("Failed answers", "NXDOMAIN: the name doesn't exist · SERVFAIL: resolution failed · REFUSED: not allowed",
|
||||
anyFailures ? lineChart({ series: fSeries, times: errors.times, step: stepSeconds[errors.step] }) : h("div", { class: "empty" }, "No failed answers " + rangeLabel + "."),
|
||||
anyFailures ? timeTable(fSeries, errors.times, stepSeconds[errors.step]) : null,
|
||||
{ wide: true, legend: anyFailures ? legend(fSeries) : null }));
|
||||
|
||||
// When is the server busy?
|
||||
parts.push(chartCard("Busiest times", "average queries per hour by weekday and hour of day (local time), last " + ranges.find((r) => r[0] === heatSince)[1],
|
||||
heatmap(heat, "queries"), heatmapTable(heat, "queries"), { wide: true }));
|
||||
|
||||
// Who asks for what.
|
||||
if (status.query_log) {
|
||||
const t = data.tops;
|
||||
parts.push(h("div", { class: "chart-grid" },
|
||||
listCard("Most queried names", "", barList(t.name, { href: (k) => "#/search?q=" + encodeURIComponent(k) })),
|
||||
listCard("Busiest clients", "", barList(t.client)),
|
||||
listCard("Names that don't exist", "NXDOMAIN answers: typos, removed hosts, misconfigured clients, malware", barList(t.nxdomain, { empty: "None " + rangeLabel + "." })),
|
||||
listCard("Refused clients", "clients asking for something they may not have (often internet scanners)", barList(t.refused, { empty: "None " + rangeLabel + "." })),
|
||||
t.servfail.length ? listCard("Names that failed to resolve", "SERVFAIL answers", barList(t.servfail)) : null));
|
||||
} else {
|
||||
parts.push(h("div", { class: "msg info" }, "Top names and clients need the response log: set stats.query_log: true in /etc/jarl/jarl.yaml and restart jarl."));
|
||||
}
|
||||
|
||||
// Breakdowns.
|
||||
const b = data.breakdowns;
|
||||
const rtt = rttOrder.map((k) => b.rtt.find((e) => e.key === k)).filter(Boolean);
|
||||
parts.push(h("div", { class: "chart-grid" },
|
||||
listCard("Record types", "", barList(b.qtype, { total: s.queries })),
|
||||
listCard("Result codes", "", barList(b.rcode, { total: s.queries })),
|
||||
b.view.length > 1 || (b.view.length === 1 && b.view[0].key !== "_default") ? listCard("Views", "", barList(b.view, { label: viewLabel })) : null,
|
||||
b.zone.length ? listCard("Zones", "queries per local zone; other = names in no local zone (recursion)", barList(b.zone, { label: (k) => (k === "-" ? "other" : k), href: (k) => (k === "-" ? null : "#/search?q=" + encodeURIComponent(k)) })) : null,
|
||||
b.answer.length ? listCard("Answers", "authoritative (your zones) or recursive (from the cache or the internet)", barList(b.answer)) : null,
|
||||
rtt.length ? listCard("Upstream response time", "how long other servers took to answer named's recursive queries", barList(rtt)) : null));
|
||||
el.classList.remove("refreshing");
|
||||
mount(el, parts);
|
||||
scheduleRefresh(el, params, query, gen);
|
||||
}
|
||||
|
||||
async function loadAll(since, heatSince, queryLog) {
|
||||
const p = {
|
||||
summary: get("/stats/summary", { since, top: 0 }),
|
||||
timeline: get("/stats/timeline", { since, key: "queries" }),
|
||||
errors: get("/stats/timeline", { since, key: failures.map((f) => f.key).join(",") }),
|
||||
heat: get("/stats/heatmap", { since: heatSince }),
|
||||
};
|
||||
const groups = ["qtype", "rcode", "view", "zone", "answer", "rtt"];
|
||||
groups.forEach((g) => { p["b_" + g] = get("/stats/breakdown", { group: g, since }); });
|
||||
if (queryLog) {
|
||||
for (const k of ["name", "client", "nxdomain", "refused", "servfail"]) p["t_" + k] = get("/stats/top", { kind: k, since, limit: 15 });
|
||||
}
|
||||
const keys = Object.keys(p);
|
||||
const vals = await Promise.all(Object.values(p));
|
||||
const out = { breakdowns: {}, tops: {} };
|
||||
keys.forEach((k, i) => {
|
||||
if (k.startsWith("b_")) out.breakdowns[k.slice(2)] = vals[i];
|
||||
else if (k.startsWith("t_")) out.tops[k.slice(2)] = vals[i];
|
||||
else out[k] = vals[i];
|
||||
});
|
||||
return out;
|
||||
}
|
||||
|
||||
// scheduleRefresh reloads the page's data every minute while it is shown,
|
||||
// keeping the current render (dimmed) until the new one is ready.
|
||||
function scheduleRefresh(el, params, query, gen) {
|
||||
setTimeout(() => {
|
||||
if (gen !== generation || !location.hash.startsWith("#/stats") || !el.isConnected) return;
|
||||
el.classList.add("refreshing");
|
||||
render(el, params, query).catch(() => el.classList.remove("refreshing"));
|
||||
}, 60_000);
|
||||
}
|
||||
|
||||
// complete drops the last bucket of a timeline if it hasn't ended yet.
|
||||
function complete(tl) {
|
||||
const step = stepSeconds[tl.step];
|
||||
const n = tl.times.length;
|
||||
if (n > 1 && tl.times[n - 1] + step > Date.now() / 1000) {
|
||||
return { ...tl, times: tl.times.slice(0, -1), series: tl.series.map((x) => ({ ...x, values: x.values.slice(0, -1) })) };
|
||||
}
|
||||
return tl;
|
||||
}
|
||||
|
||||
function filterRow(since) {
|
||||
return h("div", { class: "filter-row", role: "group", "aria-label": "Time range" },
|
||||
h("span", { class: "muted" }, "Range"),
|
||||
h("div", { class: "segmented" }, ranges.map(([k, label]) =>
|
||||
h("a", { href: "#/stats?since=" + k, class: k === since ? "active" : "", "aria-current": k === since ? "true" : null, title: "last " + label }, k))));
|
||||
}
|
||||
|
||||
function tile(label, value, sub) {
|
||||
return h("div", { class: "card stat" }, h("div", { class: "label" }, label), h("div", { class: "value big" }, value), h("div", { class: "sub" }, sub));
|
||||
}
|
||||
|
||||
function listCard(title, subtitle, body) {
|
||||
return h("section", { class: "panel" }, h("h2", null, title), subtitle ? h("div", { class: "muted small list-sub" }, subtitle) : null, body);
|
||||
}
|
||||
|
||||
function pct(r) {
|
||||
const p = r * 100;
|
||||
return (p < 10 ? p.toFixed(1) : Math.round(p)) + "%";
|
||||
}
|
||||
|
||||
function stepName(step) {
|
||||
return { "1m": "minute", "5m": "5 minutes", "15m": "15 minutes", "1h": "hour", "6h": "6 hours", "1d": "day" }[step] || step;
|
||||
}
|
||||
|
||||
function viewLabel(k) {
|
||||
return k === "_default" ? "(no view)" : k;
|
||||
}
|
||||
|
||||
function disabledPanel() {
|
||||
return h("div", { class: "panel" },
|
||||
h("h2", null, "Turn on query statistics"),
|
||||
h("p", null, "Jarl can show how many queries named answers over time, the busiest hours, the most queried names and the clients asking most. " +
|
||||
"It is off by default. To turn it on, add this to /etc/jarl/jarl.yaml on the server and restart jarl (sudo systemctl restart jarl):"),
|
||||
h("pre", { class: "code" }, "stats:\n enabled: true"),
|
||||
h("p", { class: "muted" }, "Jarl then makes named publish its counters on a local statistics channel and log responses to /var/log/named, and keeps aggregates " +
|
||||
"(never individual queries) in a separate database, by default for 7 days per minute, 90 days per hour and 2 years per day. See docs/stats.md."));
|
||||
}
|
||||
@@ -232,3 +232,114 @@ button:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.form-grid .help { grid-column: 1; }
|
||||
header.top form.search input { width: 140px; }
|
||||
}
|
||||
|
||||
/* ---- Statistics charts. Colors from the validated reference palette
|
||||
(categorical slots 1-3, sequential blue), checked against this UI's
|
||||
panel surfaces in both themes. */
|
||||
:root {
|
||||
--series-1: #2a78d6;
|
||||
--series-2: #eb6834;
|
||||
--series-3: #1baf7a;
|
||||
--chart-grid: #eceef2;
|
||||
--chart-axis: #c9cfd8;
|
||||
/* Sequential ramp, low to high (blue 100 -> 700). */
|
||||
--heat-0: #cde2fb; --heat-1: #9ec5f4; --heat-2: #6da7ec; --heat-3: #3987e5;
|
||||
--heat-4: #256abf; --heat-5: #184f95; --heat-6: #0d366b;
|
||||
}
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-theme="light"]) {
|
||||
--series-1: #3987e5;
|
||||
--series-2: #d95926;
|
||||
--series-3: #199e70;
|
||||
--chart-grid: #272c34;
|
||||
--chart-axis: #3a414d;
|
||||
/* In dark, low values recede into the surface: the ramp runs dark -> light. */
|
||||
--heat-0: #0d366b; --heat-1: #184f95; --heat-2: #256abf; --heat-3: #3987e5;
|
||||
--heat-4: #6da7ec; --heat-5: #9ec5f4; --heat-6: #cde2fb;
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"] {
|
||||
--series-1: #3987e5;
|
||||
--series-2: #d95926;
|
||||
--series-3: #199e70;
|
||||
--chart-grid: #272c34;
|
||||
--chart-axis: #3a414d;
|
||||
--heat-0: #0d366b; --heat-1: #184f95; --heat-2: #256abf; --heat-3: #3987e5;
|
||||
--heat-4: #6da7ec; --heat-5: #9ec5f4; --heat-6: #cde2fb;
|
||||
}
|
||||
|
||||
.refreshing { opacity: 0.6; transition: opacity 0.2s; }
|
||||
.filter-row { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-bottom: 12px; }
|
||||
.segmented { display: inline-flex; border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; background: var(--panel); }
|
||||
.segmented a { padding: 4px 12px; color: var(--text); border-right: 1px solid var(--border); text-decoration: none; font-variant-numeric: tabular-nums; }
|
||||
.segmented a:last-child { border-right: none; }
|
||||
.segmented a:hover { background: var(--info-soft); }
|
||||
.segmented a.active { background: var(--accent); color: var(--accent-text); font-weight: 600; }
|
||||
.card.stat .value.big { font-size: 26px; font-weight: 600; line-height: 1.2; }
|
||||
|
||||
.chart-card { margin: 0 0 14px; }
|
||||
.chart-head { display: flex; align-items: flex-start; gap: 12px; flex-wrap: wrap; margin-bottom: 8px; }
|
||||
.chart-head .grow { flex: 1; min-width: 200px; }
|
||||
.chart-head h2 { margin: 0; font-size: 16px; }
|
||||
.chart-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 0 14px; }
|
||||
.chart-grid > .panel h2 { margin: 0; font-size: 16px; }
|
||||
.list-sub { margin: 2px 0 8px; }
|
||||
|
||||
.chart { position: relative; outline: none; }
|
||||
.chart:focus-visible { box-shadow: 0 0 0 2px var(--accent); border-radius: var(--radius); }
|
||||
.chart svg { display: block; overflow: visible; }
|
||||
.chart .grid { stroke: var(--chart-grid); stroke-width: 1; }
|
||||
.chart .axis { stroke: var(--chart-axis); stroke-width: 1; }
|
||||
.chart .tick, .chart .end-label { fill: var(--muted); font-size: 11px; font-variant-numeric: tabular-nums; }
|
||||
.chart .end-label { fill: var(--text); }
|
||||
.chart .line { fill: none; stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
|
||||
.chart .area { stroke: none; fill-opacity: 0.1; }
|
||||
.chart .dot { stroke: var(--panel); stroke-width: 2; }
|
||||
.chart .crosshair { stroke: var(--muted); stroke-width: 1; }
|
||||
.chart .hit { fill: transparent; cursor: crosshair; }
|
||||
.chart .s1, .key.s1 { stroke: var(--series-1); }
|
||||
.chart .s2, .key.s2 { stroke: var(--series-2); }
|
||||
.chart .s3, .key.s3 { stroke: var(--series-3); }
|
||||
.chart .area.s1, .chart .dot.s1 { fill: var(--series-1); }
|
||||
.chart .area.s2, .chart .dot.s2 { fill: var(--series-2); }
|
||||
.chart .area.s3, .chart .dot.s3 { fill: var(--series-3); }
|
||||
.key.line { display: inline-block; width: 14px; height: 0; border-top: 2px solid; vertical-align: middle; margin-right: 6px; }
|
||||
.key.line.s1 { border-color: var(--series-1); }
|
||||
.key.line.s2 { border-color: var(--series-2); }
|
||||
.key.line.s3 { border-color: var(--series-3); }
|
||||
.chart-legend { list-style: none; display: flex; gap: 14px; margin: 2px 0 0; padding: 0; font-size: 13px; color: var(--text); flex-wrap: wrap; }
|
||||
|
||||
.chart-tip { position: absolute; z-index: 5; pointer-events: none; background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius);
|
||||
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.16); padding: 6px 10px; font-size: 13px; white-space: nowrap; }
|
||||
.chart-tip .tip-head { color: var(--muted); font-size: 12px; margin-bottom: 2px; }
|
||||
.chart-tip .tip-row strong { font-variant-numeric: tabular-nums; }
|
||||
.chart-table .scroll, .chart-table .table-wrap { max-height: 360px; overflow: auto; }
|
||||
td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
|
||||
|
||||
.heatmap-wrap { position: relative; }
|
||||
.heatmap { display: grid; grid-template-columns: 36px repeat(24, minmax(10px, 1fr)); gap: 2px; outline: none; }
|
||||
.heatmap:focus-visible { box-shadow: 0 0 0 2px var(--accent); }
|
||||
.hm-corner, .hm-col, .hm-row { font-size: 11px; color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.hm-row { display: flex; align-items: center; }
|
||||
.hm-cell { height: 22px; border-radius: 3px; }
|
||||
.hm-cell:hover, .hm-cell:focus { outline: 2px solid var(--text); outline-offset: -1px; }
|
||||
.hm-cell.empty, .hm-swatch.empty { background: transparent; box-shadow: inset 0 0 0 1px var(--chart-grid); }
|
||||
.heat-0 { background: var(--heat-0); } .heat-1 { background: var(--heat-1); } .heat-2 { background: var(--heat-2); }
|
||||
.heat-3 { background: var(--heat-3); } .heat-4 { background: var(--heat-4); } .heat-5 { background: var(--heat-5); }
|
||||
.heat-6 { background: var(--heat-6); }
|
||||
.hm-scale { display: flex; align-items: center; gap: 2px; margin-top: 10px; flex-wrap: wrap; }
|
||||
.hm-scale .muted { margin: 0 6px; }
|
||||
.hm-swatch { display: inline-block; width: 18px; height: 10px; border-radius: 2px; }
|
||||
|
||||
.bar-list { list-style: none; margin: 0; padding: 0; }
|
||||
.bar-list li { padding: 4px 0; }
|
||||
.bar-text { display: flex; gap: 8px; justify-content: space-between; font-size: 13px; }
|
||||
.bar-label { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--mono); font-size: 12.5px; min-width: 0; }
|
||||
.bar-value { white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||
.bar-track { height: 6px; margin-top: 3px; }
|
||||
.bar-fill { height: 6px; background: var(--series-1); border-radius: 0 3px 3px 0; min-width: 2px; }
|
||||
@media (max-width: 700px) {
|
||||
.heatmap { grid-template-columns: 30px repeat(24, minmax(6px, 1fr)); gap: 1px; }
|
||||
.hm-cell { height: 16px; }
|
||||
.chart-grid { grid-template-columns: 1fr; }
|
||||
}
|
||||
Reference in new issue
Block a user