fix(daemon): sample disk usage on the filesystems pi2d uses
The status tile read `—` on a fresh machine: the sampler ran `statfs` on the daemon's state dir, which is created lazily on the first instance log, so the call failed with ENOENT and `diskUsedBytes`/`diskTotalBytes`/`diskPercent` all came back null — `/info` then dropped `disk` altogether and the failure was indistinguishable from a full disk. `probeMount()` now walks up to the nearest existing ancestor and then to the filesystem boundary (`st_dev` change), so a sample describes a volume, not a directory. Candidates are pi2d's own write targets — `/` (the home volume on macOS, where `/` is the sealed read-only system volume), the pi session store and the visible workspace roots — never a mount-table dump: an unrelated or hung network mount must not stall the sampler. Rows are deduped by `st_dev`, sorted most-constrained first, capped at four, and reported as `system.disks[]` with the legacy scalars aliasing the worst row. A sample that yields nothing now carries `diskError` instead of silent nulls. The status tile shows the worst filesystem and, when several are in play, one quiet row per mount instead of a single percentage that hides the full volume.
This commit is contained in:
1 parent
1d907c08fa
commit
01fd7b9922
9 files changed
+474
-31
No files matched your search
+12
-1
@@ -145,7 +145,18 @@ export async function wireDaemon(options: WireOptions = {}): Promise<WiredDaemon
|
||||
machineId: options.machineId ?? machineIdFor(env.HOSTNAME ?? process.env.HOSTNAME ?? "localhost"),
|
||||
startedAt,
|
||||
now,
|
||||
sysinfo: createSysinfo({ now }),
|
||||
sysinfo: createSysinfo({
|
||||
now,
|
||||
// Only the filesystems pi2d actually writes to: root, the pi session
|
||||
// store (built in) and the visible workspace roots. Hidden/secondary
|
||||
// rows are excluded so a stale ghost dir never adds a disk row.
|
||||
diskPaths: () =>
|
||||
(workspaceStore?.list() ?? [])
|
||||
.filter((workspace) => workspace.exists && workspace.visibility !== "secondary")
|
||||
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
|
||||
.slice(0, 8)
|
||||
.map((workspace) => workspace.cwd),
|
||||
}),
|
||||
...(options.server?.heartbeatMs === undefined ? {} : { heartbeatMs: options.server.heartbeatMs }),
|
||||
...(options.server?.ws === undefined ? {} : { ws: options.server.ws }),
|
||||
};
|
||||
|
||||
+200
-18
@@ -2,10 +2,11 @@
|
||||
* 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 { stat as nodeStat, 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";
|
||||
import { dirname, resolve as resolvePath } from "node:path";
|
||||
import { IS_MAC, sessionsRoot, stateDir } from "./paths.js";
|
||||
|
||||
/* ------------------------------------------------------------------ */
|
||||
/* Public types */
|
||||
@@ -20,6 +21,27 @@ export interface StatFsLike {
|
||||
bsize: number;
|
||||
blocks: number;
|
||||
bfree: number;
|
||||
/** Linux filesystem magic (`f_type`); used for the best-effort `fsType` label. */
|
||||
type?: number;
|
||||
}
|
||||
|
||||
/** The slice of `fs.Stats` the mount probe needs. */
|
||||
export interface StatLike {
|
||||
dev: number | bigint;
|
||||
}
|
||||
|
||||
/**
|
||||
* One sampled filesystem. `mountPoint` is the boundary the probe found by
|
||||
* walking up while `st_dev` stayed the same — never the raw candidate path,
|
||||
* which is usually a deep, user-irrelevant directory.
|
||||
*/
|
||||
export interface DiskUsage {
|
||||
mountPoint: string;
|
||||
/** Best-effort type label (`ext4`, `btrfs`, …); absent when unknown. */
|
||||
fsType?: string;
|
||||
totalBytes: number;
|
||||
usedBytes: number;
|
||||
percent: number;
|
||||
}
|
||||
|
||||
export interface SystemStats {
|
||||
@@ -30,10 +52,15 @@ export interface SystemStats {
|
||||
memUsedBytes: number;
|
||||
memTotalBytes: number;
|
||||
memPercent: number;
|
||||
/** Mount point of the most constrained disk (`disks[0]`); legacy scalar fields alias it. */
|
||||
diskPath: string;
|
||||
diskUsedBytes: number | null;
|
||||
diskTotalBytes: number | null;
|
||||
diskPercent: number | null;
|
||||
/** At most `maxDisks` filesystems, most constrained first. */
|
||||
disks: DiskUsage[];
|
||||
/** Why no filesystem could be sampled; absent when `disks` is non-empty. */
|
||||
diskError?: string;
|
||||
}
|
||||
|
||||
export interface SysinfoSampler {
|
||||
@@ -49,7 +76,16 @@ export interface SysinfoDeps {
|
||||
freemem?: () => number;
|
||||
loadavg?: () => number[];
|
||||
platform?: NodeJS.Platform;
|
||||
/** Primary disk candidate; defaults to `/` (the home volume on macOS). */
|
||||
diskPath?: string;
|
||||
/** Where pi keeps its sessions; sampled as a second candidate. Defaults to `sessionsRoot()`. */
|
||||
sessionsPath?: string;
|
||||
/** Extra candidates sampled per request (e.g. the visible workspace roots). */
|
||||
diskPaths?: () => string[];
|
||||
/** Whether two paths share a filesystem; injectable so tests never touch the disk. */
|
||||
stat?: (path: string) => Promise<StatLike>;
|
||||
/** How many filesystems to report; defaults to 4. */
|
||||
maxDisks?: number;
|
||||
cacheMs?: number;
|
||||
}
|
||||
|
||||
@@ -120,6 +156,91 @@ export function cpuPercentBetween(prev: CpuTimes | null, next: CpuTimes): number
|
||||
return Math.min(100, Math.max(0, Math.round(busy * 100)));
|
||||
}
|
||||
|
||||
/** Linux `f_type` magics → a short label. Best effort: unknown magics stay unlabelled. */
|
||||
const FS_MAGIC: Readonly<Record<number, string>> = {
|
||||
0x01_02_19_94: "tmpfs",
|
||||
0x2f_c1_2f_c1: "zfs",
|
||||
0x41_50_46_53: "apfs",
|
||||
0x4d_44: "vfat",
|
||||
0x69_69: "nfs",
|
||||
0x96_60: "iso9660",
|
||||
0xef_53: "ext4",
|
||||
0x20_11_ba_b0: "exfat",
|
||||
0x53_46_54_4e: "ntfs",
|
||||
0x58_46_53_42: "xfs",
|
||||
0x73_71_73_68: "squashfs",
|
||||
0x79_4c_76_30: "overlay",
|
||||
0x91_23_68_3e: "btrfs",
|
||||
0xf2_f5_20_10: "f2fs",
|
||||
0xff_53_4d_42: "cifs",
|
||||
};
|
||||
|
||||
/** Best-effort filesystem label from a `statfs.type` magic number. */
|
||||
export function fsTypeFromMagic(magic: number | undefined): string | undefined {
|
||||
if (magic === undefined || !Number.isFinite(magic)) return undefined;
|
||||
return FS_MAGIC[magic];
|
||||
}
|
||||
|
||||
export interface MountProbe {
|
||||
/** Deepest existing ancestor of the candidate (what `statfs` may be called on). */
|
||||
path: string;
|
||||
/** Filesystem boundary above `path`; the user-facing label. */
|
||||
mountPoint: string;
|
||||
/** `st_dev` identity, stringified — the dedupe key. */
|
||||
dev: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a candidate path to the filesystem that backs it.
|
||||
*
|
||||
* 1. Walk up until `stat` succeeds — `statfs` fails with `ENOENT` on a directory
|
||||
* that does not exist yet (pi2d's state dir is created lazily), which used to
|
||||
* null out the whole disk tile.
|
||||
* 2. Keep walking up while the parent reports the same `st_dev`; the last dir
|
||||
* that shares it is the mount point.
|
||||
*
|
||||
* Returns `null` when no ancestor exists (the path is on an unmounted tree).
|
||||
*/
|
||||
export async function probeMount(
|
||||
candidate: string,
|
||||
stat: (path: string) => Promise<StatLike>,
|
||||
): Promise<MountProbe | null> {
|
||||
let path = resolvePath(candidate);
|
||||
let dev: string | null = null;
|
||||
for (;;) {
|
||||
try {
|
||||
dev = String((await stat(path)).dev);
|
||||
break;
|
||||
} catch {
|
||||
const parent = dirname(path);
|
||||
if (parent === path) return null;
|
||||
path = parent;
|
||||
}
|
||||
}
|
||||
let mountPoint = path;
|
||||
for (;;) {
|
||||
const parent = dirname(mountPoint);
|
||||
if (parent === mountPoint) break;
|
||||
try {
|
||||
if (String((await stat(parent)).dev) !== dev) break;
|
||||
} catch {
|
||||
break;
|
||||
}
|
||||
mountPoint = parent;
|
||||
}
|
||||
return { path, mountPoint, dev };
|
||||
}
|
||||
|
||||
function describeError(path: string, err: unknown): string {
|
||||
const code =
|
||||
typeof err === "object" && err !== null && "code" in err
|
||||
? String((err as { code?: unknown }).code)
|
||||
: err instanceof Error
|
||||
? err.message
|
||||
: String(err);
|
||||
return `${path}: ${code}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive disk usage from a statfs result.
|
||||
* Returns null if blocks is 0 (pseudo-fs like tmpfs without a block count).
|
||||
@@ -144,16 +265,83 @@ 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();
|
||||
// `/` on macOS is the sealed read-only system volume, which reports ~100%
|
||||
// used forever; the home volume is the honest "system disk" answer there.
|
||||
const diskPath = deps.diskPath ?? (platform === "darwin" ? nodeOs.homedir() : platform === "win32" ? stateDir() : "/");
|
||||
const maxDisks = Math.max(1, deps.maxDisks ?? 4);
|
||||
const sessionsPath = deps.sessionsPath ?? sessionsRoot();
|
||||
const extraDiskPaths = deps.diskPaths ?? (() => []);
|
||||
|
||||
// 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 statImpl = deps.stat ?? ((path: string) => nodeStat(path) as Promise<StatLike>);
|
||||
const cpus = deps.cpus ?? (() => nodeOs.cpus());
|
||||
const totalmem = deps.totalmem ?? (() => nodeOs.totalmem());
|
||||
const freemem = deps.freemem ?? (() => nodeOs.freemem());
|
||||
const loadavg = deps.loadavg ?? (() => nodeOs.loadavg());
|
||||
|
||||
/**
|
||||
* Sample one row per distinct filesystem. Candidates are pi2d's own write
|
||||
* targets (root, the pi session store, the visible workspace roots), never
|
||||
* an enumeration of `/proc/mounts`: `statfs` on an unrelated, hung network
|
||||
* mount would otherwise stall the whole sample.
|
||||
*/
|
||||
async function sampleDisks(): Promise<{ disks: DiskUsage[]; error?: string }> {
|
||||
const extra = (() => {
|
||||
try {
|
||||
return extraDiskPaths();
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})();
|
||||
const candidates = [diskPath, sessionsPath, ...extra]
|
||||
.filter((path, index, all) => typeof path === "string" && path !== "" && all.indexOf(path) === index)
|
||||
.slice(0, maxDisks * 2);
|
||||
|
||||
const probes = new Map<string, MountProbe>();
|
||||
const failures: string[] = [];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
const probe = await probeMount(candidate, statImpl);
|
||||
if (probe === null) {
|
||||
failures.push(`${candidate}: no existing ancestor`);
|
||||
continue;
|
||||
}
|
||||
// Same `st_dev` ⇒ same filesystem ⇒ same row, whatever the path.
|
||||
if (!probes.has(probe.dev)) probes.set(probe.dev, probe);
|
||||
} catch (err) {
|
||||
failures.push(describeError(candidate, err));
|
||||
}
|
||||
}
|
||||
|
||||
const disks: DiskUsage[] = [];
|
||||
for (const probe of probes.values()) {
|
||||
try {
|
||||
const sf = await statfsImpl(probe.mountPoint);
|
||||
const usage = diskFromStatfs(sf);
|
||||
if (usage === null) {
|
||||
failures.push(`${probe.mountPoint}: no block count`);
|
||||
continue;
|
||||
}
|
||||
const fsType = fsTypeFromMagic(sf.type);
|
||||
disks.push({
|
||||
mountPoint: probe.mountPoint,
|
||||
...(fsType === undefined ? {} : { fsType }),
|
||||
...usage,
|
||||
});
|
||||
} catch (err) {
|
||||
failures.push(describeError(probe.mountPoint, err));
|
||||
}
|
||||
}
|
||||
|
||||
// Worst first: the tile's headline number is the disk closest to full.
|
||||
disks.sort((a, b) => b.percent - a.percent || b.totalBytes - a.totalBytes);
|
||||
const capped = disks.slice(0, maxDisks);
|
||||
if (capped.length > 0) return { disks: capped };
|
||||
return { disks: [], error: failures[0] ?? "no filesystem could be sampled" };
|
||||
}
|
||||
|
||||
let prevCpuTimes: CpuTimes | null = null;
|
||||
let cachedResult: SystemStats | null = null;
|
||||
let cachedAt = -Infinity;
|
||||
@@ -245,20 +433,12 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
|
||||
: 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
|
||||
}
|
||||
const sampled = await sampleDisks();
|
||||
const worst = sampled.disks[0];
|
||||
const diskUsedBytes = worst?.usedBytes ?? null;
|
||||
const diskTotalBytes = worst?.totalBytes ?? null;
|
||||
const diskPercent = worst?.percent ?? null;
|
||||
const diskMount = worst?.mountPoint ?? diskPath;
|
||||
|
||||
return {
|
||||
sampledAt,
|
||||
@@ -268,10 +448,12 @@ export function createSysinfo(deps: SysinfoDeps = {}): SysinfoSampler {
|
||||
memUsedBytes,
|
||||
memTotalBytes,
|
||||
memPercent,
|
||||
diskPath,
|
||||
diskPath: diskMount,
|
||||
diskUsedBytes,
|
||||
diskTotalBytes,
|
||||
diskPercent,
|
||||
disks: sampled.disks,
|
||||
...(sampled.error === undefined ? {} : { diskError: sampled.error }),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user