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>
This commit is contained in:
commit
54a765510a
63 changed files with 6464 additions and 0 deletions
35
app/static/js/views/blocked.js
Normal file
35
app/static/js/views/blocked.js
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// Blocked domains: AdGuard's top blocked list plus what was blocked recently, and for whom.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ago, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root) {
|
||||
const ui = screen(root, [el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'), el('span.spacer'), el('a.btn', { href: '/queries?status=blocked' }, 'Blocked queries in the log')]);
|
||||
async function load() {
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const b = await get('/api/dns/blocked');
|
||||
fill(ui.body,
|
||||
el('p.lede', {}, b.num_queries ? `AdGuard Home blocked ${num(b.num_blocked)} of ${num(b.num_queries)} queries (${pct(b.num_blocked / b.num_queries, 1)}) in its stats period.` : 'No AdGuard stats yet.'),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Recently blocked', b.since ? `${num(b.sample)} blocked queries since ${when(b.since)}` : ''),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }, 'Clients', 'Last'],
|
||||
b.recent.map((r) => el('tr', {},
|
||||
el('td', {}, domainLink(r.domain), r.rule ? el('div.small.muted.mono', {}, r.rule) : null),
|
||||
el('td.num', {}, num(r.count)),
|
||||
el('td', {}, el('div', { style: 'display:grid;gap:2px' }, ...r.clients.slice(0, 4).map((c) => clientLink(c.ip, c.device)),
|
||||
r.clients.length > 4 ? el('span.small.muted', {}, `+${r.clients.length - 4} more`) : null)),
|
||||
el('td.nowrap', {}, ago(r.last)))), { empty: 'Nothing blocked recently.' })),
|
||||
el('div', {}, section('Most blocked', 'AdGuard stats period'),
|
||||
table(['Domain', { text: 'Times', props: { class: 'num' } }],
|
||||
b.top.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' }))),
|
||||
);
|
||||
ui.setStatus(`${b.recent.length} domains blocked recently`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
200
app/static/js/views/clients.js
Normal file
200
app/static/js/views/clients.js
Normal file
|
|
@ -0,0 +1,200 @@
|
|||
// Clients: every device seen, your labels for it, and one client's DNS activity.
|
||||
import { confirmDialog, debounce, el, store, toast } from '../ui.js';
|
||||
import { del, get, put } from '../api.js';
|
||||
import { ago, ms, num, when } from '../fmt.js';
|
||||
import { adguardProblem, domainLink, errorBox, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
const SOURCE = { arp: 'Probe ARP', dhcp: 'DHCP lease', dns: 'DNS queries', adguard: 'AdGuard client' };
|
||||
const sourceName = (s) => SOURCE[s] || (s.startsWith('adguard-') ? `AdGuard ${s.slice(8)}` : s);
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : list(root, ctx);
|
||||
}
|
||||
|
||||
function list(root) {
|
||||
const f = store.get('client-filters', { q: '', cat: '', sus: false, online: false });
|
||||
const q = el('input.input', { type: 'search', value: f.q, placeholder: 'Name, IP or MAC', 'aria-label': 'Search clients' });
|
||||
const cat = el('select.select', { 'aria-label': 'Category' }, el('option', { value: '' }, 'All categories'));
|
||||
const sus = el('input', { type: 'checkbox', checked: f.sus });
|
||||
const online = el('input', { type: 'checkbox', checked: f.online });
|
||||
const ui = screen(root, [
|
||||
q, cat,
|
||||
el('label.check', {}, sus, 'Suspicious only'),
|
||||
el('label.check', {}, online, 'Active now'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
let data = null;
|
||||
|
||||
const save = () => store.set('client-filters', { q: q.value, cat: cat.value, sus: sus.checked, online: online.checked });
|
||||
const redraw = debounce(() => { save(); draw(); }, 120);
|
||||
for (const c of [q, cat, sus, online]) c.addEventListener('input', redraw);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
data = await get('/api/clients');
|
||||
if (cat.options.length === 1) {
|
||||
cat.append(...data.categories.map((c) => el('option', { value: c }, c)), el('option', { value: '-' }, 'No category'));
|
||||
cat.value = f.cat;
|
||||
}
|
||||
draw();
|
||||
} catch (err) {
|
||||
fill(ui.body, errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function draw() {
|
||||
const needle = q.value.trim().toLowerCase();
|
||||
const rows = data.clients.filter((c) =>
|
||||
(!needle || [c.display, c.hostname, c.ip, c.mac, c.name].some((v) => v && v.toLowerCase().includes(needle))) &&
|
||||
(!cat.value || (cat.value === '-' ? !c.category : c.category === cat.value)) &&
|
||||
(!sus.checked || c.suspicious) && (!online.checked || c.online));
|
||||
rows.sort((a, b) => (b.suspicious - a.suspicious) || ((b.queries || 0) - (a.queries || 0)) || a.display.localeCompare(b.display));
|
||||
const empty = data.clients.length
|
||||
? 'No clients match these filters.'
|
||||
: data.adguard ? 'No clients yet. They appear within a minute of AdGuard Home or a probe seeing them.'
|
||||
: 'No clients yet. Connect AdGuard Home (ADGUARD_URL in the hub’s .env) or add a probe; probes report the devices in their ARP table.';
|
||||
fill(ui.body, table(
|
||||
['Client', 'Category', 'IP', 'MAC', { text: 'Queries', props: { class: 'num', title: 'AdGuard Home stats period' } }, 'Last active', 'Seen by'],
|
||||
rows.map((c) => el(`tr${c.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, el('span.chips', {},
|
||||
el('a', { href: `/clients/${encodeURIComponent(c.key)}` }, el('strong', {}, c.display)),
|
||||
c.name && c.hostname && c.name !== c.hostname ? el('span.muted.small', {}, c.hostname) : null,
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null,
|
||||
c.new ? el('span.chip.new', { title: `First seen ${when(c.first_seen)}` }, 'New') : null)),
|
||||
el('td', {}, c.category || el('span.muted', {}, '—')),
|
||||
el('td.mono', {}, c.ip || '—'),
|
||||
el('td.mono', {}, c.mac || '—'),
|
||||
el('td.num', {}, num(c.queries)),
|
||||
el('td.nowrap', { title: when(c.last_seen) }, c.online ? el('span.chip.ok', {}, 'Active') : ago(c.last_seen)),
|
||||
el('td.small.muted', {}, c.sources.map(sourceName).join(', ')))),
|
||||
{ empty }));
|
||||
const n = data.clients;
|
||||
ui.setStatus(`${rows.length} of ${n.length} clients · ${n.filter((c) => c.online).length} active in the last 10 min · ${n.filter((c) => c.suspicious).length} suspicious`);
|
||||
}
|
||||
|
||||
load();
|
||||
const t = setInterval(() => { if (!document.hidden) load(); }, 60000);
|
||||
return () => { clearInterval(t); redraw.flush(); };
|
||||
}
|
||||
|
||||
function detail(root, ctx, key) {
|
||||
const ui = screen(root, [
|
||||
el('button.btn.primary', { type: 'submit', form: 'client-form' }, 'Save changes'),
|
||||
el('a.btn', { href: `/queries?client=${encodeURIComponent(key)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn.danger', { type: 'button', onclick: () => forget() }, 'Forget client'),
|
||||
]);
|
||||
let c = null;
|
||||
let cursor = '';
|
||||
const qbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => loadQueries() }, 'Load older');
|
||||
const qwrap = el('div');
|
||||
const summary = el('div');
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
c = await get(`/api/clients/${encodeURIComponent(key)}`);
|
||||
ctx.setTitle(c.display);
|
||||
render();
|
||||
ui.setStatus(`${c.online ? 'Active now' : `Last active ${ago(c.last_seen)}`} · first seen ${when(c.first_seen)}`);
|
||||
loadSummary();
|
||||
loadQueries(true);
|
||||
} catch (err) {
|
||||
fill(ui.body, err.status === 404 ? el('div.empty', {}, 'No client with this id. It may have been merged into another entry once its MAC address was learned.', el('div', {}, el('a.btn', { href: '/clients' }, 'All clients'))) : errorBox(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
|
||||
function render() {
|
||||
const name = el('input.input', { id: 'c-name', value: c.name, maxlength: 80, placeholder: c.hostname || c.ip || '' });
|
||||
const category = el('select.select', { id: 'c-cat' }, el('option', { value: '' }, 'No category'), ...c.categories.map((x) => el('option', { value: x }, x)));
|
||||
if (c.category && !c.categories.includes(c.category)) category.append(el('option', { value: c.category }, c.category));
|
||||
category.value = c.category;
|
||||
const suspicious = el('input', { type: 'checkbox', id: 'c-sus', checked: c.suspicious });
|
||||
const notes = el('textarea.textarea', { id: 'c-notes', rows: 3, maxlength: 2000, placeholder: 'Who owns it, why it is flagged…' });
|
||||
notes.value = c.notes;
|
||||
const form = el('form.form-grid', { id: 'client-form', onsubmit: async (e) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
c = { ...c, ...(await put(`/api/clients/${encodeURIComponent(key)}`, { name: name.value, category: category.value, suspicious: suspicious.checked, notes: notes.value })) };
|
||||
ctx.setTitle(c.display);
|
||||
title.replaceWith(title = titleRow());
|
||||
toast('Changes saved');
|
||||
} catch (ex) { toast(ex.message, 'error'); }
|
||||
} },
|
||||
el('div.field', {}, el('label', { for: 'c-name' }, 'Name'), name, el('div.hint', {}, 'Shown everywhere instead of the hostname.')),
|
||||
el('div.field', {}, el('label', { for: 'c-cat' }, 'Category'), category),
|
||||
el('div.field.wide', {}, el('label.check', {}, suspicious, 'Suspicious: highlight this client in lists and query results')),
|
||||
el('div.field.wide', {}, el('label', { for: 'c-notes' }, 'Notes'), notes));
|
||||
const titleRow = () => el('div.title-row', {}, el('h2', {}, c.display),
|
||||
c.suspicious ? el('span.chip.danger', {}, 'Suspicious') : null, c.category ? el('span.chip', {}, c.category) : null,
|
||||
c.online ? el('span.chip.ok', {}, 'Active') : null);
|
||||
let title = titleRow();
|
||||
fill(ui.body,
|
||||
title,
|
||||
el('div.cols', { style: 'margin-top:12px' },
|
||||
el('dl.kv', {},
|
||||
el('dt', {}, 'IP address'), el('dd.mono', {}, c.ips.join(', ') || '—'),
|
||||
el('dt', {}, 'MAC address'), el('dd.mono', {}, c.mac || 'Unknown (no probe or DHCP lease has seen it)'),
|
||||
el('dt', {}, 'Hostname'), el('dd', {}, c.hostname || '—'),
|
||||
el('dt', {}, 'Queries'), el('dd', {}, c.queries == null ? '—' : `${num(c.queries)} in AdGuard’s stats period`),
|
||||
el('dt', {}, 'Seen by'), el('dd', {}, c.sources.map(sourceName).join(', ') || '—'),
|
||||
el('dt', {}, 'First seen'), el('dd', {}, when(c.first_seen)),
|
||||
el('dt', {}, 'Last active'), el('dd', {}, c.last_seen ? `${ago(c.last_seen)} (${when(c.last_seen)})` : '—')),
|
||||
form),
|
||||
summary,
|
||||
section('DNS requests', 'Newest first'),
|
||||
qwrap,
|
||||
);
|
||||
}
|
||||
|
||||
async function loadSummary() {
|
||||
summary.replaceChildren(section('Most requested domains'), el('div.loading', {}, 'Reading the query log…'));
|
||||
try {
|
||||
const s = await get(`/api/clients/${encodeURIComponent(key)}/summary`);
|
||||
summary.replaceChildren(
|
||||
section('Most requested domains', s.sample ? `From its last ${num(s.sample)} queries${s.since ? `, since ${when(s.since)}` : ''} · ${num(s.blocked)} blocked` : ''),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
s.top.map((d) => el('tr', {}, el('td', {}, domainLink(d.domain)), el('td.num', {}, num(d.count)), el('td.num', {}, d.blocked ? num(d.blocked) : '')),
|
||||
), { empty: 'No DNS queries from this client in the AdGuard query log.' }));
|
||||
} catch (err) {
|
||||
summary.replaceChildren(section('Most requested domains'), adguardProblem(err));
|
||||
}
|
||||
}
|
||||
|
||||
async function loadQueries(reset = false) {
|
||||
if (reset) { cursor = ''; qbody.replaceChildren(); }
|
||||
more.disabled = true;
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { client: key, older_than: cursor, limit: 100 });
|
||||
cursor = r.oldest;
|
||||
qbody.append(...r.rows.map((q) => el(`tr${q.blocked ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, `${when(q.ts)}`),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!qbody.children.length) qwrap.replaceChildren(el('div.callout', {}, 'No DNS queries from this client in the AdGuard query log.'));
|
||||
else if (reset || !qwrap.querySelector('table')) qwrap.replaceChildren(
|
||||
el('div.table-wrap', {}, el('table.table', {}, el('thead', {}, el('tr', {}, ...['Time', 'Domain', 'Type', 'Result', 'Response'].map((h) => el('th', {}, h)))), qbody)),
|
||||
el('div.more', {}, more));
|
||||
more.hidden = r.done || !cursor;
|
||||
} catch (err) {
|
||||
qwrap.replaceChildren(adguardProblem(err));
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function forget() {
|
||||
if (!c) return;
|
||||
const ok = await confirmDialog(`Forget ${c.display}?`, 'Its name, category, flag and notes are deleted. If the device is still on the network it comes back as a new client.', 'Forget client');
|
||||
if (!ok) return;
|
||||
try { await del(`/api/clients/${encodeURIComponent(key)}`); toast(`Forgot ${c.display}`); ctx.navigate('/clients'); }
|
||||
catch (e) { toast(e.message, 'error'); }
|
||||
}
|
||||
|
||||
load();
|
||||
}
|
||||
107
app/static/js/views/domains.js
Normal file
107
app/static/js/views/domains.js
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
// Domains: the most requested and most blocked, and one domain's detail.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { seriesLegend, stackedBars, hideTip } from '../charts.js';
|
||||
import { ago, hm, ms, num, pct, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, section, table, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
return ctx.rest ? detail(root, ctx, decodeURIComponent(ctx.rest)) : overview(root, ctx);
|
||||
}
|
||||
|
||||
function openBox(ctx) {
|
||||
const input = el('input.input', { type: 'search', placeholder: 'example.com', 'aria-label': 'Domain to open' });
|
||||
const form = el('form', { style: 'display:contents', onsubmit: (e) => {
|
||||
e.preventDefault();
|
||||
const d = input.value.trim().toLowerCase().replace(/^https?:\/\//, '').split('/')[0];
|
||||
if (d) ctx.navigate(`/domains/${encodeURIComponent(d)}`);
|
||||
} }, input, el('button.btn', { type: 'submit' }, 'Open domain'));
|
||||
return form;
|
||||
}
|
||||
|
||||
function overview(root, ctx) {
|
||||
const ui = screen(root, [openBox(ctx), el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh')]);
|
||||
async function load() {
|
||||
try {
|
||||
const d = await get('/api/domains');
|
||||
const list = (rows) => table(['Domain', { text: 'Requests', props: { class: 'num' } }],
|
||||
rows.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)))), { empty: 'Nothing yet.' });
|
||||
fill(ui.body, el('div.cols', {},
|
||||
el('div', {}, section('Most requested'), list(d.top_queried)),
|
||||
el('div', {}, section('Most blocked'), list(d.top_blocked))));
|
||||
ui.setStatus(`${num(d.num_queries)} queries · ${num(d.num_blocked)} blocked in AdGuard’s stats period`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
}
|
||||
}
|
||||
load();
|
||||
}
|
||||
|
||||
function detail(root, ctx, name) {
|
||||
ctx.setTitle(name);
|
||||
const ui = screen(root, [
|
||||
openBox(ctx),
|
||||
el('a.btn', { href: `/queries?domain=${encodeURIComponent(name)}` }, 'Open in query log'),
|
||||
el('span.spacer'),
|
||||
el('button.btn', { type: 'button', onclick: () => load() }, 'Refresh'),
|
||||
]);
|
||||
async function load() {
|
||||
ui.body.classList.add('stale');
|
||||
ui.setStatus('Reading the query log…');
|
||||
try {
|
||||
const d = await get(`/api/domains/${encodeURIComponent(name)}`);
|
||||
render(d);
|
||||
ui.setStatus(`Based on ${num(d.sample_rows)} queries for *.${d.base}${d.since ? ` since ${when(d.since)}` : ''}${d.complete ? ' (the whole AdGuard log)' : ''}`);
|
||||
} catch (err) {
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
ui.body.classList.remove('stale');
|
||||
}
|
||||
}
|
||||
|
||||
function render(d) {
|
||||
const now = Date.now() / 1000;
|
||||
const hourLabel = (i, full) => {
|
||||
const t = now - (23 - i) * 3600;
|
||||
return full ? `${hm(t - 3600)} – ${hm(t)}` : i === 23 ? 'now' : `${23 - i} h ago`;
|
||||
};
|
||||
fill(ui.body,
|
||||
el('div.title-row', {}, el('h2', {}, d.domain),
|
||||
d.blocked ? el('span.chip.danger', {}, d.blocked === d.count ? 'Always blocked' : 'Sometimes blocked') : d.count ? el('span.chip.ok', {}, 'Allowed') : null,
|
||||
d.domain !== d.base ? el('a.chip', { href: `/domains/${encodeURIComponent(d.base)}` }, `part of ${d.base}`) : null),
|
||||
el('div.facts', {},
|
||||
fact('Requests', num(d.count), 'in the sample below'),
|
||||
fact('Blocked', d.count ? `${num(d.blocked)} (${pct(d.blocked / d.count)})` : '—'),
|
||||
fact('Clients', num(d.clients.length)),
|
||||
fact('Avg response', ms(d.avg_ms)),
|
||||
fact('Last request', d.last ? ago(d.last) : '—'),
|
||||
d.stats_count != null ? fact('AdGuard stats', num(d.stats_count), 'top-domain count for its stats period') : null),
|
||||
d.count ? el('div', {},
|
||||
section('Last 24 hours', 'Requests per hour'),
|
||||
seriesLegend([{ name: 'Allowed', color: 'var(--viz-1)' }, { name: 'Blocked', color: 'var(--viz-2)' }], 'box'),
|
||||
stackedBars({ n: 24, xLabel: hourLabel, height: 150, label: `Requests per hour for ${d.domain}`,
|
||||
series: [{ name: 'Allowed', color: 'var(--viz-1)', values: d.hours.map((h, i) => h - d.blocked_hours[i]) },
|
||||
{ name: 'Blocked', color: 'var(--viz-2)', values: d.blocked_hours }] })) : el('div.callout', { style: 'margin-top:12px' }, `No requests for ${d.domain} in the sample. Related domains under ${d.base} are below.`),
|
||||
el('div.cols', {},
|
||||
el('div', {}, section('Clients requesting it'),
|
||||
table(['Client', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }, 'Last'],
|
||||
d.clients.map((c) => el(`tr${c.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td', {}, clientLink(c.ip, c.device, c.name)), el('td.num', {}, num(c.count)), el('td.num', {}, c.blocked ? num(c.blocked) : ''),
|
||||
el('td.nowrap', {}, ago(c.last)))), { empty: 'No clients in the sample.' })),
|
||||
el('div', {}, section(`Other names under ${d.base}`, 'Same domain, different subdomains'),
|
||||
table(['Domain', { text: 'Requests', props: { class: 'num' } }, { text: 'Blocked', props: { class: 'num' } }],
|
||||
d.related.map((r) => el('tr', {}, el('td', {}, domainLink(r.domain)), el('td.num', {}, num(r.count)), el('td.num', {}, r.blocked ? num(r.blocked) : ''))),
|
||||
{ empty: 'No other names under this domain in the sample.' }))),
|
||||
d.rules.length ? el('div', {}, section('Matching rules'), el('ul.mono', {}, ...d.rules.map(([r, n]) => el('li', {}, `${r} ×${n}`)))) : null,
|
||||
section('Recent requests'),
|
||||
table(['Time', 'Client', 'Type', 'Result', { text: 'Response', props: { class: 'num' } }],
|
||||
d.recent.map((q) => el('tr', {}, el('td.nowrap', {}, when(q.ts)), el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.mono', {}, q.type), el('td', {}, resultChip(q)), el('td.num', {}, ms(q.elapsed_ms)))), { empty: 'None in the sample.' }),
|
||||
);
|
||||
}
|
||||
const fact = (label, value, title) => el('div.fact', { title: title || '' }, el('span.label', {}, label), el('strong', {}, value));
|
||||
load();
|
||||
return hideTip;
|
||||
}
|
||||
130
app/static/js/views/health.js
Normal file
130
app/static/js/views/health.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
// 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(); };
|
||||
}
|
||||
253
app/static/js/views/probes.js
Normal file
253
app/static/js/views/probes.js
Normal file
|
|
@ -0,0 +1,253 @@
|
|||
// 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 } 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) {
|
||||
const hub = info.hub_url || location.origin;
|
||||
return `curl -fsSL ${info.install_url} | HUB_URL=${hub} PROBE_TOKEN=${token} bash`;
|
||||
}
|
||||
|
||||
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', {}, 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 starts on boot and keeps running. On Linux hosts it uses Docker (installed if needed). On macOS and inside Proxmox LXC containers it installs natively as a system service; there, Linux needs root: put sudo env before HUB_URL.'),
|
||||
commandBlock(cmd),
|
||||
el('p.small.muted', { style: 'margin:0' }, `The probe reports to ${info.hub_url || location.origin}. If that address isn't reachable from the probe, change HUB_URL in the command. The command is also on the probe's page.`),
|
||||
), { 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', {}, 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}.` }),
|
||||
);
|
||||
}
|
||||
|
||||
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(); };
|
||||
}
|
||||
67
app/static/js/views/queries.js
Normal file
67
app/static/js/views/queries.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
// The DNS query log from AdGuard Home, with search, result filter and client filter.
|
||||
import { debounce, el, segmented } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { ms, when } from '../fmt.js';
|
||||
import { adguardProblem, clientLink, domainLink, resultChip, screen, fill } from '../common.js';
|
||||
|
||||
export function mount(root, ctx) {
|
||||
const params = ctx.query;
|
||||
let status = params.get('status') || 'all';
|
||||
const client = params.get('client') || '';
|
||||
const ip = params.get('ip') || '';
|
||||
const domain = params.get('domain') || '';
|
||||
const search = el('input.input', { type: 'search', value: params.get('q') || '', placeholder: 'Domain or client', 'aria-label': 'Search queries' });
|
||||
const seg = segmented([['all', 'All'], ['blocked', 'Blocked'], ['allowed', 'Allowed']], status, (v) => { status = v; sync(); load(true); }, 'Result');
|
||||
const filterChip = client || ip || domain
|
||||
? el('span.chip.accent', {}, `${client ? 'Client' : ip ? 'IP' : 'Domain'}: ${client || ip || domain} `,
|
||||
el('a', { href: '/queries', 'aria-label': 'Clear filter', style: 'color:inherit;text-decoration:none' }, '✕'))
|
||||
: null;
|
||||
const ui = screen(root, [search, seg, filterChip, el('span.spacer'), el('button.btn', { type: 'button', onclick: () => load(true) }, 'Refresh')]);
|
||||
const tbody = el('tbody');
|
||||
const more = el('button.btn', { type: 'button', onclick: () => load() }, 'Load older');
|
||||
let cursor = '', count = 0, seq = 0;
|
||||
|
||||
function sync() {
|
||||
const u = new URLSearchParams(location.search);
|
||||
search.value ? u.set('q', search.value) : u.delete('q');
|
||||
status !== 'all' ? u.set('status', status) : u.delete('status');
|
||||
history.replaceState({}, '', `/queries${u.size ? `?${u}` : ''}`);
|
||||
}
|
||||
search.addEventListener('input', debounce(() => { sync(); load(true); }, 350));
|
||||
|
||||
async function load(reset = false) {
|
||||
const my = ++seq;
|
||||
if (reset) { cursor = ''; count = 0; }
|
||||
more.disabled = true;
|
||||
ui.setStatus('Loading…');
|
||||
try {
|
||||
const r = await get('/api/dns/queries', { search: search.value.trim(), status, client, ip, domain, older_than: cursor, limit: 100 });
|
||||
if (my !== seq) return;
|
||||
if (reset) tbody.replaceChildren();
|
||||
cursor = r.oldest;
|
||||
count += r.rows.length;
|
||||
tbody.append(...r.rows.map((q) => el(`tr${q.device?.suspicious ? '.flagged' : ''}`, {},
|
||||
el('td.nowrap', { title: q.time }, when(q.ts)),
|
||||
el('td', {}, clientLink(q.client, q.device, q.client_name)),
|
||||
el('td.domain', {}, domainLink(q.domain)),
|
||||
el('td.mono', {}, q.type),
|
||||
el('td', {}, resultChip(q)),
|
||||
el('td.num', {}, ms(q.elapsed_ms)))));
|
||||
if (!ui.body.querySelector('table')) {
|
||||
fill(ui.body, el('div.table-wrap', {}, el('table.table', {},
|
||||
el('thead', {}, el('tr', {}, ...['Time', 'Client', 'Domain', 'Type', 'Result', { t: 'Response', c: 'num' }].map((h) => el('th', h.c ? { class: h.c } : {}, h.t || h)))), tbody)),
|
||||
el('div.more', {}, more));
|
||||
}
|
||||
if (!count) fill(ui.body, el('div.empty', {}, 'No queries match.'));
|
||||
more.hidden = r.done || !cursor;
|
||||
ui.setStatus(`${count} queries${r.done ? ' · end of the AdGuard log' : ''}`);
|
||||
} catch (err) {
|
||||
if (my !== seq) return;
|
||||
fill(ui.body, adguardProblem(err));
|
||||
ui.setStatus(err.message, 'error');
|
||||
} finally {
|
||||
more.disabled = false;
|
||||
}
|
||||
}
|
||||
load(true);
|
||||
}
|
||||
42
app/static/js/views/settings.js
Normal file
42
app/static/js/views/settings.js
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
// Settings: what the hub is configured to do. Values live in the hub's .env.
|
||||
import { el } from '../ui.js';
|
||||
import { get } from '../api.js';
|
||||
import { num } from '../fmt.js';
|
||||
|
||||
export async function mount(root) {
|
||||
const intro = el('p.muted', {}, 'These come from the hub’s .env file.');
|
||||
const page = el('div.page', {}, el('h1', {}, 'Settings'), intro);
|
||||
root.append(page);
|
||||
try {
|
||||
const [i, dns] = await Promise.all([get('/api/info'), get('/api/dns/status')]);
|
||||
intro.textContent = `These come from ${i.env_file} on the hub (${i.install_mode} install). Edit that file, then restart the hub to apply: ${i.install_mode === 'docker' ? 'docker restart network-monitor' : 'sudo systemctl restart network-monitor (macOS: sudo launchctl kickstart -k system/dev.neilbantoc.network-monitor)'}. Deploy new code with ${i.update_command}.`;
|
||||
const row = (k, v, env) => [el('dt', {}, k), el('dd', {}, v, env ? el('span.muted.small.mono', {}, ` ${env}`) : null)];
|
||||
const list = (xs) => (xs.length ? xs.join(', ') : 'none');
|
||||
page.append(
|
||||
el('h2', {}, 'AdGuard Home'),
|
||||
el('dl.kv', {},
|
||||
...row('Status', dns.ok ? el('span.chip.ok', {}, `Connected · ${dns.version}`) : el('span.chip.danger', {}, dns.configured ? 'Not reachable' : 'Not set up')),
|
||||
...(dns.url ? row('Address', dns.url, 'ADGUARD_URL') : []),
|
||||
...(dns.ok ? [] : row('Problem', dns.message))),
|
||||
el('h2', {}, 'Probes'),
|
||||
el('dl.kv', {},
|
||||
...row('Report every', `${i.probe_interval} s`, 'PROBE_INTERVAL'),
|
||||
...row('LAN DNS servers', list(i.lan_dns_servers), 'LAN_DNS_SERVERS'),
|
||||
...row('Public DNS servers', list(i.dns_servers), 'DNS_SERVERS'),
|
||||
...row('DNS test name', i.dns_query_name, 'DNS_QUERY_NAME'),
|
||||
...row('Internet HTTP checks', list(i.wan_http_urls), 'WAN_HTTP_URLS'),
|
||||
...row('VPS', i.vps_url || 'none', 'VPS_URL'),
|
||||
...row('Throughput test', i.throughput_every ? `${num(i.throughput_bytes / 1e6)} MB from each peer every ${i.throughput_every} reports` : 'off', 'THROUGHPUT_EVERY, THROUGHPUT_BYTES')),
|
||||
el('h2', {}, 'Thresholds and storage'),
|
||||
el('dl.kv', {},
|
||||
...row('Slow on the LAN', `over ${i.thresholds.lan_ms} ms`, 'SLOW_LAN_MS'),
|
||||
...row('Slow to the internet', `over ${i.thresholds.wan_ms} ms`, 'SLOW_WAN_MS'),
|
||||
...row('Slow DNS', `over ${i.thresholds.dns_ms} ms`, 'SLOW_DNS_MS'),
|
||||
...row('Keep measurements', `${i.retention_days} days`, 'RETENTION_DAYS'),
|
||||
...row('Password', i.password ? 'On' : 'Off: anyone on the network can open this page', 'UI_PASSWORD'),
|
||||
...row('Version', i.version)),
|
||||
);
|
||||
} catch (err) {
|
||||
page.append(el('div.callout.error', {}, err.message));
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue