network-monitor/app/static/js/views/health.js
neil 54a765510a Network monitor: hub, probes, Docker and native installers
Hub (FastAPI + no-build web UI):
- Network health: live probe/target matrix, status strips, incidents
- Probes: add (with install command), rename, remove, latency and throughput charts
- Clients merged from AdGuard, DHCP, query log and probe ARP tables; names,
  categories, suspicious flag, notes, per-client DNS requests
- Query log, domain detail (clients, related subdomains), blocked domains via
  the AdGuard Home /control API

Probe: tests peers (ping, HTTP, throughput), gateway, LAN and public DNS,
internet URLs and an optional VPS; buffers results while the hub is down.
Gateway and ARP from /proc/net on Linux, route/arp on macOS.

Install: install.sh (hub) and install-probe.sh (generated from it), each in
docker mode (compose; default on Linux hosts) or native mode (venv + systemd
or launchd; default on macOS and in LXC). Both modes deploy with an update
command that checks the new commit and rolls back on failure.

CLAUDE.md carries shared context for Claude Code sessions on each machine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 18:10:29 -08:00

130 lines
7.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Network health: the live mesh matrix, status strips over time and the incident list.
import { el, segmented, store } from '../ui.js';
import { get } from '../api.js';
import { STATUS, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, showTip } from '../charts.js';
import { axisTime, dur, ms, pct, when } from '../fmt.js';
import { RANGES, SPANS, every, errorBox, screen, section, table, fill } from '../common.js';
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS' };
export function mount(root, ctx) {
let range = store.get('health-range', '24h');
const seg = segmented(RANGES, range, (v) => { range = v; store.set('health-range', v); load(); }, 'Time range');
const ui = screen(root, [
seg,
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
el('span.spacer'),
el('a.btn', { href: '/probes' }, 'Manage probes'),
]);
async function load() {
ui.body.classList.add('stale');
try {
const [mx, st, inc] = await Promise.all([
get('/api/health/matrix', { window: 300 }),
get('/api/health/strips', { range }),
get('/api/health/incidents', { range }),
]);
render(mx, st, inc);
const online = mx.probes.filter((p) => p.online).length;
const ongoing = inc.incidents.filter((i) => i.ongoing).length;
ui.setStatus(`${online} of ${mx.probes.length} probes reporting · ${inc.total} incidents in ${range}${ongoing ? ` · ${ongoing} ongoing` : ''} · updated ${new Date().toLocaleTimeString()}`,
ongoing ? 'error' : '');
} catch (err) {
fill(ui.body, errorBox(err));
ui.setStatus(`Couldn't load health: ${err.message}`, 'error');
} finally {
ui.body.classList.remove('stale');
}
}
function render(mx, st, inc) {
if (!mx.probes.length) {
fill(ui.body, el('div.empty', {},
el('p', {}, 'No probes yet. Probes are small containers on machines around the house that test the mesh and the internet link.'),
el('a.btn.primary', { href: '/probes?add=1' }, 'Add a probe')));
return;
}
fill(ui.body,
section('Right now', 'Last 5 minutes, per probe and target. Select a probe for its charts.'),
matrix(mx),
section('Timeline', `${range} in ${st.buckets} slices of ${dur(st.width)}. A slice is down when half its checks fail, degraded when a fifth are slow or failing.`),
statusLegend(),
strips(st),
section('Incidents', `Slow means over ${inc.thresholds.lan_ms} ms on the LAN, ${inc.thresholds.wan_ms} ms to the internet, ${inc.thresholds.dns_ms} ms for DNS, or ${pct(inc.thresholds.loss)}+ ping loss.`),
incidents(inc.incidents),
);
}
function matrix(mx) {
if (!mx.targets.length) return el('div.callout', {}, 'No measurements in the last 5 minutes. Probes report every 30 seconds or so; check that they are running.');
const byKey = new Map(mx.cells.map((c) => [`${c.probe_id}|${c.target}`, c]));
const rows = mx.probes.map((p) => el('tr', {},
el('th.row-head', {}, el('span.chips', {}, el('a', { href: `/probes/${p.id}` }, p.name), p.online ? null : el('span.chip.danger', {}, 'Offline'))),
...mx.targets.map((t) => {
const c = byKey.get(`${p.id}|${t.target}`);
if (!c) return el('td', {}, el('div.cell-empty', {}, t.target === `probe:${p.id}` ? 'self' : '—'));
const main = c.methods.icmp || c.methods.http || c.methods.dns;
const loss = c.methods.icmp?.loss;
const node = el(`a.cell.s-${c.status}`, { href: `/probes/${p.id}`, 'aria-label': `${p.name} to ${t.label}: ${STATUS[c.status].label}` },
el('strong', {}, main?.latency != null ? ms(main.latency) : STATUS[c.status].label),
el('span.muted', {}, [loss != null ? `${pct(loss)} loss` : null, c.status !== 'ok' ? STATUS[c.status].label : null].filter(Boolean).join(' · ') || 'OK'));
const tip = () => [tipTitle(`${p.name} → ${t.label}`),
...Object.entries(c.methods).map(([m, v]) => tipRow(v.latency != null ? ms(v.latency) : 'failed',
`${METHOD[m] || m} · ${STATUS[v.status].label}${v.down ? ` · ${v.down}/${v.n} failed` : ''}${v.loss ? ` · ${pct(v.loss)} loss` : ''}`)),
...Object.values(c.methods).filter((v) => v.error).slice(0, 1).map((v) => el('div.small.error-text', {}, v.error))];
node.addEventListener('pointerenter', (e) => showTip(e.clientX, e.clientY, tip()));
node.addEventListener('pointermove', (e) => showTip(e.clientX, e.clientY, tip()));
node.addEventListener('pointerleave', hideTip);
node.addEventListener('focus', () => { const r = node.getBoundingClientRect(); showTip(r.right, r.bottom, tip()); });
node.addEventListener('blur', hideTip);
return el('td', {}, node);
})));
return el('div.table-wrap', {}, el('table.table.matrix', {},
el('thead', {}, el('tr', {}, el('th', {}, 'From ↓ / to →'), ...mx.targets.map((t) => el('th', { title: t.target }, t.label)))),
el('tbody', {}, ...rows)));
}
function strips(st) {
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
const xt = axisTime(SPANS[range]);
const groups = new Map();
for (const s of st.series) {
if (!groups.has(s.probe_id)) groups.set(s.probe_id, []);
groups.get(s.probe_id).push(s);
}
const probe = new Map(st.probes.map((p) => [p.id, p]));
const describe = (s) => (i, b) => {
const t0 = st.since + i * st.width;
return [tipTitle(`${when(t0)} – ${xt(t0 + st.width)}`),
el('div', {}, el('strong', {}, `${probe.get(s.probe_id)?.name} → ${s.label}`)),
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`)
: tipRow('No data', 'no checks reported'),
b?.latency != null ? tipRow(ms(b.latency), 'average') : null];
};
return el('div.strips', {},
el('div.strip-axis', { 'aria-hidden': 'true' }, el('span'), el('span', {}, el('span', {}, xt(st.since)), el('span', {}, 'now')), el('span')),
...[...groups].map(([pid, list]) => el('div.strip-group', {},
el('h3', {}, el('a', { href: `/probes/${pid}` }, probe.get(pid)?.name || `Probe ${pid}`), probe.get(pid)?.online ? null : el('span.chip.danger', {}, 'Offline')),
...list.map((s) => el('div.strip-row', {},
el('span.name', { title: s.target }, s.label),
strip(s.buckets, describe(s)),
el('span.uptime', { title: 'Share of checks that succeeded' }, s.uptime == null ? '—' : `${s.uptime}%`))))));
}
function incidents(list) {
return table(['Started', 'Lasted', 'Probe', 'Target', 'Type', 'Checks', 'Detail'], list.map((i) => el('tr', {},
el('td.nowrap', { title: when(i.start) }, when(i.start)),
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
el('td', {}, el('a', { href: `/probes/${i.probe_id}` }, i.probe)),
el('td', {}, i.label, el('span.muted.small', {}, ` ${i.methods.map((m) => METHOD[m] || m).join(', ')}`)),
el('td', {}, statusChip(i.type)),
el('td.num', {}, i.failed ? `${i.failed}/${i.samples} failed` : `${i.samples} slow`),
el('td.small', {}, i.error || (i.max_latency ? `peak ${ms(i.max_latency)}` : '')),
)), { empty: `No incidents in the last ${range}.` });
}
load();
const stop = every(30000, load);
return () => { stop(); hideTip(); };
}