Probe: no access log, nothing written while reports get through. When the hub can't be reached, failed reports go to data/outage.jsonl and unsent results to data/backlog.jsonl (survives restarts). The first report that gets through uploads both and they are deleted. Hub: a probe that misses reports gets a "Not reporting" incident. When it reports again, the runs from its outage log become confirmed "Hub unreachable" incidents; the rest of the silence (probe off or restarting) is dropped. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
259 lines
14 KiB
JavaScript
259 lines
14 KiB
JavaScript
// Probes: the list, adding one (with its install command), and one probe's detail and charts.
|
||
import { confirmDialog, copyText, el, modal, segmented, store, toast } from '../ui.js';
|
||
import { del, get, patch, post } from '../api.js';
|
||
import { lineChart, seriesLegend, statusChip, statusLegend, strip, tipRow, tipTitle, hideTip, STATUS } from '../charts.js';
|
||
import { ago, axisTime, dur, mbps, ms, pct, when } from '../fmt.js';
|
||
import { RANGES, SPANS, every, errorBox, screen, section, table, fill, incidentChecks, incidentDetail, incidentTarget, incidentTypeText } from '../common.js';
|
||
|
||
const METHOD = { icmp: 'Ping', http: 'HTTP', dns: 'DNS', throughput: 'Throughput' };
|
||
|
||
export function mount(root, ctx) {
|
||
return ctx.rest ? detail(root, ctx, Number(ctx.rest)) : list(root, ctx);
|
||
}
|
||
|
||
function installCommand(info, token) {
|
||
// A .local name works in browsers but usually not inside Linux probes: use the hub's IP then.
|
||
const viaMdns = location.hostname.endsWith('.local');
|
||
const hub = info.hub_url || (viaMdns && info.hub_lan_url) || location.origin;
|
||
const url = info.install_url || `${hub}/install-probe.sh`;
|
||
return `curl -fsSL ${url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`;
|
||
}
|
||
|
||
const README = 'https://git.neilbantoc.dev/services/network-monitor#2-probes';
|
||
|
||
function commandBlock(cmd) {
|
||
const loopback = /^(localhost|127\.|\[::1\])/.test(location.hostname) && cmd.includes(location.origin);
|
||
return el('div', { style: 'display:grid;gap:6px' },
|
||
el('div.cmd', {}, el('pre.select-all', {}, cmd), el('button.btn', { type: 'button', onclick: () => copyText(cmd, 'Install command copied') }, 'Copy')),
|
||
loopback ? el('div.callout.error', {}, `You opened this page at ${location.host}, which other machines can't reach. Replace HUB_URL with the hub's LAN address, or set HUB_PUBLIC_URL in the hub's .env.`) : null);
|
||
}
|
||
|
||
function onlineChip(p) {
|
||
if (!p.last_seen) return el('span.chip', {}, 'Never reported');
|
||
return p.online ? el('span.chip.ok', {}, 'Reporting') : el('span.chip.danger', {}, 'Offline');
|
||
}
|
||
|
||
// ---------------------------------------------------------------- list
|
||
|
||
function list(root, ctx) {
|
||
const ui = screen(root, [
|
||
el('button.btn.primary', { type: 'button', onclick: () => addProbe() }, 'Add probe'),
|
||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||
]);
|
||
let info = null;
|
||
|
||
async function load() {
|
||
try {
|
||
info = await get('/api/probes');
|
||
const rows = info.probes.map((p) => el('tr', {},
|
||
el('td', {}, el('a', { href: `/probes/${p.id}` }, el('strong', {}, p.name))),
|
||
el('td', {}, onlineChip(p)),
|
||
el('td.mono', {}, p.address ? `${p.address}:${p.port || 8765}` : '—'),
|
||
el('td', {}, p.hostname || '—'),
|
||
el('td', {}, p.icmp == null ? '—' : p.icmp ? 'Yes' : el('span.chip.warn', { title: 'Run install-probe.sh again on that machine to enable ping' }, 'Not permitted')),
|
||
el('td.mono', {}, p.version || '—'),
|
||
el('td.nowrap', { title: when(p.last_seen) }, ago(p.last_seen)),
|
||
));
|
||
fill(ui.body,
|
||
el('p.lede', {}, 'Each probe tests every other probe (ping, HTTP and throughput), the gateway, DNS servers and the internet, then reports here.'),
|
||
table(['Name', 'Status', 'Address', 'Host', 'Ping', 'Version', 'Last report'], rows,
|
||
{ empty: 'No probes yet. Add one, then run its install command on a machine on the network.' }),
|
||
);
|
||
const off = info.probes.filter((p) => !p.online).length;
|
||
ui.setStatus(`${info.probes.length} probes · ${off} not reporting · they report every ${info.interval} s`, off ? 'error' : '');
|
||
} catch (err) {
|
||
fill(ui.body, errorBox(err));
|
||
ui.setStatus(err.message, 'error');
|
||
}
|
||
}
|
||
|
||
function addProbe() {
|
||
const name = el('input.input', { id: 'probe-name', required: true, maxlength: 60, placeholder: 'Living room', autocomplete: 'off' });
|
||
const err = el('div.error', { hidden: true });
|
||
const submit = el('button.btn.primary', { type: 'submit', form: 'add-probe' }, 'Add probe');
|
||
const form = el('form.field', { id: 'add-probe', onsubmit: async (e) => {
|
||
e.preventDefault();
|
||
submit.disabled = true;
|
||
try {
|
||
const p = await post('/api/probes', { name: name.value.trim() });
|
||
dlg.close();
|
||
showInstall(p);
|
||
load();
|
||
} catch (ex) {
|
||
err.textContent = ex.message; err.hidden = false; name.setAttribute('aria-invalid', 'true');
|
||
submit.disabled = false;
|
||
}
|
||
} }, el('label', { for: 'probe-name' }, 'Name'), name,
|
||
el('div.hint', {}, 'Where it sits, so the matrix reads well: Office, Garage, Upstairs AP.'), err);
|
||
const dlg = modal('Add a probe', form, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), submit] });
|
||
name.focus();
|
||
}
|
||
|
||
function showInstall(p) {
|
||
const cmd = installCommand(info, p.token);
|
||
const dlg = modal(`Install “${p.name}”`, el('div', { style: 'display:grid;gap:12px' },
|
||
el('p', { style: 'margin:0' }, 'Run this on the machine that will be the probe. It installs a service that starts on boot.'),
|
||
commandBlock(cmd),
|
||
el('p.small.muted', { style: 'margin:0' }, `Reports to ${(cmd.match(/HUB_URL=(\S+)/) || [])[1]}. The command is also on the probe’s page. `,
|
||
el('a', { href: README, target: '_blank', rel: 'noopener' }, 'Install notes')),
|
||
), { wide: true, footer: [el('a.btn', { href: `/probes/${p.id}`, onclick: () => dlg.close() }, 'Open probe'), el('button.btn.primary', { type: 'button', onclick: () => dlg.close() }, 'Done')] });
|
||
}
|
||
|
||
load();
|
||
if (ctx.query.get('add')) { history.replaceState({}, '', '/probes'); setTimeout(addProbe, 0); }
|
||
return every(30000, load);
|
||
}
|
||
|
||
// ---------------------------------------------------------------- detail
|
||
|
||
function detail(root, ctx, id) {
|
||
let range = store.get('probe-range', '24h');
|
||
const seg = segmented(RANGES, range, (v) => { range = v; store.set('probe-range', v); load(); }, 'Time range');
|
||
const ui = screen(root, [
|
||
seg,
|
||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||
el('span.spacer'),
|
||
el('button.btn', { type: 'button', onclick: () => rename() }, 'Rename'),
|
||
el('button.btn.danger', { type: 'button', onclick: () => remove() }, 'Remove probe'),
|
||
]);
|
||
let probe = null, listInfo = null;
|
||
|
||
async function load() {
|
||
ui.body.classList.add('stale');
|
||
try {
|
||
const [p, li, st, ser, inc] = await Promise.all([
|
||
get(`/api/probes/${id}`), get('/api/probes'),
|
||
get('/api/health/strips', { range, probe: id }), get('/api/health/series', { probe: id, range }),
|
||
get('/api/health/incidents', { range, probe: id, limit: 50 }),
|
||
]);
|
||
probe = p; listInfo = li;
|
||
ctx.setTitle(p.name);
|
||
render(st, ser, inc);
|
||
ui.setStatus(`${p.online ? 'Reporting' : 'Not reporting'} · last report ${ago(p.last_seen)} · ${inc.total} incidents in ${range}`, p.online ? '' : 'error');
|
||
} catch (err) {
|
||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'This probe was removed.', el('div', {}, el('a.btn', { href: '/probes' }, 'All probes'))) : errorBox(err));
|
||
ui.setStatus(err.message, 'error');
|
||
} finally {
|
||
ui.body.classList.remove('stale');
|
||
}
|
||
}
|
||
|
||
function render(st, ser, inc) {
|
||
const p = probe;
|
||
const addr = el('input.input', { value: p.address_locked ? p.address : '', placeholder: p.address ? `${p.address} (detected)` : 'detected from reports', 'aria-label': 'Address other probes use', style: 'max-width:260px' });
|
||
const saveAddr = el('button.btn.small', { type: 'button', onclick: async () => {
|
||
try { probe = await patch(`/api/probes/${id}`, { address: addr.value.trim() }); toast(addr.value.trim() ? 'Address saved' : 'Address will be detected again'); load(); }
|
||
catch (e) { toast(e.message, 'error'); }
|
||
} }, 'Save');
|
||
fill(ui.body,
|
||
el('div.title-row', {}, el('h2', {}, p.name), onlineChip(p)),
|
||
el('div.cols', {},
|
||
el('dl.kv', {},
|
||
el('dt', {}, 'Address'), el('dd', {}, el('span.chips', {}, addr, saveAddr)),
|
||
el('dt', {}, 'Port'), el('dd.mono', {}, String(p.port || 8765)),
|
||
el('dt', {}, 'Host'), el('dd', {}, p.hostname || '—'),
|
||
el('dt', {}, 'Ping'), el('dd', {}, p.icmp == null ? '—' : p.icmp ? 'Works' : 'Not permitted on this host. Run install-probe.sh again, which sets net.ipv4.ping_group_range.'),
|
||
el('dt', {}, 'Version'), el('dd.mono', {}, p.version || '—'),
|
||
el('dt', {}, 'Added'), el('dd', {}, when(p.created)),
|
||
el('dt', {}, 'Last report'), el('dd', {}, `${ago(p.last_seen)}${p.last_seen ? ` (${when(p.last_seen)})` : ''}`),
|
||
),
|
||
el('div', {},
|
||
el('div.label', { style: 'margin-bottom:6px' }, 'Install or reinstall'),
|
||
commandBlock(installCommand(listInfo, p.token)),
|
||
el('p.small.muted', {}, 'Leave Address empty to use what the probe reports. Set it when other probes must reach this one at a different address.')),
|
||
),
|
||
section('Timeline', `${range} in slices of ${dur(st.width)}`),
|
||
statusLegend(),
|
||
stripsFor(st),
|
||
section('Latency', 'Average per slice. Red ticks mark slices with failed checks.'),
|
||
seriesLegend([{ name: 'Ping', color: 'var(--viz-1)' }, { name: 'HTTP or DNS', color: 'var(--viz-2)' }]),
|
||
multiples(ser),
|
||
throughputChart(ser),
|
||
section('Incidents'),
|
||
table(['Started', 'Lasted', 'Target', 'Type', 'Checks', 'Detail'], inc.incidents.map((i) => el('tr', {},
|
||
el('td.nowrap', {}, when(i.start)),
|
||
el('td.nowrap', {}, i.ongoing ? el('span.chip.danger', {}, `Ongoing · ${dur(i.duration)}`) : dur(i.duration)),
|
||
el('td', {}, incidentTarget(i)),
|
||
el('td', {}, statusChip(i.type, incidentTypeText(i))),
|
||
el('td.num', {}, incidentChecks(i)),
|
||
el('td.small', {}, incidentDetail(i)))), { empty: `No incidents in the last ${range}.` }),
|
||
);
|
||
}
|
||
|
||
function stripsFor(st) {
|
||
if (!st.series.length) return el('div.callout', {}, `No measurements in the last ${range}.`);
|
||
const xt = axisTime(SPANS[range]);
|
||
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')),
|
||
...st.series.map((s) => el('div.strip-row', {},
|
||
el('span.name', { title: s.target }, s.label),
|
||
strip(s.buckets, (i, b) => [tipTitle(`${when(st.since + i * st.width)} – ${xt(st.since + (i + 1) * st.width)}`),
|
||
b ? tipRow(STATUS[b.s].label, `${b.n} checks${b.down ? ` · ${b.down} failed` : ''}${b.slow ? ` · ${b.slow} slow` : ''}`) : tipRow('No data', ''),
|
||
b?.latency != null ? tipRow(ms(b.latency), 'average') : null]),
|
||
el('span.uptime', {}, s.uptime == null ? '—' : `${s.uptime}%`))));
|
||
}
|
||
|
||
function multiples(ser) {
|
||
const xt = axisTime(SPANS[range]);
|
||
const xLabel = (i, full) => (full ? `${when(ser.since + i * ser.width)} – ${xt(ser.since + (i + 1) * ser.width)}` : xt(ser.since + (i + 0.5) * ser.width));
|
||
const cards = ser.targets.filter((t) => t.methods.icmp || t.methods.http || t.methods.dns).map((t) => {
|
||
const second = t.methods.http || t.methods.dns;
|
||
const series = [];
|
||
if (t.methods.icmp) series.push({ name: 'Ping', color: 'var(--viz-1)', values: t.methods.icmp.map((b) => b?.avg ?? null) });
|
||
if (second) series.push({ name: t.methods.http ? 'HTTP' : 'DNS', color: 'var(--viz-2)', values: second.map((b) => b?.avg ?? null) });
|
||
const methods = Object.entries(t.methods).filter(([m]) => m !== 'throughput');
|
||
const marks = Array.from({ length: ser.buckets }, (_, i) => methods.reduce((a, [, arr]) => a + (arr[i]?.failed || 0), 0));
|
||
return el('div.multiple', {},
|
||
el('h4', {}, t.label, el('span.chip', {}, t.kind === 'lan' ? 'LAN' : 'Internet')),
|
||
lineChart({ n: ser.buckets, xLabel, series, marks, fmt: ms, height: 140, label: `Latency to ${t.label}`,
|
||
describe: (i) => {
|
||
const out = [];
|
||
for (const [m, arr] of methods) {
|
||
const b = arr[i];
|
||
if (b?.failed) out.push(el('div.small.error-text', {}, `${METHOD[m]}: ${b.failed} of ${b.n} failed`));
|
||
if (m === 'icmp' && b?.loss) out.push(el('div.small', {}, `Ping loss ${pct(b.loss)}`));
|
||
}
|
||
return out;
|
||
} }));
|
||
});
|
||
return cards.length ? el('div.multiples', {}, ...cards) : el('div.callout', {}, `No latency data in the last ${range}.`);
|
||
}
|
||
|
||
function throughputChart(ser) {
|
||
const tp = ser.targets.filter((t) => t.methods.throughput);
|
||
if (!tp.length) return null;
|
||
const xt = axisTime(SPANS[range]);
|
||
const xLabel = (i, full) => (full ? when(ser.since + i * ser.width) : xt(ser.since + (i + 0.5) * ser.width));
|
||
return el('div', {},
|
||
section('Throughput to other probes', 'A timed download from each peer, every few minutes.'),
|
||
el('div.multiples', {}, ...tp.map((t) => el('div.multiple', {},
|
||
el('h4', {}, t.label),
|
||
lineChart({ n: ser.buckets, xLabel, fmt: mbps, height: 120, label: `Throughput from ${t.label}`,
|
||
series: [{ name: 'Throughput', color: 'var(--viz-1)', values: t.methods.throughput.map((b) => b?.mbps ?? null) }],
|
||
marks: t.methods.throughput.map((b) => b?.failed || 0) })))));
|
||
}
|
||
|
||
async function rename() {
|
||
const input = el('input.input', { value: probe?.name || '', maxlength: 60, 'aria-label': 'Name' });
|
||
const save = el('button.btn.primary', { type: 'button', onclick: async () => {
|
||
try { await patch(`/api/probes/${id}`, { name: input.value.trim() }); dlg.close(); toast('Renamed'); load(); }
|
||
catch (e) { toast(e.message, 'error'); }
|
||
} }, 'Save name');
|
||
const dlg = modal('Rename probe', input, { footer: [el('button.btn', { type: 'button', onclick: () => dlg.close() }, 'Cancel'), save] });
|
||
input.addEventListener('keydown', (e) => { if (e.key === 'Enter') save.click(); });
|
||
input.select();
|
||
}
|
||
|
||
async function remove() {
|
||
if (!probe) return;
|
||
const ok = await confirmDialog(`Remove ${probe.name}?`,
|
||
'Its history is deleted and its token stops working. The probe keeps running on its machine until you uninstall it there; the installer printed the uninstall command, and the README lists it.', 'Remove probe');
|
||
if (!ok) return;
|
||
try { await del(`/api/probes/${id}`); toast(`Removed ${probe.name}`); ctx.navigate('/probes'); }
|
||
catch (e) { toast(e.message, 'error'); }
|
||
}
|
||
|
||
load();
|
||
const stop = every(30000, load);
|
||
return () => { stop(); hideTip(); };
|
||
}
|