diff --git a/README.md b/README.md index 4491a4a..a85e83e 100644 --- a/README.md +++ b/README.md @@ -7,8 +7,8 @@ Kompiliertes Bun-Binary (TypeScript), läuft als SysVinit-Service auf Unraid. - **Health-Check:** `http://UNRAID-IP:3002/health` (offen; Version/Port nur mit Bearer-Token) - **Config-Server:** `http://127.0.0.1:3013/config` (localhost + separater Admin-Token) - **Auth:** API-Key (Bearer-Token) für `/mcp` -- **Profile:** `full` (alle Einzeltools, Standard) und `lite` (`/mcp/lite`, ~9 gebündelte Tools für kleine Modelle) -- **Tools:** 49 (Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox) +- **Profile:** `full` (`/mcp/full`, alle Einzeltools) und `lite` (`/mcp/lite`, 10 gebündelte Tools für kleine Modelle); Standard für `/mcp` in der WebGUI wählbar +- **Tools:** 61 (VMs, Cache/Mover, Parity, Docker, Community Applications, Netzwerk, Unraid-System und optionale Toolbox) --- @@ -203,12 +203,12 @@ Auth: Authorization: Bearer | URL | Profil | Für | |---|---|---| | `http://UNRAID-IP:3002/mcp` | Standard (`MUA_PROFILE`, sonst `full`) | | -| `http://UNRAID-IP:3002/mcp/full` | alle 49 Einzeltools | große Modelle (Claude, GPT-4-Klasse) | -| `http://UNRAID-IP:3002/mcp/lite` | ~9 Gruppen-Tools mit `action` | kleine/lokale Modelle (7B–32B) | +| `http://UNRAID-IP:3002/mcp/full` | alle 61 Einzeltools | große Modelle (Claude, GPT-4-Klasse) | +| `http://UNRAID-IP:3002/mcp/lite` | 10 Gruppen-Tools mit `action` | kleine/lokale Modelle (7B–32B) | `?profile=lite|full` an der URL funktioniert ebenfalls. Das Lite-Profil -bündelt **dieselben** Funktionen: `unraid_docker` (`action: list|logs|restart|update|…`), -`unraid_storage`, `unraid_network`, `unraid_system`, `unraid_apps`, `unraid_shell`, +bündelt **dieselben** Funktionen: `unraid_docker` (`action: list|logs|restart|update|storage|…`), +`unraid_storage` (inkl. `cache`, `mover_start`, `parity*`), `unraid_vm`, `unraid_network`, `unraid_system`, `unraid_apps`, `unraid_shell`, `unraid_toolbox`, dazu unverändert `unraid_overview` und `unraid_shell_readonly`. - Es enthält nur freigegebene Aktionen. Die `action`-Liste wird pro Anfrage aus @@ -237,6 +237,30 @@ liest nur Quellen, deren eigenes Tool freigegeben ist. (start/stop/restart/update/…) akzeptieren nur den exakten Namen oder abweichende Groß-/Kleinschreibung und antworten sonst mit „Did you mean …?“. +### Neu in r039: VMs, Cache/Mover, Parity, docker.img, Benachrichtigungen + +| Tool | Risiko | Zweck | +|---|---|---| +| `unraid_vm_list`, `unraid_vm_inspect` | read | VMs mit Zustand, vCPU/RAM, Autostart; Disks, Netz, PCI/USB-Passthrough, Grafik (ohne Passwörter), vorhandene Snapshots | +| `unraid_vm_control` | write | start, shutdown (ACPI), reboot, suspend, resume – prüft den Zustand vorher, meldet ihn danach | +| `unraid_vm_force_stop` | critical | sofort ausschalten, nur wenn shutdown hängt | +| `unraid_vm_autostart` | write | Autostart an/aus | +| `unraid_cache_status` | read | Füllstand je Pool, welche Shares ihn belegen (mit Cache-Einstellung), Mover-Zustand/-Zeitplan/-Log, Befunde wie „Dateien, die der Mover nie verschiebt“ | +| `unraid_mover_start` | write | Mover jetzt starten (wie der Move-Button) | +| `unraid_parity_status` | read | laufende Prüfung, Zeitplan (korrigierend?), letzte Prüfungen mit Fehlern | +| `unraid_parity_control` | write | start (standardmäßig nicht korrigierend), pause, resume, cancel | +| `unraid_docker_storage` | read | Füllstand von docker.img und Aufteilung (Images, Container, Volumes, Build-Cache) | +| `unraid_notify` | write | Unraid-Benachrichtigung senden (geht auch an E-Mail/ntfy/Discord-Agents) | +| `unraid_notification_archive` | write | Benachrichtigungen als gelesen archivieren | + +Befehle und Pfade sind am Unraid-WebGUI-Quellcode geprüft (`notify`, `mdcmd`, +`cmdStartMover`, `/var/run/mover.pid`, `parity-check.cron`, `parity-checks.log`). +VM-Snapshots werden nur angezeigt; anlegen/zurücksetzen bleibt im VM-Tab, weil +Unraid 7 sie selbst verwaltet. `unraid_overview` meldet zusätzlich volles +docker.img, Fehler der letzten Parity-Prüfung und abgestürzte VMs. +Neuinstallationen erhalten die neuen Lesewerkzeuge automatisch; bestehende +Installationen zeigen sie in der WebGUI mit einem Freigabe-Button an. + MUA läuft direkt auf Unraid und spricht **Streamable HTTP**. Ein SSH-Wrapper ist weder erforderlich noch empfohlen. Dadurch bleiben Verbindungen kompakt und routinemäßige Tool-Aufrufe erzeugen keine SSH-Anmeldungen im Unraid-Syslog. diff --git a/dist/mua-2026.11.21.r038-x86_64-1.txz.sha256 b/dist/mua-2026.11.21.r038-x86_64-1.txz.sha256 deleted file mode 100644 index 7fd8612..0000000 --- a/dist/mua-2026.11.21.r038-x86_64-1.txz.sha256 +++ /dev/null @@ -1 +0,0 @@ -bdef4eaf4faf61e43c32b557f653fc55e9bfb93770d8956891e6807036d350e5 mua-2026.11.21.r038-x86_64-1.txz diff --git a/dist/mua-2026.11.21.r038-x86_64-1.txz b/dist/mua-2026.11.21.r039-x86_64-1.txz similarity index 71% rename from dist/mua-2026.11.21.r038-x86_64-1.txz rename to dist/mua-2026.11.21.r039-x86_64-1.txz index 214fe2d..6b41f63 100644 Binary files a/dist/mua-2026.11.21.r038-x86_64-1.txz and b/dist/mua-2026.11.21.r039-x86_64-1.txz differ diff --git a/dist/mua-2026.11.21.r039-x86_64-1.txz.sha256 b/dist/mua-2026.11.21.r039-x86_64-1.txz.sha256 new file mode 100644 index 0000000..81e61c8 --- /dev/null +++ b/dist/mua-2026.11.21.r039-x86_64-1.txz.sha256 @@ -0,0 +1 @@ +49f9187d532089d261e6ee26b495168b7ff369d94a6ab889530f37154a23a48a mua-2026.11.21.r039-x86_64-1.txz diff --git a/package.json b/package.json index 0c28e3b..b02374e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "mua", - "version": "2026.11.21.r038", + "version": "2026.11.21.r039", "description": "Mikes Unraid Agent - MCP over HTTP(S) (Streamable HTTP) for Unraid", "type": "module", "main": "src/index.ts", diff --git a/plugin/mua.plg b/plugin/mua.plg index 104980e..eee0eae 100644 --- a/plugin/mua.plg +++ b/plugin/mua.plg @@ -2,13 +2,13 @@ - + - - + + ]> +### 2026.11.21.r039 +- WebGUI: neuer Bereich „Verbindung“ mit beiden Endpunkten (Vollständig /mcp/full, Kompakt /mcp/lite), Kopier-Buttons und Auswahl des Standardprofils für /mcp. +- WebGUI: Hinweis auf neue, noch nicht freigegebene Werkzeuge mit Button „Neue Lesewerkzeuge freigeben“; Profile „Nur Lesen“ und „Betrieb + Diagnose“ um die neuen Werkzeuge ergänzt. +- Neu: VMs auflisten, inspizieren (Disks, Netz, PCI/USB-Passthrough, Snapshots; ohne Passwörter), starten, herunterfahren, neu starten, pausieren, fortsetzen, Autostart; Notabschaltung als kritisches Werkzeug. +- Neu: Cache-/Pool-Analyse (welche Shares den Cache füllen, Cache-Einstellung, Dateien, die der Mover nie verschiebt), Mover-Status/-Log und Mover starten. +- Neu: Parity-Status mit Zeitplan und Historie; Parity-Prüfung starten (standardmäßig nicht korrigierend), pausieren, fortsetzen, abbrechen. +- Neu: docker.img-Füllstand mit Aufteilung; eigene Unraid-Benachrichtigungen senden und Benachrichtigungen archivieren. +- unraid_overview meldet zusätzlich volles docker.img, Fehler der letzten Parity-Prüfung und abgestürzte VMs. +- Fix: Ungelesene Benachrichtigungen (/tmp/notifications/unread) wurden bisher nicht gelesen; Liste und Übersicht sehen sie jetzt. +- Lite-Profil: neue Gruppe unraid_vm; Speicher-, Docker- und System-Gruppe um die neuen Aktionen erweitert. + ### 2026.11.21.r038 - Lite-Profil übernimmt die Verhaltensregeln des vollen Profils als kurze „Rules“: Updates nur auf ausdrücklichen Wunsch, exakte Containernamen für Änderungen, *_apply nur für die bestätigte Vorschau, Root-Shell nur für ausdrücklich verlangte Aufgaben, Programme nur in der Toolbox installieren, Jobs nicht doppelt starten u.a. Eine Regel erscheint nur, wenn ihre Aktion freigegeben ist. - Gleichbedeutende Werte werden je Ziel-Tool übersetzt (detail summary/compact, state active → running, severity errors → error). @@ -235,7 +246,7 @@ Das .txz enthält: install/doinst.sh (läuft nach Installation) =========================================== --> - + &txzURL; &txzSHA256; diff --git a/plugin/plugin.json b/plugin/plugin.json index 724ec08..ce928df 100644 --- a/plugin/plugin.json +++ b/plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "mua", "author": "Michael", - "version": "2026.11.21.r038", + "version": "2026.11.21.r039", "minver": "7.0.0", "pluginDirectory": "/usr/local/emhttp/plugins/mua", "configDirectory": "/boot/config/plugins/mua", diff --git a/scripts/mua.page b/scripts/mua.page index ac2d360..e034372 100644 --- a/scripts/mua.page +++ b/scripts/mua.page @@ -57,7 +57,8 @@ $health_data = mua_health($config_port, $admin_token); $health_ok = is_array($health_data) && ($health_data['status'] ?? '') === 'ok'; $running_version = $health_data['version'] ?? ''; $scheme = ($health_data['scheme'] ?? '') === 'https' ? 'https' : 'http'; -$endpoint = $health_ok ? $scheme . '://' . (str_contains($host_ip, ':') ? '[' . $host_ip . ']' : $host_ip) . ':' . ($health_data['port'] ?? $port) . '/mcp' : 'Nicht verfügbar – Dienst/Logs prüfen'; +$base_url = $health_ok ? $scheme . '://' . (str_contains($host_ip, ':') ? '[' . $host_ip . ']' : $host_ip) . ':' . ($health_data['port'] ?? $port) : ''; +$endpoint = $health_ok ? $base_url . '/mcp' : 'Nicht verfügbar – Dienst/Logs prüfen'; [$config_code, $config] = mua_api('GET', '/config', null, $admin_token, $config_port); $config_ok = $config_code === 200 && is_array($config); $flash_msg = ''; @@ -73,13 +74,21 @@ $readonly = [ 'unraid_system_shell_readonly', 'unraid_docker_update_status', 'unraid_system_health', 'unraid_storage_status', 'unraid_disk_health', 'unraid_notifications_list', 'unraid_shares_list', 'unraid_share_inspect', - 'unraid_files_inventory', + 'unraid_files_inventory', 'unraid_overview', 'unraid_vm_list', 'unraid_vm_inspect', + 'unraid_cache_status', 'unraid_parity_status', 'unraid_docker_storage', ]; $operator = array_merge($readonly, [ 'unraid_network_audit_tcp', 'unraid_network_lan_probe', 'unraid_ca_search', 'unraid_ca_install_preview', 'unraid_docker_start', 'unraid_docker_stop', 'unraid_docker_restart', + 'unraid_vm_control', 'unraid_vm_autostart', 'unraid_mover_start', 'unraid_parity_control', + 'unraid_notify', 'unraid_notification_archive', ]); +$new_tools = is_array($config['newTools'] ?? null) ? $config['newTools'] : []; +$new_read_tools = []; +foreach ($new_tools as $tool) { + if (is_array($tool) && ($tool['risk'] ?? '') === 'read' && is_string($tool['name'] ?? null)) $new_read_tools[] = $tool['name']; +} if ($_SERVER['REQUEST_METHOD'] === 'POST') { $posted_csrf = $_POST['mua_csrf'] ?? ''; @@ -96,6 +105,11 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { if ($action === 'preset_none') $payload = ['enabledTools' => [], 'allToolsEnabled' => false]; if ($action === 'preset_all') $payload = ['enabledTools' => [], 'allToolsEnabled' => true]; if ($action === 'save_toolbox') $payload = ['toolboxEnabled' => isset($_POST['toolbox_enabled'])]; + if ($action === 'save_profile') $payload = ['defaultProfile' => (($_POST['default_profile'] ?? '') === 'lite') ? 'lite' : 'full']; + if ($action === 'enable_new_read' && !empty($new_read_tools)) { + $current = is_array($config['enabledTools'] ?? null) ? $config['enabledTools'] : []; + $payload = ['enabledTools' => array_values(array_unique(array_merge($current, $new_read_tools))), 'allToolsEnabled' => false]; + } if ($action === 'save_tls') $payload = ['tls' => [ 'enabled' => isset($_POST['tls_enabled']), 'source' => $_POST['tls_source'] ?? 'manual', @@ -120,7 +134,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { [$code, $result] = mua_api('POST', '/config', $payload, $admin_token, $config_port); if ($code === 200 && is_array($result) && ($result['ok'] ?? false)) { $new_api_key = $result['generatedApiKey'] ?? ''; - $flash_msg = $action === 'save_tls' ? 'TLS-Einstellungen geprüft und gespeichert. Zum Anwenden Dienst ausdrücklich neu starten.' : ($new_api_key ? 'Neuer API-Key erzeugt. Jetzt kopieren – er wird nur dieses eine Mal angezeigt.' : 'Sicherheitseinstellungen gespeichert.'); + $flash_msg = $action === 'save_tls' ? 'TLS-Einstellungen geprüft und gespeichert. Zum Anwenden Dienst ausdrücklich neu starten.' + : ($new_api_key ? 'Neuer API-Key erzeugt. Jetzt kopieren – er wird nur dieses eine Mal angezeigt.' + : ($action === 'save_profile' ? 'Standardprofil gespeichert. Gilt sofort für neue Verbindungen auf /mcp.' + : ($action === 'enable_new_read' ? 'Neue Lesewerkzeuge freigegeben.' : 'Sicherheitseinstellungen gespeichert.'))); $flash_type = 'ok'; [$config_code, $config] = mua_api('GET', '/config', null, $admin_token, $config_port); $config_ok = $config_code === 200 && is_array($config); @@ -132,6 +149,13 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { } } +$new_tools = is_array($config['newTools'] ?? null) ? $config['newTools'] : []; +$new_read_tools = []; +foreach ($new_tools as $tool) { + if (is_array($tool) && ($tool['risk'] ?? '') === 'read' && is_string($tool['name'] ?? null)) $new_read_tools[] = $tool['name']; +} +$default_profile = ($config['defaultProfile'] ?? 'full') === 'lite' ? 'lite' : 'full'; +$profile_locked = !$config_ok || !empty($config['profileEnvOverride']); $transport = is_array($config['transport'] ?? null) ? $config['transport'] : []; $tls = is_array($transport['tls'] ?? null) ? $transport['tls'] : []; $tls_source = ($tls['source'] ?? 'unraid') === 'manual' ? 'manual' : 'unraid'; @@ -177,7 +201,34 @@ $active_count = $all_tools_enabled ? count($all_tools) : count($enabled_tools);

