import { execFile, execFileSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import type { agent } from "@crosscode/contracts"; import { readFrps } from "./central"; import { paths } from "./paths"; /** * The server's stats every 60 s (AGENT-1.0-PLAN §10, crosscode.agent-stats/1): RAM, CPU, disks, * uptime, versions, frpc, and each PM2 process with its church and product. Read from /proc and * the tools that are there; anything missing is null rather than an error. */ export const AGENT_VERSION = "1.2.0"; function run(cmd: string, args: string[], timeoutMs = 10_000): Promise { return new Promise((resolve) => { execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 10_000_000 }, (err, stdout) => resolve(err ? null : String(stdout))); }); } export function parseMeminfo(text: string): agent.AgentStats["ram"] { const kb = (key: string) => Number(new RegExp(`^${key}:\\s+(\\d+)`, "m").exec(text)?.[1] ?? 0) * 1024; const total = kb("MemTotal"); const available = kb("MemAvailable"); return { totalBytes: total, usedBytes: Math.max(0, total - available), availableBytes: available, swapTotalBytes: kb("SwapTotal"), swapUsedBytes: Math.max(0, kb("SwapTotal") - kb("SwapFree")) }; } /** CPU busy % between two /proc/stat readings. */ export function cpuPercent(a: string, b: string): number { const parse = (t: string) => { const f = (/^cpu\s+(.+)$/m.exec(t)?.[1] ?? "").trim().split(/\s+/).map(Number); const idle = (f[3] ?? 0) + (f[4] ?? 0); return { idle, total: f.reduce((s, n) => s + (Number.isFinite(n) ? n : 0), 0) }; }; const x = parse(a), y = parse(b); const total = y.total - x.total; if (total <= 0) return 0; return Math.min(100, Math.max(0, Math.round(((total - (y.idle - x.idle)) / total) * 1000) / 10)); } async function disks(): Promise { const out = await run("df", ["-P", "-B1", "-x", "tmpfs", "-x", "devtmpfs", "-x", "squashfs", "-x", "overlay"]); if (!out) return []; return out.trim().split("\n").slice(1).map((l) => l.trim().split(/\s+/)).filter((c) => c.length >= 6 && c[5]!.startsWith("/")) .slice(0, 30).map((c) => ({ mount: c[5]!, totalBytes: Number(c[1]), usedBytes: Number(c[2]), freeBytes: Number(c[3]) })); } function osName(): string { try { const t = fs.readFileSync("/etc/os-release", "utf8"); return /^PRETTY_NAME="?([^"\n]+)"?/m.exec(t)?.[1] ?? `${os.type()} ${os.release()}`; } catch { return `${os.type()} ${os.release()}`; } } const versionIn = (text: string | null) => (text ? /(\d+\.\d+(\.\d+)?)/.exec(text)?.[1] ?? null : null); /** church.env → { app user → [{ church, product, names }] }, read as data like the script does. */ export function churchProcesses(sitesDir = paths.sites): Map { const byUser = new Map(); let entries: string[]; try { entries = fs.readdirSync(sitesDir); } catch { return byUser; } for (const church of entries) { if (!/^[a-z][a-z0-9-]{0,39}$/.test(church)) continue; let text: string; try { text = fs.readFileSync(path.join(sitesDir, church, "church.env"), "utf8"); } catch { continue; } const vars = new Map(); for (const line of text.split(/\r?\n/)) { const m = /^([A-Z][A-Z0-9_]*)=("([^"]*)"|'([^']*)'|([^#\s]*))/.exec(line); if (m) vars.set(m[1]!, m[3] ?? m[4] ?? m[5] ?? ""); } for (const product of ["accounts", "events", "website", "app"] as const) { const p = product.toUpperCase(); const user = vars.get(`${p}_USER`); const names = (vars.get(`${p}_PM2`) ?? "").split(/\s+/).filter(Boolean); if (!user || !names.length || !/^[a-z_][a-z0-9_-]{0,31}$/.test(user)) continue; const list = byUser.get(user) ?? []; list.push({ church, product, names }); byUser.set(user, list); } } return byUser; } interface Pm2Proc { name?: string; monit?: { memory?: number; cpu?: number }; pm2_env?: { status?: string; restart_time?: number; pm_uptime?: number } } function pm2Running(user: string): boolean { try { const home = execFileSync("getent", ["passwd", user], { encoding: "utf8" }).split(":")[5]; const pid = Number(fs.readFileSync(`${home}/.pm2/pm2.pid`, "utf8").trim()); if (!pid) return false; process.kill(pid, 0); return true; } catch { return false; } } async function pm2Processes(): Promise { const out: agent.AgentStats["processes"] = []; for (const [user, installs] of churchProcesses()) { // Only ask a daemon that's running: `pm2 jlist` would otherwise start an empty one inside this // agent's service, which dies with the agent (found in the VM test). if (!pm2Running(user)) continue; const json = await run("sudo", ["-n", "-u", user, "-H", "--", "pm2", "jlist"]); let list: Pm2Proc[]; try { list = JSON.parse(json ?? "[]") as Pm2Proc[]; } catch { list = []; } for (const p of list) { const owner = installs.find((i) => i.names.includes(p.name ?? "")); out.push({ name: String(p.name ?? "?").slice(0, 100), church: owner?.church ?? null, product: owner?.product ?? null, status: String(p.pm2_env?.status ?? "unknown").slice(0, 40), memoryBytes: Number(p.monit?.memory ?? 0), cpuPercent: Number(p.monit?.cpu ?? 0), restarts: Math.max(0, Math.trunc(Number(p.pm2_env?.restart_time ?? 0))), uptimeSeconds: p.pm2_env?.pm_uptime ? Math.max(0, (Date.now() - p.pm2_env.pm_uptime) / 1000) : 0, }); } } return out.slice(0, 200); } /** A systemd unit is active; null when there's no systemctl. (is-active exits non-zero when inactive.) */ function active(unit: string): Promise { return new Promise((resolve) => { execFile("systemctl", ["is-active", unit], { timeout: 10_000 }, (err, stdout) => { if (err && (err as NodeJS.ErrnoException).code === "ENOENT") resolve(null); else resolve(String(stdout).trim() === "active"); }); }); } export async function collectStats(mode: agent.AgentMode): Promise { const read = (f: string) => { try { return fs.readFileSync(f, "utf8"); } catch { return ""; } }; const stat1 = read("/proc/stat"); await new Promise((r) => setTimeout(r, 1000)); const stat2 = read("/proc/stat"); const [load1, load5, load15] = os.loadavg(); const [diskList, postgres, frpc, processes, frpcRunning] = await Promise.all([ disks(), run("psql", ["--version"]), run("frpc", ["-v"]), mode === "church" ? pm2Processes() : Promise.resolve([]), mode === "church" ? active("frpc") : Promise.resolve(null), ]); const stats: agent.AgentStats = { schema: "crosscode.agent-stats/1", at: new Date().toISOString(), ram: parseMeminfo(read("/proc/meminfo")), cpu: { percent: cpuPercent(stat1, stat2), load1: load1 ?? 0, load5: load5 ?? 0, load15: load15 ?? 0, cores: Math.max(1, os.cpus().length) }, disks: diskList, uptimeSeconds: os.uptime(), versions: { os: osName().slice(0, 200), node: process.versions.node, postgres: versionIn(postgres), frpc: versionIn(frpc), agent: AGENT_VERSION }, frpcRunning, processes, }; if (mode === "central") { const frps = readFrps(); stats.central = { proxyBindAddr: frps?.proxyBindAddr ?? null, allowPorts: frps?.allowPorts ?? null, frpsRunning: await active("frps") }; } return stats; }