// Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) in the binary format every edition // shares, and the statistics-only analyzer that feeds the autopilot. const fs = require('fs'), path = require('path'); const plat = require('./platform'); const { Fmt, H, hNames, fmtMetric } = require('../public/shared'); const N = H.length, REC = 16 + 8 * N, I = Object.fromEntries(H.map((k, i) => [k, i])); const HEADER = Buffer.from([...Buffer.from('SMH1'), N, 0, REC & 255, REC >> 8]); const FILES = ['raw', 'minute', 'hour', 'day'], TIERS = ['every sample', '1 minute', '1 hour', '1 day']; const STEP = [1, 60, 3600, 86400], KEEP = [6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400]; const nowSec = () => Math.floor(Date.now() / 1000); const fileSize = f => fs.statSync(f, { throwIfNoEntry: false })?.size || 0; // a point: { ts (s; bucket start for aggregates), n samples, nUp online samples, avg[N], max[N] }, NaN = no value // file record: int64 ts, uint32 n, uint32 nUp, float32 avg[N], float32 max[N], little-endian function encode(pts) { const b = Buffer.alloc(pts.length * REC); pts.forEach((p, i) => { const o = i * REC; b.writeBigInt64LE(BigInt(p.ts), o), b.writeUInt32LE(p.n, o + 8), b.writeUInt32LE(p.nUp, o + 12); for (let k = 0; k < N; ++k) b.writeFloatLE(p.avg[k], o + 16 + 4 * k), b.writeFloatLE(p.max[k], o + 16 + 4 * (N + k)); }); return b; } function decode(b, o) { const p = { ts: Number(b.readBigInt64LE(o)), n: b.readUInt32LE(o + 8), nUp: b.readUInt32LE(o + 12), avg: new Float32Array(N), max: new Float32Array(N) }; for (let k = 0; k < N; ++k) p.avg[k] = b.readFloatLE(o + 16 + 4 * k), p.max[k] = b.readFloatLE(o + 16 + 4 * (N + k)); return p; } class Acc { // accumulates points into one bucket constructor(bucket) { this.bucket = bucket, this.n = this.nUp = 0, this.cnt = new Float64Array(N), this.sum = new Float64Array(N), this.mx = new Float32Array(N).fill(NaN); } add(p) { this.n += p.n, this.nUp += p.nUp; if (!p.nUp) return; for (let i = 0; i < N; ++i) { if (isNaN(p.avg[i])) continue; this.sum[i] += p.avg[i] * p.nUp, this.cnt[i] += p.nUp; if (isNaN(this.mx[i]) || p.max[i] > this.mx[i]) this.mx[i] = p.max[i]; } } point() { return { ts: this.bucket, n: this.n, nUp: this.nUp, avg: Float32Array.from(this.sum, (s, i) => this.cnt[i] ? s / this.cnt[i] : NaN), max: this.mx.slice() }; } } class HistoryStore { constructor(dir) { this.dir = dir, this.load(); } file(t) { return path.join(this.dir, FILES[t] + '.bin'); } bucketOf(t, ts) { return t === 3 ? Math.floor((ts + this.tz) / 86400) * 86400 - this.tz : Math.floor(ts / STEP[t]) * STEP[t]; } // days at local midnight load() { fs.mkdirSync(this.dir, { recursive: true }); const now = nowSec(); this.tz = -new Date().getTimezoneOffset() * 60, this.t = [[], [], [], []], this.acc = [], this.appends = [0, 0, 0, 0]; for (let t = 0; t < 4; ++t) { const f = this.file(t), v = this.t[t]; if (!fileSize(f)) continue; const d = fs.readFileSync(f); if (!d.subarray(0, 8).equals(HEADER)) { fs.renameSync(f, f + '.old'); continue; } let bad = (d.length - 8) % REC; // a cut-off record would misalign everything appended after it for (let off = 8; off + REC <= d.length; off += REC) { const p = decode(d, off); if (p.ts < now - KEEP[t] || p.ts > now + 86400 || (v.length && p.ts <= v.at(-1).ts)) ++bad; else v.push(p); } if (bad) this.rewrite(t); } for (let t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one const stored = this.t[t].at(-1)?.ts ?? -1; this.acc[t] = new Acc(-1); for (const p of [...this.t[t - 1], ...(this.acc[t - 1]?.n ? [this.acc[t - 1].point()] : [])]) { const b = this.bucketOf(t, p.ts); if (b <= stored) continue; if (b !== this.acc[t].bucket) { if (this.acc[t].n) this.append(t, this.acc[t].point()); this.acc[t] = new Acc(b); } this.acc[t].add(p); } } } rewrite(t) { const f = this.file(t); fs.writeFileSync(f + '.tmp', Buffer.concat([HEADER, encode(this.t[t])])), fs.renameSync(f + '.tmp', f); } append(t, p) { const v = this.t[t], f = this.file(t); if (v.length && p.ts <= v.at(-1).ts) return; v.push(p); try { if (fileSize(f) < 8) fs.writeFileSync(f, HEADER); fs.appendFileSync(f, encode([p])); if (++this.appends[t] % 500) return; // trim expired points now and then const keep = v.findIndex(x => x.ts >= p.ts - KEEP[t]); if (keep > 0) v.splice(0, keep), this.rewrite(t); } catch { /* disk full or not writable: monitoring goes on with the points in memory */ } } add(ts, val, up) { // up = false records downtime only const raw = { ts, n: 1, nUp: +up, avg: Float32Array.from(val, x => up ? x : NaN) }; raw.max = raw.avg, this.append(0, raw); for (let t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample const b = this.bucketOf(t, ts); if (this.acc[t].bucket !== b) { if (this.acc[t].n && this.acc[t].bucket < b) this.append(t, this.acc[t].point()); this.acc[t] = new Acc(b); } this.acc[t].add(raw); } } tierFor(from, to) { // finest tier covering the range const now = nowSec(), maxSpan = [6 * 3600, 8 * 86400, 400 * 86400]; let t = 0; while (t < 3 && (from < now - KEEP[t] || to - from > maxSpan[t])) ++t; return t; } range(from, to, t = this.tierFor(from, to)) { // includes the open bucket const out = this.t[t].filter(p => p.ts >= from && p.ts <= to), a = this.acc[t]; if (t && a.n && a.bucket >= from && a.bucket <= to && !(out.at(-1)?.ts >= a.bucket)) out.push(a.point()); return out; } removeFiles() { fs.rmSync(this.dir, { recursive: true, force: true }), this.load(); } firstTs() { return Math.min(...this.t.filter(v => v.length).map(v => v[0].ts), Infinity) % Infinity || 0; } // 0 when empty diskBytes() { return FILES.reduce((b, _, t) => b + fileSize(this.file(t)), 0); } } function stats(pts, m) { // max = peak of max[] const s = { min: NaN, avg: NaN, p95: NaN, max: NaN, count: 0 }, v = []; let sum = 0, w = 0; for (const p of pts) { if (!p.nUp || isNaN(p.avg[m])) continue; v.push(p.avg[m]), sum += p.avg[m] * p.nUp, w += p.nUp; if (isNaN(s.max) || p.max[m] > s.max) s.max = p.max[m]; } if (!v.length) return s; v.sort((a, b) => a - b); return Object.assign(s, { count: v.length, avg: sum / w, min: v[0], p95: v[Math.min(v.length - 1, Math.floor(v.length * 0.95))] }); } function regression(pts, m) { // [slope per second, R²] let n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0; for (const p of pts) { if (!p.nUp || isNaN(p.avg[m])) continue; const x = p.ts - pts[0].ts, y = p.avg[m]; n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y; } const den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy, ok = n >= 3 && den > 0; return [ok ? num / den : 0, ok && vy > 1e-9 ? num * num / (den * vy) : 0]; // squared correlation } const grid = fill => Array.from({ length: 7 }, () => Array(24).fill(fill)); const blankAnalysis = () => ({ when: 0, health: 100, grade: 'A', diskBasis: '', healthReasons: [], capacity: [], findings: [], anomalies: [], diskFullDays: -1, diskSlopePerDay: 0, memSlopePerHour: 0, memTrendR2: 0, up: [NaN, NaN, NaN], down: [0, 0, 0], // 24 h, 7 d, 30 d: availability %, seconds offline cpu30: stats([]), mem30: stats([]), heat: [grid(NaN), grid(NaN)], heatN: grid(0), // weekly pattern: 0 = CPU, 1 = memory }); // finding.action: disk_cleanup | restart_service | renice | kill_pid; procs / svcs are the trends tracked by the session function analyze(st, m, ap, procs, svcs, online) { const a = blankAnalysis(), now = a.when = nowSec(), [, minute, hour] = st.t, f1 = v => Fmt.fix(v, 1), f2 = v => Fmt.fix(v, 2); const add = (key, severity, category, title, detail, advice, action = '', actionArg = '', actionLabel = '', autoEligible = false) => a.findings.push({ key, severity, category, title, detail, advice, action, actionArg, actionLabel, autoEligible }); const sev = (crit, warn) => crit ? 'critical' : warn ? 'warning' : 'info'; const localHour = ts => { const d = new Date(ts * 1000); return [(d.getDay() + 6) % 7, d.getHours()]; }; // Monday = 0 // availability const spans = [86400, 7 * 86400, 30 * 86400]; spans.forEach((s, i) => { let n = 0, up = 0; for (const p of st.range(now - s, now)) n += p.n, up += p.nUp; if (n) a.up[i] = up * 100 / n, a.down[i] = (n - up) / n * Math.min(s, now - st.firstTs()); // share of the monitored part of the window }); if (a.up[0] < 99) add('avail24', sev(a.up[0] < 95, true), 'Availability', `Availability last 24 h is ${Fmt.pct(a.up[0], 2)}`, `The server could not be reached for about ${Fmt.duration(a.down[0])} in the last day.`, 'Check network stability, power and whether the machine rebooted (uptime).'); const w30 = st.range(now - spans[2], now, 2), long = w30.length >= 24 ? w30 : st.range(now - spans[1], now, 1); a.cpu30 = stats(long, I.cpu), a.mem30 = stats(long, I.mem); // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better const week = st.range(now - spans[1], now, 2), day = st.range(now - 86400, now, 1); let [slope, r2] = [0, 0]; if (week.length >= 48) [slope, r2] = regression(week, I.disk), a.diskBasis = 'hourly averages, last 7 days'; if (day.length >= 120) { const [s2, r2b] = regression(day, I.disk); if (week.length < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = 'minute averages, last 24 hours'; } a.diskSlopePerDay = slope * 86400; if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay; if (a.diskFullDays >= 0 && a.diskFullDays < 30) add('diskfull', sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), 'Disk', `Disk ${m.fullestMount} will be full in ${Fmt.duration(a.diskFullDays * 86400)}`, `Usage ${Fmt.pct(m.maxDiskPct)}, growing ${f2(a.diskSlopePerDay)} points/day (trend from ${a.diskBasis}, fit R² ${f2(r2)}).`, 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup && a.diskFullDays < ap.diskForecastDays); if (m.maxDiskPct >= ap.diskCleanupAt) add('diskhigh', sev(m.maxDiskPct >= 97, true), 'Disk', `Disk ${m.fullestMount} is ${Fmt.pct(m.maxDiskPct)} full`, `Above the cleanup threshold of ${Fmt.pct(ap.diskCleanupAt, 0)}.`, 'Free space soon: services fail when the disk is full.', 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup); // whole-machine memory trend over 6 h const six = st.range(now - 6 * 3600, now, 1); if (six.length >= 90) { const [s, fit] = regression(six, I.mem), left = (100 - m.memPct) / Math.max(0.01, s * 3600); a.memSlopePerHour = s * 3600, a.memTrendR2 = fit; if (a.memSlopePerHour > 1 && fit > 0.8 && m.memPct > 40) add('memtrend', sev(false, left < 12), 'Memory', `Memory keeps growing (+${f1(a.memSlopePerHour)} points/hour)`, `Steady growth over 6 h (R² ${f2(fit)}). At this rate memory is exhausted in about ${Fmt.duration(left * 3600)}.`, 'Look for a leaking process (Processes tab, sort by RSS).'); } // processes: leaks and runaways for (const p of procs) { if (p.kernel) continue; const who = `${p.name} (PID ${p.pid})`, pid = String(p.pid), term = ap.runawayMode === 'terminate'; if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8) add('leak:' + pid, sev(m.memPct >= ap.leakMemPressure, true), 'Process', 'Possible memory leak: ' + who, `RSS grew ${Fmt.bytes(p.rssGrowth)} (+${Fmt.pct(p.rssGrowthPct, 0)}) in ${p.minutesTracked} min and rose in ${Math.round(p.rssMonotonic * 100)}% of the minutes; now ${Fmt.bytes(p.rssNow)}.`, 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', pid, 'Terminate', ap.leakMode === 'terminate' && m.memPct >= ap.leakMemPressure); if (p.highCpuMinutes >= ap.runawayMinutes) add('runaway:' + pid, 'warning', 'Process', 'Runaway process: ' + who, `Above ${Fmt.pct(ap.runawayCpu, 0)} CPU for ${Math.round(p.highCpuMinutes)} min (now ${Fmt.pct(p.cpuNow)}, user ${p.user}).`, 'Lower its priority (renice) or stop it if it is stuck.', term ? 'kill_pid' : 'renice', pid, term ? 'Terminate' : 'Renice to 19', ap.runawayMode !== 'none'); } // services: failures and flapping for (const s of svcs) { const flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour; if (s.failedNow) add('svc:' + s.unit, sev(flap, true), 'Service', `Service ${s.unit} ${flap ? 'keeps failing' : 'has failed'}`, s.preexisting ? 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' : `Failed ${s.failsLastHour}× in the last hour; autopilot restarted it ${s.autoRestartsLastHour}×.`, flap ? 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' : 'Restart it and check the logs.', 'restart_service', s.unit, 'Restart', ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour); else if (s.failsLastHour >= 3) add('flap:' + s.unit, 'warning', 'Service', `Service ${s.unit} is unstable`, `It failed ${s.failsLastHour} times within the last hour.`, 'Inspect its logs and resource limits.'); } // overload and swap thrashing (without an I/O wait counter: memory full now + busy disks) const last15 = st.range(now - 900, now, 1), avg15 = k => stats(last15, I[k]).avg, load15 = avg15('load'), perCore = load15 / m.cpuCount; if (online && perCore > 1.5) add('load', sev(perCore > 3, true), 'CPU', `CPU is overloaded (load ${f1(load15)} on ${m.cpuCount} cores)`, `15-minute average load is ${f1(perCore)}× the number of cores; tasks are waiting for CPU.`, 'Find the busiest processes, spread work over time, or add CPU.'); if (online && m.swapPct > 50 && (plat.ui.posixCpu ? avg15('iowait') > 20 : m.memPct > 90 && avg15('diskio') > 50)) add('thrash', 'critical', 'Memory', 'Swap thrashing', plat.ui.posixCpu ? `Swap ${Fmt.pct(m.swapPct)} used and CPU waits on I/O ${Fmt.pct(avg15('iowait'))} of the time.` : `Swap ${Fmt.pct(m.swapPct)} used, memory ${Fmt.pct(m.memPct)} full and disks ${Fmt.pct(avg15('diskio'))} busy.`, 'Stop memory-hungry processes or add RAM.'); // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) const raw = st.range(now - 600, now, 0), [today, thisHour] = localHour(now); for (const [k, floor, down] of [['cpu', 5], ['mem', 3], ['load', 0.25 * Math.max(1, m.cpuCount)], ['iowait', 3], ['rx', 256e3, true], ['tx', 256e3, true]]) { if (!online || raw.length < 10 || (k === 'iowait' && !plat.ui.posixCpu)) continue; const hm = I[k], cur = stats(raw, hm).avg, ok = p => p.nUp && !isNaN(p.avg[hm]), name = hNames[hm]; let basis = 'same weekday & hour, last 8 weeks'; let v = hour.filter(p => ok(p) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && localHour(p.ts).join() === [today, thisHour].join()); if (v.length < 3) { v = minute.filter(p => ok(p) && now - p.ts <= 86400 && now - p.ts > 900), basis = 'last 24 hours'; if (v.length < 360) continue; } const mean = v.reduce((s, p) => s + p.avg[hm] / v.length, 0), sd = Math.sqrt(v.reduce((s, p) => s + (p.avg[hm] - mean) ** 2 / v.length, 0)); const z = (cur - mean) / Math.max(sd, floor), hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1; a.anomalies.push({ metric: name, baseline: basis, hm, now: cur, mean, sd, z }); if (ap.anomalyAlerts && (hi || lo)) add('anomaly:' + k, sev(false, z >= ap.anomalyZ * 2), 'Anomaly', `Unusually ${hi ? 'high' : 'low'} ${name.toLowerCase()}`, `Last 10 min ${fmtMetric(hm, cur)}, usually ${fmtMetric(hm, mean)} ± ${fmtMetric(hm, sd)} (${basis}); ${f1(z)}σ.`, hi ? 'Check what changed: deploys, cron jobs, traffic, attacks.' : 'Traffic dropped sharply - check the service is still serving.'); } // weekly heatmaps from 4 weeks of hours const sum = [grid(0), grid(0)]; for (const p of hour) { if (now - p.ts > 28 * 86400 || !p.nUp || isNaN(p.avg[I.cpu])) continue; const [d, h] = localHour(p.ts), n = ++a.heatN[d][h]; sum[0][d][h] += p.avg[I.cpu], sum[1][d][h] += p.avg[I.mem] || 0; a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n; } // capacity advice for (const [s, name, lo, hi, loTxt, hiTxt] of [[a.cpu30, 'CPU', 15, 80, 'is mostly idle', 'is often saturated - add cores or move work away'], [a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits']]) if (s.count >= 60) a.capacity.push(`${name} ${s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : 'headroom is healthy'} (p95 ${Fmt.pct(s.p95)}).`); if (a.diskFullDays >= 0) a.capacity.push(`Disk grows ${f2(a.diskSlopePerDay)} points/day - full in about ${Fmt.duration(a.diskFullDays * 86400)}.`); else if (a.diskBasis) a.capacity.push('Disk usage is stable.'); if (!a.capacity.length) a.capacity.push('Collecting history - capacity advice appears after about an hour of data.'); // health score let score = 100; const pen = (when, p, why) => { if (when && p > 0.5) score -= p, a.healthReasons.push(`−${Math.round(p)} ${why}`); }; const cpu15 = avg15('cpu'), cpu = isNaN(cpu15) ? m.cpuUsage : cpu15; const fp = a.findings.reduce((s, f) => s + (f.category === 'Availability' ? 0 : f.severity === 'critical' ? 15 : f.severity === 'warning' ? 7 : 2), 0); pen(!online, 60, 'server unreachable'); pen(cpu > 70, Math.min(24, (cpu - 70) * 0.8), `CPU busy (${Fmt.pct(cpu)})`); pen(m.memPct > 80, Math.min(30, (m.memPct - 80) * 1.5), `memory high (${Fmt.pct(m.memPct)})`); pen(m.maxDiskPct > 80, Math.min(40, (m.maxDiskPct - 80) * 2), `disk high (${Fmt.pct(m.maxDiskPct)})`); pen(m.swapPct > 50, 10, 'heavy swap use'); pen(m.maxTemp > 80, Math.min(20, (m.maxTemp - 80) * 2), `hot (${Fmt.temp(m.maxTemp)})`); pen(a.up[0] < 100, Math.min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h'); pen(true, Math.min(50, fp), `${a.findings.length} finding(s)`); a.health = Math.min(100, Math.max(0, Math.round(score))); a.grade = 'FDCBA'[a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0]; const rank = f => ['critical', 'warning'].indexOf(f.severity) & 3; // critical 0, warning 1, others 3 a.findings.sort((x, y) => rank(x) - rank(y)); return a; } module.exports = { I, TIERS, STEP, HistoryStore, stats, analyze, blankAnalysis, nowSec };