Authentifizierung

-

MCP-Endpunkt

Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich

Kompakt für kleine Modelle:

+

Verbindung

+ + + + + +
Vollständig
große Modelle (Claude, GPT)
Kompakt
kleine/lokale Modelle (Qwen, Llama …)
Standard →
+ +
+ +

Streamable HTTP · JSON-RPC 2.0 · Bearer-Authentifizierung erforderlich. Beide Profile bieten dieselben Funktionen und Freigaben: „Kompakt“ bündelt sie in rund zehn Werkzeugen mit action-Feld und spart etwa die Hälfte der Tokens. Erster Aufruf in jeder Sitzung: unraid_overview.

+
+Standardprofil für /mcp: + + + +Durch Umgebungsvariable MUA_PROFILE festgelegt. +
+
+ + +
Neu in dieser Version – noch nicht freigegeben: +(' . htmlspecialchars((string)($tool['risk'] ?? '')) . ')' ?> + +
Steuernde Werkzeuge (VMs, Mover, Parity, Benachrichtigungen) einzeln unten unter „Werkzeuge im Detail“ freigeben.
+ +
+

HTTPS / TLS

Aktiver Transport: . TLS schützt denselben MCP-Port inklusive /health; Bearer-Key und Toolfreigaben bleiben unverändert.

