"use strict"; /** * Panel metrics collector for the admin-only /status monitoring page. * * Design goals (best-practice, ultra-low overhead): * - Collect host + panel-process resource usage (CPU, RAM, storage) cheaply * using only Node core modules (os, fs) plus a single `pm2 jlist` poll for * aggregate Node/PM2 network counters. No heavy native deps. * - Live data lives in RAM. We only run the intensive 1s sampling loop while at * least one admin is actually watching the page (driven by socket room size). * When nobody watches, the loop stops -> zero ongoing cost. * - Persistence is RRD-like: one row per minute in `panel_metrics`. A monthly * cleanup keeps the table at a fixed, small size (~31 days). Writes happen * once per minute (averaged), never per second. * - All reads are wrapped so a transient failure never throws into the loop. * * This module is intentionally framework-agnostic: index.js wires it to the * existing socket.io server, admin auth, and MySQL pool. */ const os = require("os"); const path = require("path"); const fsSync = require("fs"); const fsp = require("fs/promises"); const { execFile } = require("child_process"); // --------------------------------------------------------------------------- // Tunables (overridable via env, sane defaults for cheap VPS). // --------------------------------------------------------------------------- const LIVE_SAMPLE_MS = clampInt(process.env.PANEL_METRICS_LIVE_MS, 1000, 250, 10000); const PERSIST_INTERVAL_MS = clampInt(process.env.PANEL_METRICS_PERSIST_MS, 60_000, 10_000, 600_000); const RETENTION_DAYS = clampInt(process.env.PANEL_METRICS_RETENTION_DAYS, 31, 7, 366); const PM2_POLL_MS = clampInt(process.env.PANEL_METRICS_PM2_MS, 5000, 2000, 60_000); const CLEANUP_INTERVAL_MS = 6 * 60 * 60 * 1000; // run retention sweep 4x/day function clampInt(value, def, min, max) { const n = parseInt(value, 10); if (!Number.isFinite(n)) return def; return Math.min(Math.max(n, min), max); } function nowMs() { return Date.now(); } // --------------------------------------------------------------------------- // CPU sampling: delta of os.cpus() times between two reads -> busy percentage. // Cheap: a single os.cpus() call (reads /proc/stat once on Linux). // --------------------------------------------------------------------------- function cpuTotals() { const cpus = os.cpus() || []; let idle = 0; let total = 0; for (const c of cpus) { const t = c.times; idle += t.idle; total += t.user + t.nice + t.sys + t.idle + t.irq; } return { idle, total, cores: cpus.length || 1 }; } // --------------------------------------------------------------------------- // Storage: usage of the filesystem holding the panel working directory. // Uses statfs when available (Node >= 18.15), else falls back to null. // --------------------------------------------------------------------------- async function readStorage() { try { if (typeof fsp.statfs === "function") { const s = await fsp.statfs(process.cwd()); const total = s.blocks * s.bsize; const free = s.bfree * s.bsize; const used = total - free; if (total > 0) { return { usedBytes: used, totalBytes: total, percent: round1((used / total) * 100) }; } } } catch (_) { /* ignore */ } return { usedBytes: null, totalBytes: null, percent: null }; } function round1(n) { return Math.round(n * 10) / 10; } // --------------------------------------------------------------------------- // PM2 network counters. `pm2 jlist` exposes per-process monit + env; PM2 does // not natively expose net bytes, so we read aggregate NIC counters from // /proc/net/dev (sum of all non-loopback interfaces) and derive a per-second // rate from deltas. This reflects the whole Node/PM2 host traffic, which is the // closest reliable "panel network" signal without per-socket accounting. // --------------------------------------------------------------------------- async function readNetCounters() { try { const raw = await fsp.readFile("/proc/net/dev", "utf8"); let rx = 0; let tx = 0; const lines = raw.split("\n"); for (const line of lines) { const idx = line.indexOf(":"); if (idx === -1) continue; const iface = line.slice(0, idx).trim(); if (!iface || iface === "lo") continue; const parts = line.slice(idx + 1).trim().split(/\s+/); if (parts.length < 9) continue; rx += Number(parts[0]) || 0; // bytes received tx += Number(parts[8]) || 0; // bytes transmitted } return { rxBytes: rx, txBytes: tx }; } catch (_) { return { rxBytes: null, txBytes: null }; } } // --------------------------------------------------------------------------- // pm2 process metrics (aggregate monit counters via `pm2 jlist`). // // The pm2 binary is resolved against a FIXED list of absolute directories — // never the inherited process PATH. execFile("pm2", ...) would look the name // up through whatever PATH this process inherited, and a login-shell launch // routinely includes user-writable entries (~/.local/bin, nvm/npm user bins); // a local attacker who can plant a fake `pm2` in one of those would get it // executed by this process on every metrics poll (the persist loop polls even // when nobody watches the page). // // The lookup list therefore contains only directories inside the panel's own // trust boundary: the panel's node_modules/.bin (pm2 is a panel dependency — // whoever can write there can already rewrite the panel itself, so this adds // no exposure and is what makes metrics work under the stock systemd unit, // whose minimal PATH does not include node_modules/.bin), the directory of // the running node binary (same argument — it is this process's interpreter; // covers nvm/container installs), and the root-owned system bin dirs. If pm2 // is not found there, PM2 metrics degrade to null and the inherited PATH is // never searched as a fallback. // --------------------------------------------------------------------------- const PM2_LOOKUP_DIRS = [ ...new Set([ path.join(__dirname, "..", "node_modules", ".bin"), path.dirname(process.execPath), "/usr/local/bin", "/usr/bin", ].filter(Boolean)), ]; function resolvePm2Binary(lookupDirs = PM2_LOOKUP_DIRS) { for (const dir of lookupDirs) { if (!dir || !path.isAbsolute(dir)) continue; const candidate = path.join(dir, "pm2"); try { // statSync follows symlinks: node_modules/.bin/pm2 is a symlink into // the pm2 package, which is exactly the file we want. if (!fsSync.statSync(candidate).isFile()) continue; fsSync.accessSync(candidate, fsSync.constants.X_OK); return candidate; } catch (_) { /* not here / not usable; try the next directory */ } } return null; } let _pm2Path = null; let _pm2PathResolved = false; // execPath is a test hook; production callers take the resolved, memoized // default. Resolution is deliberately once-per-process: a pm2 that appears // mid-run is picked up on restart rather than re-scanned on every poll. function pm2List(execPath) { if (execPath === undefined) { if (!_pm2PathResolved) { _pm2Path = resolvePm2Binary(); _pm2PathResolved = true; if (!_pm2Path) { console.warn(`[panel-metrics] pm2 not found in fixed lookup paths (${PM2_LOOKUP_DIRS.join(", ")}) — PM2 metrics disabled; the inherited PATH is never searched`); } } execPath = _pm2Path; } if (!execPath) return Promise.resolve(null); return new Promise((resolve) => { try { execFile(execPath, ["jlist"], { timeout: 4000, maxBuffer: 4 * 1024 * 1024, // pm2 is a Node script launched through `#!/usr/bin/env node`, so give // the child the same sanitized lookup list as its PATH — its own node // resolution then also stays inside the trusted directories. The env // spread keeps PM2_HOME / HOME intact for daemon socket discovery. env: { ...process.env, PATH: PM2_LOOKUP_DIRS.join(":") }, }, (err, stdout) => { if (err || !stdout) return resolve(null); try { resolve(JSON.parse(stdout)); } catch (_) { resolve(null); } }); } catch (_) { resolve(null); } }); } // --------------------------------------------------------------------------- // Collector // --------------------------------------------------------------------------- class PanelMetricsCollector { constructor(options = {}) { this.db = options.db || null; // { query } this.io = options.io || null; // socket.io server this.room = options.room || "monitor"; this.startTime = options.startTime || nowMs(); this.panelVersion = options.panelVersion || null; this.getServiceStatus = typeof options.getServiceStatus === "function" ? options.getServiceStatus : async () => ({}); // Live state this._prevCpu = cpuTotals(); this._prevNet = null; this._prevNetAt = 0; this._reqCounter = 0; // incremented by middleware this._prevReqCount = 0; this._prevReqAt = nowMs(); this._pm2Cache = { at: 0, data: null }; this._svcCache = { at: 0, data: null }; this._svcTtlMs = clampInt(process.env.PANEL_METRICS_SVC_MS, 5000, 2000, 60_000); // Minute-accumulator for persistence (average over the window) this._acc = this._freshAcc(); // Timers this._liveTimer = null; this._persistTimer = null; this._cleanupTimer = null; this._lastSample = null; } _freshAcc() { return { count: 0, cpu: 0, memUsed: 0, memTotal: 0, diskUsed: 0, diskTotal: 0, netRx: 0, netTx: 0, rps: 0, }; } /** * The request counter (`_reqCounter`) is incremented directly by a tiny * Express middleware in index.js (one integer add per request, no allocation). * The collector only reads/diffs it; it never touches the hot request path * beyond that single increment. */ start() { // Persistence + cleanup always run (cheap, once per minute / few hours). if (!this._persistTimer) { this._persistTimer = setInterval(() => this._persist().catch(() => {}), PERSIST_INTERVAL_MS); this._persistTimer.unref?.(); } if (!this._cleanupTimer) { // Run once shortly after boot, then on interval. setTimeout(() => this._cleanup().catch(() => {}), 30_000).unref?.(); this._cleanupTimer = setInterval(() => this._cleanup().catch(() => {}), CLEANUP_INTERVAL_MS); this._cleanupTimer.unref?.(); } // Drive the live loop from room occupancy. this._refreshLiveLoop(); } stop() { for (const t of [this._liveTimer, this._persistTimer, this._cleanupTimer]) { if (t) clearInterval(t); } this._liveTimer = this._persistTimer = this._cleanupTimer = null; } /** Called by index.js whenever a client joins/leaves the monitor room. */ onRoomChange() { this._refreshLiveLoop(); } _watcherCount() { try { const room = this.io?.sockets?.adapter?.rooms?.get(this.room); return room ? room.size : 0; } catch (_) { return 0; } } _refreshLiveLoop() { const watching = this._watcherCount() > 0; if (watching && !this._liveTimer) { // Prime baselines so the first emitted sample is sane. this._prevCpu = cpuTotals(); this._liveTimer = setInterval(() => this._tick().catch(() => {}), LIVE_SAMPLE_MS); this._liveTimer.unref?.(); // Emit one immediately. this._tick().catch(() => {}); } else if (!watching && this._liveTimer) { clearInterval(this._liveTimer); this._liveTimer = null; } } async _readPm2() { const now = nowMs(); if (this._pm2Cache.data && (now - this._pm2Cache.at) < PM2_POLL_MS) { return this._pm2Cache.data; } const list = await pm2List(); let memBytes = 0; let cpuPercent = 0; let found = false; if (Array.isArray(list)) { for (const proc of list) { const monit = proc?.monit || {}; if (typeof monit.memory === "number") memBytes += monit.memory; if (typeof monit.cpu === "number") cpuPercent += monit.cpu; found = true; } } const data = found ? { memBytes, cpuPercent: round1(cpuPercent) } : null; this._pm2Cache = { at: now, data }; return data; } /** Build one live sample (cheap). */ async _collect() { const now = nowMs(); // CPU (host) via delta const cur = cpuTotals(); let cpuPercent = 0; const idleDiff = cur.idle - this._prevCpu.idle; const totalDiff = cur.total - this._prevCpu.total; if (totalDiff > 0) { cpuPercent = round1((1 - idleDiff / totalDiff) * 100); if (cpuPercent < 0) cpuPercent = 0; if (cpuPercent > 100) cpuPercent = 100; } this._prevCpu = cur; // Memory (host) const memTotal = os.totalmem(); const memFree = os.freemem(); const memUsed = memTotal - memFree; // Storage const storage = await readStorage(); // Network rate (bytes/sec) from /proc/net/dev deltas const net = await readNetCounters(); let rxRate = null; let txRate = null; if (net.rxBytes != null && this._prevNet && this._prevNetAt) { const dt = (now - this._prevNetAt) / 1000; if (dt > 0) { rxRate = Math.max(0, Math.round((net.rxBytes - this._prevNet.rxBytes) / dt)); txRate = Math.max(0, Math.round((net.txBytes - this._prevNet.txBytes) / dt)); } } if (net.rxBytes != null) { this._prevNet = net; this._prevNetAt = now; } // RPS from request counter delta const dtReq = (now - this._prevReqAt) / 1000; let rps = 0; if (dtReq > 0) { rps = round1((this._reqCounter - this._prevReqCount) / dtReq); if (rps < 0) rps = 0; } this._prevReqCount = this._reqCounter; this._prevReqAt = now; // PM2 process aggregate (cached) const pm2 = await this._readPm2(); const sample = { ts: now, cpu: cpuPercent, cores: cur.cores, memUsed, memTotal, memPercent: memTotal > 0 ? round1((memUsed / memTotal) * 100) : 0, diskUsed: storage.usedBytes, diskTotal: storage.totalBytes, diskPercent: storage.percent, netRx: rxRate, netTx: txRate, rps, pm2MemBytes: pm2 ? pm2.memBytes : null, pm2Cpu: pm2 ? pm2.cpuPercent : null, uptimeMs: now - this.startTime, }; // Feed the minute accumulator (averages). const a = this._acc; a.count++; a.cpu += sample.cpu; a.memUsed += sample.memUsed; a.memTotal += sample.memTotal; if (sample.diskUsed != null) a.diskUsed += sample.diskUsed; if (sample.diskTotal != null) a.diskTotal += sample.diskTotal; if (sample.netRx != null) a.netRx += sample.netRx; if (sample.netTx != null) a.netTx += sample.netTx; a.rps += sample.rps; this._lastSample = sample; return sample; } async _services() { const now = nowMs(); if (this._svcCache.data && (now - this._svcCache.at) < this._svcTtlMs) { return this._svcCache.data; } let data = {}; try { data = await this.getServiceStatus(); } catch (_) { data = {}; } this._svcCache = { at: now, data }; return data; } async _tick() { const sample = await this._collect(); if (!this.io) return; const services = await this._services(); this.io.to(this.room).emit("monitor:sample", { ...sample, services }); } /** Persist one averaged row per minute. */ async _persist() { if (!this.db || typeof this.db.query !== "function") return; const a = this._acc; this._acc = this._freshAcc(); let row; if (a.count > 0) { row = { cpu: round1(a.cpu / a.count), memPercent: a.memTotal > 0 ? round1((a.memUsed / a.memTotal) * 100) : 0, diskPercent: a.diskTotal > 0 ? round1((a.diskUsed / a.diskTotal) * 100) : 0, netRx: Math.round(a.netRx / a.count), netTx: Math.round(a.netTx / a.count), rps: round1(a.rps / a.count), }; } else { // No live watchers this window: take one cheap point-in-time read so the // history graph stays continuous without running the 1s loop. const s = await this._collect(); // Reset accumulator again (the collect above pushed into it). this._acc = this._freshAcc(); row = { cpu: s.cpu, memPercent: s.memPercent, diskPercent: s.diskPercent ?? 0, netRx: s.netRx ?? 0, netTx: s.netTx ?? 0, rps: s.rps, }; } try { const d = new Date(); // Bucket to the minute (UTC) for a stable RRD-style key. const bucket = Math.floor(d.getTime() / 60000) * 60000; await this.db.query( `INSERT INTO panel_metrics (bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps) VALUES (?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE cpu_percent = VALUES(cpu_percent), mem_percent = VALUES(mem_percent), disk_percent = VALUES(disk_percent), net_rx_bps = VALUES(net_rx_bps), net_tx_bps = VALUES(net_tx_bps), rps = VALUES(rps)`, [bucket, row.cpu, row.memPercent, row.diskPercent, row.netRx, row.netTx, row.rps] ); } catch (err) { // Never let persistence crash the loop. if (!String(err && err.message).includes("panel_metrics")) { // table missing or transient; stay silent in prod, log once otherwise. } } } /** Retention sweep: drop anything older than RETENTION_DAYS. */ async _cleanup() { if (!this.db || typeof this.db.query !== "function") return; try { const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000; await this.db.query("DELETE FROM panel_metrics WHERE bucket_ts < ?", [cutoff]); } catch (_) { /* ignore */ } } /** Admin REST: fetch history rows for a given UTC day (YYYY-MM-DD). */ async getHistoryForDay(dayStr) { if (!this.db || typeof this.db.query !== "function") return []; const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dayStr || "")); if (!m) return []; const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 0, 0, 0); const end = start + 24 * 60 * 60 * 1000; const rows = await this.db.query( `SELECT bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps FROM panel_metrics WHERE bucket_ts >= ? AND bucket_ts < ? ORDER BY bucket_ts ASC`, [start, end] ); return (rows || []).map((r) => ({ ts: Number(r.bucket_ts), cpu: Number(r.cpu_percent), mem: Number(r.mem_percent), disk: Number(r.disk_percent), netRx: Number(r.net_rx_bps), netTx: Number(r.net_tx_bps), rps: Number(r.rps), })); } /** Admin REST: daily averages across the retained window (for the calendar). */ async getDailySummary() { if (!this.db || typeof this.db.query !== "function") return []; const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000; const rows = await this.db.query( `SELECT FLOOR(bucket_ts / 86400000) AS day_idx, AVG(cpu_percent) AS cpu, AVG(mem_percent) AS mem, AVG(disk_percent) AS disk, AVG(net_rx_bps) AS net_rx, AVG(net_tx_bps) AS net_tx, AVG(rps) AS rps, COUNT(*) AS samples FROM panel_metrics WHERE bucket_ts >= ? GROUP BY day_idx ORDER BY day_idx ASC`, [cutoff] ); return (rows || []).map((r) => ({ ts: Number(r.day_idx) * 86400000, cpu: round1(Number(r.cpu)), mem: round1(Number(r.mem)), disk: round1(Number(r.disk)), netRx: Math.round(Number(r.net_rx)), netTx: Math.round(Number(r.net_tx)), rps: round1(Number(r.rps)), samples: Number(r.samples), })); } /** Current snapshot for the initial REST hydrate when a watcher opens. */ async getSnapshot() { const sample = this._lastSample || (await this._collect()); const services = await this._services(); return { ...sample, services, panelVersion: this.panelVersion, startTime: this.startTime }; } } module.exports = { PanelMetricsCollector, PM2_LOOKUP_DIRS, resolvePm2Binary, pm2List };