ServerMonitor / dev /tests /web /t_session.js
mchuca's picture
Server Monitor: six editions (C++/Qt, Python, web for Linux and Windows), requirements and developer kit
bad179a
Raw History Blame Contribute Delete
9.52 kB
// session lifecycle on the Windows edition with the review stand-in powershell (nothing real runs; dry run is on).
// node t_session.js <port> <cfgdir>
const fs = require('fs'), http = require('http'), { execSync } = require('child_process'), { sleep, client, check, done } = require('./lib');
const [port, cfg] = process.argv.slice(2), { req, post, state } = client(port), ctl = w => fs.writeFileSync(cfg + '.ctl', w), log = () => fs.readFileSync(cfg + '.log', 'utf8');
const srv = async () => (await state()).servers.find(s => s.cfg.id === 'win1'), alerts = async () => (await state()).alerts;
const until = async (fn, ms) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(250)) { const v = await fn(); if (v) return v; } return false; };
const t0 = Date.now(), at = () => ((Date.now() - t0) / 1000).toFixed(1) + ' s';
const trail = []; // status changes seen on the state stream
http.get({ host: '127.0.0.1', port, path: '/api/events' }, res => { let buf = '', last; res.setEncoding('utf8').on('data', d => { buf += d; for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) { const [e, data] = buf.slice(0, i).split('\n'); if (e === 'event: state') { const s = JSON.parse(data.slice(6)).find(x => x.cfg.id === 'win1'); if (s && s.status !== last) trail.push([Date.now(), last = s.status]); } } }); });
const fakes = () => execSync(`pgrep -c -f "^python3 .*/fake/powershell" || true`).toString().trim();
(async () => {
let s = await srv();
check('online with a valid sample', s.status === 'Online' && s.online && s.m.cpuCount === 2, `${s.status}, load ${s.m.load1}`);
// the "already failed when monitoring started" rule + dry run
await post('server/analyze', { id: 'win1' });
const an = async () => { const r = await new Promise(res => http.get({ host: '127.0.0.1', port, path: '/api/events?id=win1' }, r => { let b = ''; r.setEncoding('utf8').on('data', d => { b += d; const ev = b.split('\n\n').slice(0, -1).find(e => e.startsWith('event: live\n')); if (ev) r.destroy(), res(JSON.parse(ev.split('\n')[1].slice(6))); }); })); return r; }; // the "live" event follows "hello"
let a = (await an()).an, f = a.findings.find(x => x.key === 'svc:BrokenSvc');
check('service that was failed at the start: finding, never auto-eligible', f && !f.autoEligible && /already failed when monitoring started/.test(f.detail), f && f.detail);
check('service with an empty exit code is not "failed"', !a.findings.some(x => x.key === 'svc:gupdate'));
ctl('failsvc'), await sleep(3500), await post('server/analyze', { id: 'win1' });
a = (await an()).an, f = a.findings.find(x => x.key === 'svc:Spooler');
check('service that fails while monitored: auto-eligible', f?.autoEligible && /Failed 1× in the last hour/.test(f.detail), f && f.detail);
for (let i = 0; i < 3; ++i) await post('server/analyze', { id: 'win1' });
let ev = (await alerts()).filter(e => e.severity === 'action');
check('dry run: one "would: Restart" event for Spooler (cooldown), none for BrokenSvc, nothing executed', ev.length === 1 && /Autopilot \(dry run\) would: Restart - Service Spooler has failed/.test(ev[0].message) && !/Restart-Service/.test(log()), ev.map(e => e.message).join(' | '));
ctl('nosvc'), await sleep(3500), await post('server/analyze', { id: 'win1' });
a = (await an()).an;
check('a service that left the list is forgotten', !a.findings.some(x => x.key === 'svc:Spooler') && a.findings.some(x => x.key === 'svc:BrokenSvc'), a.findings.map(x => x.key).join());
ctl('ok');
// pending commands when the link is dropped
let p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now();
await sleep(700), await post('server/reconnect', { id: 'win1' });
let r = await p;
check('Reconnect fails a pending command at once', r.code === -1 && Date.now() - t < 3000, `${JSON.stringify(r)} after ${Date.now() - t} ms`);
check('online again after Reconnect', await until(async () => (await srv()).online, 6000));
r = await post('exec', { id: 'win1', cmd: 'EXIT3' });
check('exit code and output of a command', r.code === 3 && /would run/.test(r.out), r.code);
// watchdog: the collector stays alive but sends nothing (interval 1 s -> 15 s)
ctl('stall'), t = Date.now();
p = (async () => { await sleep(3000); return post('exec', { id: 'win1', cmd: 'HANG' }); })();
const lost = await until(async () => (await srv()).status !== 'Online' && Date.now(), 25000);
s = await srv();
check('watchdog: no data for 15 s -> Offline', lost && lost - t > 13000 && lost - t < 19000 && /no data received/.test(s.err), `${((lost - t) / 1000).toFixed(1)} s: ${s.err}`);
r = await p;
check('a command pending when the link is lost fails with the reason', r.code === -1 && /connection lost: no data received/.test(r.out), JSON.stringify(r));
r = await post('exec', { id: 'win1', cmd: 'echo x' });
check('command while offline', r.code === -1 && r.out === 'server is not connected');
// back-off: reconnect attempts after 3, 5, 10 s (each attempt runs into the 25 s start watchdog while stalled, so switch to "die")
ctl('die');
const mark = Date.now() / 1000;
await sleep(45000);
const starts = log().split('\n').filter(l => l.startsWith('COLLECTOR')).map(l => +l.split(' ')[1]).filter(x => x > mark - 30), gaps = starts.slice(1).map((x, i) => Math.round(x - starts[i]));
const first = starts.find(x => x > lost / 1000) - lost / 1000;
check('reconnect back-off: attempts 3, 5, 10, 20 s after each failure', Math.round(first) === 3 && gaps.slice(-3).join() === '5,10,20', `first retry ${first.toFixed(1)} s after the loss, then ${gaps.slice(-3).join(', ')} s; error: ${(await srv()).err}`);
ev = await alerts();
check('one "unreachable" alert for the whole outage', ev.filter(e => /Server is unreachable/.test(e.message)).length === 1, ev.filter(e => e.severity === 'critical').map(e => e.message).join(' | '));
check('card shows the collector\'s error text', /boom: cannot collect/.test((await srv()).err), (await srv()).err);
const rawBefore = fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size;
await sleep(5000);
const down = (fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size - rawBefore) / 136;
check('downtime recorded once per interval while offline or reconnecting', down >= 4 && down <= 6, down + ' records in 5 s');
ctl('ok'), await post('server/reconnect', { id: 'win1' }), t = Date.now();
check('back online', await until(async () => (await srv()).online, 8000));
await sleep(500);
ev = await alerts(), a = (await an()).an;
check('"back online" event', ev.some(e => e.severity === 'resolved' && /back online/.test(e.message)));
check('analysis ran with the first valid sample (no "server unreachable" left)', a.when * 1000 >= t - 1000 && !a.healthReasons.some(x => /unreachable/.test(x)), `analyzed ${((Date.now() - a.when * 1000) / 1000).toFixed(0)} s ago: ${a.healthReasons.join('; ')}`);
const f24 = a.findings.find(x => x.key === 'avail24');
check('"could not be reached for about …" is the measured downtime, not a share of 24 h', f24 && /about (\d+m )?\d+s in the last day/.test(f24.detail), f24 ? `${f24.title} / ${f24.detail} / down ${a.down}` : 'no finding, up ' + a.up);
// pause, config change, remove with a command in flight
await post('server/pause', { id: 'win1', paused: true });
const n1 = fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size; await sleep(2500);
check('paused: nothing recorded', fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size === n1 && (await srv()).paused);
await post('server/pause', { id: 'win1', paused: false });
p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now();
await sleep(600), await post('server/update', { id: 'win1', interval: 2 });
r = await p;
check('changing the interval restarts the link and fails the pending command', r.code === -1 && Date.now() - t < 3000, JSON.stringify(r));
check('online again', await until(async () => (await srv()).online, 8000));
p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now();
const hist = post('server/analyze', { id: 'win1' });
await sleep(600), await post('server/remove', { id: 'win1', deleteHistory: true });
r = await p, await hist;
check('removing the server fails the pending command', r.code === -1 && Date.now() - t < 3000, `${JSON.stringify(r)} after ${Date.now() - t} ms`);
await sleep(800);
check('no helper process is left, history folder deleted, list saved', fakes() === '0' && !fs.existsSync(`${cfg}/ServerMonitorWeb/history/win1`) && JSON.parse(fs.readFileSync(`${cfg}/ServerMonitorWeb/servers.json`)).servers.length === 0, `${fakes()} stand-in processes`);
r = await req('POST', '/api/exec', { id: 'win1', cmd: 'x' });
const gone = await new Promise(res => http.get({ host: '127.0.0.1', port, path: '/api/events?id=win1' }, x => { let b = ''; x.setEncoding('utf8').on('data', d => b += d); setTimeout(() => (x.destroy(), res(b)), 1500); }));
check('requests for the removed server -> 404; its stream is a plain one (hello, no live)', r.status === 404 && (await req('GET', '/api/history?id=win1&range=3600')).status === 404 && gone.startsWith('event: hello') && !gone.includes('event: live'));
console.log('server stderr:', JSON.stringify(fs.readFileSync(cfg + '.err', 'utf8').slice(0, 500)));
done(), process.exit(0);
})();