commit 5f664cc8c219babe4e1e9d1b485ffbe41c6b746c Author: Claw Date: Tue Nov 17 19:16:16 2026 +0100 vmmngr 0.1.0-preview: read-only VM Manager extension (installer, vmm-ctl, GUI) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..33cc6b3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +log/* +state/* +backup/* +vendor/*/* +!vendor/.gitkeep diff --git a/README.md b/README.md new file mode 100644 index 0000000..885c951 --- /dev/null +++ b/README.md @@ -0,0 +1,52 @@ +# VM Manager for XigmaNAS (vmmngr) + +A OneButton-style extension that manages bhyve guests through **vm-bhyve** from the +XigmaNAS web GUI: list, inspect, start/stop, create, images, templates, switches. + +Status: **0.1.0-preview — read-only**. The dashboard lists and inspects existing +machines. Mutating actions arrive with the job engine in 1.0. + +## Layout + +``` +vmm-init installer / updater / self-heal / uninstaller +bin/vmm-ctl single write path to vm-bhyve (PHP CLI) +bin/vmm-lib.php shared library (provider resolution, parsers) +gui/ PHP pages, symlinked into /usr/local/www +gui/ext/vmmngr/menu.inc Extensions menu entry +vendor/ bundled binaries for embedded systems (optional) +state/ log/ backup/ runtime data, never touched by updates +``` + +## Install + +```sh +mkdir -p -m 0750 /mnt/Daten/extensions/vmmngr && cd /mnt/Daten/extensions/vmmngr +fetch https://git.familie-berner.de/.../vmm-init && chmod +x vmm-init && ./vmm-init -o +``` + +Then open **Extensions → VM Manager**. + +## Design rules + +- **Never overlay.** An existing system installation always wins; the bundle only + fills gaps (embedded systems). `vm_source = auto | system | bundle`. +- **One write path.** The GUI never calls `vm` directly, only `vmm-ctl`. +- **vm-bhyve files are the truth.** No second database of VMs. +- **Symlinks, no mounts.** Only missing targets are linked; `-p` repairs them at boot. +- **Long operations become jobs** with per-VM locks (1.0). + +## Commands + +```sh +vmm-ctl selfcheck # environment, providers, firmware, modules +vmm-ctl list # all guests +vmm-ctl info # parsed details +vmm-ctl --json selfcheck # same as JSON +``` + +## Uninstall + +```sh +./vmm-init -r --yes # removes links only; VMs and datastores stay +``` diff --git a/bin/vmm-ctl b/bin/vmm-ctl new file mode 100644 index 0000000..63a1b18 --- /dev/null +++ b/bin/vmm-ctl @@ -0,0 +1,142 @@ +#!/usr/local/bin/php + [args] human output + * vmm-ctl --json [args] JSON output + */ + +declare(strict_types=1); + +require_once __DIR__ . '/vmm-lib.php'; + +$argv = $_SERVER['argv']; +array_shift($argv); +$json = false; +if (($argv[0] ?? '') === '--json') { + $json = true; + array_shift($argv); +} +$cmd = $argv[0] ?? 'help'; +$arg = $argv[1] ?? ''; + +function out(array $data, bool $json, callable $human): never +{ + if ($json) { + echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), "\n"; + } else { + $human($data); + } + exit(0); +} + +switch ($cmd) { + case 'version': + $conf = vmm_config(); + out( + ['name' => 'vmm-ctl', 'version' => $conf['version'], 'root' => VMM_ROOT], + $json, + static function (array $d): void { + printf("vmm-ctl %s (%s)\n", $d['version'], $d['root']); + } + ); + + case 'selfcheck': + $d = vmm_selfcheck(); + out( + $d, + $json, + static function (array $d): void { + printf("platform : %s / %s / %s\n", $d['platform'], $d['product'], $d['os']); + printf("vm-bhyve : %s (rev %s) from %s\n", $d['vm']['version']['version'] ?? '?', $d['vm']['version']['rev'] ?? '?', $d['vm']['source']); + printf("grub : %s (%s)\n", $d['grub']['available'] ? 'ok' : 'missing', $d['grub']['source']); + printf("firmware : %s (%s)\n", $d['firmware']['available'] ? 'ok' : 'missing', $d['firmware']['source']); + printf("ttyd : %s (%s)\n", $d['ttyd']['available'] ? 'ok' : 'missing', $d['ttyd']['source']); + printf("vm_dir : %s\n", $d['vm_dir']); + printf("modules : vmm=%s nmdm=%s\n", $d['kld']['vmm'], $d['kld']['nmdm']); + printf("vms : %d total, %d running\n", $d['vm_count'], $d['vm_running']); + } + ); + + case 'list': + $vms = vmm_list(); + out( + ['count' => count($vms), 'vms' => $vms], + $json, + static function (array $d): void { + printf("%-14s %-9s %-6s %-4s %-7s %-22s %s\n", 'NAME', 'DATASTORE', 'LOADER', 'CPU', 'MEMORY', 'STATE', 'AUTO'); + foreach ($d['vms'] as $v) { + printf( + "%-14s %-9s %-6s %-4s %-7s %-22s %s\n", + $v['name'], + $v['datastore'], + $v['loader'], + $v['cpu'], + $v['memory'], + $v['state_raw'] ?? $v['state'], + $v['auto'] ? 'yes' : 'no' + ); + } + } + ); + + case 'info': + if ($arg === '' || !vmm_valid_name($arg)) { + fwrite(STDERR, "usage: vmm-ctl info \n"); + exit(2); + } + $d = vmm_info($arg); + if (isset($d['error'])) { + if ($json) { + vmm_json(['ok' => false, 'error' => $d['error']], 1); + } + fwrite(STDERR, "error: {$d['error']}\n"); + exit(1); + } + out( + ['ok' => true, 'vm' => $arg, 'info' => $d], + $json, + static function (array $d): void { + echo $d['info']['raw'] ?? ''; + } + ); + + case 'providers': + out( + [ + 'vm' => vmm_resolve('vm'), + 'grub' => vmm_resolve('grub'), + 'firmware' => vmm_resolve('firmware'), + 'ttyd' => vmm_resolve('ttyd'), + 'vm_source' => vmm_config()['vm_source'], + ], + $json, + static function (array $d): void { + foreach (['vm', 'grub', 'firmware', 'ttyd'] as $c) { + printf("%-9s %-8s %s\n", $c, $d[$c]['source'], $d[$c]['path']); + } + } + ); + + case 'json': + vmm_json(vmm_selfcheck()); + // no break + + default: + $help = "usage: vmm-ctl [--json] [args]\n\n" + . " version extension version\n" + . " selfcheck environment, providers, firmware, modules\n" + . " providers which source is used per component\n" + . " list all VMs (parsed)\n" + . " info full VM details (parsed)\n" + . " json selfcheck as JSON\n"; + if ($json) { + vmm_json(['ok' => false, 'error' => 'unknown command', 'usage' => $help], 2); + } + echo $help; + exit($cmd === 'help' ? 0 : 2); +} diff --git a/bin/vmm-lib.php b/bin/vmm-lib.php new file mode 100644 index 0000000..bafc1fe --- /dev/null +++ b/bin/vmm-lib.php @@ -0,0 +1,474 @@ + 'VM Manager', + 'version' => '0.1.0-preview', + 'rootfolder' => VMM_ROOT, + 'vm_source' => 'auto', // auto | system | bundle + 'bridges' => [], + 'default_bridge' => '', + 'enable' => true, + 'job_timeout' => 900, + 'vm_dir_cache' => '', + ]; + if (!is_file(VMM_CONF)) { + return $defaults; + } + $data = json_decode((string)file_get_contents(VMM_CONF), true); + if (!is_array($data)) { + return $defaults; + } + return array_merge($defaults, $data); +} + +function vmm_save_config(array $conf): bool +{ + $json = json_encode($conf, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + if ($json === false) { + return false; + } + return file_put_contents(VMM_CONF, $json . "\n") !== false; +} + +/* ------------------------------------------------------------------ */ +/* provider resolution: never overlay an existing system installation */ +/* ------------------------------------------------------------------ */ + +function vmm_is_our_link(string $path): bool +{ + if (!is_link($path)) { + return false; + } + $target = (string)readlink($path); + return str_starts_with($target, VMM_ROOT . '/'); +} + +function vmm_resolve(string $component): array +{ + $conf = vmm_config(); + $pref = (string)($conf['vm_source'] ?? 'auto'); + + $candidates = [ + 'vm' => [ + 'system' => [VMM_VM_SYSTEM, VMM_LIB_SYSTEM], + 'bundle' => [VMM_ROOT . '/vendor/vm-bhyve/sbin/vm', VMM_ROOT . '/vendor/vm-bhyve/lib'], + ], + 'grub' => [ + 'system' => [VMM_GRUB_SYSTEM], + 'bundle' => [VMM_ROOT . '/vendor/grub2-bhyve/grub-bhyve'], + ], + 'firmware' => [ + 'system' => [VMM_FW_SYSTEM], + 'bundle' => [VMM_ROOT . '/vendor/edk2-bhyve/BHYVE_UEFI.fd'], + ], + 'ttyd' => [ + 'system' => [VMM_TTYD_SYSTEM], + 'bundle' => [VMM_ROOT . '/vendor/ttyd/ttyd'], + ], + ]; + + if (!isset($candidates[$component])) { + return ['source' => 'unknown', 'path' => '', 'available' => false]; + } + + $check = static function (array $paths): bool { + foreach ($paths as $p) { + if (!is_file($p) && !is_dir($p)) { + return false; + } + } + return true; + }; + + // "system" only counts if it is a real file/dir, not our own symlink + $systemOk = $check($candidates[$component]['system']) + && !vmm_is_our_link($candidates[$component]['system'][0]); + $bundleOk = $check($candidates[$component]['bundle']); + + $useSystem = match ($pref) { + 'system' => $systemOk, + 'bundle' => false, + default => $systemOk, + }; + if ($useSystem) { + return ['source' => 'system', 'path' => $candidates[$component]['system'][0], 'available' => true]; + } + if ($bundleOk) { + return ['source' => 'bundle', 'path' => $candidates[$component]['bundle'][0], 'available' => true]; + } + return [ + 'source' => 'missing', + 'path' => $candidates[$component]['system'][0], + 'available' => false, + ]; +} + +/* ------------------------------------------------------------------ */ +/* command execution */ +/* ------------------------------------------------------------------ */ + +function vmm_run(array $argv, int $timeout = 30): array +{ + $vm = vmm_resolve('vm'); + if (!$vm['available']) { + return ['rc' => 127, 'stdout' => '', 'stderr' => 'vm-bhyve not found', 'cmd' => '']; + } + + $env = getenv(); + if ($env === false) { + $env = []; + } + $grub = vmm_resolve('grub'); + if ($grub['source'] === 'bundle') { + $env['PATH'] = VMM_ROOT . '/vendor/grub2-bhyve:' . ($env['PATH'] ?? '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'); + } + $env['LC_ALL'] = 'C'; + + $cmd = array_merge([$vm['path']], $argv); + $spec = [ + 0 => ['pipe', 'r'], + 1 => ['pipe', 'w'], + 2 => ['pipe', 'w'], + ]; + $proc = @proc_open($cmd, $spec, $pipes, null, $env); + if (!is_resource($proc)) { + return ['rc' => 127, 'stdout' => '', 'stderr' => 'proc_open failed', 'cmd' => implode(' ', $cmd)]; + } + fclose($pipes[0]); + $stdout = ''; + $stderr = ''; + $start = microtime(true); + stream_set_blocking($pipes[1], false); + stream_set_blocking($pipes[2], false); + while (true) { + $status = proc_get_status($proc); + $stdout .= (string)stream_get_contents($pipes[1]); + $stderr .= (string)stream_get_contents($pipes[2]); + if (!$status['running']) { + break; + } + if (microtime(true) - $start > $timeout) { + proc_terminate($proc, 9); + $stderr .= "\ntimeout after {$timeout}s"; + break; + } + usleep(20000); + } + $stdout .= (string)stream_get_contents($pipes[1]); + $stderr .= (string)stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + $rc = proc_close($proc); + if ($rc === -1) { + $rc = 0; + } + return [ + 'rc' => $rc, + 'stdout' => $stdout, + 'stderr' => $stderr, + 'cmd' => implode(' ', array_map('escapeshellarg', $cmd)), + ]; +} + +/* ------------------------------------------------------------------ */ +/* parsers */ +/* ------------------------------------------------------------------ */ + +function vmm_state_from_string(string $s): array +{ + $s = trim($s); + if (preg_match('/^(Running|Suspended|Stopped|Starting|Locked)\b(?:\s*\((\d+)\))?/i', $s, $m)) { + return ['state' => strtolower($m[1]), 'pid' => isset($m[2]) ? (int)$m[2] : 0, 'raw' => $s]; + } + return ['state' => strtolower($s) === '' ? 'unknown' : strtolower($s), 'pid' => 0, 'raw' => $s]; +} + +function vmm_parse_list(string $text): array +{ + $lines = preg_split('/\R/', trim($text)) ?: []; + if (count($lines) < 2) { + return []; + } + $header = array_shift($lines); + $cols = ['NAME', 'DATASTORE', 'LOADER', 'CPU', 'MEMORY', 'VNC', 'AUTO', 'STATE']; + $offsets = []; + foreach ($cols as $c) { + $pos = strpos($header, $c); + $offsets[$c] = $pos === false ? null : $pos; + } + $out = []; + foreach ($lines as $line) { + if (trim($line) === '') { + continue; + } + $row = []; + $known = array_values(array_filter($offsets, static fn($v) => $v !== null)); + $i = 0; + foreach ($cols as $c) { + $start = $offsets[$c]; + if ($start === null) { + $row[strtolower($c)] = ''; + continue; + } + $next = null; + foreach ($known as $k) { + if ($k > $start) { + $next = $k; + break; + } + } + $row[strtolower($c)] = $next === null + ? trim(substr($line, $start)) + : trim(substr($line, $start, $next - $start)); + $i++; + } + if ($row['name'] === '') { + continue; + } + $state = vmm_state_from_string($row['state'] ?? ''); + $row['state'] = $state['state']; + $row['pid'] = $state['pid']; + $row['state_raw'] = $state['raw']; + $row['auto'] = stripos((string)($row['auto'] ?? ''), 'yes') === 0; + $out[] = $row; + } + return $out; +} + +function vmm_parse_info(string $text): array +{ + $out = ['general' => [], 'blocks' => [], 'raw' => $text]; + $lines = preg_split('/\R/', $text) ?: []; + $section = null; + $index = -1; + $lastNum = []; + foreach ($lines as $line) { + if (preg_match('/^--+$/', $line) || preg_match('/^Virtual Machine:/', $line)) { + continue; + } + if (preg_match('/^ ([a-z0-9][a-z0-9-]*)$/', $line, $m)) { + $section = $m[1]; + $out['blocks'][] = ['type' => $section, 'lines' => [], 'data' => []]; + $index = count($out['blocks']) - 1; + $lastNum[$section] = -1; + continue; + } + if ($index >= 0 && preg_match('/^ ([a-z0-9][a-z0-9-]*):\s?(.*)$/', $line, $m)) { + $key = $m[1]; + $val = trim($m[2]); + // a repeated "number" key starts a new block of the same type + if ($key === 'number' && isset($out['blocks'][$index]['data']['number'])) { + $type = $out['blocks'][$index]['type']; + $out['blocks'][] = ['type' => $type, 'lines' => [], 'data' => []]; + $index = count($out['blocks']) - 1; + } + if ($key === 'number') { + $out['blocks'][$index]['data']['number'] = $val; + } else { + $out['blocks'][$index]['data'][$key] = $val; + } + continue; + } + if (preg_match('/^ ([a-z0-9][a-z0-9-]*):\s?(.*)$/', $line, $m)) { + $out['general'][$m[1]] = trim($m[2]); + continue; + } + if ($index >= 0 && trim($line) !== '') { + $out['blocks'][$index]['lines'][] = trim($line); + } + } + // build convenience indexes + $out['sections'] = []; + foreach ($out['blocks'] as $b) { + $out['sections'][$b['type']][] = $b; + } + return $out; +} + +function vmm_parse_table(string $text): array +{ + $lines = preg_split('/\R/', trim($text)) ?: []; + if (count($lines) < 2) { + return []; + } + $header = preg_split('/\s{2,}/', trim(array_shift($lines))) ?: []; + $out = []; + foreach ($lines as $line) { + $line = trim($line); + if ($line === '') { + continue; + } + $parts = preg_split('/\s{2,}/', $line) ?: []; + $row = []; + foreach ($header as $i => $h) { + $row[strtolower(trim($h))] = $parts[$i] ?? ''; + } + if ($row !== []) { + $out[] = $row; + } + } + return $out; +} + +/* ------------------------------------------------------------------ */ +/* higher level helpers */ +/* ------------------------------------------------------------------ */ + +function vmm_list(): array +{ + // note: "vm list -r" lists running guests only; we want everything + $res = vmm_run(['list'], 30); + return vmm_parse_list($res['stdout']); +} + +function vmm_info(string $name): array +{ + if (!vmm_valid_name($name)) { + return ['error' => 'invalid name']; + } + $res = vmm_run(['info', $name], 30); + if ($res['rc'] !== 0) { + return ['error' => trim($res['stderr'] ?: $res['stdout']), 'rc' => $res['rc']]; + } + return vmm_parse_info($res['stdout']); +} + +function vmm_valid_name(string $name): bool +{ + return (bool)preg_match('/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/', $name); +} + +function vmm_size_to_bytes(string $size): int +{ + if (!preg_match('/^([0-9.]+)\s*([KMGTP]?)i?B?$/i', trim($size), $m)) { + return 0; + } + $n = (float)$m[1]; + $mult = ['K' => 1024, 'M' => 1024 ** 2, 'G' => 1024 ** 3, 'T' => 1024 ** 4, 'P' => 1024 ** 5]; + $u = strtoupper($m[2]); + return (int)($n * ($mult[$u] ?? 1)); +} + +function vmm_human_bytes(int $bytes): string +{ + $units = ['B', 'K', 'M', 'G', 'T']; + $i = 0; + $v = (float)$bytes; + while ($v >= 1024 && $i < count($units) - 1) { + $v /= 1024; + $i++; + } + return $i === 0 ? (string)$bytes : sprintf('%.1f%s', $v, $units[$i]); +} + +function vmm_vm_version(): array +{ + $res = vmm_run(['version'], 15); + $text = trim($res['stdout'] . "\n" . $res['stderr']); + if (preg_match('/vm-bhyve:?[^\n]*?(v?([0-9][0-9a-z.\-]*))\s*\(rev\.?\s*([0-9]+)\)/i', $text, $m)) { + return ['version' => $m[2], 'rev' => $m[3], 'raw' => $text]; + } + return ['version' => '', 'rev' => '', 'raw' => $text]; +} + +function vmm_datastores(): array +{ + $res = vmm_run(['datastore', 'list'], 15); + return vmm_parse_table($res['stdout']); +} + +function vmm_switches(): array +{ + $res = vmm_run(['switch', 'list'], 15); + return vmm_parse_table($res['stdout']); +} + +function vmm_images(): array +{ + $res = vmm_run(['image', 'list'], 15); + return vmm_parse_table($res['stdout']); +} + +function vmm_vm_dir(): string +{ + $res = vmm_run(['get', 'all'], 15); + $text = $res['stdout']; + if (preg_match('/^vm_dir="?([^"\n]+)"?/m', $text, $m)) { + return $m[1]; + } + $rc = @shell_exec('/usr/bin/grep -E "^vm_dir=" /etc/rc.conf 2>/dev/null'); + if (is_string($rc) && preg_match('/vm_dir="?([^"\n]+)"?/', $rc, $m)) { + return $m[1]; + } + return ''; +} + +function vmm_selfcheck(): array +{ + $vm = vmm_resolve('vm'); + $grub = vmm_resolve('grub'); + $fw = vmm_resolve('firmware'); + $ttyd = vmm_resolve('ttyd'); + $out = [ + 'timestamp' => date('c'), + 'platform' => trim((string)@file_get_contents('/etc/platform')), + 'product' => trim((string)@file_get_contents('/etc/prd.name')), + 'os' => trim((string)@shell_exec('uname -r')), + 'php' => PHP_VERSION, + 'root' => VMM_ROOT, + 'vm' => $vm, + 'grub' => $grub, + 'firmware' => $fw, + 'ttyd' => $ttyd, + 'vm_dir' => vmm_vm_dir(), + 'kld' => [ + 'vmm' => trim((string)@shell_exec('kldstat -q -n vmm && echo loaded || echo missing')), + 'nmdm' => trim((string)@shell_exec('kldstat -q -n nmdm && echo loaded || echo missing')), + ], + ]; + $out['vm']['version'] = $vm['available'] ? vmm_vm_version() : []; + $out['datastores'] = $vm['available'] ? vmm_datastores() : []; + $out['switches'] = $vm['available'] ? vmm_switches() : []; + $vms = $vm['available'] ? vmm_list() : []; + $out['vm_count'] = count($vms); + $out['vm_running'] = count(array_filter($vms, static fn($v) => ($v['state'] ?? '') === 'running')); + if ($vm['available']) { + $fwFile = $fw['source'] === 'system' ? VMM_FW_SYSTEM : VMM_ROOT . '/vendor/edk2-bhyve/BHYVE_UEFI.fd'; + $out['firmware']['file'] = $fwFile; + $out['firmware']['mtime'] = is_file($fwFile) ? date('Y-m-d H:i', (int)filemtime($fwFile)) : ''; + $out['firmware']['size'] = is_file($fwFile) ? filesize($fwFile) : 0; + } + return $out; +} + +function vmm_json(array $data, int $code = 0): never +{ + http_response_code($code); + header('Content-Type: application/json; charset=utf-8'); + echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + exit; +} diff --git a/gui/ext/vmmngr/menu.inc b/gui/ext/vmmngr/menu.inc new file mode 100644 index 0000000..8943e33 --- /dev/null +++ b/gui/ext/vmmngr/menu.inc @@ -0,0 +1 @@ +VM Manager diff --git a/gui/ext/vmmngr/vmmngr.conf b/gui/ext/vmmngr/vmmngr.conf new file mode 100644 index 0000000..0a83429 --- /dev/null +++ b/gui/ext/vmmngr/vmmngr.conf @@ -0,0 +1,10 @@ +{ + "appname": "VM Manager", + "version": "0.1.0-preview", + "rootfolder": "/mnt/Daten/extensions/vmmngr", + "vm_source": "auto", + "bridges": ["ix0bridge"], + "default_bridge": "ix0bridge", + "enable": true, + "job_timeout": 900 +} diff --git a/gui/vmmngr-boot.inc b/gui/vmmngr-boot.inc new file mode 100644 index 0000000..7e67e7f --- /dev/null +++ b/gui/vmmngr-boot.inc @@ -0,0 +1,44 @@ + ['vmm-running', gettext('Running')], + 'stopped' => ['vmm-stopped', gettext('Stopped')], + 'suspended' => ['vmm-suspended', gettext('Suspended')], + 'starting' => ['vmm-starting', gettext('Starting')], + 'locked' => ['vmm-locked', gettext('Locked')], + ]; + [$cls, $label] = $map[$state] ?? ['vmm-unknown', ucfirst($state)]; + return sprintf('%s', $cls, htmlspecialchars($label)); + } + + function vmm_h(string $s): string + { + return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); + } + + function vmm_source_label(array $p): string + { + $icon = match ($p['source']) { + 'system' => '🖥', + 'bundle' => '📦', + default => '⚠', + }; + return sprintf('%s %s', $icon, $p['source']); + } +} diff --git a/gui/vmmngr.php b/gui/vmmngr.php new file mode 100644 index 0000000..5ee55ab --- /dev/null +++ b/gui/vmmngr.php @@ -0,0 +1,128 @@ + '', 'rev' => '']; +$vm_dir = $vmprov['available'] ? vmm_vm_dir() : ''; + +$running = array_values(array_filter($vms, static fn(array $v): bool => ($v['state'] ?? '') === 'running')); +$mem_used = 0; +$cpus = 0; +foreach ($running as $v) { + $mem_used += vmm_size_to_bytes((string)($v['memory'] ?? '0')); + $cpus += (int)($v['cpu'] ?? 0); +} + +include 'fbegin.inc'; +?> + + +
+ + + ' . gettext('Install vm-bhyve or run the installer with a bundled vendor tree.')); ?> + + +
+
+
+
/
+
+
+
+
+
+
vCPU
+
+
+
+
+
· rev
+
+
+
+
+
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+ +
+ +
+ diff --git a/gui/vmmngr_api.php b/gui/vmmngr_api.php new file mode 100644 index 0000000..623d5d2 --- /dev/null +++ b/gui/vmmngr_api.php @@ -0,0 +1,42 @@ + false, 'error' => 'forbidden'], 403); +} + +$action = (string)($_REQUEST['action'] ?? ''); +$name = (string)($_REQUEST['name'] ?? ''); + +switch ($action) { + case 'list': + $vms = vmm_list(); + vmm_json(['ok' => true, 'count' => count($vms), 'vms' => $vms]); + // no break + + case 'info': + if (!vmm_valid_name($name)) { + vmm_json(['ok' => false, 'error' => 'invalid name'], 400); + } + $info = vmm_info($name); + if (isset($info['error'])) { + vmm_json(['ok' => false, 'error' => $info['error']], 500); + } + vmm_json(['ok' => true, 'vm' => $name, 'info' => $info]); + // no break + + case 'selfcheck': + case '': + vmm_json(['ok' => true, 'selfcheck' => vmm_selfcheck()]); + // no break + + default: + vmm_json(['ok' => false, 'error' => 'unknown action'], 400); +} diff --git a/gui/vmmngr_config.php b/gui/vmmngr_config.php new file mode 100644 index 0000000..02775da --- /dev/null +++ b/gui/vmmngr_config.php @@ -0,0 +1,120 @@ + + + +
+ + + + + + + + + + + + + + + + + +
· ·
PHP
vm_dir
+ vmm: · + nmdm: +
,
+ +
+ + + + + + + + + + + gettext('vm-bhyve'), + 'grub' => gettext('grub-bhyve'), + 'firmware' => gettext('UEFI firmware'), + 'ttyd' => gettext('Web terminal (ttyd)'), + ]; + foreach ($rows as $key => $label): + $p = $sc[$key]; + $ok = !empty($p['available']); + ?> + + + + + + + +
+ + · : +
+ +
(rev )
+ + +
·
+ +
vm_source = —
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +
+ +
+
+ +
+ diff --git a/gui/vmmngr_vm.php b/gui/vmmngr_vm.php new file mode 100644 index 0000000..6b9981e --- /dev/null +++ b/gui/vmmngr_vm.php @@ -0,0 +1,104 @@ + + + +
+ + + + + + + + + + + + + + + + + + + + + +
PID
vCPU · ()
UUID
+ +
+ + $blocks): ?> + + + + + + + + + + + $v): ?> + + + + + + + + + + + + + + + + +
—
—
+
+ + +
+ +
+
+ + +
+ +
+ +
+ diff --git a/vendor/.gitkeep b/vendor/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/version.txt b/version.txt new file mode 100644 index 0000000..2c31a29 --- /dev/null +++ b/version.txt @@ -0,0 +1 @@ +0.1.0-preview diff --git a/vmm-init b/vmm-init new file mode 100644 index 0000000..84724eb --- /dev/null +++ b/vmm-init @@ -0,0 +1,299 @@ +#!/bin/sh +# +# vmm-init - installer / updater / self-heal / uninstaller for the +# XigmaNAS "VM Manager" extension (vmmngr). +# +# Usage: +# ./vmm-init -o install (or reinstall in place) +# ./vmm-init -u update (refresh links, keep state/logs/config) +# ./vmm-init -p postinit / self-heal (called at boot) +# ./vmm-init -r --yes uninstall (keeps VMs, images, datastores) +# ./vmm-init -s status +# +# Design notes: +# * Nothing is mounted. Only symlinks are placed into the RAM/system tree, +# and only where the target does not already exist. +# * Persistent data (VMs, images, config) lives under /mnt and is never +# touched by install/update/remove. + +set -u + +PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin +export PATH +LC_ALL=C +export LC_ALL + +CWDIR=$(cd "$(dirname "$0")" && pwd -P) +APPNAME="vmmngr" +VERSION=$(cat "${CWDIR}/version.txt" 2>/dev/null || echo "unknown") +WWW="/usr/local/www" +WWWEXT="${WWW}/ext" +LOGDIR="${CWDIR}/log" +LOGFILE="${LOGDIR}/vmm-init.log" +CONFDIR="${CWDIR}/gui/ext/${APPNAME}" +LOG_MAX=1048576 + +mkdir -p "${LOGDIR}" + +log() { + printf '[%s] %s\n' "$(date '+%Y-%m-%d %H:%M:%S')" "$*" | tee -a "${LOGFILE}" >&2 +} + +fail() { + log "ERROR: $*" + exit 1 +} + +rotate_log() { + if [ -f "${LOGFILE}" ]; then + size=$(stat -f %z "${LOGFILE}" 2>/dev/null || echo 0) + if [ "${size}" -gt "${LOG_MAX}" ]; then + mv -f "${LOGFILE}" "${LOGFILE}.old" + fi + fi +} + +banner() { + echo "------------------------------------------------------------" + echo " VM Manager (${APPNAME}) ${VERSION}" + echo " ${1}" + echo "------------------------------------------------------------" +} + +# ---------------------------------------------------------------- preflight +preflight() { + [ "$(uname -m)" = "amd64" ] || fail "only amd64 is supported" + platform=$(cat /etc/platform 2>/dev/null || echo unknown) + case "${platform}" in + *livecd*|*liveusb*) fail "live media is not supported for extensions (platform: ${platform})" ;; + esac + [ -d "${CWDIR}" ] || fail "install directory ${CWDIR} is missing" + mkdir -p "${CWDIR}/state" "${CWDIR}/log" "${CWDIR}/backup" "${CWDIR}/templates" + + free_kb=$(df -k "${CWDIR}" | awk 'NR==2 {print $4}') + if [ -n "${free_kb}" ] && [ "${free_kb}" -lt 1048576 ]; then + log "WARNING: less than 1 GB free on ${CWDIR}" + fi + + if [ -d "${WWWEXT}/vm_bhyve" ]; then + log "WARNING: legacy extension 'vm_bhyve' found in ${WWWEXT} - remove it to avoid duplicate menu entries" + fi + + vm_bin="" + if [ -x "/usr/local/sbin/vm" ] && [ ! -L "/usr/local/sbin/vm" ]; then + vm_bin="/usr/local/sbin/vm" + log "vm-bhyve: using system installation (${vm_bin})" + elif [ -x "${CWDIR}/vendor/vm-bhyve/sbin/vm" ]; then + vm_bin="${CWDIR}/vendor/vm-bhyve/sbin/vm" + log "vm-bhyve: system installation not found, bundle will be linked" + else + log "WARNING: neither /usr/local/sbin/vm nor a bundled vm-bhyve was found" + fi + + if ! kldstat -q -n vmm; then + log "vmm.ko not loaded, trying kldload" + kldload vmm 2>/dev/null || log "WARNING: could not load vmm.ko (needed for bhyve)" + fi + if ! kldstat -q -n nmdm; then + log "nmdm.ko not loaded, trying kldload" + kldload nmdm 2>/dev/null || log "WARNING: could not load nmdm.ko (needed for serial console)" + fi +} + +# ---------------------------------------------------------------- symlinks +link_force() { + # link_force + target="$1" + link="$2" + if [ -e "${link}" ] && [ ! -L "${link}" ]; then + log "keep existing regular file: ${link}" + return 0 + fi + if [ -L "${link}" ] && [ "$(readlink "${link}")" = "${target}" ]; then + return 0 + fi + mkdir -p "$(dirname "${link}")" + ln -sfn "${target}" "${link}" || fail "cannot link ${link} -> ${target}" + log "linked ${link} -> ${target}" +} + +link_missing() { + # link_missing (only if link does not exist at all) + target="$1" + link="$2" + if [ -e "${link}" ] || [ -L "${link}" ]; then + return 0 + fi + mkdir -p "$(dirname "${link}")" + ln -sfn "${target}" "${link}" || fail "cannot link ${link} -> ${target}" + log "linked ${link} -> ${target}" +} + +do_symlinks() { + mkdir -p "${WWWEXT}" + link_force "${CONFDIR}" "${WWWEXT}/${APPNAME}" + + for f in "${CWDIR}"/gui/*.php "${CWDIR}"/gui/*.inc; do + [ -e "${f}" ] || continue + link_force "${f}" "${WWW}/$(basename "${f}")" + done + + # CLI helper: only where nothing else lives + link_missing "${CWDIR}/bin/vmm-ctl" "/usr/local/sbin/vmm-ctl" + link_missing "${CWDIR}/bin/vmm-ctl" "/usr/local/bin/vmm-ctl" + + # bundled components are only linked when the system lacks them + if [ ! -e "/usr/local/sbin/vm" ] && [ -e "${CWDIR}/vendor/vm-bhyve/sbin/vm" ]; then + mkdir -p /usr/local/lib + link_missing "${CWDIR}/vendor/vm-bhyve/sbin/vm" "/usr/local/sbin/vm" + link_missing "${CWDIR}/vendor/vm-bhyve/lib" "/usr/local/lib/vm-bhyve" + chmod 0555 "${CWDIR}/vendor/vm-bhyve/sbin/vm" 2>/dev/null + fi + if [ ! -e "/usr/local/sbin/grub-bhyve" ] && [ -e "${CWDIR}/vendor/grub2-bhyve/grub-bhyve" ]; then + link_missing "${CWDIR}/vendor/grub2-bhyve/grub-bhyve" "/usr/local/sbin/grub-bhyve" + chmod 0555 "${CWDIR}/vendor/grub2-bhyve/grub-bhyve" 2>/dev/null + fi + if [ ! -e "/usr/local/share/uefi-firmware/BHYVE_UEFI.fd" ] && [ -e "${CWDIR}/vendor/edk2-bhyve/BHYVE_UEFI.fd" ]; then + mkdir -p /usr/local/share/uefi-firmware + for fw in BHYVE_UEFI.fd BHYVE_UEFI_CODE.fd BHYVE_UEFI_VARS.fd; do + [ -e "${CWDIR}/vendor/edk2-bhyve/${fw}" ] || continue + link_missing "${CWDIR}/vendor/edk2-bhyve/${fw}" "/usr/local/share/uefi-firmware/${fw}" + done + fi +} + +# ---------------------------------------------------------------- helpers +write_default_conf() { + conf="${CONFDIR}/vmmngr.conf" + [ -f "${conf}" ] && return 0 + cat > "${conf}" </dev/null + chmod 0555 "${CWDIR}/vmm-init" 2>/dev/null + find "${CWDIR}/bin" -type f -exec chmod 0555 {} \; 2>/dev/null + find "${CWDIR}/gui" -type f \( -name '*.php' -o -name '*.inc' \) -exec chmod 0644 {} \; 2>/dev/null + find "${CWDIR}/gui" -type f \( -name '*.js' -o -name '*.css' \) -exec chmod 0644 {} \; 2>/dev/null + chmod 0750 "${CWDIR}/state" "${CWDIR}/log" "${CWDIR}/backup" 2>/dev/null +} + +selfcheck() { + if [ -x "${CWDIR}/bin/vmm-ctl" ]; then + echo + echo "--- selfcheck ---" + "${CWDIR}/bin/vmm-ctl" selfcheck || log "selfcheck reported a problem" + fi +} + +# ---------------------------------------------------------------- commands +cmd_install() { + banner "install" + rotate_log + preflight + write_default_conf + set_permissions + do_symlinks + log "installed version ${VERSION}" + selfcheck + echo + echo "Open: Extensions > VM Manager" +} + +cmd_update() { + banner "update" + rotate_log + preflight + if [ -d "${CWDIR}/backup" ]; then + ts=$(date '+%Y%m%d-%H%M%S') + mkdir -p "${CWDIR}/backup/${ts}" + for d in bin gui; do + [ -d "${CWDIR}/${d}" ] && cp -Rp "${CWDIR}/${d}" "${CWDIR}/backup/${ts}/" 2>/dev/null + done + log "backup written to ${CWDIR}/backup/${ts}" + fi + write_default_conf + set_permissions + do_symlinks + log "updated to version ${VERSION}" + selfcheck +} + +cmd_postinit() { + # Runs at boot (rc postinit) on embedded systems. Must be quiet and fast, + # and must not touch the config when nothing is missing. + rotate_log + do_symlinks +} + +cmd_status() { + banner "status" + echo "version : ${VERSION}" + echo "root : ${CWDIR}" + echo + for l in "${WWWEXT}/${APPNAME}" "${WWW}/vmmngr.php"; do + if [ -L "${l}" ]; then + echo "link ok : ${l} -> $(readlink "${l}")" + elif [ -e "${l}" ]; then + echo "present : ${l}" + else + echo "MISSING : ${l}" + fi + done + [ -f "/usr/local/sbin/vmm-ctl" ] && echo "cli : /usr/local/sbin/vmm-ctl" + selfcheck +} + +cmd_remove() { + if [ "${1:-}" != "--yes" ]; then + echo "refusing to uninstall without --yes" + echo "usage: $0 -r --yes" + exit 2 + fi + banner "uninstall" + rm -f "${WWWEXT}/${APPNAME}" + for f in "${CWDIR}"/gui/*.php "${CWDIR}"/gui/*.inc; do + [ -e "${f}" ] || continue + lnk="${WWW}/$(basename "${f}")" + if [ -L "${lnk}" ] && [ "$(readlink "${lnk}")" = "${f}" ]; then + rm -f "${lnk}" + fi + done + for l in /usr/local/sbin/vmm-ctl /usr/local/bin/vmm-ctl; do + if [ -L "${l}" ] && [ "$(readlink "${l}")" = "${CWDIR}/bin/vmm-ctl" ]; then + rm -f "${l}" + fi + done + mkdir -p /mnt/.recycle 2>/dev/null + dest="/mnt/.recycle/${APPNAME}-$(date '+%Y%m%d-%H%M%S')" + mv "${CWDIR}" "${dest}" && log "moved to ${dest}" + echo "Removed. VMs, images and datastores were not touched." +} + +case "${1:-}" in + -o|--install) cmd_install ;; + -u|--update) cmd_update ;; + -p|--postinit) cmd_postinit ;; + -s|--status) cmd_status ;; + -r|--remove) shift; cmd_remove "${1:-}" ;; + -h|--help|"") + sed -n '2,20p' "$0" + ;; + *) + echo "unknown option: $1" >&2 + sed -n '2,20p' "$0" >&2 + exit 2 + ;; +esac