vps-health-api/metrics.js
le king fu b740f221af
All checks were successful
CI / verification (pull_request) Successful in 59s
feat(health): 24 h load history and a "saturated" state
GET /health only gave a snapshot, so the monitoring missed the 2026-11-03
saturation and the nights before it. A one-minute tick, armed in the
require.main block, now records host load, CPU by /proc/stat difference
and, when TLS_PROBE_HOSTS is set, the TLS handshake time of each listed
host into an in-memory buffer of 1440 samples (load-history.js, pure).

- /health gains `saturation` ({state: ok|saturated|unknown, since,
  coverageMinutes, load1, cores}) and `tls`, appended after the existing
  keys. Saturated = the last five samples of an unbroken series all have
  load1 > cores; unknown under five samples, after a gap over 3 minutes,
  or when the last sample is over 3 minutes old. No sample at start-up,
  so the state stays unknown for the first five minutes after a deploy.
- GET /health/history (read token) serves {since, coverageMinutes, cores,
  samples}. The buffer restarts from zero at every deploy.
- probeTls() verifies the certificate, times out after 3 s and reports an
  error code only. TLS_PROBE_HOSTS is empty by default: no network call in
  the tests, the CI or boot-from-copy.sh.
- Dockerfile COPY, REVIEW.md Haut table (and review-levels.py), CLAUDE.md,
  docs and .env.example updated.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 20:26:05 -05:00

89 lines
3.2 KiB
JavaScript

const os = require("node:os");
const { execSync } = require("node:child_process");
const { setTimeout: delay } = require("node:timers/promises");
// Host metrics collection (CPU / memory / disk), extracted from index.js so the
// same code can be reused by the local workstation agent. Pure host probing:
// no HTTP, no config, no side effects — the caller owns the response shape.
function readProcStat() {
try {
const line = execSync("head -1 /proc/stat", { encoding: "utf-8" }).trim();
const parts = line.split(/\s+/).slice(1).map(Number);
const idle = parts[3] + parts[4];
const total = parts.reduce((a, b) => a + b, 0);
return { idle, total };
} catch {
return null;
}
}
// Busy share of the CPU between two /proc/stat readings, in percent. Null when
// a reading is missing or no tick elapsed: the caller decides the fallback.
function cpuPercentBetween(prev, cur) {
if (!prev || !cur) return null;
const dIdle = cur.idle - prev.idle;
const dTotal = cur.total - prev.total;
if (dTotal <= 0) return null;
return Math.round((1 - dIdle / dTotal) * 100);
}
async function getCpuPercent() {
const t1 = readProcStat();
if (!t1) return 0;
// Sample over 500ms without blocking the event loop, so other async work
// (e.g. the Logto healthcheck) can run concurrently.
await delay(500);
// /health has always answered 0 when /proc/stat cannot be read: keep it.
return cpuPercentBetween(t1, readProcStat()) ?? 0;
}
function getDisk() {
try {
// Alpine df doesn't support --output, use standard POSIX format
const out = execSync("df -k /", { encoding: "utf-8" });
const parts = out.trim().split("\n")[1].trim().split(/\s+/);
// df -k columns: Filesystem, 1K-blocks, Used, Available, Use%, Mounted
const totalGB = +(parseInt(parts[1], 10) / 1e6).toFixed(1);
const usedGB = +(parseInt(parts[2], 10) / 1e6).toFixed(1);
const freeGB = +(parseInt(parts[3], 10) / 1e6).toFixed(1);
const usagePercent = totalGB > 0 ? Math.round((usedGB / totalGB) * 100) : 0;
return { totalGB, usedGB, freeGB, usagePercent };
} catch {
return { totalGB: 0, usedGB: 0, freeGB: 0, usagePercent: 0 };
}
}
// Collect CPU, memory and disk into the `{ cpu, memory, disk }` slice of the
// /health payload. Awaiting getCpuPercent() first is deliberate: the 500ms
// sample is the only await here, so a caller running this inside a
// Promise.all() keeps its other work (the Logto check) fully concurrent.
// Everything else is cheap and synchronous.
async function collectMetrics() {
const cpus = os.cpus();
const totalMem = os.totalmem();
const freeMem = os.freemem();
const usedMem = totalMem - freeMem;
const cpuUsagePercent = await getCpuPercent();
return {
cpu: {
model: cpus[0]?.model?.trim() || "unknown",
cores: cpus.length,
loadAvg: os.loadavg().map((l) => +l.toFixed(2)),
usagePercent: cpuUsagePercent,
},
memory: {
totalGB: +(totalMem / 1e9).toFixed(1),
usedGB: +(usedMem / 1e9).toFixed(1),
freeGB: +(freeMem / 1e9).toFixed(1),
usagePercent: Math.round((usedMem / totalMem) * 100),
},
disk: getDisk(),
};
}
module.exports = { readProcStat, cpuPercentBetween, getCpuPercent, getDisk, collectMetrics };