data = $product; $this->push = new PusherNotification; $this->telegram = new Telegram; $this->action = $action; $this->update = $update; } public function handle(ServiceVCenter $serviceVCenter) { $product = ModuleVmware::with([ 'Customer', 'IpAddress.Host.Datacenter.vCenter' ])->find($this->data); if (!$product || !$product->IpAddress?->Host?->Datacenter?->vCenter) { throw new \Exception("VMJobs: product {$this->data} missing vCenter relationship"); } $vcenter = $product->IpAddress->Host->Datacenter->vCenter; $serviceVCenter->setConnection($vcenter->host, $vcenter->token); $vmwareId = $product->vmware_id; $VirtualMachineStatus = null; $status = 1; $call = function (callable $action) use ($serviceVCenter, $vcenter) { $result = $action(); if ($result === 'Login_Again') { $token = $serviceVCenter->loginServer($vcenter); if ($token) { vCenter::where('id', $vcenter->id)->update(['token' => $token]); $serviceVCenter->token = $token; } $result = $action(); } return $result; }; $powerState = fn () => $call(fn () => $serviceVCenter->CheckVirtualMachine($vmwareId))['power_state'] ?? null; switch ($this->action) { case 'Suspend': $VirtualMachineStatus = $call(fn () => $serviceVCenter->SuspendVirtualMachine($vmwareId)); $status = 2; break; case 'Reboot': $VirtualMachineStatus = $call(fn () => $serviceVCenter->RebootVirtualMachine($product, $vmwareId)); break; case 'Start': if ($powerState() !== 'POWERED_ON') { $VirtualMachineStatus = $call(fn () => $serviceVCenter->StartVirtualMachine($product, $vmwareId)); } break; case 'ShutdownGuest': $status = 0; if ($powerState() !== 'POWERED_OFF') { $VirtualMachineStatus = $call(fn () => $serviceVCenter->ShutdownGuestVirtualMachine($product, $vmwareId)); } break; case 'PowerOff': $status = 0; if ($powerState() !== 'POWERED_OFF') { $VirtualMachineStatus = $call(fn () => $serviceVCenter->PowerOffVirtualMachine($vmwareId)); } break; } if (is_array($VirtualMachineStatus) && ($VirtualMachineStatus['error'] ?? false)) { throw new \Exception(json_encode($VirtualMachineStatus['data'] ?? $VirtualMachineStatus)); } if ($this->update) { $product->update(['status' => $status]); } } public function failed(Throwable $exception) { Event(new NotificationStatus("Notification: " . $exception->getMessage(), false)); $this->telegram->SendErrorMessage($exception->getMessage()); } }