import { afterAll, beforeEach, describe, expect, test } from "bun:test"; import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { cacheStatus, describeParitySchedule, dockerStorage, moverStart, notificationArchive, notifySend, parityControl, parityStatus, parseParityHistory, summarizeDomainXml, vmAutostart, vmControl, vmInspect, vmList, } from "./host"; import { parityDate } from "./overview"; const sandbox = mkdtempSync(join(tmpdir(), "mua-host-")); const ROOT = join(sandbox, "root"); const BIN = join(sandbox, "bin"); const LOG = join(sandbox, "calls.log"); process.env["MUA_HOST_ROOT"] = ROOT; process.env["MUA_HOST_BIN"] = BIN; afterAll(() => { delete process.env["MUA_HOST_ROOT"]; delete process.env["MUA_HOST_BIN"]; rmSync(sandbox, { recursive: true, force: true }); }); const file = (path: string, content: string) => { mkdirSync(join(ROOT, path, ".."), { recursive: true }); writeFileSync(join(ROOT, path), content); }; const script = (name: string, body: string) => { mkdirSync(BIN, { recursive: true }); writeFileSync(join(BIN, name), `#!/bin/sh\nprintf '%s\\n' "${name} $*" >> "${LOG}"\n${body}\n`); chmodSync(join(BIN, name), 0o755); }; const calls = () => (existsSync(LOG) ? readFileSync(LOG, "utf-8").trim().split("\n") : []); // Zustandsbehaftetes virsh: Zustand je VM in $STATE/ const STATE = join(sandbox, "vmstate"); function fakeVirsh() { mkdirSync(STATE, { recursive: true }); writeFileSync(join(STATE, "Windows 11"), "running"); writeFileSync(join(STATE, "HomeAssistant"), "shut off"); script("virsh", ` S="${STATE}" cmd="$1"; shift case "$cmd" in list) ls "$S" ;; dominfo) st=$(cat "$S/$1"); auto=disable; [ -f "$S/$1.auto" ] && auto=enable printf 'Id: 1\\nName: %s\\nState: %s\\nCPU(s): 4\\nMax memory: 8388608 KiB\\nPersistent: yes\\nAutostart: %s\\n' "$1" "$st" "$auto" ;; domblklist) printf ' Type Device Target Source\\n------------------------------------\\n file disk hdc /mnt/user/domains/%s/vdisk1.img\\n' "$1" ;; domiflist) printf ' Interface Type Source Model MAC\\n---------------------------------------------\\n vnet0 bridge br0 virtio 52:54:00:aa:bb:cc\\n' ;; dumpxml) printf "\n \n hvm\n \n \n \n \n \n \n
\n \n \n \n\n" ;; snapshot-list) echo "" ;; start) echo running > "$S/$1" ;; shutdown) echo "shut off" > "$S/$1" ;; destroy) echo "shut off" > "$S/$1" ;; suspend) echo paused > "$S/$1" ;; resume) echo running > "$S/$1" ;; reboot) : ;; autostart) if [ "$1" = "--disable" ]; then rm -f "$S/$2.auto"; else touch "$S/$1.auto"; fi ;; esac`); } beforeEach(() => { rmSync(LOG, { force: true }); rmSync(ROOT, { recursive: true, force: true }); rmSync(BIN, { recursive: true, force: true }); }); describe("VMs", () => { test("list, inspect (no passwords) and fuzzy read names", async () => { fakeVirsh(); const list = JSON.parse(await vmList()); expect(list).toMatchObject({ vm_count: 2, running: 1 }); expect(list.vms.find((v: any) => v.name === "Windows 11")).toMatchObject({ state: "running", vcpus: 4, memory_mb: 8192, autostart: false }); const info = JSON.parse(await vmInspect("windows")); expect(info.name).toBe("Windows 11"); expect(info.resolved).toContain("→ 'Windows 11'"); expect(info.disks[0].source).toBe("/mnt/user/domains/Windows 11/vdisk1.img"); expect(info.pci_passthrough).toEqual(["01:00.0"]); expect(JSON.stringify(info)).not.toContain("secret123"); expect(info.graphics[0]).toEqual({ type: "vnc", port: "5900", password_set: true }); }); test("control checks the state before and reports it after", async () => { fakeVirsh(); const started = JSON.parse(await vmControl("HomeAssistant", "start")); expect(started).toMatchObject({ ok: true, state_before: "shut off", state_now: "running" }); const again = JSON.parse(await vmControl("HomeAssistant", "start")); expect(again.ok).toBe(false); expect(again.note).toContain("Cannot start a VM that is 'running'"); expect(JSON.parse(await vmControl("Windows 11", "suspend")).state_now).toBe("paused"); expect(JSON.parse(await vmControl("Windows 11", "resume")).state_now).toBe("running"); expect(JSON.parse(await vmControl("Windows 11", "force_stop")).state_now).toBe("shut off"); }); test("write operations never act on a guessed VM name", async () => { fakeVirsh(); await expect(vmControl("windows", "shutdown")).rejects.toThrow(/Did you mean 'Windows 11'/); expect(calls().some((c) => c.startsWith("virsh shutdown"))).toBe(false); expect(JSON.parse(await vmControl("homeassistant", "start")).vm).toBe("HomeAssistant"); // nur Groß/klein }); test("autostart toggles and unknown operations are rejected", async () => { fakeVirsh(); expect(JSON.parse(await vmAutostart("HomeAssistant", true)).autostart).toBe(true); expect(JSON.parse(await vmAutostart("HomeAssistant", false)).autostart).toBe(false); await expect(vmAutostart("HomeAssistant", "yes")).rejects.toThrow(/true or false/); await expect(vmControl("HomeAssistant", "explode")).rejects.toThrow(/operation must be one of/); }); test("missing libvirt gives a clear message", async () => { await expect(vmList()).rejects.toThrow(/VM management \(libvirt\/virsh\) is not available on this host/); }); test("domain XML summary handles USB and missing parts", () => { const x = summarizeDomainXml(""); expect(x.usb_passthrough).toEqual(["046d:c52b"]); expect(x.pci_passthrough).toEqual([]); }); }); describe("cache and mover", () => { function fakeStorage(cacheUsedPct: number) { const size = 1_000_000_000_000; const used = size * cacheUsedPct / 100; script("df", `printf 'Mounted on Size Used Avail\\n/mnt/disk1 8000000000000 4000000000000 4000000000000\\n/mnt/cache ${size} ${used} ${size - used}\\n/mnt/user 8000000000000 4000000000000 4000000000000\\n/var/lib/docker 21474836480 19327352832 2147483648\\n'`); script("du", `case "$2" in *appdata) echo "300000000000 $2";; *media) echo "500000000000 $2";; *system) echo "50000000000 $2";; esac`); for (const d of ["appdata", "media", "system"]) mkdirSync(join(ROOT, "mnt/cache", d), { recursive: true }); file("/boot/config/shares/appdata.cfg", 'shareUseCache="prefer"\nshareCachePool="cache"\n'); file("/boot/config/shares/media.cfg", 'shareUseCache="no"\nshareCachePool="cache"\n'); file("/boot/config/shares/system.cfg", 'shareUseCache="only"\nshareCachePool="cache"\n'); file("/var/local/emhttp/var.ini", 'shareMoverSchedule="40 3 * * *"\nshareMoverLogging="yes"\n'); file("/var/log/syslog", "Nov 20 03:40:01 tower root: mover: started\nNov 20 03:40:02 tower kernel: unrelated\nNov 20 03:52:10 tower root: mover: finished\n"); } test("explains what fills the pool and finds files the mover will never move", async () => { fakeStorage(93); const r = JSON.parse(await cacheStatus()); expect(r.pools).toHaveLength(1); expect(r.pools[0]).toMatchObject({ pool: "cache", used_percent: 93 }); expect(r.pools[0].contents.map((c: any) => c.share)).toEqual(["media", "appdata", "system"]); expect(r.shares.find((s: any) => s.name === "media").meaning).toContain("mover ignores it"); const messages = r.findings.map((f: any) => f.message).join("\n"); expect(messages).toContain("share 'media' sit on pool 'cache' but the share is set to array only"); expect(messages).toContain("Pool 'cache' is 93% full. Largest: media 500 GB (no)"); expect(r.mover).toMatchObject({ running: false, schedule: "40 3 * * *", logging: "yes" }); expect(r.mover.recent_log).toHaveLength(2); }); test("mover start uses the WebGUI command and refuses while running", async () => { script("emcmd", `mkdir -p "${ROOT}/var/run" && touch "${ROOT}/var/run/mover.pid"`); const r = JSON.parse(await moverStart()); expect(r).toMatchObject({ ok: true, started: true }); expect(calls()).toContain("emcmd cmdStartMover=Move"); expect(JSON.parse(await moverStart())).toMatchObject({ ok: false, note: "Mover is already running." }); }); test("docker.img fill level and breakdown", async () => { fakeStorage(10); file("/boot/config/docker.cfg", 'DOCKER_IMAGE_FILE="/mnt/user/system/docker/docker.img"\n'); script("docker", `echo '{"Type":"Images","TotalCount":"31","Active":"24","Size":"14.2GB","Reclaimable":"3.1GB (21%)"}'`); const r = JSON.parse(await dockerStorage()); expect(r).toMatchObject({ mode: "image", used_percent: 90, free_gb: 2.1 }); expect(r.breakdown[0]).toMatchObject({ type: "Images", count: 31, gb: 14.2 }); }); }); describe("parity", () => { test("history, schedule and progress", async () => { file("/var/local/emhttp/var.ini", 'mdState="STARTED"\nmdResync="1000"\nmdResyncPos="250"\nmdResyncSize="1000"\nmdResyncAction="check P"\n'); file("/boot/config/plugins/dynamix/parity-check.cron", "# parity\n0 2 1 * * /usr/local/sbin/mdcmd check NOCORRECT &> /dev/null\n"); file("/boot/config/parity-checks.log", "2025 Oct 1 05:00:00|36000|222.2 MB/s|0|0|check P|8000000000000\n2025 Nov 1 06:10:00|39000|205.1 MB/s|0|3|check P|8000000000000\n"); const r = JSON.parse(await parityStatus()); expect(r).toMatchObject({ running: true, progress_percent: 25, action: "check P" }); expect(r.schedule).toMatchObject({ correcting: false, text: "day 1 of month every month at 02:00" }); expect(r.history[0]).toMatchObject({ date: "2025 Nov 1 06:10:00", status: "ok", errors: 3 }); }); test("control maps to mdcmd and checks preconditions", async () => { script("mdcmd", ""); file("/var/local/emhttp/var.ini", 'mdState="STARTED"\nmdResync="0"\n'); expect(JSON.parse(await parityControl("start", undefined))).toMatchObject({ ok: true, correcting: false }); expect(JSON.parse(await parityControl("start", true))).toMatchObject({ ok: true, correcting: true }); expect(JSON.parse(await parityControl("cancel", undefined)).ok).toBe(false); file("/var/local/emhttp/var.ini", 'mdState="STARTED"\nmdResync="5"\n'); await parityControl("pause", undefined); await parityControl("cancel", undefined); expect(calls()).toEqual(["mdcmd check NOCORRECT", "mdcmd check", "mdcmd nocheck pause", "mdcmd nocheck"]); file("/var/local/emhttp/var.ini", 'mdState="STOPPED"\nmdResync="0"\n'); expect(JSON.parse(await parityControl("start", undefined)).note).toContain("Array is STOPPED"); }); test("schedule and history parsers", () => { expect(describeParitySchedule("30 1 * * 0 /usr/local/sbin/mdcmd check").text).toBe("every Sun at 01:30"); expect(describeParitySchedule("30 1 * * 0 /usr/local/sbin/mdcmd check").correcting).toBe(true); expect(describeParitySchedule(null).text).toBe("No scheduled parity check."); expect(parseParityHistory("2025 Jan 2 01:00:00|10|1 MB/s|-4|0|check P|1")[0].status).toBe("canceled"); expect(parityDate("2025 Jan 7 05:23:11")).toBe(Date.parse("Jan 7 2025 05:23:11")); expect(parityDate("garbage")).toBeNull(); }); }); describe("notifications", () => { test("send passes safe arguments to Unraid's notify script", async () => { script("notify", ""); await notifySend({ subject: "Backup done", description: "3 containers updated", importance: "warning", link: "/Docker" }); expect(calls()[0]).toBe("notify -e MUA Agent -s Backup done -i warning -d 3 containers updated -l /Docker"); await expect(notifySend({ subject: "x", importance: "urgent" })).rejects.toThrow(/importance/); await expect(notifySend({ subject: "x", link: "https://evil.example" })).rejects.toThrow(/WebGUI path/); await expect(notifySend({})).rejects.toThrow(/subject/); }); test("archive one or all unread notifications", async () => { script("notify", `[ "$1" = archive ] && mv "${ROOT}/tmp/notifications/unread/$2" "${ROOT}/tmp/notifications/archive/$2"`); mkdirSync(join(ROOT, "tmp/notifications/archive"), { recursive: true }); file("/tmp/notifications/unread/a_1.notify", 'importance="alert"\nsubject="A"\n'); file("/tmp/notifications/unread/b_2.notify", 'importance="normal"\nsubject="B"\n'); file("/tmp/notifications/unread/c_3.notify", 'importance="normal"\nsubject="C"\n'); expect(JSON.parse(await notificationArchive({ file: "a_1.notify" }))).toMatchObject({ archived: 1, remaining_unread: 2 }); await expect(notificationArchive({ file: "../../etc/passwd" })).rejects.toThrow(); await expect(notificationArchive({ file: "missing.notify" })).rejects.toThrow(/No unread notification/); expect(JSON.parse(await notificationArchive({ all: true, importance: "normal" }))).toMatchObject({ archived: 2, remaining_unread: 0 }); }); });