'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; }