Files
opencode-system-monitor/tests/linux.test.mjs
T
David Meincke aa8a5f35f6 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.
2026-11-20 13:51:04 +01:00

204 lines
9.5 KiB
JavaScript

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/)
})