From 88354ec07807d9785a32ad42075d05e216c16f26 Mon Sep 17 00:00:00 2001 From: yuez Date: Wed, 28 Oct 2026 08:13:58 +0800 Subject: [PATCH] feat(daemon): sample host cpu, memory and disk for /info and /resources MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- src/cli/wiring.ts | 2 + src/core/sysinfo.ts | 301 ++++++++++++++++++++++++++++++++++++++ src/daemon/http.ts | 21 ++- src/daemon/server.ts | 1 + test/core/sysinfo.test.ts | 122 +++++++++++++++ test/daemon/harness.ts | 24 +++ test/daemon/http.test.ts | 26 ++++ 7 files changed, 492 insertions(+), 5 deletions(-) create mode 100644 src/core/sysinfo.ts create mode 100644 test/core/sysinfo.test.ts diff --git a/src/cli/wiring.ts b/src/cli/wiring.ts index e887eed..6566c61 100644 --- a/src/cli/wiring.ts +++ b/src/cli/wiring.ts @@ -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; +} + +export interface SysinfoDeps { + now?: () => number; + readFile?: (path: string) => Promise; + statfs?: (path: string) => Promise; + 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); + 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 | null = null; + + async function doSample(): Promise { + 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 { + 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; + }, + }; +} diff --git a/src/daemon/http.ts b/src/daemon/http.ts index 9993e3b..bb866a3 100644 --- a/src/daemon/http.ts +++ b/src/daemon/http.ts @@ -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 { 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 { 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 { 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 }; diff --git a/src/daemon/server.ts b/src/daemon/server.ts index 6c8c877..19ac4ee 100644 --- a/src/daemon/server.ts +++ b/src/daemon/server.ts @@ -102,6 +102,7 @@ export async function startServer(config: Config, deps: ServerDeps): Promise ({ connections: ws.connections(), eventsSent: ws.eventsSent() }), + sysinfo: deps.sysinfo, }); let closing: Promise | undefined; diff --git a/test/core/sysinfo.test.ts b/test/core/sysinfo.test.ts new file mode 100644 index 0000000..70453b5 --- /dev/null +++ b/test/core/sysinfo.test.ts @@ -0,0 +1,122 @@ +import { describe, expect, it } from "vitest"; +import { + cpuPercentBetween, + cpuTimesFromCpus, + createSysinfo, + diskFromStatfs, + parseMeminfo, + parseProcStat, +} from "../../src/core/sysinfo.js"; + +const mem = (available = "MemAvailable: 512 kB") => `MemTotal: 1024 kB\n${available}\nMemFree: 128 kB\nBuffers: 64 kB\nCached: 128 kB\n`; +const cpus = (user: number, idle: number) => [{ times: { user, nice: 0, sys: 0, idle, irq: 0 } }]; + +describe("sysinfo", () => { + it("parses meminfo using MemAvailable and fallback fields", () => { + expect(parseMeminfo(mem())).toEqual({ totalBytes: 1024 * 1024, availableBytes: 512 * 1024 }); + expect(parseMeminfo(mem("MemFree: 128 kB"))).toEqual({ totalBytes: 1024 * 1024, availableBytes: 320 * 1024 }); + expect(parseMeminfo("MemAvailable: 1 kB")).toBeNull(); + }); + + it("parses proc stat and aggregates cpu times", () => { + expect(parseProcStat("cpu 10 2 3 40 5 6 7\ncpu0 1 0 0 1 0 0 0\n")).toEqual({ idle: 45, total: 73 }); + expect(cpuTimesFromCpus(cpus(10, 40))).toEqual({ idle: 40, total: 50 }); + }); + + it("calculates bounded CPU percentages", () => { + expect(cpuPercentBetween(null, { idle: 1, total: 2 })).toBeNull(); + expect(cpuPercentBetween({ idle: 1, total: 2 }, { idle: 1, total: 2 })).toBeNull(); + expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 5, total: 10 })).toBeNull(); + expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 15, total: 30 })).toBe(50); + expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 0, total: 30 })).toBe(100); + expect(cpuPercentBetween({ idle: 10, total: 20 }, { idle: 30, total: 30 })).toBe(0); + }); + + it("calculates disk usage and handles null cases", () => { + expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 4 })).toEqual({ totalBytes: 1000, usedBytes: 600, percent: 60 }); + expect(diskFromStatfs({ bsize: 100, blocks: 0, bfree: 0 })).toBeNull(); + expect(diskFromStatfs({ bsize: 0, blocks: 10, bfree: 0 })).toBeNull(); + expect(diskFromStatfs({ bsize: Number.NaN, blocks: 10, bfree: 0 })).toBeNull(); + expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: 20 })).toEqual({ + totalBytes: 1000, + usedBytes: 0, + percent: 0, + }); + expect(diskFromStatfs({ bsize: 100, blocks: 10, bfree: -1 })).toBeNull(); + }); + + it("clamps malformed memory sampler values", async () => { + const result = await createSysinfo({ + now: () => 1, + platform: "darwin", + cpus: () => cpus(10, 10), + totalmem: () => Number.NaN, + freemem: () => Number.POSITIVE_INFINITY, + loadavg: () => [0, 0, 0], + statfs: async () => ({ bsize: 100, blocks: 10, bfree: 20 }), + }).sample(); + expect(result.memTotalBytes).toBe(0); + expect(result.memUsedBytes).toBe(0); + expect(result.memPercent).toBe(0); + expect(result.diskPercent).toBe(0); + }); + + it("samples injected system data, caches, and expires", async () => { + let clock = 1000; + let reads = 0; + let stats = 0; + const sampler = createSysinfo({ + now: () => clock, + platform: "linux", + diskPath: "/test", + readFile: async (path) => { reads++; return path === "/proc/stat" ? "cpu 10 0 0 10 0 0 0" : mem(); }, + statfs: async () => { stats++; return { bsize: 100, blocks: 10, bfree: 4 }; }, + cpus: () => cpus(10, 10), + totalmem: () => 999, + freemem: () => 1, + loadavg: () => [1.234, 2.345, 3.456], + cacheMs: 100, + }); + const first = await sampler.sample(); + expect(first).toEqual({ sampledAt: 1000, cpuPercent: null, cpuCores: 1, loadAvg: [1.23, 2.35, 3.46], memUsedBytes: 512 * 1024, memTotalBytes: 1024 * 1024, memPercent: 50, diskPath: "/test", diskUsedBytes: 600, diskTotalBytes: 1000, diskPercent: 60 }); + await sampler.sample(); + expect(reads).toBe(2); + expect(stats).toBe(1); + clock = 1100; + await sampler.sample(); + expect(reads).toBe(4); + expect(stats).toBe(2); + }); + + it("resolves when total memory probing throws", async () => { + const sampler = createSysinfo({ + platform: "darwin", + cpus: () => cpus(1, 1), + totalmem: () => { throw new Error("totalmem unavailable"); }, + freemem: () => 25, + statfs: async () => ({ bsize: 1, blocks: 1, bfree: 0 }), + loadavg: () => [0, 0, 0], + }); + await expect(sampler.sample()).resolves.toMatchObject({ memTotalBytes: 0, memUsedBytes: 0, memPercent: 0 }); + }); + + it("falls back and resolves I/O failures with null CPU and disk", async () => { + const result = await createSysinfo({ + now: () => 1, + platform: "linux", + readFile: async () => { throw new Error("read"); }, + statfs: async () => { throw new Error("statfs"); }, + cpus: () => { throw new Error("cpu"); }, + totalmem: () => 0, + freemem: () => 0, + loadavg: () => { throw new Error("load"); }, + }).sample(); + expect(result.cpuPercent).toBeNull(); + expect(result.loadAvg).toBeNull(); + expect(result.diskUsedBytes).toBeNull(); + expect(result.diskTotalBytes).toBeNull(); + expect(result.diskPercent).toBeNull(); + expect(result.memTotalBytes).toBe(0); + expect(result.memUsedBytes).toBe(0); + }); +}); diff --git a/test/daemon/harness.ts b/test/daemon/harness.ts index 76c3017..ecde64b 100644 --- a/test/daemon/harness.ts +++ b/test/daemon/harness.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { AuthStore } from "../../src/daemon/auth.js"; import { startServer, type StartedServer } from "../../src/daemon/server.js"; import type { Config, Limits } from "../../src/config.js"; +import type { SysinfoSampler, SystemStats } from "../../src/core/sysinfo.js"; import type { WorkspaceInfo } from "../../src/protocol/types.js"; import { FakeBus, FakeInstanceManager, FakeWorkspaceStore } from "./fakes.js"; @@ -31,6 +32,26 @@ export function testConfig(overrides: Partial = {}): Config { return { ...base, ...overrides, limits: { ...base.limits, ...(overrides.limits ?? {}) } }; } +/** Deterministic fake sampler returned when no override is provided. */ +export const FAKE_SYSTEM_STATS: SystemStats = { + sampledAt: 1_700_000_000_000, + cpuPercent: 42, + cpuCores: 4, + loadAvg: [1.5, 1.2, 0.9], + memUsedBytes: 4 * 1024 ** 3, + memTotalBytes: 16 * 1024 ** 3, + memPercent: 25, + diskPath: "/tmp/pi2-test", + diskUsedBytes: 50 * 1024 ** 3, + diskTotalBytes: 200 * 1024 ** 3, + diskPercent: 25, +}; + +export function makeFakeSysinfoSampler(stats: Partial = {}): SysinfoSampler { + const merged: SystemStats = { ...FAKE_SYSTEM_STATS, ...stats }; + return { sample: async () => merged }; +} + export interface HarnessOptions { workspaces?: WorkspaceInfo[]; seedInstances?: string[]; @@ -45,6 +66,8 @@ export interface HarnessOptions { snapshotWaitMs?: number; measureBufferedAmount?: (socket: unknown) => number; }; + /** Override the sysinfo sampler; defaults to a deterministic fake (no real OS I/O). */ + sysinfo?: SysinfoSampler; } export interface Harness { @@ -107,6 +130,7 @@ export async function createHarness(options: HarnessOptions = {}): Promise { expect(res.status).toBe(401); }); + it("includes injected system stats in resources", async () => { + const custom = await createHarness({ sysinfo: (await import("./harness.js")).makeFakeSysinfoSampler({ cpuPercent: 42 }) }); + try { + const customToken = custom.createToken(); + const response = await fetch(`${custom.url}/api/v1/resources`, { + headers: { Authorization: `Bearer ${customToken}` }, + }); + expect(response.status).toBe(200); + expect((await response.json()).system).toEqual(expect.objectContaining({ cpuPercent: 42 })); + } finally { + await custom.cleanup(); + } + }); + + it("includes system stats in info", async () => { + const response = await fetch(`${h.url}/api/v1/info`); + expect(response.status).toBe(200); + expect(await response.json()).toEqual(expect.objectContaining({ + cpuCores: 4, + loadAvg: [1.5, 1.2, 0.9], + cpu: 42, + mem: 25, + disk: 25, + })); + }); + it("redirects a scanned /pair/ link to the zero-input connect page", async () => { const res = await fetch(`${h.url}/pair/abcd2345`, { redirect: "manual" }); expect(res.status).toBe(302);