vmmngr 0.1.0-preview: read-only VM Manager extension (installer, vmm-ctl, GUI)

This commit is contained in:
Claw committed 2026-11-17 19:16:16 +01:00
commit 5f664cc8c2
14 files changed
+1422

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
log/*
state/*
backup/*
vendor/*/*
!vendor/.gitkeep
+52
View File
@@ -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 <vm> # parsed details
vmm-ctl --json selfcheck # same as JSON
```
## Uninstall
```sh
./vmm-init -r --yes # removes links only; VMs and datastores stay
```
+142
View File
@@ -0,0 +1,142 @@
#!/usr/local/bin/php
<?php
/**
* vmm-ctl - single write path to vm-bhyve for the VM Manager extension.
*
* Preview 0.1.0: read-only subcommands (selfcheck, list, info, ...).
* Mutating subcommands are added in 1.0 behind jobs and locks.
*
* Usage: vmm-ctl <command> [args] human output
* vmm-ctl --json <command> [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 <vm>\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] <command> [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 <vm> 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);
}
+474
View File
@@ -0,0 +1,474 @@
<?php
/**
* vmm-lib.php - shared library for vmm-ctl (CLI) and the VM Manager GUI.
*
* Single place that talks to vm-bhyve. No shell interpolation: proc_open with
* an argv array, fixed subcommands only.
*/
declare(strict_types=1);
// Repository root = parent of bin/ (symlinks resolved).
if (!defined('VMM_ROOT')) {
define('VMM_ROOT', dirname(dirname(realpath(__FILE__))));
}
if (!defined('VMM_CONF')) {
define('VMM_CONF', VMM_ROOT . '/gui/ext/vmmngr/vmmngr.conf');
}
const VMM_VM_SYSTEM = '/usr/local/sbin/vm';
const VMM_LIB_SYSTEM = '/usr/local/lib/vm-bhyve';
const VMM_FW_SYSTEM = '/usr/local/share/uefi-firmware/BHYVE_UEFI.fd';
const VMM_GRUB_SYSTEM = '/usr/local/sbin/grub-bhyve';
const VMM_TTYD_SYSTEM = '/usr/local/bin/ttyd';
function vmm_config(): array
{
$defaults = [
'appname' => '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;
}
+1
View File
@@ -0,0 +1 @@
<a href="vmmngr.php">VM Manager</a>
+10
View File
@@ -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
}
+44
View File
@@ -0,0 +1,44 @@
<?php
/**
* vmmngr-boot.inc - bootstrap for all VM Manager pages.
*
* Works both in the extension tree and through the symlinks in /usr/local/www:
* realpath() resolves the link, so the shared library is found either way.
*/
require_once 'auth.inc';
require_once 'guiconfig.inc';
$vmm_self = realpath(__FILE__);
$vmm_root = dirname(dirname($vmm_self));
require_once $vmm_root . '/bin/vmm-lib.php';
if (!function_exists('vmm_badge')) {
function vmm_badge(string $state): string
{
$map = [
'running' => ['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('<span class="vmm-badge %s">%s</span>', $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']);
}
}
+128
View File
@@ -0,0 +1,128 @@
<?php
/*
* vmmngr.php - VM Manager dashboard (read-only preview 0.1.0)
*/
require_once 'vmmngr-boot.inc';
$pgtitle = [gettext('Extensions'), gettext('VM Manager')];
$conf = vmm_config();
$vmprov = vmm_resolve('vm');
$vms = $vmprov['available'] ? vmm_list() : [];
$ver = $vmprov['available'] ? vmm_vm_version() : ['version' => '', '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';
?>
<style>
.vmm-badge{display:inline-block;padding:1px 8px;border-radius:10px;font-size:11px;font-weight:600;letter-spacing:.02em}
.vmm-running{background:#153e2b;color:#5ee79b;border:1px solid #2f7d54}
.vmm-stopped{background:#3a2c2c;color:#e0a0a0;border:1px solid #7d4a4a}
.vmm-suspended,.vmm-starting{background:#3a3320;color:#e8cf7a;border:1px solid #7d6a2f}
.vmm-unknown,.vmm-locked{background:#2c2c3a;color:#a9a9d0;border:1px solid #4a4a7d}
.vmm-grid{display:flex;flex-wrap:wrap;gap:10px;margin:10px 0 14px}
.vmm-card{flex:1 1 150px;min-width:150px;padding:10px 12px;border:1px solid #3a3f46;border-radius:6px;background:#23272c}
.vmm-card .k{font-size:11px;text-transform:uppercase;letter-spacing:.05em;opacity:.65}
.vmm-card .v{font-size:20px;font-weight:600;margin-top:2px}
.vmm-card .s{font-size:11px;opacity:.7;margin-top:2px}
.vmm-mono{font-family:monospace;font-size:12px}
</style>
<form action="vmmngr.php" method="post" name="iform" id="iform"><table id="area_data"><tbody><tr><td id="area_data_frame">
<?php if (!$vmprov['available']): ?>
<?php print_info_box(sprintf(gettext('vm-bhyve was not found. Neither %s nor the bundled copy exists.'), '/usr/local/sbin/vm') . '<br />' . gettext('Install vm-bhyve or run the installer with a bundled vendor tree.')); ?>
<?php endif; ?>
<div class="vmm-grid">
<div class="vmm-card">
<div class="k"><?=gettext('Virtual Machines');?></div>
<div class="v"><?=count($running);?> / <?=count($vms);?></div>
<div class="s"><?=gettext('running / total');?></div>
</div>
<div class="vmm-card">
<div class="k"><?=gettext('Assigned Memory');?></div>
<div class="v"><?=vmm_human_bytes($mem_used);?></div>
<div class="s"><?=$cpus;?> vCPU</div>
</div>
<div class="vmm-card">
<div class="k"><?=gettext('vm-bhyve');?></div>
<div class="v"><?=vmm_h((string)($ver['version'] ?? '?'));?></div>
<div class="s"><?=vmm_source_label($vmprov);?> · rev <?=vmm_h((string)($ver['rev'] ?? '?'));?></div>
</div>
<div class="vmm-card">
<div class="k"><?=gettext('Datastore');?></div>
<div class="v"><?=vmm_h(ltrim(str_replace('zfs:', '', $vm_dir), '/'));?></div>
<div class="s vmm-mono"><?=vmm_h($vm_dir);?></div>
</div>
</div>
<table class="area_data_selection" style="width:100%;table-layout:fixed;border-collapse:collapse;">
<colgroup>
<col style="width:20%">
<col style="width:12%">
<col style="width:9%">
<col style="width:7%">
<col style="width:9%">
<col style="width:18%">
<col style="width:7%">
<col style="width:18%">
</colgroup>
<thead>
<?php
html_separator2();
html_titleline2(gettext('Virtual Machines'), 8);
?>
<tr>
<th class="lhell"><?=gettext('Name');?></th>
<th class="lhell"><?=gettext('State');?></th>
<th class="lhell"><?=gettext('Loader');?></th>
<th class="lhell"><?=gettext('vCPU');?></th>
<th class="lhell"><?=gettext('Memory');?></th>
<th class="lhell"><?=gettext('Datastore');?></th>
<th class="lhell"><?=gettext('Autostart');?></th>
<th class="lhebl"><?=gettext('Details');?></th>
</tr>
</thead>
<tbody>
<?php if ($vms === []): ?>
<tr><td class="lcell" colspan="8"><?=gettext('No virtual machines found.');?></td></tr>
<?php else: ?>
<?php foreach ($vms as $v): ?>
<tr>
<td class="lcell"><strong><?=vmm_h((string)$v['name']);?></strong></td>
<td class="lcell"><?=vmm_badge((string)$v['state']);?></td>
<td class="lcell"><?=vmm_h((string)$v['loader']);?></td>
<td class="lcell"><?=vmm_h((string)$v['cpu']);?></td>
<td class="lcell"><?=vmm_h((string)$v['memory']);?></td>
<td class="lcell"><?=vmm_h((string)$v['datastore']);?></td>
<td class="lcell"><?=!empty($v['auto']) ? gettext('yes') : gettext('no');?></td>
<td class="lcebl">
<a class="formbtn" href="vmmngr_vm.php?name=<?=urlencode((string)$v['name']);?>"><?=gettext('Open');?></a>
</td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
<div id="remarks">
<?php
html_remark2(
'preview',
gettext('Preview build'),
gettext('This build is read-only on purpose: it lists and inspects the existing machines but does not start, stop or change anything. Actions, creation wizard, images and templates follow in the next milestone.')
);
?>
</div>
</td></tr></tbody></table></form>
<?php include 'fend.inc'; ?>
+42
View File
@@ -0,0 +1,42 @@
<?php
/*
* vmmngr_api.php - read-only JSON endpoint.
*
* GET/POST ?action=list|info|selfcheck
* Every request requires an authenticated admin session (XigmaNAS auth.inc).
*/
require_once 'vmmngr-boot.inc';
if (!session::is_admin()) {
vmm_json(['ok' => 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);
}
+120
View File
@@ -0,0 +1,120 @@
<?php
/*
* vmmngr_config.php - environment and provider self-check (preview 0.1.0)
*/
require_once 'vmmngr-boot.inc';
$pgtitle = [gettext('Extensions'), gettext('VM Manager'), gettext('Configuration')];
$sc = vmm_selfcheck();
$conf = vmm_config();
include 'fbegin.inc';
?>
<style>
.vmm-mono{font-family:monospace;font-size:12px}
.vmm-raw{background:#1b1f23;border:1px solid #333a41;border-radius:4px;padding:10px;overflow:auto;max-height:420px}
.vmm-ok{color:#5ee79b}
.vmm-miss{color:#e0a0a0}
</style>
<form action="vmmngr_config.php" method="post" name="iform" id="iform"><table id="area_data"><tbody><tr><td id="area_data_frame">
<table class="area_data_settings" style="width:100%;border-collapse:collapse;">
<colgroup>
<col class="area_data_settings_col_tag">
<col class="area_data_settings_col_data">
</colgroup>
<thead>
<?php html_separator2(); html_titleline2(gettext('Environment'), 2); ?>
</thead>
<tbody>
<tr><td class="celltag"><?=gettext('Platform');?></td><td class="celldata"><?=vmm_h($sc['platform']);?> · <?=vmm_h($sc['product']);?> · <?=vmm_h($sc['os']);?></td></tr>
<tr><td class="celltag">PHP</td><td class="celldata"><?=vmm_h($sc['php']);?></td></tr>
<tr><td class="celltag"><?=gettext('Extension root');?></td><td class="celldata vmm-mono"><?=vmm_h($sc['root']);?></td></tr>
<tr><td class="celltag">vm_dir</td><td class="celldata vmm-mono"><?=vmm_h($sc['vm_dir']);?></td></tr>
<tr><td class="celltag"><?=gettext('Kernel modules');?></td><td class="celldata">
vmm: <span class="<?=$sc['kld']['vmm'] === 'loaded' ? 'vmm-ok' : 'vmm-miss';?>"><?=vmm_h($sc['kld']['vmm']);?></span> ·
nmdm: <span class="<?=$sc['kld']['nmdm'] === 'loaded' ? 'vmm-ok' : 'vmm-miss';?>"><?=vmm_h($sc['kld']['nmdm']);?></span>
</td></tr>
<tr><td class="celltag"><?=gettext('Virtual machines');?></td><td class="celldata"><?=$sc['vm_count'];?> <?=gettext('total');?>, <?=$sc['vm_running'];?> <?=gettext('running');?></td></tr>
</tbody>
</table>
<br />
<table class="area_data_settings" style="width:100%;border-collapse:collapse;">
<colgroup>
<col class="area_data_settings_col_tag">
<col class="area_data_settings_col_data">
</colgroup>
<thead>
<?php html_separator2(); html_titleline2(gettext('Components and provider'), 2); ?>
</thead>
<tbody>
<?php
$rows = [
'vm' => 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']);
?>
<tr>
<td class="celltag"><?=$label;?></td>
<td class="celldata">
<span class="<?=$ok ? 'vmm-ok' : 'vmm-miss';?>"><?=$ok ? gettext('available') : gettext('missing');?></span>
· <?=gettext('source');?>: <strong><?=vmm_h((string)$p['source']);?></strong>
<div class="vmm-mono"><?=vmm_h((string)$p['path']);?></div>
<?php if ($key === 'vm' && !empty($sc['vm']['version']['version'])): ?>
<div class="vmm-mono"><?=vmm_h((string)$sc['vm']['version']['version']);?> (rev <?=vmm_h((string)($sc['vm']['version']['rev'] ?? '?'));?>)</div>
<?php endif; ?>
<?php if ($key === 'firmware' && !empty($sc['firmware']['mtime'])): ?>
<div class="vmm-mono"><?=vmm_h((string)$sc['firmware']['mtime']);?> · <?=vmm_h(vmm_human_bytes((int)$sc['firmware']['size']));?></div>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
<tr><td class="celltag"><?=gettext('Update policy');?></td><td class="celldata"><span class="vmm-mono">vm_source = <?=vmm_h((string)$conf['vm_source']);?></span> — <?=gettext('the system installation always wins; the bundle only fills gaps.');?></td></tr>
</tbody>
</table>
<br />
<table class="area_data_settings" style="width:100%;border-collapse:collapse;">
<colgroup>
<col class="area_data_settings_col_tag">
<col class="area_data_settings_col_data">
</colgroup>
<thead>
<?php html_separator2(); html_titleline2(gettext('Datastores and switches'), 2); ?>
</thead>
<tbody>
<?php foreach (($sc['datastores'] ?? []) as $ds): ?>
<tr>
<td class="celltag"><?=gettext('Datastore');?></td>
<td class="celldata vmm-mono"><?=vmm_h(implode(' · ', array_map('strval', $ds)));?></td>
</tr>
<?php endforeach; ?>
<?php if (($sc['datastores'] ?? []) === []): ?>
<tr><td class="celltag"><?=gettext('Datastore');?></td><td class="celldata"><?=gettext('none reported');?></td></tr>
<?php endif; ?>
<?php foreach (($sc['switches'] ?? []) as $sw): ?>
<tr>
<td class="celltag"><?=gettext('Switch');?></td>
<td class="celldata vmm-mono"><?=vmm_h(implode(' · ', array_map('strval', $sw)));?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<details style="margin-top:12px;">
<summary style="cursor:pointer;padding:6px 0;"><?=gettext('Raw self-check (JSON)');?></summary>
<pre class="vmm-raw vmm-mono"><?=vmm_h(json_encode($sc, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));?></pre>
</details>
</td></tr></tbody></table></form>
<?php include 'fend.inc'; ?>
+104
View File
@@ -0,0 +1,104 @@
<?php
/*
* vmmngr_vm.php - VM detail view (read-only preview 0.1.0)
*/
require_once 'vmmngr-boot.inc';
$name = (string)($_GET['name'] ?? '');
if ($name === '' || !vmm_valid_name($name)) {
header('Location: vmmngr.php');
exit;
}
$info = vmm_info($name);
$pgtitle = [gettext('Extensions'), gettext('VM Manager'), $name];
include 'fbegin.inc';
?>
<style>
.vmm-badge{display:inline-block;padding:1px 8px;border-radius:10px;font-size:11px;font-weight:600}
.vmm-running{background:#153e2b;color:#5ee79b;border:1px solid #2f7d54}
.vmm-stopped{background:#3a2c2c;color:#e0a0a0;border:1px solid #7d4a4a}
.vmm-suspended,.vmm-starting{background:#3a3320;color:#e8cf7a;border:1px solid #7d6a2f}
.vmm-unknown,.vmm-locked{background:#2c2c3a;color:#a9a9d0;border:1px solid #4a4a7d}
.vmm-mono{font-family:monospace;font-size:12px}
.vmm-raw{background:#1b1f23;border:1px solid #333a41;border-radius:4px;padding:10px;overflow:auto;max-height:420px}
</style>
<form action="vmmngr_vm.php" method="post" name="iform" id="iform"><table id="area_data"><tbody><tr><td id="area_data_frame">
<?php if (isset($info['error'])): ?>
<?php print_info_box(sprintf(gettext('Could not read VM details: %s'), vmm_h((string)$info['error']))); ?>
<?php else: ?>
<?php
$g = $info['general'] ?? [];
$state = vmm_state_from_string((string)($g['state'] ?? ''));
?>
<table class="area_data_settings" style="width:100%;border-collapse:collapse;">
<colgroup>
<col class="area_data_settings_col_tag">
<col class="area_data_settings_col_data">
</colgroup>
<thead>
<?php
html_separator2();
html_titleline2(sprintf('%s: %s', gettext('Virtual Machine'), $name), 2);
?>
</thead>
<tbody>
<tr><td class="celltag"><?=gettext('State');?></td><td class="celldata"><?=vmm_badge($state['state']);?> <?php if ($state['pid']): ?><span class="vmm-mono">PID <?=$state['pid'];?></span><?php endif; ?></td></tr>
<tr><td class="celltag"><?=gettext('Loader');?></td><td class="celldata"><?=vmm_h((string)($g['loader'] ?? ''));?></td></tr>
<tr><td class="celltag"><?=gettext('vCPU / Memory');?></td><td class="celldata"><?=vmm_h((string)($g['cpu'] ?? ''));?> vCPU · <?=vmm_h((string)($g['memory'] ?? ''));?><?php if (!empty($g['memory-resident'])): ?> <span class="vmm-mono">(<?=vmm_h((string)$g['memory-resident']);?>)</span><?php endif; ?></td></tr>
<tr><td class="celltag"><?=gettext('Datastore');?></td><td class="celldata"><?=vmm_h((string)($g['datastore'] ?? ''));?></td></tr>
<tr><td class="celltag">UUID</td><td class="celldata vmm-mono"><?=vmm_h((string)($g['uuid'] ?? ''));?></td></tr>
</tbody>
</table>
<br />
<?php foreach (($info['sections'] ?? []) as $type => $blocks): ?>
<table class="area_data_settings" style="width:100%;border-collapse:collapse;">
<colgroup>
<col class="area_data_settings_col_tag">
<col class="area_data_settings_col_data">
</colgroup>
<thead>
<?php html_separator2(); html_titleline2(vmm_h(ucwords(str_replace('-', ' ', $type))), 2); ?>
</thead>
<tbody>
<?php foreach ($blocks as $b): ?>
<?php foreach ($b['data'] as $k => $v): ?>
<tr>
<td class="celltag"><?=vmm_h((string)$k);?></td>
<td class="celldata vmm-mono"><?=vmm_h((string)$v);?></td>
</tr>
<?php endforeach; ?>
<?php foreach ($b['lines'] as $line): ?>
<tr>
<td class="celltag">—</td>
<td class="celldata vmm-mono"><?=vmm_h((string)$line);?></td>
</tr>
<?php endforeach; ?>
<?php if ($b['data'] === [] && $b['lines'] === []): ?>
<tr><td class="celltag">—</td><td class="celldata"><?=gettext('none');?></td></tr>
<?php endif; ?>
<?php endforeach; ?>
</tbody>
</table>
<br />
<?php endforeach; ?>
<details>
<summary style="cursor:pointer;padding:6px 0;"><?=gettext('Raw vm-bhyve output');?></summary>
<pre class="vmm-raw vmm-mono"><?=vmm_h((string)($info['raw'] ?? ''));?></pre>
</details>
<?php endif; ?>
<div id="remarks">
<?php html_remark2('preview', gettext('Read-only'), gettext('Actions are intentionally not wired yet. This page shows exactly what vm-bhyve reports.')); ?>
</div>
</td></tr></tbody></table></form>
<?php include 'fend.inc'; ?>
View File
Whitespace-only changes.
+1
View File
@@ -0,0 +1 @@
0.1.0-preview
+299
View File
@@ -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> <link>
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 <target> <link> (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}" <<EOF
{
"appname": "VM Manager",
"version": "${VERSION}",
"rootfolder": "${CWDIR}",
"vm_source": "auto",
"bridges": [],
"default_bridge": "",
"enable": true,
"job_timeout": 900
}
EOF
log "created default configuration ${conf}"
}
set_permissions() {
chmod 0750 "${CWDIR}" 2>/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