Files
Virtnet.bond/extensions/Servers/Proxmox/Livewire/Component.php
2025-11-30 11:57:22 +01:00

91 lines
2.5 KiB
PHP

<?php
namespace Paymenter\Extensions\Servers\Proxmox\Livewire;
use App\Livewire\Component as BaseComponent;
use Paymenter\Extensions\Servers\Proxmox\Models\Server;
use Paymenter\Extensions\Servers\Proxmox\Proxmox;
class Component extends BaseComponent
{
/**
* The server instance.
*/
public Server $server;
/**
* Latest VM status snapshot shared with all Proxmox views.
*/
public ?object $status = null;
/**
* Controls dynamic polling interval (shared with layout header).
*/
public bool $fastPolling = false;
/**
* Mount the component with the server.
*/
public function mount(Server $server): void
{
$this->server = $server;
if ($server->user_id != auth()->id()) {
abort(403);
}
$this->loadVmStatus();
}
/**
* Perform a VM lifecycle action (start/stop/etc).
*/
public function do(string $action): void
{
if (!in_array($action, ['start', 'shutdown', 'reboot', 'stop', 'reset'], true)) {
$this->notify('Invalid action', 'error');
return;
}
try {
$proxmox = new Proxmox;
$response = $proxmox->request(
'/nodes/' . $this->server->node->name . '/qemu/' . $this->server->vm_id . '/status/' . $action,
'post',
['vmid' => $this->server->vm_id]
);
if ($response->successful()) {
$this->notify('Action performed successfully', 'success');
if (property_exists($this, 'fastPolling')) {
$this->fastPolling = true;
}
} else {
$message = $response->json()['errors'][0]['message'] ?? 'Unknown error';
$this->notify('Action failed: ' . $message, 'error');
}
} catch (\Throwable $e) {
$this->notify('Action failed: ' . $e->getMessage(), 'error');
} finally {
$this->loadVmStatus();
}
}
/**
* Refresh the cached VM status from Proxmox.
*/
public function loadVmStatus(): void
{
try {
$proxmox = new Proxmox;
$data = $proxmox->request(
'/nodes/' . $this->server->node->name . '/qemu/' . $this->server->vm_id . '/status/current'
)->json()['data'] ?? null;
$this->status = $data ? (object) $data : null;
} catch (\Throwable $e) {
$this->status = null;
}
}
}