// Connection to one machine (local shell or the system ssh), the per-server session (metrics, live rows, rules, // autopilot) and the manager of all sessions. const { spawn } = require('child_process'), { EventEmitter } = require('events'); const fs = require('fs'), os = require('os'), path = require('path'); const plat = require('./platform'), model = require('./model'); const { blank } = require('./metrics'); const { HistoryStore, analyze, blankAnalysis, nowSec } = require('./history'); const { Fmt, ruleMetrics, def, conditionText, actionText } = require('../public/shared'); // ---- link: streams collector frames and runs one-shot commands; close() kills everything ---- const SSH_OPTS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR']; const links = new Set(); // every open link: closing them ends every child process let askpass; // helper script that answers ssh's password prompt, created on first use and removed on exit let reaper; // platform helper that ends the children if this process is killed without a chance to do it function reap(sign, pid) { // "+pid" when a child starts, "-pid" when it has ended if (!plat.reaper || !pid) return; if (!reaper) (reaper = spawn(plat.reaper[0], plat.reaper.slice(1), { stdio: ['pipe', 'ignore', 'ignore'], detached: true })).on('error', () => {}), reaper.stdin.on('error', () => {}); reaper.stdin.write(sign + pid + '\n'); } function askpassFile() { if (askpass) return askpass; const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-')); process.on('exit', () => fs.rmSync(dir, { recursive: true, force: true })); fs.writeFileSync(askpass = path.join(dir, plat.askpass[0]), plat.askpass[1], { mode: 0o700 }); return askpass; } class Link { constructor(cfg) { this.c = cfg, this.procs = new Set(), this.closed = '', links.add(this); } spawn(argv, input) { const c = this.c, env = { ...process.env }; let cmd = argv[0], args = argv.slice(1); if (c.transport) { args = SSH_OPTS.flatMap(o => ['-o', o]), cmd = 'ssh'; if (!c.password) args.push('-o', 'BatchMode=yes'); else { args.push('-o', 'NumberOfPasswordPrompts=1'); Object.assign(env, { SSH_ASKPASS: askpassFile(), SSH_ASKPASS_REQUIRE: 'force', SERVERMONITOR_ASKPASS: c.password, DISPLAY: env.DISPLAY || ':0' }); } if (c.keyFile) args.push('-i', c.keyFile.startsWith('~/') ? os.homedir() + c.keyFile.slice(1) : c.keyFile); if (c.port !== 22) args.push('-p', String(c.port)); args.push('-T', (c.user && c.user + '@') + c.host, argv.join(' ')); } const p = spawn(cmd, args, { env, windowsHide: true, detached: plat.detached }); this.procs.add(p), reap('+', p.pid); p.on('exit', () => (this.procs.delete(p), reap('-', p.pid), setTimeout(() => (p.stdout.destroy(), p.stderr.destroy()), 300))); // a grandchild may keep the pipes open p.stdin.on('error', () => {}); // the process may end before it reads its input p.stdin.end(input); for (const s of [p.stdout, p.stderr]) s.setEncoding('utf8'); return p; } start(onFrame, onLost) { const p = this.spawn(plat.shell(this.c.interval), plat.collector(this.c.interval)); let buf = '', err = ''; const lost = why => this.closed || onLost(why); p.stdout.on('data', d => { buf += d; for (let end; !this.closed && (end = buf.indexOf('@@SNAP_END')) >= 0; buf = buf.slice(end + 10)) { const begin = buf.lastIndexOf('@@SNAP_BEGIN', end); if (begin >= 0) onFrame(buf.slice(begin, end)); } if (buf.length > 8 << 20) buf = ''; }); p.stderr.on('data', d => err = (err + d).slice(-4096)); p.on('error', e => lost(`cannot start ${p.spawnfile}: ${e.message}`)); p.on('close', code => lost(err.split('\n').filter(l => l.trim()).pop()?.trim() || `connection closed (exit code ${code})`)); } exec(input, timeoutMs) { // -> { code, out }; code -1 = could not run, killed or timed out return new Promise(resolve => { const p = this.spawn(plat.shell(), input), stop = () => (killed = true, p.stdout.destroy(), p.stderr.destroy(), plat.kill(p)), timer = setTimeout(stop, timeoutMs); let out = '', killed = false; const done = r => (clearTimeout(timer), resolve(r)); for (const s of [p.stdout, p.stderr]) s.on('data', d => (out += d).length > 4 << 20 && stop()); // endless output must not fill the memory p.on('error', e => done({ code: -1, out: e.message })); p.on('close', (code, signal) => done(this.closed ? { code: -1, out: this.closed } : killed || signal ? { code: -1, out: out + '\n[killed or timed out]' } : { code, out })); }); } close(why) { this.closed = why, links.delete(this); for (const p of this.procs) plat.kill(p); } } // two frames prove that data and rates work function testConnection(cfg) { return new Promise(resolve => { const link = new Link({ ...cfg, interval: 1 }), engine = {}, t0 = Date.now(); let frames = 0; const finish = (ok, text) => (clearTimeout(timer), link.close('done'), resolve({ ok, text })); const timer = setTimeout(() => finish(false, '✗ Timed out after 20 s'), 20000); link.start(raw => { const m = plat.parse(raw, engine, Date.now()); if (++frames === 2) finish(true, `✓ Connected in ${Date.now() - t0} ms — ${m.hostname} · ${m.os} · ${m.cpuCount} cores · ${Fmt.bytes(m.memTotal)} RAM · CPU ${Fmt.pct(m.cpuUsage, 0)}`); }, why => finish(false, '✗ ' + why)); }); } // ---- session ---- // one row of the live charts (the last hour is kept in memory); the page reads v[] by position const r2 = x => Math.round(x * 100) / 100; const liveRow = m => ({ t: m.timestamp, v: [m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps, m.diskReadBps, m.diskWriteBps, m.load1].map(r2), net: Object.fromEntries(m.nets.map(n => [n.name, [Math.round(n.rxBps), Math.round(n.txBps)]])), }); class Session extends EventEmitter { // events: updated, sample(row), analysis, alert(event) constructor(cfg, dir) { super(); Object.assign(this, { cfg, status: 'Disabled', err: '', m: blank(0), live: [], retries: 0, paused: false, offlineAlerted: false, an: blankAnalysis(), store: new HistoryStore(path.join(dir, 'history', cfg.id)), reported: new Set(), dry: new Set(), cooldown: {}, rules: {}, procs: new Map(), svcs: new Map() }); this.timers = [setInterval(() => this.analyzeNow(), 60000), setTimeout(() => this.analyzeNow(), 3000)]; this.tick(); } destroy() { this.stop(), [...this.timers, this.offlineTick].forEach(clearTimeout), this.removeAllListeners(); } tick() { // downtime -> availability: one sample per interval, like uptime clearInterval(this.offlineTick); this.offlineTick = setInterval(() => (this.status === 'Offline' || (this.status === 'Connecting' && this.retries)) && this.record(false), this.cfg.interval * 1000); } get online() { return this.status === 'Online' && this.m.valid; } setPaused(p) { this.paused = p, this.emit('updated'); } reconnect() { this.retries = 0, this.paused = false, this.start(); } setConfig(c) { const old = this.cfg, reconnect = ['transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled'].some(k => c[k] !== old[k]); this.cfg = c, this.tick(); if (reconnect) this.live = [], this.m = blank(0), this.procs.clear(), this.svcs.clear(), c.enabled ? this.start() : this.stop(); // may be another machine now this.emit('updated'); } drop(why) { clearTimeout(this.retry), clearTimeout(this.watchdog), this.link?.close(why), this.link = null; } watch(sec) { clearTimeout(this.watchdog), this.watchdog = setTimeout(() => this.onLost('no data received (timeout)'), sec * 1000); } start() { this.drop('connection restarted'); if (!this.cfg.enabled) return this.setStatus('Disabled'); this.engine = {}, this.m.valid = false, this.link = new Link(this.cfg); // online only again with a fresh sample this.setStatus('Connecting'), this.watch(25); this.link.start(raw => this.onFrame(raw), why => this.onLost(why)); } stop() { this.drop('connection stopped'), this.setStatus(this.cfg.enabled ? 'Offline' : 'Disabled'); } setStatus(s, err = '') { if (err || s === 'Online') this.err = err; if (s !== this.status) this.status = s, this.emit('updated'); } onFrame(raw) { const now = Date.now(), m = plat.parse(raw, this.engine, now); this.watch(Math.max(15, this.cfg.interval * 5 + 10)); if (m.uptime <= 0) return; if (this.status !== 'Online') { this.retries = 0; if (this.offlineAlerted) this.offlineAlerted = false, this.raise('resolved', 'Server is back online'); this.setStatus('Online'); } if (!m.valid || this.paused) return; // the first sample has no rates yet if (m.uptime < this.m.uptime) this.procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes const first = !this.m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" this.m = m, this.live.push(liveRow(m)); if (this.live.length > 1800) this.live.shift(); this.record(true), this.track(now), this.evaluateRules(); if (first) this.analyzeNow(); this.emit('sample', this.live.at(-1)); } onLost(why) { const was = this.status === 'Online'; this.drop('connection lost: ' + why), this.setStatus('Offline', why); if ((was || this.retries === 1) && !this.offlineAlerted) this.raise('critical', 'Server is unreachable: ' + why), this.offlineAlerted = true; if (this.cfg.enabled) this.retry = setTimeout(() => this.start(), [3, 5, 10, 20, 30, 60][Math.min(this.retries++, 5)] * 1000); // back-off } // privileged + "useSudo" wraps the command in sudo -n exec(cmd, privileged, timeoutMs = 60000) { if (!this.link || this.status !== 'Online') return Promise.resolve({ code: -1, out: 'server is not connected' }); return this.link.exec(plat.wrap(cmd, privileged && this.cfg.useSudo), timeoutMs); } activeAlerts() { return [...(this.status === 'Offline' ? ['Unreachable: ' + this.err] : []), ...this.cfg.rules.filter(r => this.rules[r.id]?.active).map(conditionText)]; } raise(severity, message) { this.emit('alert', { time: Date.now(), serverName: this.cfg.name, severity, message }); } // info|warning|critical|resolved|action record(up) { const m = this.m, or = (has, x) => has ? x : NaN; // in the order of the history record this.store.add(nowSec(), [m.cpuUsage, m.cpuIowait, m.load1, m.memPct, or(m.swapTotal > 0, m.swapPct), or(m.mounts.length, m.maxDiskPct), m.maxDiskUtil, m.netRxBps, m.netTxBps, m.diskReadBps, m.diskWriteBps, or(m.temps.length, m.maxTemp), m.procs.length, or(m.gpus.length, model.gpuMax(m, 'util')), m.servicesFailed], up); } // per-process CPU streaks + RSS per minute; service failure transitions track(now) { const procs = new Map(); for (const p of this.m.procs) { let t = this.procs.get(p.pid); if (t?.name !== p.name) t = { name: p.name, highSince: 0, lastMinute: 0, rss: [] }; // new or pid reused t.kernel = plat.isProtected(p); t.highSince = p.cpu < this.cfg.autopilot.runawayCpu ? 0 : t.highSince || now; if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss.push(p.rss); if (t.rss.length > 60) t.rss.shift(); procs.set(p.pid, t); } this.procs = procs; const svcs = new Map(); for (const s of this.m.services) { const failed = s.active === 'failed'; let t = this.svcs.get(s.unit); if (!t) t = { last: '', preexisting: failed, fails: [], restarts: [] }; // failed before monitoring started: leave it alone else if (failed && t.last !== 'failed') t.fails.push(now), t.preexisting = false; else if (!failed) t.preexisting = false; t.last = s.active, svcs.set(s.unit, t); for (const v of [t.fails, t.restarts]) while (now - v[0] > 3600000) v.shift(); } if (svcs.size) this.svcs = svcs; // forgets removed services; a sample without a service list changes nothing } evaluateRules() { const now = Date.now(), m = this.m, vals = model.metricValues(m); for (const r of this.cfg.rules) { const st = this.rules[r.id] ??= {}, v = vals[r.metric] ?? 0, now1 = Fmt.fix(v, 1), unit = def(ruleMetrics, r.metric)[2]; const off = !r.enabled || (r.metric.startsWith('gpu') && !m.gpus.length) || (r.metric === 'temp' && !m.temps.length); if (off || (r.op === '<' ? v >= r.value : v <= r.value)) { if (!off && st.active) this.raise('resolved', `Recovered: ${conditionText(r)} (now ${now1})`); this.rules[r.id] = {}; continue; } st.since ||= now; if (now - st.since < r.duration * 1000) continue; if (st.active && (r.action === 'notify' || now - st.lastFire < r.cooldown * 1000)) continue; if (!st.active) this.raise(r.severity, `${conditionText(r)} (now ${now1}${unit && ' ' + unit})`); st.active = true, st.lastFire = now; if (r.action === 'notify') continue; let action = r.action, arg = r.arg; if (action.startsWith('kill_top')) { // heaviest user process, never a protected one const k = action === 'kill_top_mem' ? 'rss' : 'cpu', best = m.procs.filter(p => !plat.isProtected(p)).reduce((a, p) => !a || p[k] > a[k] ? p : a, null); if (!best) continue; action = 'kill_pid', arg = String(best.pid); } this.run(action, arg, `Automation "${conditionText(r)}": ${actionText(plat.ui.ruleActions, r)}`); } } async run(action, arg, what) { const cmd = action === 'command' ? arg : action === 'disk_cleanup' ? this.cfg.autopilot.diskCleanupCommand : plat.command(action, arg); if (!cmd) return { code: -1, out: 'nothing to do' }; const r = await this.exec(cmd, true, 300000), tail = r.out.trim().replace(/\s+/g, ' ').slice(-300); // one line: events are lines in alerts.log this.raise('action', `${what} -> ${r.code ? `failed (${r.code})` : 'OK'}${tail && ' | ' + tail}`); return r; } runFinding(f, automatic) { if (automatic && f.action === 'restart_service') this.svcs.get(f.actionArg)?.restarts.push(Date.now()); return this.run(f.action, f.action === 'disk_cleanup' ? '' : f.actionArg, `${automatic ? 'Autopilot' : 'Manual fix'}: ${f.actionLabel} (${f.title})`); } analyzeNow() { const now = Date.now(), ap = this.cfg.autopilot, procs = [], svcs = []; for (const p of this.m.procs) { const t = this.procs.get(p.pid) || { rss: [] }, n = t.rss.length, growth = n >= 2 ? t.rss[n - 1] - t.rss[0] : 0; const highCpuMinutes = t.highSince ? (now - t.highSince) / 60000 : 0; if (highCpuMinutes > 0 || n >= 30) procs.push({ pid: p.pid, minutesTracked: n, name: p.name, user: p.user, cpuNow: p.cpu, highCpuMinutes, rssNow: p.rss, kernel: t.kernel, rssGrowth: growth, rssGrowthPct: t.rss[0] > 0 ? growth * 100 / t.rss[0] : 0, rssMonotonic: n >= 2 ? t.rss.filter((x, i) => i && x > t.rss[i - 1]).length / (n - 1) : 0 }); } for (const [unit, t] of this.svcs) if (t.last === 'failed' || t.fails.length) svcs.push({ unit, failedNow: t.last === 'failed', preexisting: t.preexisting, failsLastHour: t.fails.length, autoRestartsLastHour: t.restarts.length }); this.an = analyze(this.store, this.m, ap, procs, svcs, this.online); for (const f of this.an.findings) // announce each new finding once if (!this.reported.has(f.key) && f.category !== 'Availability') this.raise(f.severity, `Insight: ${f.title} - ${f.detail}`); this.reported = new Set(this.an.findings.map(f => f.key)); const dry = new Set(); // act on eligible findings, with cooldowns; a dry run says once what it would do for (const f of ap.enabled && this.online ? this.an.findings.filter(f => f.autoEligible) : []) { const cd = f.action === 'disk_cleanup' ? 6 * 3600000 : f.action === 'restart_service' ? 120000 : 900000; if (ap.dryRun) dry.add(f.key), this.dry.has(f.key) || this.raise('action', `Autopilot (dry run) would: ${f.actionLabel} - ${f.title}`); else if (now - (this.cooldown[f.key] || 0) >= cd) this.cooldown[f.key] = now, this.runFinding(f, true); } this.dry = dry, this.emit('analysis'); } deleteHistory() { this.store.removeFiles(), this.an = blankAnalysis(), this.emit('analysis'); } } // ---- manager ---- class Manager extends EventEmitter { // events: updated(session), sample(session, row), analysis(session), alert(event) constructor() { super(); this.dir = plat.configDir(), this.sessions = [], this.alerts = []; fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 }); // alerts.log holds command output } session(id) { return this.sessions.find(s => s.cfg.id === id); } attach(cfg) { const s = new Session(cfg, this.dir); for (const ev of ['updated', 'sample', 'analysis']) s.on(ev, x => this.emit(ev, s, x)); s.on('alert', e => { const log = path.join(this.dir, 'alerts.log'); this.alerts.unshift(e), this.alerts.length = Math.min(this.alerts.length, 2000); try { // starts over at 5 MB fs.appendFileSync(log, `${Fmt.iso(e.time)}\t${e.severity}\t${e.serverName}\t${e.message}\n`, { flag: fs.statSync(log, { throwIfNoEntry: false })?.size > 5 << 20 ? 'w' : 'a' }); } catch { /* disk full or not writable: the event still reaches the page */ } this.emit('alert', e); }); this.sessions.push(s); return s; } load() { const file = path.join(this.dir, 'servers.json'); if (fs.existsSync(file)) { let servers = []; try { servers = JSON.parse(fs.readFileSync(file, 'utf8')).servers; } catch { fs.copyFileSync(file, file + '.bad'); } // not JSON: start empty; the next save replaces the file, so keep a copy for (const o of Array.isArray(servers) ? servers : []) if (o && typeof o === 'object') this.attach(model.fromJson(o)); } else { // first start: monitor this machine this.attach(model.make({ name: 'This computer', group: 'Local', transport: 0 }, '')); this.save(); } for (const s of this.sessions) s.start(); } save() { const file = path.join(this.dir, 'servers.json'); fs.writeFileSync(file + '.tmp', JSON.stringify({ version: 1, servers: this.sessions.map(s => model.toJson(s.cfg)) }, null, 4), { mode: 0o600 }); fs.renameSync(file + '.tmp', file); } add(cfg) { this.attach(cfg).start(), this.save(); } update(cfg) { this.session(cfg.id).setConfig(cfg), this.save(); } remove(id, deleteHistory) { const s = this.session(id); this.sessions.splice(this.sessions.indexOf(s), 1), s.destroy(); if (deleteHistory) fs.rmSync(s.store.dir, { recursive: true, force: true }); this.save(); } move(id, d) { const v = this.sessions, i = v.indexOf(this.session(id)), j = Math.min(v.length - 1, Math.max(0, i + d)); if (i >= 0 && i !== j) v.splice(j, 0, v.splice(i, 1)[0]), this.save(); } close() { // ends every child process, also those of connection tests for (const s of this.sessions) s.destroy(); for (const l of links) l.close('monitor stopped'); } } module.exports = { Manager, testConnection };