0.2.0: job engine, VM actions, theme-aware styling

This commit is contained in:
Claw committed 2026-11-17 19:23:28 +01:00
1 parent c62de24cc0
commit 485a267ffe
14 files changed
+901 -71

No files matched your search

+249
View File
@@ -472,3 +472,252 @@ function vmm_json(array $data, int $code = 0): never
echo json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
exit;
}
/* ------------------------------------------------------------------ */
/* job engine */
/* ------------------------------------------------------------------ */
const VMM_JOBDIR = VMM_ROOT . '/state/jobs';
const VMM_LOCKDIR = VMM_ROOT . '/state/locks';
const VMM_ACTIONS = [
'start' => ['argv' => ['start'], 'timeout' => 300, 'needs' => 'stopped'],
'stop' => ['argv' => ['stop'], 'timeout' => 180, 'needs' => 'running'],
'restart' => ['argv' => ['restart'], 'timeout' => 300, 'needs' => 'running'],
'reset' => ['argv' => ['reset', '-f'], 'timeout' => 120, 'needs' => 'running'],
'poweroff' => ['argv' => ['poweroff', '-f'], 'timeout' => 120, 'needs' => 'running'],
'destroy' => ['argv' => ['destroy', '-f'], 'timeout' => 300, 'needs' => 'stopped'],
];
function vmm_ensure_state_dirs(): void
{
foreach ([VMM_JOBDIR, VMM_LOCKDIR] as $d) {
if (!is_dir($d)) {
@mkdir($d, 0750, true);
}
}
}
function vmm_vm_state(string $name): string
{
foreach (vmm_list() as $v) {
if (($v['name'] ?? '') === $name) {
return (string)$v['state'];
}
}
return 'absent';
}
function vmm_ram_budget(): array
{
$conf = vmm_config();
$limitPct = (int)($conf['ram_budget_pct'] ?? 85);
$total = 0;
$out = trim((string)@shell_exec('/sbin/sysctl -n hw.physmem 2>/dev/null'));
if ($out !== '' && ctype_digit($out)) {
$total = (int)$out;
}
if ($total <= 0) {
$total = 8 * 1024 ** 3;
}
return ['total' => $total, 'limit' => (int)($total * $limitPct / 100), 'pct' => $limitPct];
}
function vmm_ram_used(): int
{
$used = 0;
foreach (vmm_list() as $v) {
if (($v['state'] ?? '') === 'running') {
$used += vmm_size_to_bytes((string)($v['memory'] ?? '0'));
}
}
return $used;
}
function vmm_action_check(string $verb, string $name, string $confirm = ''): array
{
if (!isset(VMM_ACTIONS[$verb])) {
return ['ok' => false, 'error' => 'unknown action'];
}
if (!vmm_valid_name($name)) {
return ['ok' => false, 'error' => 'invalid vm name'];
}
$state = vmm_vm_state($name);
if ($state === 'absent') {
return ['ok' => false, 'error' => 'vm not found'];
}
$needs = VMM_ACTIONS[$verb]['needs'];
if ($needs === 'running' && $state !== 'running') {
return ['ok' => false, 'error' => "vm is {$state}, not running"];
}
if ($needs === 'stopped' && $state === 'running') {
return ['ok' => false, 'error' => 'vm is running; stop it first'];
}
if ($verb === 'start') {
$budget = vmm_ram_budget();
$used = vmm_ram_used();
$need = 0;
foreach (vmm_list() as $v) {
if (($v['name'] ?? '') === $name) {
$need = vmm_size_to_bytes((string)($v['memory'] ?? '0'));
}
}
if ($need > 0 && $used + $need > $budget['limit']) {
return [
'ok' => false,
'error' => sprintf(
'RAM budget: %s in use + %s requested exceeds limit of %s (%d%%)',
vmm_human_bytes($used),
vmm_human_bytes($need),
vmm_human_bytes($budget['limit']),
$budget['pct']
),
];
}
}
if ($verb === 'destroy') {
if ($confirm !== $name) {
return ['ok' => false, 'error' => 'confirmation mismatch: type the vm name exactly'];
}
}
return ['ok' => true, 'state' => $state];
}
function vmm_job_path(string $id): string
{
return VMM_JOBDIR . '/' . $id . '.json';
}
function vmm_job_write(array $job): void
{
$job['updated'] = time();
$tmp = vmm_job_path($job['id']) . '.tmp';
file_put_contents($tmp, json_encode($job, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
rename($tmp, vmm_job_path($job['id']));
}
function vmm_job_get(string $id): ?array
{
if (!preg_match('/^[0-9]{8}-[0-9]{6}-[a-f0-9]{8}$/', $id)) {
return null;
}
$f = vmm_job_path($id);
if (!is_file($f)) {
return null;
}
$job = json_decode((string)file_get_contents($f), true);
return is_array($job) ? $job : null;
}
function vmm_job_list(int $limit = 50, string $vm = ''): array
{
$files = glob(VMM_JOBDIR . '/*.json') ?: [];
rsort($files);
$out = [];
foreach ($files as $f) {
$job = json_decode((string)file_get_contents($f), true);
if (!is_array($job)) {
continue;
}
if ($vm !== '' && ($job['vm'] ?? '') !== $vm) {
continue;
}
$out[] = $job;
if (count($out) >= $limit) {
break;
}
}
return $out;
}
function vmm_job_log(string $id, int $maxBytes = 65536): string
{
$f = VMM_JOBDIR . '/' . $id . '.log';
if (!is_file($f)) {
return '';
}
$size = filesize($f);
if ($size <= $maxBytes) {
return (string)file_get_contents($f);
}
$fh = fopen($f, 'rb');
fseek($fh, $maxBytes * -1, SEEK_END);
$data = (string)stream_get_contents($fh);
fclose($fh);
return "... (truncated)\n" . $data;
}
function vmm_job_new(string $verb, string $name): array
{
vmm_ensure_state_dirs();
$id = date('Ymd-His') . '-' . bin2hex(random_bytes(4));
$job = [
'id' => $id,
'verb' => $verb,
'vm' => $name,
'state' => 'queued',
'created' => time(),
'started' => null,
'ended' => null,
'pid' => null,
'rc' => null,
'error' => '',
'by' => (string)($_SERVER['REMOTE_ADDR'] ?? 'cli'),
];
vmm_job_write($job);
@touch(VMM_JOBDIR . '/' . $id . '.log');
$php = PHP_BINARY !== '' ? PHP_BINARY : '/usr/local/bin/php';
$cmd = sprintf(
'/usr/bin/nohup %s %s %s > /dev/null 2>&1 &',
escapeshellarg($php),
escapeshellarg(VMM_ROOT . '/bin/vmm-jobd'),
escapeshellarg($id)
);
exec($cmd);
return $job;
}
function vmm_job_recover(): int
{
$fixed = 0;
foreach (vmm_job_list(200) as $job) {
if (($job['state'] ?? '') !== 'running') {
continue;
}
$pid = (int)($job['pid'] ?? 0);
$alive = vmm_pid_alive($pid);
if (!$alive) {
$job['state'] = 'failed';
$job['error'] = 'interrupted (process gone)';
$job['ended'] = time();
vmm_job_write($job);
$fixed++;
}
}
return $fixed;
}
function vmm_pid_alive(int $pid): bool
{
if ($pid <= 0) {
return false;
}
if (function_exists('posix_kill')) {
return @posix_kill($pid, 0);
}
exec('/bin/kill -0 ' . $pid . ' > /dev/null 2>&1', $o, $rc);
return $rc === 0;
}
function vmm_job_cancel(string $id): array
{
$job = vmm_job_get($id);
if ($job === null) {
return ['ok' => false, 'error' => 'job not found'];
}
if (!in_array($job['state'], ['queued', 'running'], true)) {
return ['ok' => false, 'error' => 'job already finished'];
}
@touch(VMM_JOBDIR . '/' . $id . '.cancel');
return ['ok' => true, 'id' => $id];
}