feat(daemon): sample host cpu, memory and disk for /info and /resources

The status page had no host figures: `/api/v1/info` only carried identity and
`/api/v1/resources` only carried instance RSS, so the CPU/mem/disk tiles fell
back to "—" and the memory tile faked its percentage from RSS over physical
memory.

src/core/sysinfo.ts is a zero-dependency sampler: CPU from the /proc/stat delta
(null on the first read, since it needs two samples), load average from
os.loadavg(), memory from os.freemem/os.totalmem, and disk via statfs on the
daemon's state dir. One sample is cached for ~1 s and shared between /info and
/resources, so polling both does not double the syscalls. /info gains additive
`cpu`, `mem`, `disk` percentages plus `cpuCores` and `loadAvg`; /resources gains
a `system` object with the byte counts, the disk path and `sampledAt`.

Every field is optional on the client side: an older daemon simply omits them.
This commit is contained in:
yuez committed 2026-10-28 08:13:58 +08:00
1 parent 1664227c3b
commit 88354ec078
7 files changed
+492 -5

No files matched your search

+2
View File
@@ -16,6 +16,7 @@ import { join } from "node:path";
import { loadConfig, type Config, type ConfigEnv } from "../config.js";
import { dataDir, daemonSocketPath, daemonTokenPath, runtimeDir, stateDir } from "../core/paths.js";
import type { Logger } from "../core/interfaces.js";
import { createSysinfo } from "../core/sysinfo.js";
import { AuthStore } from "../daemon/auth.js";
import { InMemoryBus } from "../daemon/hub.js";
import { startServer, type ServerDeps, type StartedServer } from "../daemon/server.js";
@@ -144,6 +145,7 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
startedAt,
now,
sysinfo: createSysinfo({ now }),
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
};
+301
View File
@@ -0,0 +1,301 @@
/**
* Host sysinfo sampler — CPU / memory / disk with injectable I/O.
* Zero runtime dependencies; no OS calls at import time.
*/
import { statfs as nodeStatfs } from "node:fs/promises";
import * as nodeOs from "node:os";
import { readFile as nodeReadFile } from "node:fs/promises";
import { stateDir } from "./paths.js";
/* ------------------------------------------------------------------ */
/* Public types */
/* ------------------------------------------------------------------ */
export interface CpuTimes {
idle: number;
total: number;
}
export interface StatFsLike {
bsize: number;
blocks: number;
bfree: number;
}
export interface SystemStats {
sampledAt: number;
cpuPercent: number | null;
cpuCores: number;
loadAvg: [number, number, number] | null;
memUsedBytes: number;
memTotalBytes: number;
memPercent: number;
diskPath: string;
diskUsedBytes: number | null;
diskTotalBytes: number | null;
diskPercent: number | null;
}
export interface SysinfoSampler {
sample(): Promise<SystemStats>;
}
export interface SysinfoDeps {
now?: () => number;
readFile?: (path: string) => Promise<string>;
statfs?: (path: string) => Promise<StatFsLike>;
cpus?: () => Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>;
totalmem?: () => number;
freemem?: () => number;
loadavg?: () => number[];
platform?: NodeJS.Platform;
diskPath?: string;
cacheMs?: number;
}
/* ------------------------------------------------------------------ */
/* Pure parsing helpers (exported for tests) */
/* ------------------------------------------------------------------ */
/**
* Parse /proc/meminfo text.
* Tries MemAvailable; falls back to MemFree + Buffers + Cached.
*/
export function parseMeminfo(text: string): { totalBytes: number; availableBytes: number } | null {
const kbOf = (label: string): number | null => {
const m = new RegExp(`^${label}:\\s+(\\d+)\\s+kB`, "m").exec(text);
return m ? Number(m[1]) * 1024 : null;
};
const total = kbOf("MemTotal");
if (total === null) return null;
let available = kbOf("MemAvailable");
if (available === null) {
const free = kbOf("MemFree");
const buffers = kbOf("Buffers") ?? 0;
const cached = kbOf("Cached") ?? 0;
if (free === null) return null;
available = free + buffers + cached;
}
return { totalBytes: total, availableBytes: available };
}
/**
* Parse the aggregate `cpu ` line from /proc/stat.
* Returns cumulative idle and total jiffies.
*/
export function parseProcStat(text: string): CpuTimes | null {
const m = /^cpu\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)/m.exec(text);
if (!m) return null;
const [, user, nice, sys, idle, iowait, irq, softirq] = m.map(Number);
const idleTime = idle! + iowait!;
const total = user! + nice! + sys! + idle! + iowait! + irq! + softirq!;
return { idle: idleTime, total };
}
/** Aggregate os.cpus() array into CpuTimes. */
export function cpuTimesFromCpus(
cpus: Array<{ times: { user: number; nice: number; sys: number; idle: number; irq: number } }>,
): CpuTimes {
let idle = 0;
let total = 0;
for (const cpu of cpus) {
const t = cpu.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total };
}
/**
* Derive CPU busy % from two successive CpuTimes snapshots.
* Returns null on the first sample (prev === null) or when the delta is zero.
*/
export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number | null {
if (prev === null) return null;
const totalDelta = next.total - prev.total;
if (totalDelta <= 0) return null;
const idleDelta = next.idle - prev.idle;
const busy = 1 - idleDelta / totalDelta;
return Math.min(100, Math.max(0, Math.round(busy * 100)));
}
/**
* Derive disk usage from a statfs result.
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
*/
export function diskFromStatfs(stats: StatFsLike): { totalBytes: number; usedBytes: number; percent: number } | null {
const { bsize, blocks, bfree } = stats;
if (![bsize, blocks, bfree].every((value) => Number.isFinite(value) && value >= 0)) return null;
if (blocks <= 0 || bsize <= 0) return null;
const totalBytes = blocks * bsize;
if (!Number.isFinite(totalBytes)) return null;
const rawUsedBytes = (blocks - bfree) * bsize;
const usedBytes = Math.min(totalBytes, Math.max(0, Number.isFinite(rawUsedBytes) ? rawUsedBytes : 0));
const percent = Math.min(100, Math.max(0, Math.round((usedBytes / totalBytes) * 100)));
return { totalBytes, usedBytes, percent };
}
/* ------------------------------------------------------------------ */
/* Sampler factory */
/* ------------------------------------------------------------------ */
export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
const now = deps.now ?? Date.now;
const cacheMs = deps.cacheMs ?? 1000;
const platform = deps.platform ?? process.platform;
const diskPath = deps.diskPath ?? stateDir();
// I/O callables — real by default, injectable for tests
const readFile = deps.readFile ?? ((path: string) => nodeReadFile(path, "utf8"));
const statfsImpl = deps.statfs ?? ((path: string) => nodeStatfs(path) as Promise<StatFsLike>);
const cpus = deps.cpus ?? (() => nodeOs.cpus());
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
const freemem = deps.freemem ?? (() => nodeOs.freemem());
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
let prevCpuTimes: CpuTimes | null = null;
let cachedResult: SystemStats | null = null;
let cachedAt = -Infinity;
let inFlight: Promise<SystemStats> | null = null;
async function doSample(): Promise<SystemStats> {
const sampledAt = now();
// ── CPU ──────────────────────────────────────────────────────
let nextCpuTimes: CpuTimes | null = null;
if (platform === "linux") {
try {
const text = await readFile("/proc/stat");
nextCpuTimes = parseProcStat(text);
} catch {
// fall through to os.cpus()
}
}
if (nextCpuTimes === null) {
try {
nextCpuTimes = cpuTimesFromCpus(cpus());
} catch {
nextCpuTimes = null;
}
}
const cpuPercent = nextCpuTimes !== null ? cpuPercentBetween(prevCpuTimes, nextCpuTimes) : null;
if (nextCpuTimes !== null) prevCpuTimes = nextCpuTimes;
let cpuCores = 1;
try {
cpuCores = Math.max(1, cpus().length);
} catch {
// keep 1
}
// ── loadAvg ──────────────────────────────────────────────────
let loadAvgResult: [number, number, number] | null = null;
if (platform !== "win32") {
try {
const raw = loadavg();
if (raw.length >= 3) {
loadAvgResult = [
Math.round(raw[0]! * 100) / 100,
Math.round(raw[1]! * 100) / 100,
Math.round(raw[2]! * 100) / 100,
];
}
} catch {
loadAvgResult = null;
}
}
// ── Memory ───────────────────────────────────────────────────
let memTotalBytes: number;
let memUsedBytes: number;
let parsed: { totalBytes: number; availableBytes: number } | null = null;
if (platform === "linux") {
try {
const text = await readFile("/proc/meminfo");
parsed = parseMeminfo(text);
} catch {
// fall through to os
}
}
if (parsed !== null && Number.isFinite(parsed.totalBytes) && parsed.totalBytes >= 0 &&
Number.isFinite(parsed.availableBytes) && parsed.availableBytes >= 0) {
memTotalBytes = parsed.totalBytes;
memUsedBytes = parsed.totalBytes - parsed.availableBytes;
} else {
let rawTotal = 0;
let rawFree = 0;
try {
rawTotal = totalmem();
} catch {
// leave the total at zero
}
try {
rawFree = freemem();
} catch {
// leave free memory at zero
}
memTotalBytes = Number.isFinite(rawTotal) && rawTotal >= 0 ? rawTotal : 0;
const freeBytes = Number.isFinite(rawFree) && rawFree >= 0 ? rawFree : 0;
memUsedBytes = memTotalBytes - freeBytes;
}
memUsedBytes = Math.min(memTotalBytes, Math.max(0, Number.isFinite(memUsedBytes) ? memUsedBytes : 0));
const memPercent = memTotalBytes > 0
? Math.min(100, Math.max(0, Math.round((memUsedBytes / memTotalBytes) * 100)))
: 0;
// ── Disk ─────────────────────────────────────────────────────
let diskUsedBytes: number | null = null;
let diskTotalBytes: number | null = null;
let diskPercent: number | null = null;
try {
const sf = await statfsImpl(diskPath);
const result = diskFromStatfs(sf);
if (result !== null) {
diskUsedBytes = result.usedBytes;
diskTotalBytes = result.totalBytes;
diskPercent = result.percent;
}
} catch {
// leave nulls
}
return {
sampledAt,
cpuPercent,
cpuCores,
loadAvg: loadAvgResult,
memUsedBytes,
memTotalBytes,
memPercent,
diskPath,
diskUsedBytes,
diskTotalBytes,
diskPercent,
};
}
return {
async sample(): Promise<SystemStats> {
const t = now();
if (cachedResult !== null && t - cachedAt < cacheMs) {
return cachedResult;
}
if (inFlight) return inFlight;
inFlight = doSample().then(
(result) => {
cachedResult = result;
cachedAt = now();
inFlight = null;
return result;
},
(err) => {
inFlight = null;
// should never throw, but just in case
throw err;
},
);
return inFlight;
},
};
}
+16 -5
View File
@@ -8,6 +8,7 @@ import type { Bus, InstanceManager, Logger, WorkspaceStore } from "../core/inter
import { ERROR_CODES, errorBody } from "../protocol/errors.js";
import { PROTOCOL_VERSION, type CommandRequest } from "../protocol/types.js";
import type { Config } from "../config.js";
import type { SysinfoSampler } from "../core/sysinfo.js";
import { networkBases } from "../core/network.js";
import { encodeQr, fitsQr } from "../core/qr.js";
import type { AuthStore, DevicePublic } from "./auth.js";
@@ -39,6 +40,7 @@ export interface AppDeps {
startedAt?: number;
now?: () => number;
metrics?: () => DaemonMetrics;
sysinfo?: SysinfoSampler;
/** Redeem budget; injectable so tests can advance the clock. */
pairLimiter?: PairRateLimiter;
}
@@ -191,8 +193,9 @@ export function createApp(deps: AppDeps): Hono<Env> {
await next();
});
app.get("/api/v1/info", (c) =>
c.json({
app.get("/api/v1/info", async (c) => {
const system = await deps.sysinfo?.sample();
return c.json({
v: PROTOCOL_VERSION,
daemonId: deps.daemonId,
machineId: deps.machineId ?? deps.daemonId,
@@ -207,8 +210,13 @@ export function createApp(deps: AppDeps): Hono<Env> {
limits: config.limits,
host: config.host,
publicUrl: config.publicUrl,
}),
);
cpuCores: system?.cpuCores,
loadAvg: system?.loadAvg ?? null,
...(typeof system?.cpuPercent === "number" ? { cpu: system.cpuPercent } : {}),
...(typeof system?.memPercent === "number" ? { mem: system.memPercent } : {}),
...(typeof system?.diskPercent === "number" ? { disk: system.diskPercent } : {}),
});
});
/**
* Local-browser login handshake: loopback + the local CLI token only.
@@ -324,7 +332,10 @@ export function createApp(deps: AppDeps): Hono<Env> {
return c.body(null, 204);
});
app.get("/api/v1/resources", async (c) => c.json(await instances.resources()));
app.get("/api/v1/resources", async (c) => {
const [snapshot, system] = await Promise.all([instances.resources(), deps.sysinfo?.sample()]);
return c.json(system === undefined ? snapshot : { ...snapshot, system });
});
app.get("/api/v1/diagnostics", (c) => {
const metrics = deps.metrics?.() ?? { connections: 0 };
+1
View File
@@ -102,6 +102,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise<Sta
startedAt: deps.startedAt,
now: deps.now,
metrics: () => ({ connections: ws.connections(), eventsSent: ws.eventsSent() }),
sysinfo: deps.sysinfo,
});
let closing: Promise<void> | undefined;