File size: 10,935 Bytes
bad179a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 | // Server Monitor (web): HTTP server for the page, live updates over Server-Sent Events and a small JSON API.
// Only reachable from this computer; see README.md for the security model.
const http = require('http'), fs = require('fs'), path = require('path');
const plat = require('./core/platform'), model = require('./core/model');
const { Manager, testConnection } = require('./core/session');
const { I, TIERS, STEP, stats, nowSec } = require('./core/history');
const { Fmt, H } = require('./public/shared');
const PORT = +process.env.PORT || 8765, ORIGINS = [`127.0.0.1:${PORT}`, `localhost:${PORT}`];
const PUBLIC = path.join(__dirname, 'public'), MIME = { html: 'text/html', js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml' };
const FILES = Object.fromEntries(fs.readdirSync(PUBLIC).map(f => ['/' + f.replace(/^index\.html$/, ''), f]));
const HEADERS = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Cross-Origin-Resource-Policy': 'same-origin',
'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'" };
const mgr = new Manager();
const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }); };
const sess = id => mgr.session(id) || fail('unknown server', 404);
const send = (res, status, body, type = 'application/json', extra) =>
res.writeHead(status, { ...HEADERS, 'Content-Type': type + '; charset=utf-8', ...extra }).end(type === 'application/json' ? JSON.stringify(body) : body);
// ---- what the page sees ----
const SUMMARY = ['hostname', 'os', 'kernel', 'cpuCount', 'memTotal', 'cpuUsage', 'memPct', 'maxDiskPct', 'swapPct', 'maxTemp', 'netRxBps', 'netTxBps', 'load1', 'uptime'];
const summary = s => ({ // sidebar row, dashboard card and detail header of one server
cfg: model.forPage(s.cfg), address: model.address(s.cfg), status: s.status, err: s.err, paused: s.paused, online: s.online, alerts: s.activeAlerts(),
m: { ...Object.fromEntries(SUMMARY.map(k => [k, s.m[k]])), procs: s.m.procs.length, temps: s.m.temps.length },
health: s.an.health, grade: s.an.grade, findings: s.an.findings.map(f => f.severity), spark: [0, 5].map(k => s.live.slice(-150).map(r => r.v[k])), // CPU, memory
});
const servers = () => mgr.sessions.map(summary);
const snapshot = () => ({ plat: plat.ui, dir: mgr.dir, rule: model.RULE, defaultRules: model.defaultRules(), alerts: mgr.alerts, servers: servers() });
const sample = (s, row) => ({ m: s.m, vals: model.metricValues(s.m), row });
// the stored points of a range (seconds back from now, 0 = everything) in the finest tier that covers it
function points(s, range) {
const now = nowSec(), from = +range ? now - range : Math.max(1, s.store.firstTs()), tier = s.store.tierFor(from, now);
return { now, from, tier, pts: s.store.range(from, now, tier) };
}
// History tab: chart series with gaps where nothing was recorded, statistics per metric
const SERIES = ['cpu', 'cpuMax', 'mem', 'swap', 'disk', 'rd', 'wr', 'rx', 'tx', 'rxMax', 'load', 'temp', 'tempMax', 'avail'];
function history(s, range) {
const { now, from, tier, pts } = points(s, range), step = Math.max(STEP[tier], s.cfg.interval), t = [], v = Object.fromEntries(SERIES.map(k => [k, []]));
const online = p => p.n ? p.nUp * 100 / p.n : 0, r2 = x => Math.round(x * 100) / 100;
let n = 0, up = 0;
const push = (ts, p) => { // p = null inserts a gap
t.push(ts * 1000);
for (const k of SERIES) v[k].push(!p ? null : k === 'avail' ? r2(online(p)) : !p.nUp ? null : r2((k.endsWith('Max') ? p.max : p.avg)[I[k.replace('Max', '')]]));
};
for (const p of pts) {
if (t.length && p.ts * 1000 - t.at(-1) > step * 3000) push(t.at(-1) / 1000 + step, null); // the monitor was not running
push(p.ts, p), n += p.n, up += p.nUp;
}
if (t.length && now * 1000 - t.at(-1) > step * 3000) push(now, null);
return { t, v, tier: TIERS[tier], aggregated: tier > 0, span: (now - from) * 1000, points: pts.length, availability: n ? up * 100 / n : null,
bytes: s.store.diskBytes(), stats: H.map((_, m) => stats(pts, m)) };
}
function csv(s, range) {
const num = x => isNaN(x) ? '' : x.toFixed(3), online = p => p.n ? p.nUp * 100 / p.n : 0;
return ['time,samples,online_pct' + H.map(k => `,${k}_avg,${k}_max`).join(''),
...points(s, range).pts.map(p => [Fmt.iso(p.ts * 1000), p.n, Fmt.num(online(p)), ...H.flatMap((_, m) => [num(p.avg[m]), num(p.max[m])])].join(','))].join('\n');
}
// ---- live updates: one stream per page (browsers allow six connections per site) with the server list and events,
// plus the samples of the server whose id the page asked for ----
const clients = new Set();
function cast(id, event, make) {
let msg;
for (const c of clients) {
if (id && c.id !== id) continue;
if (c.res.writableLength > 8 << 20) c.res.destroy(); // the client stopped reading: drop it instead of buffering for ever (the page reconnects)
else c.res.write(msg ??= `event: ${event}\ndata: ${JSON.stringify(make())}\n\n`);
}
}
function subscribe(res, id) {
const c = { id, res }, s = mgr.session(id);
res.writeHead(200, { ...HEADERS, 'Content-Type': 'text/event-stream' });
res.write(`event: hello\ndata: ${JSON.stringify(snapshot())}\n\n` + (s ? `event: live\ndata: ${JSON.stringify({ ...sample(s), rows: s.live, an: s.an })}\n\n` : ''));
clients.add(c), res.on('close', () => clients.delete(c));
}
let dirty = false; // the server list goes out at most once a second
const pushState = () => (dirty = false, cast('', 'state', servers));
setInterval(() => dirty && pushState(), 1000);
mgr.on('updated', () => dirty = true);
mgr.on('sample', (s, row) => (dirty = true, cast(s.cfg.id, 'sample', () => sample(s, row))));
mgr.on('analysis', s => (dirty = true, cast(s.cfg.id, 'analysis', () => s.an)));
mgr.on('alert', e => cast('', 'alert', () => e));
// ---- API ----
// a config sent by the page, on top of the stored one; an empty password keeps the stored password
function config(b) {
const old = b.id ? sess(b.id).cfg : {}, c = model.make({ ...old, ...b }, b.clearPassword ? '' : String(b.password || old.password || ''));
if (!c.name || (c.transport && !c.host)) fail('Please enter a name and an address.');
if (c.host.startsWith('-') || c.user.startsWith('-')) fail('Address and user must not start with "-".');
return c;
}
const GET = {
'/api/state': () => snapshot(),
'/api/history': q => history(sess(q.id), q.range),
'/api/history.csv': (q, res) => send(res, 200, csv(sess(q.id), q.range), 'text/csv', { 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(sess(q.id).cfg.name)}-history.csv` }),
'/api/alerts.log': (q, res) => send(res, 200, fs.readFileSync(path.join(mgr.dir, 'alerts.log'), { flag: 'a+' }), 'text/plain', { 'Content-Disposition': 'attachment; filename="alerts.log"' }),
'/api/events': (q, res) => subscribe(res, q.id),
};
const POST = { // every handler gets the JSON body; servers are addressed by b.id
'/api/server/add': b => { const c = config({ ...b, id: '' }); mgr.add(c); return { id: c.id }; },
'/api/server/update': b => mgr.update(config({ ...b, id: sess(b.id).cfg.id })),
'/api/server/remove': b => mgr.remove(sess(b.id).cfg.id, !!b.deleteHistory),
'/api/server/move': b => mgr.move(b.id, b.delta < 0 ? -1 : 1),
'/api/server/test': b => testConnection(config(b)),
'/api/server/reconnect': b => sess(b.id).reconnect(),
'/api/server/pause': b => sess(b.id).setPaused(!!b.paused),
'/api/server/analyze': b => sess(b.id).analyzeNow(),
'/api/exec': b => sess(b.id).exec(String(b.cmd), !!b.privileged, 120000), // console
'/api/run': b => { // a process / priority / service action from the platform tables; b.arg = pid or service name
const tpl = ['procActions', 'priorities', 'serviceActions'].includes(b.list) && plat.ui[b.list][b.i]?.cmd || fail('unknown command');
if (tpl.includes('{n}') && !(/^\d+$/.test(b.arg) && +b.arg > 0)) fail('not a process id'); // pid 0 or -1 would address whole process groups
const cmd = tpl.replace('{n}', +b.arg).replace('{q}', () => plat.quote(String(b.arg)));
return sess(b.id).exec(cmd, true).then(r => ({ ...r, cmd }));
},
'/api/logs': b => sess(b.id).exec(plat.serviceLogs(String(b.unit), Math.min(5000, Math.max(50, parseInt(b.lines) || 300))), true),
'/api/power': b => sess(b.id).exec(plat.power(!!b.reboot), true),
'/api/finding': b => { const s = sess(b.id); return s.runFinding(s.an.findings.find(f => f.key === b.key) || fail('this finding is gone', 404), false); },
'/api/alerts/clear': () => (mgr.alerts = [], cast('', 'alerts', () => [])),
};
function body(req) { // JSON object, at most 1 MB
return new Promise((resolve, reject) => {
let s = '';
req.setEncoding('utf8').on('data', d => (s += d).length > 1 << 20 && req.destroy()).on('error', reject).on('end', () => {
try { resolve(Object(JSON.parse(s))); } catch { reject(Object.assign(new Error('invalid JSON'), { status: 400 })); }
});
});
}
http.createServer(async (req, res) => {
try {
const url = new URL(req.url, 'http://x'), route = url.pathname, origin = req.headers.origin;
// DNS rebinding: the browser must have addressed this computer by name; other sites cannot send the header or read replies (no CORS)
if (!ORIGINS.includes(req.headers.host) || (origin && !ORIGINS.includes(origin.replace('http://', '')))) return send(res, 403, { error: 'forbidden host or origin' });
if (req.method === 'GET') {
if (FILES[route]) return send(res, 200, fs.readFileSync(path.join(PUBLIC, FILES[route])), MIME[path.extname(FILES[route]).slice(1)]);
const r = GET[route] ? await GET[route](Object.fromEntries(url.searchParams), res) : fail('not found', 404);
return res.headersSent || send(res, 200, r);
}
if (req.method !== 'POST' || !POST[route]) fail('not found', 404);
if (req.headers['x-sm'] !== '1' || !/^application\/json\b/.test(req.headers['content-type'])) fail('state-changing requests need Content-Type: application/json and X-SM: 1', 403);
send(res, 200, await POST[route](await body(req)) ?? { ok: true });
pushState();
} catch (e) {
res.headersSent ? res.end() : send(res, e.status || 500, { error: e.message });
}
}).listen(PORT, '127.0.0.1', () => {
mgr.load();
console.log(`Server Monitor (${plat.ui.name}) is running: http://127.0.0.1:${PORT} - config: ${mgr.dir}`);
}).on('error', e => (console.error(`Cannot listen on 127.0.0.1:${PORT} (is the monitor already running?): ${e.message}`), process.exit(1)));
process.on('exit', () => mgr.close()); // however this process ends, its child processes end with it
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => process.exit(0));
|