Files
Homelab-manager/server/test/windowsAgentHealth.test.ts
T
bobbanandClaude Sonnet 5.5 ec9c2f73f0 Dependencies beyond servers, web push, inventory auto-fill with QR labels, Windows agent health
- Dependencies: servers and integrations can depend on each other; alerts are folded under the root cause, and a failure explained by something down isn't announced
- Web push: hand-written VAPID and RFC 8291 encryption, per-device subscriptions, a fifth notification channel, service worker handlers
- Inventory: maker/model/serial from the agents fill blank fields, "Refresh from agent", QR label printing and ?asset= deep links
- Windows agent (v4) reports failed services, disk health, Storage Spaces pools and hardware identity; Linux agent (v5) reports hardware identity

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 18:53:30 +02:00

127 lines
7.9 KiB
TypeScript

/**
* What the Windows agent says about the machine: services that have failed, each disk's health, Storage Spaces pools and what the machine
* is. The mapping from what Windows returns is tested with stand-in objects, and the real collectors are run once as a smoke test.
*
* Run with: npm test --workspace server
*/
import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
const repoRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const script = join(repoRoot, "agent", "windows", "report-tasks.ps1");
const probe = process.platform === "win32" ? spawnSync("pwsh", ["-NoProfile", "-Command", "$PSVersionTable.PSVersion.Major"], { encoding: "utf8" }) : null;
const havePwsh = probe?.status === 0;
/** Runs PowerShell with the agent script loaded (without running it) and returns what the snippet printed as JSON. */
function run(snippet: string): unknown {
const work = mkdtempSync(join(tmpdir(), "hm-winhealth-"));
try {
const file = join(work, "t.ps1");
writeFileSync(file, `$ErrorActionPreference = 'Stop'\n. '${script.replace(/'/g, "''")}'\n${snippet}\n`);
const r = spawnSync("pwsh", ["-NoProfile", "-NonInteractive", "-File", file], { encoding: "utf8" });
assert.equal(r.stderr.trim(), "", `PowerShell said:\n${r.stderr}\n${r.stdout}`);
return JSON.parse(r.stdout.trim());
} finally {
rmSync(work, { recursive: true, force: true });
}
}
describe("the Windows agent's health parts", { skip: !havePwsh }, () => {
test("it says it is version 4, and stays plain ASCII", () => {
const text = readFileSync(script, "utf8");
assert.match(text, /^\$script:AgentVersion = 4\s*$/m);
assert.ok(!/[^\x00-\x7f]/.test(text));
});
test("a service has failed when it starts by itself, isn't running, and stopped with an error — not for exit 0, never-started, or on request", () => {
const out = run(`
function svc($n, $d, $mode, $state, $code) { [pscustomobject]@{ Name = $n; DisplayName = $d; StartMode = $mode; State = $state; ExitCode = $code } }
$list = @(
(svc 'Crashed' 'A crashed service' 'Auto' 'Stopped' 1066),
(svc 'Crashed2' 'Another' 'Auto' 'Stopped' 2),
(svc 'Finished' 'Did its job' 'Auto' 'Stopped' 0),
(svc 'Triggered' 'Starts on a trigger' 'Auto' 'Stopped' 1077),
(svc 'OnRequest' 'Manual one' 'Manual' 'Stopped' 1066),
(svc 'Disabled' 'Disabled one' 'Disabled' 'Stopped' 1066),
(svc 'Fine' 'Running' 'Auto' 'Running' 0),
(svc 'Starting' 'On its way' 'Auto' 'Start Pending' 1066),
(svc 'gupdate' 'Google Update' 'Auto' 'Stopped' 1),
(svc 'NoCode' 'No code at all' 'Auto' 'Stopped' $null)
)
ConvertTo-Json -InputObject @{ all = @(ConvertTo-FailedUnits $list); ignoring = @(ConvertTo-FailedUnits $list @('gupdate*', 'Crashed2')); none = @(ConvertTo-FailedUnits @()) } -Compress
`) as { all: { unit: string; description: string }[]; ignoring: { unit: string }[]; none: unknown[] };
assert.deepEqual(out.all.map((u) => u.unit), ["Crashed", "Crashed2", "gupdate"]);
assert.equal(out.all[0].description, "A crashed service");
assert.deepEqual(out.ignoring.map((u) => u.unit), ["Crashed"], "names and patterns in the ignore list are left out");
assert.deepEqual(out.none, []);
});
test("a disk passes when Windows says Healthy; Warning and Unhealthy don't; Unknown says nothing; temperature and wear come from the counter where sane", () => {
const out = run(`
function disk($id, $name, $health, $bus = 'SATA') { [pscustomobject]@{ DeviceId = $id; FriendlyName = $name; HealthStatus = $health; BusType = $bus } }
$disks = @(
(disk '0' ' Samsung SSD 850 ' 'Healthy'),
(disk '1' 'Old HDD' 'Warning'),
(disk '2' 'Dead HDD' 'Unhealthy'),
(disk '3' 'Mystery' 'Unknown'),
(disk '4' 'NVMe' 'Healthy' 'NVMe'),
(disk '5' 'Virtual' 'Healthy' 'File Backed Virtual'),
(disk '6' 'Odd readings' 'Healthy')
)
$counters = @{
'0' = [pscustomobject]@{ Temperature = 36; Wear = 7 }
'4' = [pscustomobject]@{ Temperature = 0; Wear = 0 }
'6' = [pscustomobject]@{ Temperature = 4000; Wear = 900 }
}
ConvertTo-Json -InputObject @(ConvertTo-DiskHealth $disks $counters) -Compress
`) as { device: string; model: string; healthy: boolean | null; temperature_c: number | null; wear_percent: number | null }[];
const byDevice = Object.fromEntries(out.map((d) => [d.device, d]));
assert.deepEqual(Object.keys(byDevice), ["PhysicalDisk0", "PhysicalDisk1", "PhysicalDisk2", "PhysicalDisk3", "PhysicalDisk4", "PhysicalDisk6"], "the virtual disk is left out");
assert.deepEqual([byDevice.PhysicalDisk0.healthy, byDevice.PhysicalDisk1.healthy, byDevice.PhysicalDisk2.healthy, byDevice.PhysicalDisk3.healthy], [true, false, false, null]);
assert.equal(byDevice.PhysicalDisk0.model, "Samsung SSD 850", "names are trimmed");
assert.deepEqual([byDevice.PhysicalDisk0.temperature_c, byDevice.PhysicalDisk0.wear_percent], [36, 7]);
assert.deepEqual([byDevice.PhysicalDisk4.temperature_c, byDevice.PhysicalDisk4.wear_percent], [null, 0], "0 degrees isn't a reading, 0% wear is");
assert.deepEqual([byDevice.PhysicalDisk6.temperature_c, byDevice.PhysicalDisk6.wear_percent], [null, null], "nonsense is no reading");
assert.deepEqual([byDevice.PhysicalDisk1.temperature_c, byDevice.PhysicalDisk1.wear_percent], [null, null], "a disk with no counter has none");
});
test("Storage Spaces pools are reported in ZFS's words, with how full they are; one Windows can't judge is left out", () => {
const out = run(`
function pool($n, $h, $size, $alloc) { [pscustomobject]@{ FriendlyName = $n; HealthStatus = $h; Size = $size; AllocatedSize = $alloc } }
ConvertTo-Json -InputObject @(ConvertTo-PoolHealth @(
(pool 'Media' 'Healthy' 1000 250),
(pool 'Backups' 'Warning' 1000 900),
(pool 'Broken' 'Unhealthy' 0 0),
(pool 'Strange' 'Unknown' 1000 1)
)) -Compress
`) as { name: string; health: string; capacity_percent: number | null }[];
assert.deepEqual(out.map((p) => [p.name, p.health, p.capacity_percent]), [["Media", "ONLINE", 25], ["Backups", "DEGRADED", 90], ["Broken", "FAULTED", null]]);
});
test("a maker's placeholders aren't a model or a serial number", () => {
const out = run(`
$t = @('To Be Filled By O.E.M.', 'Default string', 'System Serial Number', 'System Product Name', '0000000', ' ', 'None', 'Unknown', 'ASUS', 'ROG STRIX B560-F', 'PF2ABCDE', '0A1B')
ConvertTo-Json -InputObject @($t | ForEach-Object { Test-PlaceholderText $_ }) -Compress
`) as boolean[];
assert.deepEqual(out, [true, true, true, true, true, true, true, true, false, false, false, false]);
});
test("on this machine the real collectors answer, in a shape the server reads, and one that can't be read is left out rather than reported well", () => {
const out = run(`
$health = Get-HostHealth @{ IgnoreServices = @() }
$hardware = Get-HardwareInfo
ConvertTo-Json -InputObject @{ health = $health; hardware = $hardware } -Depth 6 -Compress
`) as { health: { failed_units?: unknown[]; smart?: { device: string; healthy: boolean | null }[]; zfs?: unknown[] } | null; hardware: { manufacturer?: string; model?: string; serial?: string } | null };
if (out.health) {
for (const part of ["failed_units", "smart", "zfs"] as const) if (out.health[part] !== undefined) assert.ok(Array.isArray(out.health[part]), `${part} is a list`);
for (const d of out.health.smart ?? []) assert.match(d.device, /^PhysicalDisk\d+$/);
}
if (out.hardware) for (const v of Object.values(out.hardware)) assert.ok(typeof v === "string" && v.length > 0 && v.length <= 150);
});
});