update fix deadcode, security

This commit is contained in:
baodev0
2026-09-28 08:26:29 +07:00
parent 3af59bd9c5
commit 82080b5b84
452 changed files with 4857 additions and 26289 deletions
@@ -1,121 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Action;
use App\Http\Services\vCenter;
use App\Mail\ChangePortRemote;
use App\Models\ModuleVmware;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Str;
class ChangeRemotePortJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 180;
public function __construct(
public string $productId,
public string $newPort,
public string $password,
public int $userId,
public string $email
) {
}
public function handle(vCenter $serviceVCenter): void
{
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter', 'os.osGroup')
->where('vmware_id', $this->productId)
->where('customer_id', $this->userId)
->firstOrFail();
$osFamily = (string) ($product->os->osGroup->name ?? '');
$isWindows = stripos($osFamily, 'windows') !== false;
if (!$isWindows) {
throw new \RuntimeException('Only Windows is supported by this reset job.');
}
$vmName = $product->ipAddress->vm_name
?? $product->name
?? $product->hostname
?? null;
if (!$vmName && preg_match('/^vm-\d+$/i', (string) $product->vmware_id)) {
$rawName = trim($serviceVCenter->runPsCommand("(Get-VM -Id '" . addslashes($product->vmware_id) . "').Name"));
if (($p = strpos($rawName, '[STDERR]')) !== false) {
$rawName = trim(substr($rawName, 0, $p));
}
$vmName = trim(preg_replace('/\s+/', ' ', $rawName));
}
if (!$vmName) {
throw new \RuntimeException('Cannot resolve VM Name on vCenter.');
}
$guestUser = 'Administrator';
$result = $serviceVCenter->changeRDPPortWindows(
vmName: $vmName,
guestUser: 'Administrator',
guestPassword: $this->password,
newPort: $this->newPort,
);
if ($result === 'Login_Fail' || $result === false || $result === null) {
throw new \RuntimeException('SSH runner login failed.');
}
if (is_string($result)) {
throw new \RuntimeException('Script returned non-JSON output: ' . $result);
}
$row = null;
if (is_array($result)) {
if (isset($result['vm']) && isset($result['status'])) {
$row = $result;
} else {
foreach ($result as $it) {
if (is_array($it) && (($it['vm'] ?? null) === $vmName)) {
$row = $it;
break;
}
}
if ($row === null && isset($result[0]) && is_array($result[0])) {
$row = $result[0];
}
}
}
if (!is_array($row) || empty($row)) {
Log::error('ChangeRemotePortJob: invalid script response shape', ['vm' => $vmName, 'raw' => $result]);
throw new \RuntimeException('Invalid script response.');
}
$status = strtolower((string) ($row['status'] ?? ''));
$message = (string) ($row['message'] ?? '');
$newPort = (string) ($row['newPort'] ?? $this->newPort);
$ok = ($status === 'ok');
ModuleVmware::where('id', $product->id)->update([
'port' => (int) $newPort,
'updated_at' => now(),
]);
if (!$ok) {
throw new \RuntimeException($message !== '' ? $message : ('Change RDP port failed with status: ' . $status));
}
Mail::to($this->email)->send(
new ChangePortRemote(vmName: $vmName, newPort: (string) $newPort)
);
}
}
@@ -1,101 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Action;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Http\Services\vCenter;
use App\Mail\VmPasswordResetSuccess;
use App\Models\ModuleVmware;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
class ResetVmPasswordJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 180;
public function __construct(
public string $productId,
public string $oldPassword,
public string $newPassword,
public int $userId,
public string $email
) {}
public function handle(vCenter $serviceVCenter): void
{
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter','os.osGroup')
->where('vmware_id', $this->productId)
->where('customer_id', $this->userId)
->firstOrFail();
$osFamily = (string)($product->os->osGroup->name ?? '');
$isWindows = stripos($osFamily, 'windows') !== false;
if (!$isWindows) {
throw new \RuntimeException('Only Windows is supported by this reset job.');
}
$vmName = $product->ipAddress->vm_name
?? $product->name
?? $product->hostname
?? null;
if (!$vmName && preg_match('/^vm-\d+$/i', (string)$product->vmware_id)) {
$rawName = trim($serviceVCenter->runPsCommand("(Get-VM -Id '".addslashes($product->vmware_id)."').Name"));
if (($p = strpos($rawName, '[STDERR]')) !== false) {
$rawName = trim(substr($rawName, 0, $p));
}
$vmName = trim(preg_replace('/\s+/', ' ', $rawName));
}
if (!$vmName) {
throw new \RuntimeException('Cannot resolve VM Name on vCenter.');
}
$guestUser = 'Administrator';
$guestPassword = $this->oldPassword;
$result = $serviceVCenter->resetGuestPasswordViaPs1(
vmName: $vmName,
guestUser: $guestUser,
guestPassword: $guestPassword,
newPassword: $this->newPassword,
);
$product->update(['password' => encrypt($this->newPassword)]);
if ($result === 'Login_Fail' || $result === false || $result === null) {
throw new \RuntimeException('SSH runner login failed.');
}
if (is_string($result)) {
throw new \RuntimeException('Script returned non-JSON output: '.$result);
}
$row = $result;
if (isset($result[0])) {
$row = $result[0];
foreach ($result as $it) {
if (is_array($it) && (($it['vm'] ?? null) === $vmName)) { $row = $it; break; }
}
}
$status = strtolower($row['status'] ?? '');
if ($status !== 'ok') {
throw new \RuntimeException($row['message'] ?? 'Reset failed by script');
}
// Gửi mail thông báo
Mail::to($this->email)->send(
new VmPasswordResetSuccess(vmName: $vmName, newPassword: $this->newPassword)
);
Log::info('ResetVmPasswordJob: success', ['vm'=>$vmName]);
}
}
@@ -1,94 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class CheckIPAddress implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
protected array $info;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$virtual_info,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
$this->info = $virtual_info;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$DetailVirtualMachine = $this->serviceVCenter->GetIPAddressVirtualMachine($this->vmware_id);
if ($DetailVirtualMachine['error']) {
throw new \Exception(json_encode($DetailVirtualMachine['message']));
}
// Get expected IP address with null safety
$expectedIP = null;
// Try to get IP from old relationship first
if ($this->data && isset($this->data->IpAddress) && $this->data->IpAddress) {
$expectedIP = $this->data->IpAddress->ip;
}
// If no IP from old relationship, try to get from ModuleVmware
if (!$expectedIP && $this->data) {
// Try to find ModuleVmware by vmware_id
$moduleVmware = \App\Models\ModuleVmware::with('ipAddress')
->where('vmware_id', $this->vmware_id)
->first();
if ($moduleVmware && $moduleVmware->ipAddress) {
$expectedIP = $moduleVmware->ipAddress->ip;
}
}
// If still no expected IP, log warning but don't fail
if (!$expectedIP) {
\Illuminate\Support\Facades\Log::warning('⚠️ Không tìm thấy expected IP cho VM', [
'vmware_id' => $this->vmware_id,
'data_class' => $this->data ? get_class($this->data) : 'null',
'has_ip_address_relation' => isset($this->data->IpAddress) && $this->data->IpAddress ? 'yes' : 'no'
]);
// Skip IP check and continue to next job
$jobs_configDB = new ConfigDatabase($this->data, $this->info);
dispatch($jobs_configDB)->delay(now()->addSeconds(5));
return;
}
// Compare actual vs expected IP
if ($DetailVirtualMachine['data']['ip_address'] !== $expectedIP) {
\Illuminate\Support\Facades\Log::warning('⚠️ IP address mismatch', [
'vmware_id' => $this->vmware_id,
'actual_ip' => $DetailVirtualMachine['data']['ip_address'],
'expected_ip' => $expectedIP
]);
throw new \Exception('IP address mismatch: actual=' . $DetailVirtualMachine['data']['ip_address'] . ', expected=' . $expectedIP);
}
$jobs_configDB = new ConfigDatabase($this->data,$this->info);
dispatch($jobs_configDB)->delay(now()->addSeconds(5));
}
}
@@ -1,54 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class CheckStatusVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$status = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
if ($status['error'] === true) {
throw new \Exception(json_encode($status['message']));
}
if ($status['data']['operations_ready'] === false) {
do {
sleep(10);
$status = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
} while ($status['data']['operations_ready'] !== true);
}
$jobs_configNetwork = new GetNetworkVirtualMachine($this->vmware_id,$this->data,$this->serviceVCenter);
dispatch($jobs_configNetwork)->delay(now()->addSeconds(5));
}
}
@@ -1,208 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Facade\HelperFacade as Helper;
use App\Jobs\Mail\SendInformationVirtualMachine;
use App\Models\Setting;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class ConfigCLICommand implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data,$service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
// Generate new password
$PasswordVirtualMachine = Helper::general_password();
$usersName = '';
$port = '';
// Get VM with relationships
$vm = \App\Models\ModuleVmware::with(['ipAddress', 'os.osGroup'])
->where('vmware_id', $this->vmware_id)
->first();
if (!$vm) {
Log::error('❌ ConfigCLICommand: VM not found', ['vmware_id' => $this->vmware_id]);
return;
}
// Determine OS type and config
$osGroupName = $vm->os?->osGroup?->name ?? '';
$osVersion = $vm->os?->version ?? '';
try {
switch (true) {
case (str_contains($osGroupName, "Windows") && str_contains($osVersion, 10)):
$usersName = 'administrator';
$port = 3389;
$this->serviceVCenter->ConfigWindowsVersion10($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
case (str_contains($osGroupName, "Windows")):
$usersName = 'administrator';
$port = 3389;
$this->serviceVCenter->ConfigWindowsServer($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
case (str_contains($osGroupName, "CentOS") && str_contains($osVersion, 7)):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigCentOSVersion7($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
case (str_contains($osGroupName, "CentOS") && str_contains($osVersion, 8)):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigCentOSVersion8($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
case (str_contains($osGroupName, "Ubuntu")):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigVirtualMachineUbuntu($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
case (str_contains($osGroupName, "Rocky")):
$usersName = 'root';
$port = 22;
$this->serviceVCenter->ConfigRockyLinuxVersion9($this->vmware_id, $vm, $PasswordVirtualMachine);
break;
default:
Log::warning('❌ ConfigCLICommand: Unknown OS', [
'vmware_id' => $this->vmware_id,
'os_group' => $osGroupName,
'os_version' => $osVersion,
]);
return;
}
// Wait for VM to be ready
sleep(20);
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
if ($VirtualMachine['data']['operations_ready'] === false) {
$maxAttempts = 30; // 5 minutes max (30 * 10 seconds)
$attempt = 0;
do {
sleep(10);
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
Log::channel('Custom')->info(json_encode($VirtualMachine));
$attempt++;
} while ($VirtualMachine['data']['operations_ready'] !== true && $attempt < $maxAttempts);
}
// Fix Windows click if Windows
if (str_contains($osGroupName, "Windows")) {
$this->serviceVCenter->ConfigFixWindowsClick($this->vmware_id, $vm);
}
// ✅ Save password to DB AFTER successful config
$vm->update([
'password' => \App\Http\Facade\SignRSA::EncryptFunc($PasswordVirtualMachine),
'plain_password' => $PasswordVirtualMachine,
'port' => $port,
'user' => $usersName,
]);
Log::info('✅ ConfigCLICommand: Password changed and saved', [
'vmware_id' => $this->vmware_id,
'username' => $usersName,
'port' => $port,
]);
// Send email with new password to customer
$this->sendPasswordEmail($vm, $PasswordVirtualMachine, $usersName, $port);
// Dispatch CheckIP job
$jobs_CheckIP = new CheckIPAddress(
$this->vmware_id,
$vm,
['user' => $usersName, 'password' => $PasswordVirtualMachine, 'port' => $port],
$this->serviceVCenter
);
dispatch($jobs_CheckIP)->delay(now()->addSeconds(5));
} catch (\Exception $e) {
Log::error('❌ ConfigCLICommand: Error during configuration', [
'vmware_id' => $this->vmware_id,
'error' => $e->getMessage(),
'trace' => $e->getTraceAsString(),
]);
throw $e;
}
}
/**
* Send email with new password to customer
*/
private function sendPasswordEmail($vm, string $password, string $username, int $port): void
{
try {
$customer = $vm->customer;
if (!$customer) {
Log::error('ConfigCLICommand: Cannot find customer', ['vm_id' => $vm->id]);
return;
}
$setting = Setting::where('key', 'setting')->first();
$settingValue = $setting ? json_decode($setting->value) : null;
$emailData = [
'company_name' => $settingValue->company ?? 'Thế Giới Số',
'company_logo' => $settingValue->logo ?? '',
'client_name' => trim($customer->firstname . ' ' . $customer->lastname),
'product_name' => 'Cloud VPS',
'product_billing' => 'N/A',
'product_price' => 'N/A',
'service_host' => $vm->ipAddress?->ip ?? 'N/A',
'service_username' => $username,
'service_port' => $port,
'service_password' => $password,
'os_name' => $vm->os?->osGroup?->name . ' ' . $vm->os?->version ?? 'Unknown OS',
'service_due_exp' => $vm->next_due_date ? date('d/m/Y', $vm->next_due_date) : 'N/A',
];
SendInformationVirtualMachine::dispatch($emailData, $customer)
->delay(now()->addSeconds(10));
Log::info('✅ ConfigCLICommand: Password email dispatched', [
'customer_email' => $customer->email,
'vmware_id' => $vm->vmware_id,
]);
} catch (\Throwable $e) {
Log::error('❌ ConfigCLICommand: Failed to dispatch password email: ' . $e->getMessage(), [
'vmware_id' => $vm->vmware_id,
'error' => $e->getMessage(),
]);
}
}
}
@@ -1,84 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Events\Create_VirtualMachine_Success;
use App\Http\Facade\SignRSA;
use App\Http\Facade\HelperFacade as Helper;
use App\Http\Services\Telegram;
use App\Jobs\Mail\SendInformationVirtualMachine;
use App\Models\Setting;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class ConfigDatabase implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $data;
protected $info;
protected $telegram;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($data,$info)
{
$this->data = $data;
$this->info = $info;
$this->telegram = new Telegram();
//
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$this->data->update([
'name' => $this->data->ipaddress->ip . '_' . $this->data->cannotustomer->firstname,
'port' => $this->info['port'],
'user' => $this->info['user'],
'password' => SignRSA::EncryptFunc($this->info['password']),
'status' => 1
]);
$this->data->ipAddress->update([
'vm_name' => $this->data->IpAddress->ip . '_' . $this->data->Customer->firstname,
'status' => 1
]);
$setting = Setting::where('key', 'setting')->first();
$data = [
'company_name' => json_decode($setting->value)->company,
'company_logo' => json_decode($setting->value)->logo,
'client_name' => $this->data->Customer->firstname . " " . $this->data->Customer->lastname,
'product_name' => $this->data->GetInvoiceItem()->GetItemProduct()->name,
'product_billing' => Helper::billing_cycle($this->data->GetInvoiceItem()->billing),
'product_price' => number_format($this->data->GetInvoiceItem()->amount, 0, ',', '.'),
'service_host' => $this->data->IpAddress->ip,
'service_username' => $this->info['user'],
'service_port' => $this->info['port'],
'service_password' => $this->info['password'],
'os_name' => $this->data->Os->OsGroup->name . " " . $this->data->Os->version,
'service_due_exp' => Carbon::parse($this->data->next_due_date)->format('d/m/Y')
];
// Note: Email is now sent by ConfigCLICommand after password is changed
// $mail = new SendInformationVirtualMachine($data, $this->data->Customer);
// dispatch($mail)->delay(now()->addSeconds(5));
Event(new Create_VirtualMachine_Success("Máy chủ của bạn đã được khởi tạo thành công!",
$this->data->customer->id));
$this->telegram->SendInformation($this->data, $this->info['user'], $this->info['password'], $this->info['port']);
}
}
@@ -1,61 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class GetNetworkVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $vmware_id;
protected $serviceVCenter;
protected $data;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($vmware_id, $data, $service)
{
$this->vmware_id = $vmware_id;
$this->serviceVCenter = $service;
$this->data = $data;
}
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$NetworkForVirtualMachine = $this->serviceVCenter->GetNetworkVirtualMachine($this->vmware_id);
if ($NetworkForVirtualMachine['error']) {
throw new \Exception(json_encode($NetworkForVirtualMachine['message']));
}
$Network = $this->data->IpAddress->Network->network;
if ($Network !== $NetworkForVirtualMachine['data']['network']) {
$ConfigNetwork = [
"spec" => [
"backing" => [
"type" => $this->data->IpAddress->Network->type,
"network" => $this->data->IpAddress->Network->network
]
]
];
$this->serviceVCenter->ConfigNetworkVirtualMachine($this->vmware_id,$ConfigNetwork);
}
$jobs_configCLI = new ConfigCLICommand($this->vmware_id,$this->data,$this->serviceVCenter);
dispatch($jobs_configCLI)->delay(now()->addSeconds(5));
}
}
@@ -1,57 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Create;
use App\Http\Services\vCenter as ServiceVCenter;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class GetVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected string $name;
protected $data;
protected $response = '';
protected ServiceVCenter $serviceVCenter;
/**
* Create a new job instance.
*
* @return void
*/
public function __construct($name = '', $data,$service)
{
//
$this->name = $name;
$this->data = $data;
$this->serviceVCenter = $service;
}
/**
* Execute the job.
*
* @return bool|string
*/
public function handle()
{
$vmware_id = $this->serviceVCenter->FindVirtualMachine($this->name);
Log::channel('detail')->info("==================");
Log::channel('detail')->info($vmware_id);
return $vmware_id;
}
public function failed(\Throwable $error)
{
Log::channel('error')->info($error->getMessage());
}
}
@@ -1,95 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Handle;
use App\Events\VirtualMachine_Panel_Status;
use App\Http\Services\vCenter as ServiceVCenter;
use App\Models\ModuleVmware;
use Illuminate\Bus\Queueable;
use Illuminate\Console\Scheduling\Event;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class WaitStatusVirtualMachine implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected int $productId;
protected bool $status;
public function __construct(int $productId, bool $status)
{
$this->productId = $productId;
$this->status = $status;
}
public function handle(ServiceVCenter $serviceVCenter)
{
$product = ModuleVmware::with(['IpAddress.Host.Datacenter.vCenter'])->find($this->productId);
if (!$product || !$product->IpAddress?->Host?->Datacenter?->vCenter) {
Log::error("WaitStatusVirtualMachine: Product {$this->productId} missing vCenter relationship");
return;
}
$vcenter = $product->IpAddress->Host->Datacenter->vCenter;
$serviceVCenter->setConnection($vcenter->host, $vcenter->token);
$vmwareId = $product->vmware_id;
$userId = $product->customer_id;
Log::info("WaitStatusVirtualMachine: Started for VM {$vmwareId}, Target Status: " . ($this->status ? 'True' : 'False'));
$status = $serviceVCenter->CheckVirtualMachine($vmwareId);
if ($status['error'] === true) {
Log::error("WaitStatusVirtualMachine: Error checking status for VM {$vmwareId}: " . json_encode($status['message']));
throw new \Exception(json_encode($status['message']));
}
Log::info("WaitStatusVirtualMachine: Initial operations_ready: " . ($status['data']['operations_ready'] ? 'True' : 'False'));
if ($status['data']['operations_ready'] === $this->status) {
Log::info("WaitStatusVirtualMachine: Entering wait loop...");
do {
sleep(10);
$status = $serviceVCenter->CheckVirtualMachine($vmwareId);
if ($status['error'] === true) {
Log::warning("WaitStatusVirtualMachine: Failed to check status in loop. Breaking.");
break;
}
Log::info("WaitStatusVirtualMachine: Loop check - operations_ready: " . ($status['data']['operations_ready'] ? 'True' : 'False'));
} while ($status['data']['operations_ready'] === $this->status);
} else {
Log::info("WaitStatusVirtualMachine: Skipping wait loop, condition already met.");
}
\Illuminate\Support\Facades\Cache::forget(\App\Support\Cache\CacheKey::build('vm', 'info', ['id' => $vmwareId]));
$product->refresh();
if ($product) {
$newStatus = ($this->status === true) ? 0 : 1;
Log::info("WaitStatusVirtualMachine: Setting status to $newStatus");
$product->update(['status' => $newStatus]);
$msg = ($newStatus == 1)
? __('Máy ảo đã hoạt động trở lại.')
: __('Máy ảo đã tắt hoàn toàn.');
$statusStr = ($newStatus == 1) ? 'running' : 'stopped';
\App\Events\VirtualMachineStatusChanged::dispatch($userId, $vmwareId, $statusStr, $msg);
}
Event(new VirtualMachine_Panel_Status('Yêu cầu được xử lý thành công', $userId));
}
}
@@ -1,86 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Power;
use App\Http\Services\vCenter;
use App\Jobs\VirtualMachine\Handle\WaitStatusVirtualMachine;
use App\Models\ModuleVmware;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class RebootVmJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 120;
public $tries = 3;
protected $productId;
protected $userId;
/**
* Create a new job instance.
*/
public function __construct($productId, $userId)
{
$this->productId = $productId;
$this->userId = $userId;
}
/**
* Execute the job.
*/
public function handle(vCenter $vCenterService)
{
Log::info("Job RebootVmJob started for Product ID: {$this->productId}");
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter')->find($this->productId);
if (!$product) {
Log::error("RebootVmJob: Product not found ID: {$this->productId}");
return;
}
try {
$result = $vCenterService->RebootVirtualMachine($product, $product->vmware_id);
if ($result === 'Login_Again') {
$vCenterService->loginServer($product->ipAddress->host->datacenter->vCenter);
$result = $vCenterService->RebootVirtualMachine($product, $product->vmware_id);
}
if (is_array($result) && isset($result['error']) && $result['error'] === false) {
Log::info("RebootVmJob: Command sent successfully for VM {$product->vmware_id}");
// Clear VM info cache
\Illuminate\Support\Facades\Cache::forget(\App\Support\Cache\CacheKey::build('vm', 'info', ['id' => $product->vmware_id]));
// Dispatch Event to Frontend
\App\Events\VirtualMachineStatusChanged::dispatch(
$this->userId,
$product->vmware_id,
'rebooted',
__('Máy ảo đã được khởi động lại thành công.')
);
$product->update(['status' => 3]); // Processing
// In VMJobs: $jobs = new WaitStatusVirtualMachine($product->vmware_id,$serviceVCenter,$product->customer_id,false);
dispatch(new WaitStatusVirtualMachine($this->productId, false))->delay(now()->addSeconds(5));
} else {
$msg = is_array($result) ? ($result['data'] ?? 'Unknown error') : $result;
Log::error("RebootVmJob: Failed for VM {$product->vmware_id}. Error: {$msg}");
}
} catch (\Exception $e) {
Log::error("RebootVmJob: Exception for VM {$product->vmware_id}: " . $e->getMessage());
$this->fail($e);
}
}
}
@@ -1,97 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Power;
use App\Http\Services\vCenter;
use App\Jobs\VirtualMachine\Handle\WaitStatusVirtualMachine;
use App\Models\ModuleVmware;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class StartVmJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 120; // 2 minutes
public $ries = 3;
protected $productId;
protected $userId;
/**
* Create a new job instance.
*/
public function __construct($productId, $userId)
{
$this->productId = $productId;
$this->userId = $userId;
}
/**
* Execute the job.
*/
public function handle(vCenter $vCenterService)
{
Log::info("Job StartVmJob started for Product ID: {$this->productId}");
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter')->find($this->productId);
if (!$product) {
Log::error("StartVmJob: Product not found ID: {$this->productId}");
return;
}
try {
// Call vCenter Service
$result = $vCenterService->StartVirtualMachine($product, $product->vmware_id);
// Check for Login_Again
if ($result === 'Login_Again') {
$vCenterService->loginServer($product->ipAddress->host->datacenter->vCenter);
$result = $vCenterService->StartVirtualMachine($product, $product->vmware_id);
}
if (is_array($result) && isset($result['error']) && $result['error'] === false) {
Log::info("StartVmJob: Command sent successfully for VM {$product->vmware_id}");
// Clear VM info cache
\Illuminate\Support\Facades\Cache::forget(\App\Support\Cache\CacheKey::build('vm', 'info', ['id' => $product->vmware_id]));
// Dispatch Event to Frontend
\App\Events\VirtualMachineStatusChanged::dispatch(
$this->userId,
$product->vmware_id,
'running',
__('Máy ảo đã được khởi động thành công.')
);
// Update status to 'processing' (e.g., 3) if needed, or leave it to WaitStatus
$product->update(['status' => 3]); // 3 = Processing/Pending
// Dispatch wait status job
// Note: WaitStatusVirtualMachine expects ($vmware_id, $service, $user, $status_to_wait_for?)
// Looking at existing code:
// $status = 2; // Suspend
// $jobs = new WaitStatusVirtualMachine($product->vmware_id,$serviceVCenter,$product->customer_id,true); (true = wait for operations_ready?)
// For Start:
// $jobs = new WaitStatusVirtualMachine($product->vmware_id, $serviceVCenter, $product->customer_id, false);
dispatch(new WaitStatusVirtualMachine($this->productId, false))->delay(now()->addSeconds(5));
} else {
$msg = is_array($result) ? ($result['data'] ?? 'Unknown error') : $result;
Log::error("StartVmJob: Failed for VM {$product->vmware_id}. Error: {$msg}");
// Optionally notify user via Pusher/Telegram here
}
} catch (\Exception $e) {
Log::error("StartVmJob: Exception for VM {$product->vmware_id}: " . $e->getMessage());
$this->fail($e);
}
}
}
@@ -1,84 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Power;
use App\Http\Services\vCenter;
use App\Jobs\VirtualMachine\Handle\WaitStatusVirtualMachine;
use App\Models\ModuleVmware;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
class StopVmJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public $timeout = 120;
public $tries = 3;
protected $productId;
protected $userId;
/**
* Create a new job instance.
*/
public function __construct($productId, $userId)
{
$this->productId = $productId;
$this->userId = $userId;
}
/**
* Execute the job.
*/
public function handle(vCenter $vCenterService)
{
Log::info("Job StopVmJob started for Product ID: {$this->productId}");
$product = ModuleVmware::with('ipAddress.host.datacenter.vCenter')->find($this->productId);
if (!$product) {
Log::error("StopVmJob: Product not found ID: {$this->productId}");
return;
}
try {
// Call vCenter Service - Graceful Shutdown
$result = $vCenterService->ShutdownGuestVirtualMachine($product, $product->vmware_id);
// Check for Login_Again
if ($result === 'Login_Again') {
$vCenterService->loginServer($product->ipAddress->host->datacenter->vCenter);
$result = $vCenterService->ShutdownGuestVirtualMachine($product, $product->vmware_id);
}
if (is_array($result) && isset($result['error']) && $result['error'] === false) {
// Clear VM info cache
\Illuminate\Support\Facades\Cache::forget(\App\Support\Cache\CacheKey::build('vm', 'info', ['id' => $product->vmware_id]));
// Dispatch Event to Frontend
\App\Events\VirtualMachineStatusChanged::dispatch(
$this->userId,
$product->vmware_id,
'stopped',
__('Máy ảo đã được tắt thành công.')
);
$product->update(['status' => 3]); // Processing
dispatch(new WaitStatusVirtualMachine($this->productId, true))->delay(now()->addSeconds(5));
} else {
$msg = is_array($result) ? ($result['data'] ?? 'Unknown error') : $result;
Log::error("StopVmJob: Failed for VM {$product->vmware_id}. Error: {$msg}");
}
} catch (\Exception $e) {
Log::error("StopVmJob: Exception for VM {$product->vmware_id}: " . $e->getMessage());
$this->fail($e);
}
}
}
@@ -6,12 +6,9 @@ namespace App\Jobs\VirtualMachine\Provision;
use App\Http\Facade\SignRSA;
use App\Http\Services\Telegram;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use App\Models\ModuleVmware;
use App\Models\Os;
use App\Models\Service;
use App\Models\VirtualMachines;
use App\Http\Services\vCenter as vCenterService;
use App\Models\vCenter;
use App\Services\VirtualMachine\VmProvisionLogger;
@@ -26,6 +23,7 @@ use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Jobs\VirtualMachine\Provision\Concerns\ManagesIpReservation;
/**
* AssignIpToGuestJob
*
@@ -48,6 +46,7 @@ use Illuminate\Support\Facades\Log;
class AssignIpToGuestJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
use ManagesIpReservation;
/** All retries handled internally — no Laravel-level retry needed */
public int $tries = 1;
@@ -318,181 +317,6 @@ class AssignIpToGuestJob implements ShouldQueue
// IP reservation helpers
// ─────────────────────────────────────────────────────────────────────────
/**
* Reserve a free IP from the pool inside a DB transaction with row-level locks.
*
* Strategy:
* 1. Lock all existing ModuleIpAddress rows for the network → prevents double-pick
* 2. Lock the chosen IpPool row → prevents concurrent reservations
* 3. Create a pending ModuleIpAddress (status=0) to hold the slot
*
* Returns the pending ModuleIpAddress record, or null if pool is exhausted.
*/
/**
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
*/
private function reserveIp(
int $networkId,
int $hostId,
string $dns,
): ?array {
return DB::transaction(function () use ($networkId, $hostId, $dns) {
// ip_pools.status is the single source of truth for availability.
$ipPool = IpPool::where('module_network_id', $networkId)
->whereIn('status', ['free', 'reserved'])
->lockForUpdate()
->inRandomOrder()
->first();
if (!$ipPool) {
return null;
}
// Hold the pool slot
$ipPool->update(['status' => 'reserved']);
$cidr = (int) ($ipPool->cidr ?: 24);
$gateway = (string) ($ipPool->gateway ?? '');
$netmask = $ipPool->netmask ?: $this->cidrToNetmask($cidr);
// module_ip_address mirrors ip_pools — update the existing synced row
// (created when the IP was added to ip_pools) instead of inserting a new one.
$reservation = ModuleIpAddress::where('ip', $ipPool->ip_address)
->where('module_network_id', $networkId)
->lockForUpdate()
->first();
$attrs = [
'vm_name' => '__pending__',
'module_host_id' => $hostId,
'module_network_id' => $networkId,
'ip' => $ipPool->ip_address,
'gateway' => $gateway,
'netmask' => $netmask,
'dns' => $dns,
'status' => 0, // 0 = pending/reserved, not yet confirmed
];
if ($reservation) {
$reservation->update($attrs);
} else {
$reservation = ModuleIpAddress::create($attrs);
}
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPool->id,
'gateway' => $gateway,
'cidr' => $cidr,
];
});
}
/**
* Load a reservation that was created upstream (e.g. by CreateVirtualMachineJob).
* Returns the same shape as reserveIp() so the rest of the flow is identical.
*
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
*/
private function loadReservation(int $reservationId, ?int $ipPoolId, VmProvisionLogger $logger): ?array
{
$reservation = ModuleIpAddress::find($reservationId);
if (!$reservation) {
$logger->error('upstream reservation missing', [
'reservation_id' => $reservationId,
]);
return null;
}
$ipPool = $ipPoolId ? IpPool::find($ipPoolId) : null;
$cidr = (int) ($ipPool->cidr ?? 24);
$gateway = (string) ($reservation->gateway ?: ($ipPool->gateway ?? ''));
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPoolId ?? 0,
'gateway' => $gateway,
'cidr' => $cidr ?: 24,
];
}
/**
* Release a failed reservation by resetting the mirrored ModuleIpAddress row.
* This returns the IP to the available pool.
*/
private function releaseIp(ModuleIpAddress $reservation, ?int $ipPoolId, VmProvisionLogger $logger): void
{
try {
$reservation->update(['vm_name' => null, 'status' => 0]);
if ($ipPoolId) {
IpPool::where('id', $ipPoolId)->update(['status' => 'free']);
}
$logger->step('IP reservation released', ['ip' => $reservation->ip]);
} catch (\Throwable $e) {
$logger->warning('could not release IP reservation', [
'ip' => $reservation->ip,
'error' => $e->getMessage(),
]);
}
}
/**
* Confirm a successful IP assignment:
* - Update ModuleIpAddress: status → 1 (assigned), vm_name → real name
* - Update ModuleVmware: ip, dns, module_ip_address FK
* - Update VirtualMachines: ip, ip_pool_id FK (matched by vmId)
*
* IP is only written to DB AFTER guest-side verification passes.
*/
private function persistIp(
ModuleIpAddress $reservation,
ModuleVmware $moduleVmware,
?int $ipPoolId,
?int $serviceId,
): void {
DB::transaction(function () use ($reservation, $moduleVmware, $ipPoolId, $serviceId) {
$reservation->update([
'vm_name' => $moduleVmware->name ?? ('VM-' . $this->vmId),
'status' => 1, // assigned
]);
$moduleVmware->update([
'ip' => $reservation->ip,
'dns' => $reservation->dns,
'module_ip_address' => $reservation->id,
]);
// Sync to virtual_machines — matched by vSphere vmId
VirtualMachines::where('vm_id', $this->vmId)->update([
'ip' => $reservation->ip,
'ip_pool_id' => $ipPoolId,
]);
// Flip ip_pools row to assigned and link service
if ($ipPoolId) {
IpPool::where('id', $ipPoolId)->update([
'status' => 'assigned',
'service_id' => $serviceId,
]);
}
// Touch services row so server_name reflects the provisioned VM.
// Note: services.vm_id is an FK to module_vmware.id (already set by VmServiceSyncService) — do not overwrite with vSphere vmId string.
if ($serviceId) {
Service::where('id', $serviceId)->update([
'server_name' => $moduleVmware->name,
]);
}
});
}
/** Convert CIDR prefix length to dotted-decimal netmask (e.g. 24 → 255.255.255.0). */
private function cidrToNetmask(int $cidr): string
{
$cidr = max(0, min(32, $cidr));
return long2ip(-1 << (32 - $cidr));
}
// ─────────────────────────────────────────────────────────────────────────
// Micro-helpers
// ─────────────────────────────────────────────────────────────────────────
@@ -507,5 +331,4 @@ class AssignIpToGuestJob implements ShouldQueue
$data = json_decode(trim($output), true);
return is_array($data) && ($data['status'] ?? '') === 'ok';
}
}
@@ -1,138 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs\VirtualMachine\Provision;
use App\Services\VmProvisionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
/**
* ChangePasswordJob
*
* Connects to the VM via SSH (Linux) or WinRM (Windows) using the
* template default password (TGS@123), then:
* [7] Generates a new secure 16-char password
* [8] Changes the password on the OS
* [9] Verifies the new password works (re-login)
* [10] Saves encrypted password + plain_password to module_vmware
* [11] Dispatches SendVmCredentialsEmailJob
*
* Uses the REAL IP reported by VMware Tools (from WaitVmReadyJob),
* NOT the IP pool address.
*
* Up to 3 job-level retries if an unexpected error occurs.
*/
class ChangePasswordJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
/** SSH + WinRM operations should complete within 2 min */
public int $timeout = 120;
public function __construct(
public readonly int $moduleVmwareId,
public readonly string $vmId,
public readonly string $guestIp, // real IP from VMware Tools
public readonly string $osFamily, // VmProvisionService::OS_LINUX | OS_WINDOWS
public readonly string $username, // root | Administrator
) {}
public function handle(VmProvisionService $provision): void
{
Log::info('ChangePasswordJob: starting', [
'vm_id' => $this->vmId,
'ip' => $this->guestIp,
'os_family' => $this->osFamily,
'username' => $this->username,
]);
// [7] Generate secure password
$newPassword = $provision->generatePassword(16);
// [8] Change password on OS
$this->changePassword($provision, $newPassword);
// [9] Verify new credentials work (critical — throws on failure)
$this->verifyPassword($provision, $newPassword);
// [10] Persist encrypted password + guest IP to DB
$provision->savePassword($this->moduleVmwareId, $this->guestIp, $newPassword);
// [11] Send credentials email
SendVmCredentialsEmailJob::dispatch($this->moduleVmwareId);
Log::info('ChangePasswordJob: completed', [
'vm_id' => $this->vmId,
'module_vmware_id' => $this->moduleVmwareId,
]);
}
public function failed(\Throwable $e): void
{
Log::error('ChangePasswordJob: failed after max retries', [
'vm_id' => $this->vmId,
'module_vmware_id' => $this->moduleVmwareId,
'error' => $e->getMessage(),
]);
\App\Models\ModuleVmware::where('id', $this->moduleVmwareId)
->update(['status' => 0]);
}
// -------------------------------------------------------------------------
private function changePassword(VmProvisionService $provision, string $newPassword): void
{
if ($this->osFamily === VmProvisionService::OS_WINDOWS) {
Log::info('ChangePasswordJob: changing password via WinRM', [
'vm_id' => $this->vmId,
'ip' => $this->guestIp,
]);
$provision->winrmChangePassword(
$this->guestIp,
$this->username,
$newPassword,
$this->vmId,
);
} else {
Log::info('ChangePasswordJob: changing password via SSH', [
'vm_id' => $this->vmId,
'ip' => $this->guestIp,
]);
$provision->sshChangePassword(
$this->guestIp,
$this->username,
$newPassword,
$this->vmId,
);
}
}
private function verifyPassword(VmProvisionService $provision, string $newPassword): void
{
Log::info('ChangePasswordJob: verifying new credentials', [
'vm_id' => $this->vmId,
'ip' => $this->guestIp,
]);
if ($this->osFamily === VmProvisionService::OS_WINDOWS) {
$provision->verifyWinrmLogin($this->guestIp, $this->username, $newPassword, $this->vmId);
} else {
$provision->verifySshLogin($this->guestIp, $this->username, $newPassword, $this->vmId);
}
Log::info('ChangePasswordJob: credential verification passed', [
'vm_id' => $this->vmId,
]);
}
}
@@ -0,0 +1,189 @@
<?php
namespace App\Jobs\VirtualMachine\Provision\Concerns;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use App\Models\ModuleVmware;
use App\Models\Service;
use App\Models\VirtualMachines;
use App\Services\VirtualMachine\VmProvisionLogger;
use Illuminate\Support\Facades\DB;
trait ManagesIpReservation
{
/**
* Reserve a free IP from the pool inside a DB transaction with row-level locks.
*
* Strategy:
* 1. Lock all existing ModuleIpAddress rows for the network → prevents double-pick
* 2. Lock the chosen IpPool row → prevents concurrent reservations
* 3. Create a pending ModuleIpAddress (status=0) to hold the slot
*
* Returns the pending ModuleIpAddress record, or null if pool is exhausted.
*/
/**
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
*/
private function reserveIp(
int $networkId,
int $hostId,
string $dns,
): ?array {
return DB::transaction(function () use ($networkId, $hostId, $dns) {
// ip_pools.status is the single source of truth for availability.
$ipPool = IpPool::where('module_network_id', $networkId)
->whereIn('status', ['free', 'reserved'])
->lockForUpdate()
->inRandomOrder()
->first();
if (!$ipPool) {
return null;
}
// Hold the pool slot
$ipPool->update(['status' => 'reserved']);
$cidr = (int) ($ipPool->cidr ?: 24);
$gateway = (string) ($ipPool->gateway ?? '');
$netmask = $ipPool->netmask ?: $this->cidrToNetmask($cidr);
// module_ip_address mirrors ip_pools — update the existing synced row
// (created when the IP was added to ip_pools) instead of inserting a new one.
$reservation = ModuleIpAddress::where('ip', $ipPool->ip_address)
->where('module_network_id', $networkId)
->lockForUpdate()
->first();
$attrs = [
'vm_name' => '__pending__',
'module_host_id' => $hostId,
'module_network_id' => $networkId,
'ip' => $ipPool->ip_address,
'gateway' => $gateway,
'netmask' => $netmask,
'dns' => $dns,
'status' => 0, // 0 = pending/reserved, not yet confirmed
];
if ($reservation) {
$reservation->update($attrs);
} else {
$reservation = ModuleIpAddress::create($attrs);
}
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPool->id,
'gateway' => $gateway,
'cidr' => $cidr,
];
});
}
/**
* Load a reservation that was created upstream (e.g. by CreateVirtualMachineJob).
* Returns the same shape as reserveIp() so the rest of the flow is identical.
*
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
*/
private function loadReservation(int $reservationId, ?int $ipPoolId, VmProvisionLogger $logger): ?array
{
$reservation = ModuleIpAddress::find($reservationId);
if (!$reservation) {
$logger->error('upstream reservation missing', [
'reservation_id' => $reservationId,
]);
return null;
}
$ipPool = $ipPoolId ? IpPool::find($ipPoolId) : null;
$cidr = (int) ($ipPool->cidr ?? 24);
$gateway = (string) ($reservation->gateway ?: ($ipPool->gateway ?? ''));
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPoolId ?? 0,
'gateway' => $gateway,
'cidr' => $cidr ?: 24,
];
}
/**
* Release a failed reservation by resetting the mirrored ModuleIpAddress row.
* This returns the IP to the available pool.
*/
private function releaseIp(ModuleIpAddress $reservation, ?int $ipPoolId, VmProvisionLogger $logger): void
{
try {
$reservation->update(['vm_name' => null, 'status' => 0]);
if ($ipPoolId) {
IpPool::where('id', $ipPoolId)->update(['status' => 'free']);
}
$logger->step('IP reservation released', ['ip' => $reservation->ip]);
} catch (\Throwable $e) {
$logger->warning('could not release IP reservation', [
'ip' => $reservation->ip,
'error' => $e->getMessage(),
]);
}
}
/**
* Confirm a successful IP assignment:
* - Update ModuleIpAddress: status → 1 (assigned), vm_name → real name
* - Update ModuleVmware: ip, dns, module_ip_address FK
* - Update VirtualMachines: ip, ip_pool_id FK (matched by vmId)
*
* IP is only written to DB AFTER guest-side verification passes.
*/
private function persistIp(
ModuleIpAddress $reservation,
ModuleVmware $moduleVmware,
?int $ipPoolId,
?int $serviceId,
): void {
DB::transaction(function () use ($reservation, $moduleVmware, $ipPoolId, $serviceId) {
$reservation->update([
'vm_name' => $moduleVmware->name ?? ('VM-' . $this->vmId),
'status' => 1, // assigned
]);
$moduleVmware->update([
'ip' => $reservation->ip,
'dns' => $reservation->dns,
'module_ip_address' => $reservation->id,
]);
// Sync to virtual_machines — matched by vSphere vmId
VirtualMachines::where('vm_id', $this->vmId)->update([
'ip' => $reservation->ip,
'ip_pool_id' => $ipPoolId,
]);
// Flip ip_pools row to assigned and link service
if ($ipPoolId) {
IpPool::where('id', $ipPoolId)->update([
'status' => 'assigned',
'service_id' => $serviceId,
]);
}
// Touch services row so server_name reflects the provisioned VM.
// Note: services.vm_id is an FK to module_vmware.id (already set by VmServiceSyncService) — do not overwrite with vSphere vmId string.
if ($serviceId) {
Service::where('id', $serviceId)->update([
'server_name' => $moduleVmware->name,
]);
}
});
}
/** Convert CIDR prefix length to dotted-decimal netmask (e.g. 24 → 255.255.255.0). */
private function cidrToNetmask(int $cidr): string
{
$cidr = max(0, min(32, $cidr));
return long2ip(-1 << (32 - $cidr));
}
}
@@ -1,136 +0,0 @@
<?php
declare(strict_types=1);
namespace App\Jobs\VirtualMachine\Provision;
use App\Http\Services\vCenter as VCenterService;
use App\Services\VmProvisionService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
/**
* WaitVmReadyJob
*
* Polls vSphere REST API every 15 s until VMware Tools is running
* and the guest IP is available. No direct TCP port check is required
* because password changes are performed via Invoke-VMScript (vSphere
* path), not direct SSH/WinRM into the VM.
*
* Max 40 attempts × 15 s ≈ 10 minutes before giving up.
* On success → dispatches ChangePasswordViaVsphereJob.
*/
class WaitVmReadyJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
/** 40 attempts × 15 s release delay ≈ 10 min total */
public int $tries = 40;
/** Each poll attempt must finish within 30 s */
public int $timeout = 30;
public function __construct(
public readonly int $moduleVmwareId,
public readonly string $vmId,
public readonly int $vcenterId,
public readonly string $osFamily, // VmProvisionService::OS_LINUX | OS_WINDOWS
public readonly string $username, // root | Administrator
) {}
// -------------------------------------------------------------------------
public function handle(VCenterService $vCenterService, VmProvisionService $provision): void
{
$attempt = $this->attempts();
Log::info('WaitVmReadyJob: polling', [
'vm_id' => $this->vmId,
'attempt' => $attempt,
'os_family' => $this->osFamily,
]);
// ── 1. Login to vCenter ───────────────────────────────────────────────
$vcenter = \App\Models\vCenter::find($this->vcenterId);
if (!$vcenter) {
Log::error('WaitVmReadyJob: vCenter model not found', ['vcenter_id' => $this->vcenterId]);
$this->fail(new \RuntimeException("vCenter id={$this->vcenterId} not found"));
return;
}
try {
$provision->loginVCenter($vcenter, $vCenterService);
} catch (\Throwable $e) {
Log::warning('WaitVmReadyJob: vCenter login failed, will retry', [
'vm_id' => $this->vmId,
'error' => $e->getMessage(),
]);
$this->releaseOrFail(15, $attempt);
return;
}
// ── 2. Check VMware Tools + guest IP ─────────────────────────────────
// Invoke-VMScript requires VMware Tools to be running inside the guest.
$guest = $provision->getVmGuestInfo($vCenterService, $this->vmId);
Log::info('WaitVmReadyJob: guest info', [
'vm_id' => $this->vmId,
'attempt' => $attempt,
'tools_running' => $guest['tools_running'],
'ip_address' => $guest['ip_address'],
]);
if (!$guest['tools_running'] || $guest['ip_address'] === null) {
Log::info('WaitVmReadyJob: VMware Tools not ready yet', ['vm_id' => $this->vmId]);
$this->releaseOrFail(15, $attempt);
return;
}
$guestIp = $guest['ip_address'];
// ── 3. VM ready — dispatch password-change job ────────────────────────
Log::info('WaitVmReadyJob: VMware Tools ready, dispatching ChangePasswordViaVsphereJob', [
'vm_id' => $this->vmId,
'guest_ip' => $guestIp,
]);
ChangePasswordViaVsphereJob::dispatch(
$this->moduleVmwareId,
$this->vmId,
$this->osFamily,
);
}
// -------------------------------------------------------------------------
public function failed(\Throwable $e): void
{
Log::error('WaitVmReadyJob: exceeded max attempts, marking VM failed', [
'vm_id' => $this->vmId,
'module_vmware_id' => $this->moduleVmwareId,
'error' => $e->getMessage(),
]);
\App\Models\ModuleVmware::where('id', $this->moduleVmwareId)
->update(['status' => 0]);
}
// -------------------------------------------------------------------------
private function releaseOrFail(int $delaySeconds, int $attempt): void
{
if ($attempt >= $this->tries) {
$this->fail(new \RuntimeException(
"VM {$this->vmId} not ready after {$this->tries} attempts (~10 min)",
));
return;
}
$this->release($delaySeconds);
}
}
@@ -10,7 +10,6 @@ use App\Jobs\Mail\Customer\VmRebuildFailedJob;
use App\Jobs\Mail\SendInformationVirtualMachine;
use App\Models\Invoice;
use App\Models\ModuleVmware;
use App\Models\Service;
use App\Models\ReinstallLog;
use App\Models\Setting;
use App\Services\VirtualMachine\Rebuild\VmRebuildService;
@@ -1,157 +0,0 @@
<?php
namespace App\Jobs\VirtualMachine\Sync;
use App\Http\Services\vCenter;
use App\Models\Invoice;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
class UpdateVMInfoJob implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public int $tries = 3;
public int $timeout = 30;
public int $backoff = 60; // Wait 1 minute between retries
protected int $invoiceId;
protected string $vmId;
/**
* Create a new job instance.
*/
public function __construct(int $invoiceId, string $vmId)
{
$this->invoiceId = $invoiceId;
$this->vmId = $vmId;
}
/**
* Execute the job.
*/
public function handle(vCenter $vCenterService): void
{
try {
$invoice = Invoice::with([
'invoiceItem.os.osGroup',
'invoiceItem.addons'
])->find($this->invoiceId);
if (!$invoice) {
Log::warning('Invoice not found for VM info update', ['invoice_id' => $this->invoiceId]);
return;
}
$orderItem = $invoice->invoiceItem->first();
if (!$orderItem) {
Log::warning('Order item not found for invoice', ['invoice_id' => $this->invoiceId]);
return;
}
$product = $orderItem->getProductAttribute();
if (!$product) {
Log::warning('Product not found for order item', ['order_item_id' => $orderItem->id]);
return;
}
$host = $product->host;
$datacenter = $host?->datacenter;
$vcenter = $datacenter?->vcenter;
if (!$vcenter) {
Log::warning('vCenter not found for VM', ['vm_id' => $this->vmId]);
return;
}
// Login to vCenter
if (!$vCenterService->loginServer($vcenter)) {
Log::warning('Failed to login to vCenter', ['vm_id' => $this->vmId]);
return;
}
// Get VM details
$vmDetail = $vCenterService->GetDetailVirtualMachine($this->vmId);
if ($vmDetail['error'] === true) {
Log::warning('Failed to get VM details', ['vm_id' => $this->vmId, 'error' => $vmDetail['message'] ?? 'Unknown error']);
return;
}
$vmData = $vmDetail['data'];
// Get IP information
$ipInfo = $vCenterService->GetIPAddressVirtualMachine($this->vmId);
$ipAddress = 'N/A';
if ($ipInfo['error'] === false && !empty($ipInfo['data']['ip_addresses'])) {
$ipAddress = $ipInfo['data']['ip_addresses'][0] ?? 'N/A';
}
// Calculate hardware information
$cpuCount = $vmData['cpu']['count'] ?? 1;
$memoryMB = $vmData['memory']['size_MiB'] ?? 1024;
$memoryGB = round($memoryMB / 1024, 1);
$diskSizeGB = 0;
if (isset($vmData['disks']) && is_array($vmData['disks'])) {
foreach ($vmData['disks'] as $disk) {
$diskSizeGB += round(($disk['value']['capacity'] ?? 0) / (1024 * 1024 * 1024), 1);
}
}
$vmInfo = [
'vm_id' => $this->vmId,
'status' => $vmData['power_state'],
'ip_address' => $ipAddress,
'hostname' => $orderItem->server_name ?? 'Unknown',
'os' => $orderItem->os->osGroup->name ?? 'Unknown',
'cpu' => $cpuCount . ' cores',
'ram' => $memoryGB . ' GB',
'disk' => $diskSizeGB . ' GB',
'uptime' => 'N/A',
'last_updated' => now()->format('Y-m-d H:i:s'),
'vm_name' => $vmData['name'] ?? 'Unknown',
'vm_folder' => $vmData['folder'] ?? 'Unknown',
'vm_resource_pool' => $vmData['resource_pool'] ?? 'Unknown',
'vm_datastore' => $vmData['datastore'] ?? 'Unknown',
'vm_network' => $vmData['nics'][0]['backing']['network'] ?? 'Unknown',
'vm_mac' => $vmData['nics'][0]['mac_address'] ?? 'N/A',
'vm_guest_id' => $vmData['guest_ID'] ?? 'Unknown',
'vm_version' => $vmData['version'] ?? 'Unknown',
'vm_hardware_version' => $vmData['hardware']['version'] ?? 'Unknown',
];
// Cache the result for 5 minutes
$cacheKey = \App\Support\Cache\CacheKey::build('vm', 'info', ['id' => $this->vmId]);
Cache::put($cacheKey, $vmInfo, 300);
Log::info('VM info updated successfully', ['vm_id' => $this->vmId]);
} catch (\Exception $e) {
Log::error('Error updating VM info', [
'vm_id' => $this->vmId,
'invoice_id' => $this->invoiceId,
'error' => $e->getMessage()
]);
// Don't throw exception to prevent job from failing completely
// The job will be retried automatically
}
}
/**
* Handle a job failure.
*/
public function failed(\Throwable $exception): void
{
Log::error('UpdateVMInfoJob failed', [
'vm_id' => $this->vmId,
'invoice_id' => $this->invoiceId,
'error' => $exception->getMessage()
]);
}
}