feat: support Linux system monitoring

Add procfs memory and mount-aware disk collectors, Intel and AMD GPU backends, bounded Intel sampling, portable validation tools, and Linux setup documentation. Bump to 0.2.0 and verify on Windows and Ubuntu 24.04 under WSL2.
This commit is contained in:
David Meincke
2026-11-20 13:51:04 +01:00
parent 7ab4e9fd0b
commit aa8a5f35f6
15 changed files with 701 additions and 100 deletions
+47
View File
@@ -0,0 +1,47 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { parseIntelGpuTop, sampleIntelGpu } from "../dist/linux.js"
async function fakeGpuTool(t, ignoreInterrupt) {
const directory = await mkdtemp(path.join(os.tmpdir(), "system-monitor-gpu-test-"))
const pidFile = path.join(directory, "pid")
const originalPath = process.env.PATH
const source = `#!${process.execPath}
import { writeFileSync } from "node:fs";
writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
process.stdout.write('[{"engines":{"Render/0":{"busy":31}}}');
process.on("SIGINT", () => { ${ignoreInterrupt ? "" : 'process.stdout.write("]"); process.exit(0);'} });
setInterval(() => {}, 1000);
`
await writeFile(path.join(directory, "intel_gpu_top"), source, { mode: 0o755 })
await writeFile(path.join(directory, "package.json"), '{"type":"module"}')
process.env.PATH = `${directory}:${originalPath}`
t.after(async () => {
process.env.PATH = originalPath
// Clean up our own fake process if an assertion or the collector fails.
try {
const pid = Number(await readFile(pidFile, "utf8"))
try { process.kill(pid, "SIGKILL") } catch { /* already exited */ }
} catch { /* process never started */ }
await rm(directory, { recursive: true, force: true })
})
return async () => Number(await readFile(pidFile, "utf8"))
}
test("Linux Intel sampling interrupts the streaming tool and leaves no process running", { skip: process.platform !== "linux" }, async t => {
const pid = await fakeGpuTool(t, false)
const output = await sampleIntelGpu("/dev/dri/card0")
assert.equal(parseIntelGpuTop(output), 31)
const childPID = await pid()
assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH")
})
test("Linux Intel sampling forcibly terminates a tool that ignores its interrupt", { skip: process.platform !== "linux" }, async t => {
const pid = await fakeGpuTool(t, true)
await assert.rejects(sampleIntelGpu("/dev/dri/card0"), /counters unavailable/)
const childPID = await pid()
assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH")
})
+203
View File
@@ -0,0 +1,203 @@
import { test } from "node:test"
import assert from "node:assert/strict"
import { Monitor } from "../dist/metrics.js"
import { diskFromStatfs, parseIntelGpuTop, parseMeminfo, parseMountinfo, readLinuxDisks, readLinuxGpu, sampleIntelGpu } from "../dist/linux.js"
import { report } from "../dist/format.js"
function fixtures({ files = {}, directories = {}, stats = {}, nondirectories = [], sampleIntel } = {}) {
return {
readText: async path => {
if (!(path in files)) throw Object.assign(new Error(`Missing fixture: ${path}`), { code: "ENOENT" })
return files[path]
},
readNames: async path => directories[path] ?? [],
isDirectory: async path => !nondirectories.includes(path),
filesystem: async path => {
if (!(path in stats)) throw new Error("Filesystem unavailable")
return stats[path]
},
sampleIntel: sampleIntel ?? (async () => { throw new Error("intel_gpu_top is not installed") }),
}
}
const fs = { blocks: 1000, bfree: 400, bavail: 350, bsize: 1024 }
const mountinfo = [
"24 1 8:1 / / rw - ext4 /dev/sda1 rw",
"25 24 8:2 / /home rw shared:1 - ext4 /dev/sda2 rw",
"26 24 8:2 /users /srv/users rw - ext4 /dev/sda2 rw",
"27 24 8:3 / /media/My\\040Disk rw - exfat /dev/sdb1 rw",
"28 24 0:1 / /proc rw - proc proc rw",
"29 24 0:2 / /run rw - tmpfs tmpfs rw",
"30 24 7:0 / /snap/app/1 ro - squashfs /dev/loop0 ro",
"31 24 0:3 / /network rw - nfs server:/export rw",
"32 24 8:4 / /etc/hosts rw - ext4 /dev/sdc1 rw",
"33 24 8:5 /headers /usr/src/linux-headers ro - ext4 /dev/sdd ro",
].join("\n")
test("Linux memory counts reclaimable cache as available, not as application usage", () => {
const result = parseMeminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nMemAvailable: 600 kB\nCached: 500 kB\n")
assert.equal(result.total, 1000 * 1024)
assert.equal(result.free, 600 * 1024)
assert.equal(result.used, 400 * 1024)
assert.equal(result.percent, 40)
assert.throws(() => parseMeminfo("bad input"), /Invalid/)
})
test("Older Linux memory files fall back to free + reclaimable memory, and clamp estimates", () => {
const result = parseMeminfo("MemTotal: 1000 kB\nMemFree: 100 kB\nBuffers: 20 kB\nCached: 400 kB\nSReclaimable: 50 kB\nShmem: 30 kB\n")
assert.equal(result.free, 540 * 1024)
assert.equal(parseMeminfo("MemTotal: 100 kB\nMemAvailable: 500 kB\n").free, 100 * 1024)
})
test("Mount parser handles escaped paths and optional fields, and omits pseudo/network/loop mounts", () => {
const mounts = parseMountinfo(mountinfo)
assert.deepEqual(mounts.map(mount => mount.point), ["/", "/home", "/etc/hosts", "/srv/users", "/media/My Disk"])
assert.equal(mounts.find(mount => mount.point === "/media/My Disk").source, "/dev/sdb1")
assert.equal(parseMountinfo("invalid\n").length, 0)
const overlay = "1 0 0:1 / / rw - overlay overlay rw\n2 1 0:2 / /container rw - overlay overlay rw"
assert.deepEqual(parseMountinfo(overlay).map(mount => mount.point), ["/"])
})
test("Linux disks deduplicate bind mounts, skip file mounts, and keep independent filesystems", async () => {
const io = fixtures({
files: { "/proc/self/mountinfo": mountinfo },
stats: { "/": fs, "/home": fs, "/media/My Disk": fs },
nondirectories: ["/etc/hosts"],
})
const result = await readLinuxDisks(io)
assert.equal(result.error, null)
assert.deepEqual(result.items.map(disk => disk.id), ["/", "/home", "/media/My Disk"])
})
test("Filesystem reserved blocks are neither used data nor user-available free space", () => {
const disk = diskFromStatfs("/", "root", fs)
assert.equal(disk.total, 1000 * 1024)
assert.equal(disk.used, 600 * 1024)
assert.equal(disk.free, 350 * 1024)
assert.equal(disk.reserved, 50 * 1024)
assert.equal(disk.percent, 600 / 950 * 100)
assert.equal(disk.used + disk.free + disk.reserved, disk.total)
assert.equal(diskFromStatfs("/", "root", { ...fs, bavail: -1 }).free, 0)
assert.throws(() => diskFromStatfs("/", "broken", { ...fs, bfree: 2000 }), /Invalid/)
})
test("Failed mounts don't discard healthy disks, and missing procfs still reports root", async () => {
const partial = await readLinuxDisks(fixtures({ files: { "/proc/self/mountinfo": mountinfo }, stats: { "/": fs } }))
assert.equal(partial.items.length, 1)
assert.match(partial.error, /\/home/)
const root = await readLinuxDisks(fixtures({ stats: { "/": fs } }))
assert.equal(root.items[0].id, "/")
assert.equal(root.error, null)
})
test("WSL local Windows mounts are allowed, but unrelated 9p network mounts are skipped", () => {
const mounts = parseMountinfo("1 0 0:1 / /mnt/c rw - 9p C:\\134 rw,aname=drvfs;path=C:\\134\n2 0 0:2 / /remote rw - 9p remote rw")
assert.equal(mounts.length, 1)
assert.equal(mounts[0].point, "/mnt/c")
assert.equal(mounts[0].source, "C:\\")
})
test("Intel JSON sampler uses the last complete physical-engine sample, not client totals", () => {
const data = '[{"engines":{"Render/0":{"busy":10},"Video/0":{"busy":20}}},' +
'{"engines":{"Render/0":{"busy":23.5},"Video/0":{"busy":40}},"clients":{"1":{"busy":99}}},' +
'{"engines":{"Render/0":{"busy":'
assert.equal(parseIntelGpuTop(data), 40)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":0}}}]'), 0)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":null},"Video":{"busy":"---"}}}]'), null)
assert.equal(parseIntelGpuTop("Permission denied"), null)
assert.equal(parseIntelGpuTop('[{"engines":{"Render":{"busy":101}}}]'), null)
})
test("Intel sampler only accepts a discovered DRM device path", async () => {
await assert.rejects(sampleIntelGpu("/dev/dri/card0;whoami"), /Invalid DRM/)
})
test("AMD reads sysfs utilization and memory without launching external GPU tools", async () => {
const io = fixtures({
directories: { "/sys/class/drm": ["card1", "card1-DP-1", "renderD128"] },
files: {
"/sys/class/drm/card1/device/vendor": "0x1002\n",
"/sys/class/drm/card1/device/product_name": "AMD Radeon Graphics\n",
"/sys/class/drm/card1/device/gpu_busy_percent": "37\n",
"/sys/class/drm/card1/device/mem_info_vram_used": "268435456\n",
"/sys/class/drm/card1/device/mem_info_vram_total": "2147483648\n",
},
sampleIntel: () => { throw new Error("Unexpected Intel sampler call") },
})
const result = await readLinuxGpu(io)
assert.equal(result.error, null)
assert.equal(result.adapter.vendor, "AMD")
assert.equal(result.adapter.percent, 37)
assert.equal(result.adapter.memoryUsed, 268435456)
assert.equal(result.adapter.memoryKind, "vram")
})
test("Linux prefers Intel and selects its exact DRM device, not another adapter's counters", async () => {
let device
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0", "card2", "card1"] },
files: {
"/sys/class/drm/card0/device/vendor": "0x10de",
"/sys/class/drm/card1/device/vendor": "0x1002",
"/sys/class/drm/card2/device/vendor": "0x8086",
},
sampleIntel: async path => { device = path; return '[{"engines":{"Render/0":{"busy":12}}}]' },
}))
assert.equal(device, "/dev/dri/card2")
assert.equal(result.adapter.vendor, "Intel")
assert.equal(result.adapter.percent, 12)
assert.equal(result.adapter.memoryUsed, null)
assert.equal(result.adapter.memoryKind, "unknown")
assert.equal(result.error, null)
})
test("Missing Intel tool, GPU permissions and unknown drivers remain unavailable rather than idle", async () => {
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0"] },
files: { "/sys/class/drm/card0/device/vendor": "0x8086" },
}))
assert.equal(result.adapter.percent, null)
assert.match(result.error, /not installed/)
const wsl = await readLinuxGpu(fixtures({ files: { "/proc/sys/kernel/osrelease": "6.6.87-microsoft-standard-WSL2" } }))
assert.equal(wsl.adapter, null)
assert.match(wsl.error, /WSL/)
const headless = await readLinuxGpu(fixtures())
assert.equal(headless.adapter, null)
assert.match(headless.error, /No supported/)
})
test("Invalid AMD counters remain unavailable, while explicit zero means idle", async () => {
for (const [text, expected] of [["garbage", null], ["101", null], ["", null], ["0", 0]]) {
const result = await readLinuxGpu(fixtures({
directories: { "/sys/class/drm": ["card0"] },
files: { "/sys/class/drm/card0/device/vendor": "0x1002", "/sys/class/drm/card0/device/gpu_busy_percent": text },
}))
assert.equal(result.adapter.percent, expected)
assert.equal(result.adapter.memoryUsed, null)
}
})
test("Complete Linux collection uses procfs/sysfs and never invokes PowerShell", async () => {
const io = fixtures({
files: {
"/proc/meminfo": "MemTotal: 1000 kB\nMemAvailable: 600 kB\n",
"/proc/self/mountinfo": mountinfo,
"/sys/class/drm/card0/device/vendor": "0x1002",
"/sys/class/drm/card0/device/gpu_busy_percent": "24",
},
directories: { "/sys/class/drm": ["card0"] },
stats: { "/": fs, "/home": fs, "/media/My Disk": fs },
nondirectories: ["/etc/hosts"],
})
const monitor = new Monitor(async () => { throw new Error("Linux must not launch PowerShell") }, { platform: "linux", linux: io })
const first = monitor.snapshot()
assert.equal(first, monitor.snapshot())
const snapshot = await first
assert.equal(snapshot.ram.percent, 40)
assert.equal(snapshot.disks.items.length, 3)
assert.equal(snapshot.gpu.adapter.vendor, "AMD")
assert.equal(snapshot.gpu.adapter.percent, 24)
assert.equal(snapshot.gpu.error, null)
const text = report(snapshot)
assert.match(text, /AMD/)
assert.doesNotMatch(text.split("\n").filter(line => line.startsWith("- **GPU")).join("\n"), /Intel|included in system RAM/)
})
+6 -5
View File
@@ -34,7 +34,7 @@ test("Only a DXGI LUID can be inserted in the fixed PowerShell query", () => {
assert.throws(() => intelCountersScript("'; exit; '"), /Invalid GPU adapter identity/)
})
test("Intel-only collection excludes another GPU, coalesces concurrent calls, and caches", { skip: process.platform !== "win32" }, async () => {
test("Windows Intel-only collection excludes another GPU, coalesces concurrent calls, and caches", async () => {
let calls = 0
const collector = new Monitor(async (file, args) => {
calls++
@@ -46,20 +46,21 @@ test("Intel-only collection excludes another GPU, coalesces concurrent calls, an
engines: [engine(1, intel, 0, 12), engine(2, intel, 0, 8), engine(3, nvidia, 0, 99)],
memory: [{ SharedUsage: 256 * 1024 ** 2 }],
})
})
}, { platform: "win32" })
const first = collector.snapshot()
assert.equal(first, collector.snapshot())
const snapshot = await first
assert.equal(snapshot.gpu.adapter.percent, 20)
assert.equal(snapshot.gpu.adapter.sharedUsed, 256 * 1024 ** 2)
assert.equal(snapshot.gpu.adapter.memoryUsed, 256 * 1024 ** 2)
assert.equal(snapshot.gpu.adapter.memoryKind, "shared")
assert.equal(snapshot.disks.items[0].percent, 25)
assert.equal(snapshot.gpu.error, null)
assert.equal(await collector.snapshot(), snapshot)
assert.equal(calls, 3)
})
test("A missing GPU or failed disk query shows unavailable, never false idle/full values", { skip: process.platform !== "win32" }, async () => {
const collector = new Monitor(async () => { throw new Error("Permission denied") })
test("A missing GPU or failed Windows disk query shows unavailable, never false idle/full values", async () => {
const collector = new Monitor(async () => { throw new Error("Permission denied") }, { platform: "win32" })
const snapshot = await collector.snapshot()
assert.equal(snapshot.gpu.adapter, null)
assert.match(snapshot.gpu.error, /Permission denied/)