diff --git a/scripts/unraid-mcp-status-helper.php b/scripts/unraid-mcp-status-helper.php index f898c5c..fea1bf5 100644 --- a/scripts/unraid-mcp-status-helper.php +++ b/scripts/unraid-mcp-status-helper.php @@ -210,7 +210,15 @@ function notification_fields(string $contents): array { function notification_list(int $limit, ?string $importance): array { $limit = max(1, min(50, $limit)); - $files = array_merge(glob('/tmp/notifications/*.notify') ?: [], glob('/tmp/notifications/archive/*.notify') ?: []); + // Unraid (dynamix/scripts/notify): ungelesen in /tmp/notifications/unread, + // gelesen in /tmp/notifications/archive. Die Wurzel wird für ältere + // Versionen weiterhin mitgelesen. + $base = getenv('MUA_NOTIFICATIONS_DIR') ?: '/tmp/notifications'; + $files = array_merge( + glob("$base/unread/*.notify") ?: [], + glob("$base/*.notify") ?: [], + glob("$base/archive/*.notify") ?: [] + ); usort($files, fn($a, $b) => filemtime($b) <=> filemtime($a)); $items = []; foreach ($files as $file) { @@ -227,6 +235,7 @@ function notification_list(int $limit, ?string $importance): array { 'subject' => clean_text(trim((string)($n['subject'] ?? ''), '"'), 180), 'description' => clean_text(trim((string)($n['description'] ?? ''), '"'), 500), 'archived' => str_contains($file, '/archive/'), + 'file' => basename($file), ]; if (count($items) >= $limit) break; } diff --git a/src/auth.ts b/src/auth.ts index f542175..30ca3be 100644 --- a/src/auth.ts +++ b/src/auth.ts @@ -48,6 +48,11 @@ export interface MUAConfig { // werden. export const SAFE_DEFAULT_TOOLS = [ "unraid_overview", + "unraid_vm_list", + "unraid_vm_inspect", + "unraid_cache_status", + "unraid_parity_status", + "unraid_docker_storage", "unraid_docker_list", "unraid_docker_inspect", "unraid_docker_logs", @@ -132,6 +137,7 @@ export function parseConfig(content: string): MUAConfig { if (!cfg.allToolsEnabled && [ "unraid_system_health", "unraid_storage_status", "unraid_docker_list", "unraid_docker_update_status", "unraid_notifications_list", + "unraid_docker_storage", "unraid_parity_status", "unraid_vm_list", ].some((t) => cfg.enabledTools.includes(t))) { grant("unraid_overview"); } @@ -296,6 +302,12 @@ export function getDefaultProfile(): "full" | "lite" { return loadConfig().defaultProfile ?? "full"; } +export function setDefaultProfile(profile: "full" | "lite"): void { + const cfg = loadConfig(); + cfg.defaultProfile = profile; + saveConfig(cfg); +} + export function getToolboxEnabled(): boolean { return loadConfig().toolboxEnabled; } diff --git a/src/dispatch.ts b/src/dispatch.ts index 3d56db0..ef313c5 100644 --- a/src/dispatch.ts +++ b/src/dispatch.ts @@ -30,7 +30,18 @@ export function listTools(ctx: Pick) // ── Container-Namen ────────────────────────────────────────────────────── -type Mode = "read" | "write"; +import { resolveName as resolveContainerNameImpl, NameError, type Mode, type NameResolution } from "./names"; +export type { NameResolution }; + +/** Löst einen (ungenauen) Containernamen auf oder wirft mit Vorschlägen. */ +export function resolveContainerName(raw: string, names: string[], mode: Mode): NameResolution { + try { + return resolveContainerNameImpl(raw, names, mode, "container"); + } catch (error) { + if (error instanceof NameError) throw new DispatchError(error.message); + throw error; + } +} const CONTAINER_PARAMS: Record = { unraid_docker_inspect: { param: "container", mode: "read" }, unraid_docker_logs: { param: "container", mode: "read" }, @@ -45,49 +56,6 @@ const CONTAINER_PARAMS: Record s.toLowerCase().replace(/[^a-z0-9]/g, ""); - -function editDistance(a: string, b: string): number { - const dp = Array.from({ length: b.length + 1 }, (_, i) => i); - for (let i = 1; i <= a.length; i++) { - let prev = dp[0]; - dp[0] = i; - for (let j = 1; j <= b.length; j++) { - const tmp = dp[j]; - dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); - prev = tmp; - } - } - return dp[b.length]; -} - -export interface NameResolution { name: string; note?: string } - -/** Löst einen (ungenauen) Containernamen auf oder wirft mit Vorschlägen. */ -export function resolveContainerName(raw: string, names: string[], mode: Mode): NameResolution { - const wanted = raw.trim().replace(/^\//, ""); - if (names.includes(wanted)) return { name: wanted }; - const ci = names.filter((n) => n.toLowerCase() === wanted.toLowerCase()); - if (ci.length === 1) return { name: ci[0], note: `container '${raw}' → '${ci[0]}'` }; - - const key = squash(wanted); - const partial = key ? names.filter((n) => squash(n).includes(key)) : []; - const suggestions = partial.length > 0 - ? partial.slice(0, 5) - : [...names].sort((a, b) => editDistance(squash(a), key) - editDistance(squash(b), key)).slice(0, 3); - - if (mode === "read" && partial.length === 1) { - return { name: partial[0], note: `container '${raw}' → '${partial[0]}'` }; - } - if (partial.length > 1) { - throw new DispatchError(`Container '${raw}' is ambiguous. Did you mean: ${suggestions.join(", ")}?`); - } - if (mode === "write" && partial.length === 1) { - throw new DispatchError(`No container named exactly '${raw}'. Did you mean '${partial[0]}'? Repeat the call with that exact name.`); - } - throw new DispatchError(`No container named '${raw}'.${suggestions.length ? ` Closest: ${suggestions.join(", ")}.` : ""} Use list to see all containers.`); -} - async function resolveContainers( tool: string, args: Record, diff --git a/src/helpers.ts b/src/helpers.ts index 4caa472..d790053 100644 --- a/src/helpers.ts +++ b/src/helpers.ts @@ -19,7 +19,7 @@ import { redactKnownSecrets } from "./redact"; // ── Konstanten ────────────────────────────────────────────────────────── export const MUA_SERVER_NAME = "mua"; -export const MUA_VERSION = "2026.11.21.r038"; +export const MUA_VERSION = "2026.11.21.r039"; export const MUA_PROTOCOL_VERSION = "2025-03-26"; export const PHP_HELPER = "/usr/local/bin/unraid-docker-mcp-helper.php"; export const STATUS_HELPER = "/usr/local/bin/unraid-mcp-status-helper.php"; @@ -296,7 +296,7 @@ export function pruneFinishedJobs(maxAgeMs = 7 * 24 * 60 * 60 * 1000, now = Date return removed; } -async function runArgv( +export async function runArgv( label: string, argv: string[], timeoutSec = 60, diff --git a/src/host.test.ts b/src/host.test.ts new file mode 100644 index 0000000..4a0b307 --- /dev/null +++ b/src/host.test.ts @@ -0,0 +1,222 @@ +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 }); + }); +}); diff --git a/src/host.ts b/src/host.ts new file mode 100644 index 0000000..e83c2f8 --- /dev/null +++ b/src/host.ts @@ -0,0 +1,450 @@ +/** + * 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 }); +} diff --git a/src/index.ts b/src/index.ts index bd6d4ab..8d4462f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -26,7 +26,7 @@ import { killForegroundGroups, runInProcessScope } from "./process-group"; import { listTools, prepareCall, type PreparedCall } from "./dispatch"; import { profileFromUrl, type Profile } from "./profiles"; import { registerSecret } from "./redact"; -import { TOOLS, getToolRisk } from "./tools"; +import { TOOLS, getToolRisk, NEW_IN_RELEASE } from "./tools"; import { checkAuth, isToolEnabled, @@ -39,6 +39,7 @@ import { setToolboxEnabled, getAutoGrantedTools, getDefaultProfile, + setDefaultProfile, safeEqual, } from "./auth"; import { randomBytes } from "node:crypto"; @@ -608,6 +609,10 @@ try { enabledTools: getEnabledTools(), allToolsEnabled: getAllToolsEnabled(), autoGrantedTools: getAutoGrantedTools(), + defaultProfile: getDefaultProfile(), + profileEnvOverride: ["lite", "full"].includes(String(process.env["MUA_PROFILE"] ?? "").toLowerCase()), + newTools: NEW_IN_RELEASE.filter((name) => !isToolEnabled(name)) + .map((name) => ({ name, risk: getToolRisk(name) })), allTools: TOOLS.filter((t) => !TOOLBOX_TOOL_NAMES.has(t.name)).map((t) => ({ name: t.name, description: t.description, @@ -644,6 +649,13 @@ try { } } + if (body["defaultProfile"] !== undefined) { + if (body["defaultProfile"] !== "full" && body["defaultProfile"] !== "lite") { + return Response.json({ error: "defaultProfile must be full or lite" }, { status: 400 }); + } + setDefaultProfile(body["defaultProfile"]); + } + // "generate": neuen API-Key generieren let generatedApiKey: string | undefined; if (body["generate"] === true) generatedApiKey = generateApiKey(); diff --git a/src/lite.test.ts b/src/lite.test.ts index 3ea9905..9f807a5 100644 --- a/src/lite.test.ts +++ b/src/lite.test.ts @@ -18,7 +18,7 @@ describe("lite profile: tools/list", () => { const full = listTools({ profile: "full", isAvailable: ALL }); const lite = listTools({ profile: "lite", isAvailable: ALL }); expect(lite.map((t) => t.name)).toEqual([ - "unraid_overview", "unraid_shell_readonly", "unraid_docker", "unraid_storage", + "unraid_overview", "unraid_shell_readonly", "unraid_docker", "unraid_storage", "unraid_vm", "unraid_network", "unraid_system", "unraid_apps", "unraid_shell", "unraid_toolbox", ]); expect(schemaSize(lite)).toBeLessThan(schemaSize(full) * 0.6); @@ -35,7 +35,9 @@ describe("lite profile: tools/list", () => { expect(actions).toContain(hint.arguments["action"] as string); // Rückweg: die Aktion landet wieder beim selben Tool (Batch-Update ausgenommen: Fallback). if (t.name !== "unraid_docker_update") { - const required = Object.fromEntries(((t.inputSchema as any).required ?? []).map((r: string) => [r, r === "containers" ? "Sonarr" : r === "container" ? "Sonarr" : "x"])); + const props = (t.inputSchema as any).properties ?? {}; + const required = Object.fromEntries(((t.inputSchema as any).required ?? []).map((r: string) => + [r, props[r]?.enum ? props[r].enum[0] : props[r]?.type === "boolean" ? true : r === "containers" || r === "container" ? "Sonarr" : "x"])); const back = await prepareCall(hint.tool, { ...callHint(t.name, required, "lite").arguments }, ctx(ALL)); expect(back.tool.name).toBe(t.name); } @@ -222,6 +224,7 @@ function deps(data: Record, profile: "full" | "lite" = "full", profile, isEnabled: enabled, timeoutMs: 200, run: async (tool: string) => { const v = data[tool]; + if (v === undefined) throw new Error(`${tool} is not available on this host (test)`); if (v === "hang") return new Promise(() => {}); if (v instanceof Error) throw v; return JSON.stringify(v ?? {}); diff --git a/src/names.ts b/src/names.ts new file mode 100644 index 0000000..6d89724 --- /dev/null +++ b/src/names.ts @@ -0,0 +1,53 @@ +/** + * MUA — Mikes Unraid Agent + * names.ts — Fehlertolerante Namensauflösung (Container, VMs). + * Lesend: eindeutige Teilnamen werden aufgelöst. Schreibend: nur exakt oder + * abweichende Groß-/Kleinschreibung, sonst ein Vorschlag. + */ + +export type Mode = "read" | "write"; +export class NameError extends Error {} + +const squash = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, ""); + +function editDistance(a: string, b: string): number { + const dp = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + let prev = dp[0]; + dp[0] = i; + for (let j = 1; j <= b.length; j++) { + const tmp = dp[j]; + dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1)); + prev = tmp; + } + } + return dp[b.length]; +} + +export interface NameResolution { name: string; note?: string } + +/** Löst einen (ungenauen) Namen auf oder wirft mit Vorschlägen. */ +export function resolveName(raw: string, names: string[], mode: Mode, kind = "container"): NameResolution { + const wanted = raw.trim().replace(/^\//, ""); + if (names.includes(wanted)) return { name: wanted }; + const ci = names.filter((n) => n.toLowerCase() === wanted.toLowerCase()); + if (ci.length === 1) return { name: ci[0], note: `${kind} '${raw}' → '${ci[0]}'` }; + + const key = squash(wanted); + const partial = key ? names.filter((n) => squash(n).includes(key)) : []; + const suggestions = partial.length > 0 + ? partial.slice(0, 5) + : [...names].sort((a, b) => editDistance(squash(a), key) - editDistance(squash(b), key)).slice(0, 3); + + if (mode === "read" && partial.length === 1) { + return { name: partial[0], note: `${kind} '${raw}' → '${partial[0]}'` }; + } + if (partial.length > 1) { + throw new NameError(`${kind[0].toUpperCase()}${kind.slice(1)} '${raw}' is ambiguous. Did you mean: ${suggestions.join(", ")}?`); + } + if (mode === "write" && partial.length === 1) { + throw new NameError(`No ${kind} named exactly '${raw}'. Did you mean '${partial[0]}'? Repeat the call with that exact name.`); + } + throw new NameError(`No ${kind} named '${raw}'.${suggestions.length ? ` Closest: ${suggestions.join(", ")}.` : ""} Use list to see all ${kind}s.`); +} + diff --git a/src/overview.ts b/src/overview.ts index a3cca73..346f467 100644 --- a/src/overview.ts +++ b/src/overview.ts @@ -17,7 +17,7 @@ export type Severity = "critical" | "warning" | "info"; export interface AttentionItem { severity: Severity; - area: "storage" | "system" | "docker" | "notifications"; + area: "storage" | "system" | "docker" | "notifications" | "vm"; message: string; next?: { tool: string; arguments: Record }; } @@ -37,6 +37,9 @@ const SOURCES = { docker: "unraid_docker_list", updates: "unraid_docker_update_status", notifications: "unraid_notifications_list", + docker_storage: "unraid_docker_storage", + parity: "unraid_parity_status", + vms: "unraid_vm_list", } as const; const RANK: Record = { critical: 0, warning: 1, info: 2 }; @@ -61,6 +64,13 @@ function duration(seconds: number): string { return d > 0 ? `${d}d ${h}h` : `${h}h ${Math.floor((seconds % 3600) / 60)}m`; } +/** "2025 Jan 7 05:23:11" (parity-checks.log) → ms, sonst null. */ +export function parityDate(raw: string): number | null { + const m = /^(\d{4})\s+([A-Za-z]{3})\s+(\d{1,2})\s+(\d{1,2}:\d{2}(?::\d{2})?)/.exec(raw.trim()); + const t = m ? Date.parse(`${m[2]} ${m[3]} ${m[1]} ${m[4]}`) : Date.parse(raw); + return Number.isFinite(t) ? t : null; +} + /** Exit-Codes, die beim normalen Stoppen entstehen (SIGKILL/SIGTERM). */ const NORMAL_EXIT = new Set([0, 137, 143]); @@ -80,17 +90,23 @@ export async function buildOverview(deps: OverviewDeps): Promise { try { return JSON.parse(await withTimeout(deps.run(tool, args), timeoutMs)); } catch (error) { - unavailable[key] = (error instanceof Error ? error.message : String(error)).slice(0, 200); + const message = (error instanceof Error ? error.message : String(error)); + // Funktion auf diesem Host nicht vorhanden (z.B. VM-Manager aus): kein Fehler. + if (/not available on this host/.test(message)) { skipped.push(`${key} (not available on this host)`); return null; } + unavailable[key] = message.slice(0, 200); return null; } }; - const [system, storage, docker, updates, notifications] = await Promise.all([ + const [system, storage, docker, updates, notifications, dockerStorage, parity, vms] = await Promise.all([ load("system"), load("storage"), load("docker", { state: "all" }), load("updates"), load("notifications", { limit: 30, importance: "all" }), + load("docker_storage"), + load("parity"), + load("vms"), ]); // ── System ──────────────────────────────────────────────────────────── @@ -194,6 +210,41 @@ export async function buildOverview(deps: OverviewDeps): Promise { } } + // ── docker.img ──────────────────────────────────────────────────────── + if (dockerStorage && typeof dockerStorage.used_percent === "number") { + const used = dockerStorage.used_percent; + const dockerSummary = (summary["docker"] ??= {}) as Record; + dockerSummary["storage_used_percent"] = used; + const label = dockerStorage.mode === "directory" ? "Docker directory" : "docker.img"; + if (used >= 90) add({ severity: "critical", area: "docker", message: `${label} ${used}% full (${dockerStorage.free_gb} GB free); containers may fail to start or write`, next: hint("unraid_docker_storage") }); + else if (used >= 80) add({ severity: "warning", area: "docker", message: `${label} ${used}% full (${dockerStorage.free_gb} GB free)`, next: hint("unraid_docker_storage") }); + } + + // ── Parity-Historie ─────────────────────────────────────────────────── + if (parity) { + const last = Array.isArray(parity.history) ? parity.history[0] : undefined; + const storageSummary = (summary["storage"] ??= {}) as Record; + if (parity.schedule?.text) storageSummary["parity_schedule"] = parity.schedule.text; + if (last) { + storageSummary["last_parity_check"] = `${last.date} (${last.status}${last.errors ? `, ${last.errors} errors` : ""})`; + if ((last.errors ?? 0) > 0) { + add({ severity: "warning", area: "storage", message: `Last parity check (${last.date}) reported ${last.errors} error(s)`, next: hint("unraid_parity_status") }); + } + const when = parityDate(String(last.date)); + if (when && Date.now() - when > 120 * 86400_000) { + add({ severity: "info", area: "storage", message: `Last parity check was on ${last.date} (over 120 days ago)`, next: hint("unraid_parity_status") }); + } + } + } + + // ── VMs ─────────────────────────────────────────────────────────────── + if (vms && Array.isArray(vms.vms)) { + summary["vms"] = { running: vms.running, stopped: vms.stopped }; + for (const vm of vms.vms.filter((v: any) => v.state === "crashed" || v.state === "in shutdown")) { + add({ severity: vm.state === "crashed" ? "critical" : "info", area: "vm", message: `VM ${vm.name} is ${vm.state}`, next: hint("unraid_vm_inspect", { vm: vm.name }) }); + } + } + // ── Benachrichtigungen ──────────────────────────────────────────────── if (notifications) { const active: any[] = (Array.isArray(notifications.notifications) ? notifications.notifications : []) @@ -212,7 +263,7 @@ export async function buildOverview(deps: OverviewDeps): Promise { } attention.sort((a, b) => RANK[a.severity] - RANK[b.severity]); - const loaded = [system, storage, docker, updates, notifications].filter((x) => x !== null).length; + const loaded = [system, storage, docker, updates, notifications, dockerStorage, parity, vms].filter((x) => x !== null).length; const missing = Object.keys(unavailable); const count = (s: Severity) => attention.filter((a) => a.severity === s).length; // Ohne gelesene Quelle darf niemals "ok" gemeldet werden. diff --git a/src/profiles.ts b/src/profiles.ts index cda7340..151142b 100644 --- a/src/profiles.ts +++ b/src/profiles.ts @@ -30,6 +30,8 @@ interface LiteAction { rule?: string; /** Lite-Parametername → Parametername des Ziel-Tools. */ rename?: Record; + /** Feste Argumente des Ziel-Tools; werden gesetzt und nicht angezeigt. */ + fixed?: Record; /** Ausweich-Ziel, falls `tool` nicht freigegeben ist. */ fallback?: string; /** Eingaben vor dem Aufruf anpassen (nach rename). */ @@ -101,6 +103,7 @@ export const LITE_GROUPS: LiteGroup[] = [ processes: { tool: "unraid_docker_processes", summary: "processes inside a container" }, stats: { tool: "unraid_docker_stats", summary: "CPU/RAM/IO of running containers" }, info: { tool: "unraid_docker_info", summary: "Docker engine info" }, + storage: { tool: "unraid_docker_storage", summary: "docker.img fill level and what uses it" }, update_status: { tool: "unraid_docker_update_status", summary: "which containers have updates", rule: "If status_complete is false, updates_available is only a minimum: name the unknown containers." }, start: { tool: "unraid_docker_start", summary: "start", rule: EXACT_NAME }, stop: { tool: "unraid_docker_stop", summary: "stop", rule: EXACT_NAME }, @@ -125,6 +128,13 @@ export const LITE_GROUPS: LiteGroup[] = [ status: { tool: "unraid_storage_status", summary: "array, parity, pools, disk alerts" }, disks: { tool: "unraid_disk_health", summary: "SMART/errors/temperature, one or all disks", rule: "disks uses cached SMART data and never spins disks up; diagnose smart for full detail." }, diagnose: { tool: "unraid_storage_diagnostics", rename: OPERATION, summary: "zfs_pool|zfs_dataset|zfs_snapshots|smart|parity_history" }, + cache: { tool: "unraid_cache_status", summary: "pool fill level, which shares use it, mover state/log", rule: "For a full cache or stuck files start with cache, not with shell commands." }, + mover_start: { tool: "unraid_mover_start", summary: "run the mover now" }, + parity: { tool: "unraid_parity_status", summary: "parity progress, schedule, last checks" }, + parity_start: { tool: "unraid_parity_control", fixed: { operation: "start" }, summary: "start a parity check (non-correcting unless correct=true)", rule: "parity_start only on request; correct=true only if the user explicitly wants corrections written." }, + parity_pause: { tool: "unraid_parity_control", fixed: { operation: "pause" }, summary: "pause the running check" }, + parity_resume: { tool: "unraid_parity_control", fixed: { operation: "resume" }, summary: "resume a paused check" }, + parity_cancel: { tool: "unraid_parity_control", fixed: { operation: "cancel" }, summary: "cancel the running check" }, shares: { tool: "unraid_shares_list", summary: "all shares with usage" }, share: { tool: "unraid_share_inspect", summary: "one share in detail" }, files: { tool: "unraid_files_inventory", summary: "list folders/files inside a share (metadata only)", rule: "files: find a folder with name_contains first, then call again with it as relative_path. Never reads file contents." }, @@ -134,6 +144,22 @@ export const LITE_GROUPS: LiteGroup[] = [ share_apply: { tool: "unraid_share_apply", summary: "apply a previewed share change", rule: "share_apply: only the exact preview the user approved." }, }, }, + { + name: "unraid_vm", + intro: "Virtual machines (libvirt).", + aliases: { name: "vm", vm_name: "vm", domain: "vm", enable: "enabled" }, + actions: { + list: { tool: "unraid_vm_list", summary: "all VMs with state" }, + inspect: { tool: "unraid_vm_inspect", summary: "disks, network, passthrough, snapshots" }, + start: { tool: "unraid_vm_control", fixed: { operation: "start" }, summary: "start", rule: "VM changes need the exact name from list." }, + shutdown: { tool: "unraid_vm_control", fixed: { operation: "shutdown" }, summary: "graceful ACPI shutdown", rule: "VM changes need the exact name from list." }, + reboot: { tool: "unraid_vm_control", fixed: { operation: "reboot" }, summary: "reboot", rule: "VM changes need the exact name from list." }, + suspend: { tool: "unraid_vm_control", fixed: { operation: "suspend" }, summary: "pause in RAM", rule: "VM changes need the exact name from list." }, + resume: { tool: "unraid_vm_control", fixed: { operation: "resume" }, summary: "continue a suspended VM", rule: "VM changes need the exact name from list." }, + force_stop: { tool: "unraid_vm_force_stop", summary: "pull the plug (data loss possible)", rule: "force_stop only if shutdown hangs and the user agreed." }, + autostart: { tool: "unraid_vm_autostart", summary: "autostart on/off" }, + }, + }, { name: "unraid_network", intro: "Networking of host and containers.", @@ -154,6 +180,8 @@ export const LITE_GROUPS: LiteGroup[] = [ health: { tool: "unraid_system_health", summary: "CPU load, RAM, temperatures, uptime" }, notifications: { tool: "unraid_notifications_list", summary: "recent Unraid notifications" }, connection_test: { tool: "unraid_system_connection_test", summary: "check MUA can run commands" }, + notify: { tool: "unraid_notify", summary: "send an Unraid notification (also to e-mail/ntfy/Discord agents)", rule: "Use notify to report the result of long tasks; do not spam." }, + notifications_archive: { tool: "unraid_notification_archive", summary: "mark notifications as read (file or all)" }, }, }, { @@ -243,6 +271,7 @@ export function buildLiteTools( const required = new Set(schema.required ?? []); const params: string[] = []; for (const [param, spec] of Object.entries(schema.properties ?? {})) { + if (action.fixed && param in action.fixed) continue; const liteName = liteParamName(action, param); params.push(required.has(param) ? `${liteName}*` : liteName); if (!properties[liteName]) { @@ -334,6 +363,7 @@ export function resolveLiteCall( } let args: Record = {}; for (const [key, value] of Object.entries(lite)) args[action.rename?.[key] ?? key] = value; + if (action.fixed) Object.assign(args, action.fixed); if (action.prepare && target === action.tool) { args = action.prepare(args); } else if (target === action.fallback && known.has("container") && args["container"] === undefined && args["containers"] !== undefined) { @@ -366,7 +396,7 @@ export function resolveLiteCall( for (const k of ignored) delete args[k]; const missing = (schema.required ?? []).filter((r) => args[r] === undefined || args[r] === ""); if (missing.length > 0) { - const params = [...known].map((p) => { + const params = [...known].filter((p) => !(action.fixed && p in action.fixed)).map((p) => { const liteName = liteParamName(action, p); return (schema.required ?? []).includes(p) ? `${liteName}*` : liteName; }); @@ -394,8 +424,12 @@ export function callHint( for (const group of LITE_GROUPS) { for (const [actionName, action] of Object.entries(group.actions)) { if (action.tool === fullTool || action.fallback === fullTool) { + if (action.fixed && !Object.entries(action.fixed).every(([k, v]) => args[k] === undefined || args[k] === v)) continue; const mapped: Record = { action: actionName }; - for (const [k, v] of Object.entries(args)) mapped[liteParamName(action, k)] = v; + for (const [k, v] of Object.entries(args)) { + if (action.fixed && k in action.fixed) continue; + mapped[liteParamName(action, k)] = v; + } return { tool: group.name, arguments: mapped }; } } diff --git a/src/tools.ts b/src/tools.ts index 7173582..ec02949 100644 --- a/src/tools.ts +++ b/src/tools.ts @@ -35,6 +35,10 @@ import { } from "./helpers"; import { READ_ONLY_PROGRAMS } from "./readonly"; import { buildOverview } from "./overview"; +import { + cacheStatus, dockerStorage, moverStart, notificationArchive, notifySend, parityControl, parityStatus, + vmAutostart, vmControl, vmInspect, vmList, +} from "./host"; import { isToolEnabled } from "./auth"; export interface ToolDef { @@ -60,12 +64,26 @@ const CRITICAL_TOOLS = new Set([ "unraid_ca_install", "unraid_share_apply", "unraid_docker_template_apply", + "unraid_vm_force_stop", ]); const WRITE_TOOLS = new Set([ "unraid_docker_start", "unraid_docker_stop", "unraid_docker_restart", + "unraid_vm_control", + "unraid_vm_autostart", + "unraid_mover_start", + "unraid_parity_control", + "unraid_notify", + "unraid_notification_archive", ]); + +/** In r039 hinzugekommene Werkzeuge (für den Hinweis in der WebGUI). */ +export const NEW_IN_RELEASE = [ + "unraid_vm_list", "unraid_vm_inspect", "unraid_vm_control", "unraid_vm_force_stop", "unraid_vm_autostart", + "unraid_cache_status", "unraid_mover_start", "unraid_parity_status", "unraid_parity_control", + "unraid_docker_storage", "unraid_notify", "unraid_notification_archive", +]; const ACTIVE_TOOLS = new Set([ "unraid_network_audit_tcp", "unraid_network_lan_probe", @@ -122,6 +140,119 @@ export const TOOLS: ToolDef[] = [ profile: a["__profile"] === "lite" ? "lite" : "full", }), }, + // ── r039: VMs, Cache/Mover, Parity, docker.img, Benachrichtigungen ────── + { + name: "unraid_vm_list", + description: "List virtual machines (libvirt) with state, vCPUs, memory and autostart.", + inputSchema: empty, + handler: () => vmList(), + }, + { + name: "unraid_vm_inspect", + description: "Details of one VM: state, disks, network, PCI/USB passthrough, graphics (no passwords) and existing snapshots. Partial names are resolved.", + inputSchema: { type: "object", properties: { vm: str("VM name as shown by unraid_vm_list") }, required: ["vm"], additionalProperties: false }, + handler: (a) => vmInspect(a["vm"]), + }, + { + name: "unraid_vm_control", + description: "Start, gracefully shut down (ACPI), reboot, suspend or resume a VM. Checks the current state first and reports the new state. Requires the exact VM name.", + inputSchema: { + type: "object", + properties: { + vm: str("Exact VM name"), + operation: { type: "string", enum: ["start", "shutdown", "reboot", "suspend", "resume"] }, + }, + required: ["vm", "operation"], + additionalProperties: false, + }, + handler: (a) => vmControl(a["vm"], String(a["operation"] ?? "")), + }, + { + name: "unraid_vm_force_stop", + description: "CRITICAL: Power off a VM immediately (like pulling the plug; unsaved guest data is lost). Use only when a graceful shutdown hangs and the user agreed.", + inputSchema: { type: "object", properties: { vm: str("Exact VM name") }, required: ["vm"], additionalProperties: false }, + handler: (a) => vmControl(a["vm"], "force_stop"), + }, + { + name: "unraid_vm_autostart", + description: "Enable or disable autostart of a VM when the array starts.", + inputSchema: { + type: "object", + properties: { vm: str("Exact VM name"), enabled: bool("true = start automatically") }, + required: ["vm", "enabled"], + additionalProperties: false, + }, + handler: (a) => vmAutostart(a["vm"], a["enabled"]), + }, + { + name: "unraid_cache_status", + description: "Explain cache/pool usage: fill level per pool, which shares occupy it (with their cache setting), mover state, schedule and recent mover log, plus findings such as files the mover will never move.", + inputSchema: empty, + handler: () => cacheStatus(), + }, + { + name: "unraid_mover_start", + description: "Start the Unraid mover now (same as the Move button). Refuses if it is already running.", + inputSchema: empty, + handler: () => moverStart(), + }, + { + name: "unraid_parity_status", + description: "Parity operation state and progress, the configured schedule (correcting or not) and the last parity checks with duration and errors.", + inputSchema: empty, + handler: () => parityStatus(), + }, + { + name: "unraid_parity_control", + description: "Start, pause, resume or cancel a parity check. start is non-correcting unless correct=true (only if the user explicitly wants corrections written).", + inputSchema: { + type: "object", + properties: { + operation: { type: "string", enum: ["start", "pause", "resume", "cancel"] }, + correct: bool("start only: write corrections to parity (default false)"), + }, + required: ["operation"], + additionalProperties: false, + }, + handler: (a) => parityControl(String(a["operation"] ?? ""), a["correct"]), + }, + { + name: "unraid_docker_storage", + description: "Fill level of docker.img / the Docker directory and what uses it (images, containers, volumes, build cache, reclaimable).", + inputSchema: empty, + handler: () => dockerStorage(), + }, + { + name: "unraid_notify", + description: "Send an Unraid notification (shown in the WebGUI and forwarded to configured agents such as e-mail, ntfy, Discord). Use it to report results of longer tasks.", + inputSchema: { + type: "object", + properties: { + subject: str("Short subject"), + description: str("One-line description"), + message: str("Optional longer text"), + importance: { type: "string", enum: ["normal", "warning", "alert"] }, + link: str("Optional WebGUI path, e.g. /Docker"), + }, + required: ["subject"], + additionalProperties: false, + }, + handler: (a) => notifySend(a), + }, + { + name: "unraid_notification_archive", + description: "Archive (mark as read) one unread Unraid notification by its file name from the notifications list, or all unread ones (optionally of one importance).", + inputSchema: { + type: "object", + properties: { + file: str("File name from unraid_notifications_list"), + all: bool("Archive all unread notifications"), + importance: { type: "string", enum: ["normal", "warning", "alert"] }, + }, + additionalProperties: false, + }, + handler: (a) => notificationArchive(a), + }, ...ADMIN_TOOLS, // These two tools are exposed dynamically only when a labeled toolbox is // present and the dedicated WebGUI switch is enabled (see index.ts).