/** * MUA — Mikes Unraid Agent * host.ts — VMs, Cache/Mover, Parity, docker.img und Benachrichtigungen. * * Verifiziert am Unraid-WebGUI-Quellcode (unraid/webgui): * - notify: emhttp/plugins/dynamix/scripts/notify (-e -s -d -i -m -l, `archive `), * ungelesen in /tmp/notifications/unread, Archiv in …/archive * - Parity: /usr/local/sbin/mdcmd check [NOCORRECT] | nocheck pause | check resume, * Zeitplan /boot/config/plugins/dynamix/parity-check.cron, * Historie /boot/config/parity-checks.log (date|duration|speed|status|errors|action|size) * - Mover: WebGUI-Feld cmdStartMover (emcmd), PID /var/run/mover.pid, * Einstellungen shareMoverSchedule/shareMoverLogging in var.ini * - Shares: /boot/config/shares/.cfg mit shareUseCache, shareCachePool, shareCachePool2 * VMs laufen über libvirt (`virsh`); fehlt es, melden die Tools das klar. * * Für Tests: MUA_HOST_ROOT (Präfix für Dateien) und MUA_HOST_BIN (Verzeichnis * mit Ersatzprogrammen) lenken alle Zugriffe um. */ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; import { basename } from "node:path"; import { runArgv } from "./helpers"; import { NameError, resolveName, type Mode } from "./names"; const root = (path: string) => `${process.env["MUA_HOST_ROOT"] ?? ""}${path}`; const BIN_DEFAULTS: Record = { virsh: "/usr/bin/virsh", mdcmd: "/usr/local/sbin/mdcmd", emcmd: "/usr/local/sbin/emcmd", notify: "/usr/local/emhttp/plugins/dynamix/scripts/notify", docker: "/usr/bin/docker", df: "/bin/df", du: "/usr/bin/du", }; function bin(name: keyof typeof BIN_DEFAULTS): string { const dir = process.env["MUA_HOST_BIN"]; return dir ? `${dir}/${name}` : BIN_DEFAULTS[name]; } function requireBin(name: keyof typeof BIN_DEFAULTS, what: string): string { const path = bin(name); if (!existsSync(path)) throw new Error(`${what} is not available on this host (${path} not found).`); return path; } function readText(path: string): string | null { try { return readFileSync(root(path), "utf-8"); } catch { return null; } } /** Flaches INI (KEY="value") wie var.ini, share.cfg, docker.cfg. */ export function parseFlatIni(text: string | null): Record { const out: Record = {}; for (const line of (text ?? "").split(/\r?\n/)) { const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*"?(.*?)"?\s*$/.exec(line); if (m) out[m[1]] = m[2]; } return out; } const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); const json = (value: unknown) => JSON.stringify(value); // ── VMs ────────────────────────────────────────────────────────────────── async function virsh(args: string[], timeout = 30): Promise { return runArgv("virsh", [requireBin("virsh", "VM management (libvirt/virsh)"), ...args], timeout, 200_000, 8_000); } async function vmNames(): Promise { const raw = await virsh(["list", "--all", "--name"]); return raw.split("\n").map((n) => n.trim()).filter(Boolean); } function wrapName(fn: () => T): T { try { return fn(); } catch (e) { if (e instanceof NameError) throw new Error(e.message); throw e; } } async function resolveVm(raw: unknown, mode: Mode): Promise<{ name: string; note?: string }> { const wanted = typeof raw === "string" ? raw : ""; if (!wanted.trim()) throw new Error("vm is required (VM name as shown by list)"); const names = await vmNames(); if (names.length === 0) throw new Error("No VMs are defined on this host."); return wrapName(() => resolveName(wanted, names, mode, "vm")); } export function parseDominfo(text: string): Record { const out: Record = {}; for (const line of text.split("\n")) { const i = line.indexOf(":"); if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim(); } return out; } function kibToMb(value: string | undefined): number | null { const m = /^(\d+)\s*KiB/i.exec(value ?? ""); return m ? Math.round(Number(m[1]) / 1024) : null; } async function vmSummary(name: string) { const info = parseDominfo(await virsh(["dominfo", name])); return { name, state: info["state"] ?? "unknown", vcpus: Number(info["cpu(s)"]) || null, memory_mb: kibToMb(info["max memory"]), autostart: info["autostart"] === "enable", persistent: info["persistent"] === "yes", }; } export async function vmList(): Promise { const names = await vmNames(); const vms = []; for (const name of names.slice(0, 64)) { try { vms.push(await vmSummary(name)); } catch (e) { vms.push({ name, state: "unknown", error: String(e).slice(0, 160) }); } } const running = vms.filter((v) => v.state === "running").length; return json({ vm_count: vms.length, running, stopped: vms.length - running, vms }); } /** Wichtige Teile der Domain-XML ohne Passwörter (VNC passwd!). */ export function summarizeDomainXml(xml: string) { const pci = [...xml.matchAll(/]*type=['"]pci['"][\s\S]*?[\s\S]*?]*bus=['"](0x[0-9a-f]+)['"][^>]*slot=['"](0x[0-9a-f]+)['"][^>]*function=['"](0x[0-9a-f]+)['"]/gi)] .map((m) => `${m[1].replace(/^0x/, "").padStart(2, "0")}:${m[2].replace(/^0x/, "").padStart(2, "0")}.${m[3].replace(/^0x/, "")}`); const usb = [...xml.matchAll(/]*type=['"]usb['"][\s\S]*? `${m[1].replace(/^0x/, "")}:${m[2].replace(/^0x/, "")}`); const graphics = [...xml.matchAll(/]*)>/gi)].map((m) => { const attr = (k: string) => new RegExp(`${k}=['"]([^'"]*)['"]`).exec(m[1])?.[1]; return { type: attr("type"), port: attr("port"), password_set: /passwd=/.test(m[1]) }; }); const machine = /]*machine=['"]([^'"]+)['"]/.exec(xml)?.[1] ?? null; return { pci_passthrough: pci, usb_passthrough: usb, graphics, machine }; } function parseTable(text: string): string[][] { return text.split("\n").slice(2).map((l) => l.trim()).filter(Boolean).map((l) => l.split(/\s{2,}|\s+(?=\S)/).filter(Boolean)); } export async function vmInspect(raw: unknown): Promise { const { name, note } = await resolveVm(raw, "read"); const summary = await vmSummary(name); const disks = parseTable(await virsh(["domblklist", name, "--details"]).catch(() => "")) .map(([type, device, target, ...source]) => ({ type, device, target, source: source.join(" ") })) .filter((d) => d.device !== "cdrom" || d.source !== "-"); const nics = parseTable(await virsh(["domiflist", name]).catch(() => "")) .map(([iface, type, source, model, mac]) => ({ interface: iface, type, source, model, mac })); const xml = summarizeDomainXml(await virsh(["dumpxml", name]).catch(() => "")); const libvirtSnapshots = (await virsh(["snapshot-list", name, "--name"]).catch(() => "")) .split("\n").map((s) => s.trim()).filter(Boolean); // Unraid-7-Snapshots (eigene Verwaltung neben libvirt) nur auflisten. const snapDir = root(`/etc/libvirt/qemu/snapshotdb/${name}`); const unraidSnapshots = existsSync(snapDir) ? readdirSync(snapDir).filter((f) => !f.startsWith(".")).slice(0, 50) : []; return json({ ...summary, ...(note ? { resolved: note } : {}), disks, network: nics, ...xml, snapshots: { libvirt: libvirtSnapshots, unraid: unraidSnapshots, note: "Create/revert snapshots in the Unraid VM tab; MUA only lists them." }, }); } const VM_OPS: Record = { start: { args: ["start"], requires: ["shut off", "crashed"], after: "running" }, shutdown: { args: ["shutdown"], requires: ["running"], after: "shut off" }, reboot: { args: ["reboot"], requires: ["running"], after: "running" }, suspend: { args: ["suspend"], requires: ["running"], after: "paused" }, resume: { args: ["resume"], requires: ["paused"], after: "running" }, force_stop: { args: ["destroy"], requires: ["running", "paused", "in shutdown", "crashed"], after: "shut off" }, }; export async function vmControl(raw: unknown, operation: string): Promise { const op = VM_OPS[operation]; if (!op) throw new Error(`operation must be one of: ${Object.keys(VM_OPS).filter((o) => o !== "force_stop").join(", ")}`); const { name, note } = await resolveVm(raw, "write"); const before = (await vmSummary(name)).state; if (!op.requires.includes(before)) { return json({ ok: false, vm: name, state: before, note: `Cannot ${operation} a VM that is '${before}'. Allowed from: ${op.requires.join(", ")}.` }); } await virsh([...op.args, name], 60); // shutdown ist ein ACPI-Signal: kurz beobachten, aber nicht blockieren. let state = before; for (let i = 0; i < (operation === "shutdown" ? 10 : 6); i++) { await sleep(500); state = (await vmSummary(name)).state; if (state === op.after) break; } return json({ ok: true, vm: name, ...(note ? { resolved: note } : {}), operation, state_before: before, state_now: state, ...(operation === "shutdown" && state !== "shut off" ? { note: "ACPI shutdown requested; the guest decides when to power off. Check again with inspect. Use force_stop only if it hangs." } : {}), }); } export async function vmAutostart(raw: unknown, enabled: unknown): Promise { if (typeof enabled !== "boolean") throw new Error("enabled must be true or false"); const { name } = await resolveVm(raw, "write"); await virsh(enabled ? ["autostart", name] : ["autostart", "--disable", name]); return json({ ok: true, vm: name, autostart: (await vmSummary(name)).autostart }); } // ── Cache / Mover ──────────────────────────────────────────────────────── const NON_POOL_MOUNTS = new Set(["user", "user0", "addons", "remotes", "disks", "rootshare"]); interface Mount { target: string; size: number; used: number; avail: number } async function mounts(paths: string[] = []): Promise { const raw = await runArgv("df", [requireBin("df", "df"), "-B1", "--output=target,size,used,avail", ...paths], 30, 200_000, 8_000) .catch((e) => { if (paths.length) throw e; return ""; }); return raw.split("\n").slice(1).map((l) => l.trim().split(/\s+/)).filter((p) => p.length >= 4) .map(([target, size, used, avail]) => ({ target, size: Number(size), used: Number(used), avail: Number(avail) })); } const pct = (used: number, size: number) => (size > 0 ? Math.round((used / size) * 1000) / 10 : 0); const gb = (b: number) => Math.round((b / 1e9) * 10) / 10; /** Bedeutung von shareUseCache (Unraid 6.12-Schreibweise, in 7.x weiter so gespeichert). */ const USE_CACHE: Record = { yes: "new files on pool; mover moves pool → array", prefer: "kept on pool; mover moves array → pool", only: "pool only; mover ignores it", no: "array only; mover ignores it (files left on a pool stay there)", }; export function readShareConfigs(): { name: string; use_cache: string; pool: string; secondary: string }[] { const dir = root("/boot/config/shares"); if (!existsSync(dir)) return []; return readdirSync(dir).filter((f) => f.endsWith(".cfg")).sort().map((f) => { const c = parseFlatIni(readFileSync(`${dir}/${f}`, "utf-8")); return { name: f.slice(0, -4), use_cache: (c["shareUseCache"] ?? "no").toLowerCase(), pool: c["shareCachePool"] ?? "", secondary: c["shareCachePool2"] ?? "" }; }); } function tailLines(path: string, match: RegExp, max: number): string[] { const full = root(path); if (!existsSync(full)) return []; const size = statSync(full).size; const start = Math.max(0, size - 2_000_000); const text = readFileSync(full).subarray(start).toString("utf-8"); return text.split("\n").filter((l) => match.test(l)).slice(-max); } export async function cacheStatus(): Promise { const allMounts = await mounts(); const pools = allMounts.filter((m) => { const parts = m.target.split("/"); return parts.length === 3 && parts[1] === "mnt" && !/^disk\d+$/.test(parts[2]) && !NON_POOL_MOUNTS.has(parts[2]); }); const shares = readShareConfigs(); const deadline = Date.now() + 45_000; const findings: { severity: string; message: string }[] = []; const poolReports = []; for (const pool of pools) { const poolName = pool.target.slice(5); const usage: { share: string; bytes: number | null; use_cache: string }[] = []; let entries: string[] = []; try { entries = readdirSync(root(pool.target)).filter((e) => !e.startsWith(".")); } catch { /* unlesbar */ } for (const entry of entries.slice(0, 100)) { const cfg = shares.find((s) => s.name === entry); let bytes: number | null = null; const remaining = Math.floor((deadline - Date.now()) / 1000); if (remaining > 1) { try { const out = await runArgv("du", [requireBin("du", "du"), "-sb", root(`${pool.target}/${entry}`)], Math.min(20, remaining), 10_000, 4_000); bytes = Number(out.split(/\s+/)[0]) || 0; } catch { bytes = null; } } usage.push({ share: entry, bytes, use_cache: cfg?.use_cache ?? "unknown" }); if (cfg && cfg.use_cache === "no" && (bytes ?? 0) > 1e8) { findings.push({ severity: "warning", message: `${gb(bytes!)} GB of share '${entry}' sit on pool '${poolName}' but the share is set to array only (use_cache=no): the mover will not move them.` }); } } usage.sort((a, b) => (b.bytes ?? -1) - (a.bytes ?? -1)); const used = pct(pool.used, pool.size); if (used >= 90) { const top = usage.filter((u) => u.bytes).slice(0, 3).map((u) => `${u.share} ${gb(u.bytes!)} GB (${u.use_cache})`).join(", "); findings.push({ severity: used >= 97 ? "critical" : "warning", message: `Pool '${poolName}' is ${used}% full. Largest: ${top || "unknown"}.` }); } poolReports.push({ pool: poolName, size_gb: gb(pool.size), used_gb: gb(pool.used), free_gb: gb(pool.avail), used_percent: used, contents: usage.slice(0, 20).map((u) => ({ ...u, gb: u.bytes === null ? null : gb(u.bytes) })) }); } const v = parseFlatIni(readText("/var/local/emhttp/var.ini")); const moverRunning = existsSync(root("/var/run/mover.pid")); const log = tailLines("/var/log/syslog", /\bmove(r)?\b[:]?/i, 15); return JSON.stringify({ pools: poolReports, shares: shares.map((s) => ({ ...s, meaning: USE_CACHE[s.use_cache] ?? "unknown setting" })), mover: { running: moverRunning, schedule: v["shareMoverSchedule"] ?? null, logging: v["shareMoverLogging"] ?? null, recent_log: log.map((l) => l.slice(0, 240)), ...(log.length === 0 ? { log_note: "No mover lines in syslog; enable mover logging in Settings > Scheduler to see details." } : {}), }, findings, }); } export async function moverStart(): Promise { if (existsSync(root("/var/run/mover.pid"))) return json({ ok: false, note: "Mover is already running." }); // Wie der Button in der WebGUI (Feld cmdStartMover). await runArgv("emcmd", [requireBin("emcmd", "emcmd"), "cmdStartMover=Move"], 30, 10_000, 4_000); let running = false; for (let i = 0; i < 10 && !running; i++) { await sleep(500); running = existsSync(root("/var/run/mover.pid")); } return json({ ok: true, started: running, note: running ? "Mover started. Follow progress with cache_status." : "Start requested; mover may have finished immediately (nothing to move) or not started. Check cache_status." }); } // ── Parity ─────────────────────────────────────────────────────────────── export interface ParityRun { date: string; duration_s: number | null; speed: string; status: string; errors: number | null; action: string } export function parseParityHistory(text: string | null, max = 5): ParityRun[] { const rows = (text ?? "").split("\n").map((l) => l.trim()).filter(Boolean); return rows.slice(-max).reverse().map((row) => { const [date = "", duration = "", speed = "", status = "", errors = "", action = ""] = row.split("|"); const code = Number(status); return { date, duration_s: Number(duration) || null, speed, status: status === "" ? "unknown" : code === 0 ? "ok" : code === -4 ? "canceled" : `error ${status}`, errors: errors === "" ? null : Number(errors), action, }; }); } export function describeParitySchedule(cron: string | null): { cron: string | null; correcting: boolean | null; text: string } { const line = (cron ?? "").split("\n").find((l) => /mdcmd\s+check/.test(l) && !l.trim().startsWith("#")); if (!line) return { cron: null, correcting: null, text: "No scheduled parity check." }; const [min, hour, dotm, month, dow] = line.trim().split(/\s+/); const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const when = `${hour.padStart(2, "0")}:${min.padStart(2, "0")}`; const text = dotm !== "*" ? `day ${dotm} of month ${month === "*" ? "every month" : month} at ${when}` : dow !== "*" ? `every ${dow.split(",").map((d) => days[Number(d)] ?? d).join(",")} at ${when}` : `daily at ${when}`; return { cron: line.trim().split(/\s+/).slice(0, 5).join(" "), correcting: !/NOCORRECT/.test(line), text }; } export async function parityStatus(): Promise { const v = parseFlatIni(readText("/var/local/emhttp/var.ini")); const size = Number(v["mdResyncSize"]) || 0; const pos = Number(v["mdResyncPos"]) || 0; const running = (Number(v["mdResync"]) || 0) > 0; return json({ array_state: v["mdState"] ?? null, running, action: v["mdResyncAction"] ?? null, progress_percent: running && size > 0 ? Math.round((pos / size) * 1000) / 10 : null, corrections: Number(v["mdResyncCorr"]) || 0, schedule: describeParitySchedule(readText("/boot/config/plugins/dynamix/parity-check.cron")), history: parseParityHistory(readText("/boot/config/parity-checks.log")), }); } export async function parityControl(operation: string, correct: unknown): Promise { const v = parseFlatIni(readText("/var/local/emhttp/var.ini")); const running = (Number(v["mdResync"]) || 0) > 0; const mdcmd = requireBin("mdcmd", "Parity control (mdcmd)"); let args: string[]; switch (operation) { case "start": if (v["mdState"] && v["mdState"] !== "STARTED") return json({ ok: false, note: `Array is ${v["mdState"]}; start the array first.` }); if (running) return json({ ok: false, note: "A parity operation is already running." }); args = correct === true ? ["check"] : ["check", "NOCORRECT"]; break; case "pause": if (!running) return json({ ok: false, note: "No parity operation is running." }); args = ["nocheck", "pause"]; break; case "resume": args = ["check", "resume"]; break; case "cancel": if (!running) return json({ ok: false, note: "No parity operation is running." }); args = ["nocheck"]; break; default: throw new Error("operation must be one of: start, pause, resume, cancel"); } await runArgv("mdcmd", [mdcmd, ...args], 30, 10_000, 4_000); return json({ ok: true, operation, correcting: operation === "start" ? correct === true : undefined, note: operation === "start" && correct !== true ? "Non-correcting check (reports errors, does not write parity)." : undefined }); } // ── docker.img ─────────────────────────────────────────────────────────── const SIZE_UNITS: Record = { B: 1, KB: 1e3, MB: 1e6, GB: 1e9, TB: 1e12, kB: 1e3 }; function parseDockerSize(s: string): number { const m = /^([\d.]+)\s*([kKMGT]?B)/.exec(s.trim()); return m ? Number(m[1]) * (SIZE_UNITS[m[2]] ?? SIZE_UNITS[m[2].toUpperCase()] ?? 1) : 0; } export async function dockerStorage(): Promise { const found = await mounts(["/var/lib/docker"]).catch(() => [] as Mount[]); const m = found.find((x) => x.target === "/var/lib/docker") ?? (found.length === 1 ? found[0] : undefined); const cfg = parseFlatIni(readText("/boot/config/docker.cfg")); const imageFile = cfg["DOCKER_IMAGE_FILE"] ?? ""; let breakdown: Record[] = []; try { const raw = await runArgv("docker", [requireBin("docker", "Docker"), "system", "df", "--format", "{{json .}}"], 60, 50_000, 4_000); breakdown = raw.split("\n").filter((l) => l.trim().startsWith("{")).map((l) => { const r = JSON.parse(l); return { type: r.Type, count: Number(r.TotalCount), active: Number(r.Active), gb: gb(parseDockerSize(String(r.Size ?? ""))), reclaimable: r.Reclaimable }; }); } catch { /* Docker gestoppt */ } return json({ mode: imageFile ? (imageFile.endsWith(".img") ? "image" : "directory") : "unknown", ...(imageFile ? { image_file: imageFile } : {}), ...(m ? { size_gb: gb(m.size), used_gb: gb(m.used), free_gb: gb(m.avail), used_percent: pct(m.used, m.size) } : { note: "/var/lib/docker is not mounted (Docker stopped?)" }), breakdown, hint: "Reclaim space with unused images/build cache (docker image prune) via the root shell if the user asks.", }); } // ── Benachrichtigungen ────────────────────────────────────────────────── const IMPORTANCE = new Set(["normal", "warning", "alert"]); export async function notifySend(a: Record): Promise { const subject = String(a["subject"] ?? "").trim(); if (!subject) throw new Error("subject is required"); const importance = String(a["importance"] ?? "normal").toLowerCase(); if (!IMPORTANCE.has(importance)) throw new Error("importance must be normal, warning or alert"); const link = a["link"] === undefined ? "" : String(a["link"]); if (link && !/^\/[A-Za-z0-9/_.-]*$/.test(link)) throw new Error("link must be a WebGUI path like /Docker or /Main"); const args = ["-e", String(a["event"] ?? "MUA Agent").slice(0, 60), "-s", subject.slice(0, 200), "-i", importance]; if (a["description"]) args.push("-d", String(a["description"]).slice(0, 500)); if (a["message"]) args.push("-m", String(a["message"]).slice(0, 2000)); if (link) args.push("-l", link); await runArgv("notify", [requireBin("notify", "Unraid notifications"), ...args], 30, 10_000, 4_000); return json({ ok: true, importance, subject: subject.slice(0, 200), note: "Delivered through the Unraid notification settings (browser and configured agents such as e-mail, ntfy, Discord)." }); } const NOTIFY_FILE = /^[A-Za-z0-9._ -]+\.notify$/; export async function notificationArchive(a: Record): Promise { const unreadDir = root("/tmp/notifications/unread"); const unread = existsSync(unreadDir) ? readdirSync(unreadDir).filter((f) => NOTIFY_FILE.test(f)) : []; let targets: string[]; if (a["all"] === true) { const importance = a["importance"] ? String(a["importance"]) : ""; targets = unread.filter((f) => !importance || new RegExp(`importance\\s*=\\s*"?${importance}"?`).test(readFileSync(`${unreadDir}/${f}`, "utf-8"))); } else { const file = basename(String(a["file"] ?? "")); if (!NOTIFY_FILE.test(file)) throw new Error("file is required (from notifications list), or set all=true"); if (!unread.includes(file)) throw new Error(`No unread notification named ${file}.`); targets = [file]; } const notify = requireBin("notify", "Unraid notifications"); let archived = 0; for (const f of targets.slice(0, 200)) { await runArgv("notify", [notify, "archive", f], 15, 4_000, 4_000); archived += 1; } return json({ ok: true, archived, remaining_unread: unread.length - archived }); }