feat: Add IP address and DNS fields to module_vmware table
- Introduced `ip` and `dns` columns to the `module_vmware` table to store assigned IP addresses and DNS configurations. - Implemented `ChangePasswordViaSshJob` for secure password changes via SSH. - Created `ChangePasswordJob` for handling password changes during VM provisioning. - Developed `ChangePasswordViaVsphereJob` to reset VM guest OS passwords using PowerShell scripts executed on the vSphere host. - Added `SendVmCredentialsEmailJob` to send final VM credentials to customers. - Implemented `WaitVmReadyJob` to poll vSphere API until VMware Tools are running and guest IP is available. - Created `VmProvisionService` for managing VM provisioning tasks, including password generation and updates. - Developed `VsphereHostSshService` for executing PowerShell scripts on the vSphere host via SSH. - Added `IpPoolSeeder` to populate IP pools for VM service initialization.
This commit is contained in:
@@ -0,0 +1,192 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Jobs\VirtualMachine\Create;
|
||||
|
||||
use App\Http\Facade\SignRSA;
|
||||
use App\Jobs\Mail\SendInformationVirtualMachine;
|
||||
use App\Models\ModuleVmware;
|
||||
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 ChangePasswordViaSshJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
public int $tries = 3;
|
||||
public int $backoff = 120;
|
||||
|
||||
public function __construct(
|
||||
public readonly int $moduleVmwareId,
|
||||
public readonly string $ip,
|
||||
public readonly string $username,
|
||||
public readonly string $initialPassword,
|
||||
public readonly string $newPassword,
|
||||
) {}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
public function handle(): void
|
||||
{
|
||||
Log::info('ChangePasswordViaSshJob: starting', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'ip' => $this->ip,
|
||||
'username' => $this->username,
|
||||
]);
|
||||
|
||||
$output = $this->runWithRetry();
|
||||
|
||||
if ($output === null) {
|
||||
$this->fail(new \RuntimeException(
|
||||
"SSH connection to {$this->ip} failed after max attempts"
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
Log::info('ChangePasswordViaSshJob: chpasswd output', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'output' => trim($output),
|
||||
]);
|
||||
|
||||
// Update DB
|
||||
$vm = ModuleVmware::find($this->moduleVmwareId);
|
||||
|
||||
if (!$vm) {
|
||||
Log::error('ChangePasswordViaSshJob: ModuleVmware not found', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$vm->update([
|
||||
'password' => SignRSA::EncryptFunc($this->newPassword),
|
||||
'plain_password' => $this->newPassword,
|
||||
]);
|
||||
|
||||
$this->sendPasswordEmail($vm);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Run chpasswd on the remote VM via sshpass + native SSH.
|
||||
* Retries up to 10 times with 30 s delay (VM may still be booting).
|
||||
*/
|
||||
private function runWithRetry(int $maxAttempts = 10, int $sleepSeconds = 30): ?string
|
||||
{
|
||||
// Remote bash command: echo 'user:pass' | chpasswd
|
||||
$credential = $this->username . ':' . $this->newPassword;
|
||||
$remoteCmd = 'echo ' . escapeshellarg($credential) . ' | chpasswd 2>&1';
|
||||
|
||||
$sshCmd = sprintf(
|
||||
'sshpass -p %s ssh -o StrictHostKeyChecking=no -o ConnectTimeout=10 -p 22 %s@%s %s 2>&1',
|
||||
escapeshellarg($this->initialPassword),
|
||||
escapeshellarg($this->username),
|
||||
escapeshellarg($this->ip),
|
||||
escapeshellarg($remoteCmd),
|
||||
);
|
||||
|
||||
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
|
||||
$output = shell_exec($sshCmd);
|
||||
|
||||
// null = shell_exec failed (command not found, etc.)
|
||||
// sshpass exits non-zero on connection failure → output contains error text
|
||||
if ($output !== null && !$this->isSshConnectionError($output)) {
|
||||
Log::info('ChangePasswordViaSshJob: SSH connected', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'attempt' => $attempt,
|
||||
]);
|
||||
return $output;
|
||||
}
|
||||
|
||||
Log::warning('ChangePasswordViaSshJob: SSH not ready, retrying', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'attempt' => $attempt,
|
||||
'output_preview' => substr((string) $output, 0, 200),
|
||||
]);
|
||||
|
||||
if ($attempt < $maxAttempts) {
|
||||
sleep($sleepSeconds);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect SSH connection failures (not auth errors) in sshpass output.
|
||||
*/
|
||||
private function isSshConnectionError(string $output): bool
|
||||
{
|
||||
$lower = strtolower($output);
|
||||
|
||||
return str_contains($lower, 'connection refused')
|
||||
|| str_contains($lower, 'no route to host')
|
||||
|| str_contains($lower, 'connection timed out')
|
||||
|| str_contains($lower, 'host is down')
|
||||
|| str_contains($lower, 'network is unreachable');
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
public function failed(\Throwable $e): void
|
||||
{
|
||||
Log::error('ChangePasswordViaSshJob: failed', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'ip' => $this->ip,
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────
|
||||
|
||||
private function sendPasswordEmail(ModuleVmware $vm): void
|
||||
{
|
||||
try {
|
||||
$customer = $vm->customer;
|
||||
|
||||
if (!$customer) {
|
||||
Log::error('ChangePasswordViaSshJob: customer not found', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
return;
|
||||
}
|
||||
|
||||
$setting = Setting::where('key', 'setting')->first();
|
||||
$settingValue = $setting ? json_decode((string) $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' => $this->ip,
|
||||
'service_username' => $this->username,
|
||||
'service_port' => 22,
|
||||
'service_password' => $this->newPassword,
|
||||
'os_name' => ($vm->os?->osGroup?->name ?? '') . ' ' . ($vm->os?->version ?? ''),
|
||||
'service_due_exp' => $vm->next_due_date ? date('d/m/Y', (int) $vm->next_due_date) : 'N/A',
|
||||
];
|
||||
|
||||
SendInformationVirtualMachine::dispatch($emailData, $customer)
|
||||
->delay(now()->addSeconds(5));
|
||||
|
||||
Log::info('ChangePasswordViaSshJob: email dispatched', [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
'customer_email' => $customer->email,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
Log::error('ChangePasswordViaSshJob: email failed: ' . $e->getMessage(), [
|
||||
'module_vmware_id' => $this->moduleVmwareId,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
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;
|
||||
@@ -36,87 +38,171 @@ class ConfigCLICommand implements ShouldQueue
|
||||
*/
|
||||
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 {
|
||||
$vm = \App\Models\ModuleVmware::where('vmware_id', $this->vmware_id)->first();
|
||||
if ($vm) {
|
||||
$vm->update([
|
||||
'password' => \App\Http\Facade\SignRSA::EncryptFunc($PasswordVirtualMachine),
|
||||
'plain_password' => $PasswordVirtualMachine,
|
||||
]);
|
||||
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('❌ Lỗi khi lưu password: ' . $e->getMessage());
|
||||
Log::error('❌ ConfigCLICommand: Error during configuration', [
|
||||
'vmware_id' => $this->vmware_id,
|
||||
'error' => $e->getMessage(),
|
||||
'trace' => $e->getTraceAsString(),
|
||||
]);
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
switch (true) {
|
||||
case (str_contains($this->data->Os->OsGroup->name, "Windows") && str_contains($this->data->Os->version, 10)):
|
||||
$usersName = 'administrator';
|
||||
$port = 533892;
|
||||
$this->serviceVCenter->ConfigWindowsVersion10($this->vmware_id, $this->data, $PasswordVirtualMachine);
|
||||
break;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
case (str_contains($this->data->Os->OsGroup->name, "Windows")):
|
||||
$usersName = 'administrator';
|
||||
$port = 53389;
|
||||
$this->serviceVCenter->ConfigWindowsServer($this->vmware_id, $this->data,
|
||||
$PasswordVirtualMachine);
|
||||
$setting = Setting::where('key', 'setting')->first();
|
||||
$settingValue = $setting ? json_decode($setting->value) : null;
|
||||
|
||||
break;
|
||||
$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',
|
||||
];
|
||||
|
||||
case (str_contains($this->data->Os->OsGroup->name, "CentOS") && str_contains($this->data->Os->version, 7)):
|
||||
$usersName = 'root';
|
||||
$port = 22;
|
||||
$this->serviceVCenter->ConfigCentOSVersion7($this->vmware_id, $this->data,
|
||||
$PasswordVirtualMachine);
|
||||
SendInformationVirtualMachine::dispatch($emailData, $customer)
|
||||
->delay(now()->addSeconds(10));
|
||||
|
||||
break;
|
||||
|
||||
case (str_contains($this->data->Os->OsGroup->name, "CentOS") && str_contains($this->data->Os->version, 8)):
|
||||
$usersName = 'root';
|
||||
$port = 22;
|
||||
$this->serviceVCenter->ConfigCentOSVersion8($this->vmware_id, $this->data,
|
||||
$PasswordVirtualMachine);
|
||||
|
||||
break;
|
||||
|
||||
case (str_contains($this->data->Os->OsGroup->name, "Ubuntu")):
|
||||
$usersName = 'root';
|
||||
$port = 22;
|
||||
$this->serviceVCenter->ConfigVirtualMachineUbuntu($this->vmware_id, $this->data,
|
||||
$PasswordVirtualMachine);
|
||||
break;
|
||||
|
||||
case (str_contains($this->data->Os->OsGroup->name, "Rocky")):
|
||||
$usersName = 'root';
|
||||
$port = 22;
|
||||
$this->serviceVCenter->ConfigRockyLinuxVersion9($this->vmware_id, $this->data,
|
||||
$PasswordVirtualMachine);
|
||||
break;
|
||||
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(),
|
||||
]);
|
||||
}
|
||||
sleep(20);
|
||||
|
||||
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
|
||||
|
||||
if ($VirtualMachine['data']['operations_ready'] === false) {
|
||||
do {
|
||||
sleep(10);
|
||||
|
||||
$VirtualMachine = $this->serviceVCenter->CheckVirtualMachine($this->vmware_id);
|
||||
|
||||
Log::channel('Custom')->info(json_encode($VirtualMachine));
|
||||
} while ($VirtualMachine['data']['operations_ready'] !== true);
|
||||
|
||||
}
|
||||
if (str_contains($this->data->Os->OsGroup->name, "Windows"))
|
||||
{
|
||||
$this->serviceVCenter->ConfigFixWindowsClick($this->vmware_id, $this->data);
|
||||
}
|
||||
$jobs_CheckIP = new CheckIPAddress($this->vmware_id,$this->data,['user' => $usersName,'password' => $PasswordVirtualMachine,'port' => $port],$this->serviceVCenter);
|
||||
dispatch($jobs_CheckIP)->delay(now()->addSeconds(5));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,9 +72,9 @@ class ConfigDatabase implements ShouldQueue
|
||||
'service_due_exp' => Carbon::parse($this->data->next_due_date)->format('d/m/Y')
|
||||
];
|
||||
|
||||
$mail = new SendInformationVirtualMachine($data, $this->data->Customer);
|
||||
|
||||
dispatch($mail)->delay(now()->addSeconds(5));
|
||||
// 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));
|
||||
|
||||
@@ -6,8 +6,9 @@ use App\Http\Facade\SignRSA;
|
||||
use App\Http\Services\Telegram;
|
||||
use App\Http\Services\vCenter;
|
||||
use App\Jobs\Mail\Customer\VMCreationFailedJob;
|
||||
use App\Jobs\VirtualMachine\Create\AssignIPJob;
|
||||
use App\Jobs\VirtualMachine\Create\ConfigCLICommand;
|
||||
use App\Jobs\Mail\SendInformationVirtualMachine;
|
||||
use App\Jobs\VirtualMachine\Provision\ChangePasswordViaVsphereJob;
|
||||
use App\Services\VmProvisionService;
|
||||
use App\Models\OrderItem;
|
||||
use App\Models\Os;
|
||||
use App\Models\ModuleVmware;
|
||||
@@ -15,6 +16,7 @@ use App\Models\ModuleIpAddress;
|
||||
use App\Models\IpPool;
|
||||
use App\Models\Log as CustomerLog;
|
||||
use App\Models\Service;
|
||||
use App\Models\Setting;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Contracts\Queue\ShouldQueue;
|
||||
use Illuminate\Foundation\Bus\Dispatchable;
|
||||
@@ -27,6 +29,12 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
{
|
||||
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
|
||||
|
||||
/** Cho phép job chạy tối đa 10 phút (VM clone có thể mất 5-8 phút) */
|
||||
public int $timeout = 600;
|
||||
|
||||
/** Không retry tự động — lỗi VM cần admin kiểm tra thủ công */
|
||||
public int $tries = 1;
|
||||
|
||||
public OrderItem $item;
|
||||
public bool $isRetry = false;
|
||||
|
||||
@@ -152,6 +160,12 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
}
|
||||
}
|
||||
|
||||
// Xác định OS family để chọn username và luồng cấu hình phù hợp
|
||||
$osGroupName = $osModel->osGroup?->name ?? '';
|
||||
$isWindows = str_contains(strtolower($osGroupName), 'windows');
|
||||
$vmUser = $isWindows ? 'administrator' : 'root';
|
||||
$vmPort = $isWindows ? 3389 : 22;
|
||||
|
||||
$result = $vCenter->CreateVirtualMachine([
|
||||
'item' => $this->item,
|
||||
'host' => $host,
|
||||
@@ -205,10 +219,7 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
// vm_id được lưu vào tbl.services qua ModuleVmwareObserver::created()
|
||||
$startResult = $this->startVirtualMachineDirectly($vCenter, $vmId);
|
||||
|
||||
if (is_array($startResult) && $startResult['error'] === false) {
|
||||
$configJob = new ConfigCLICommand($vmId, $this->item, $vCenter);
|
||||
dispatch($configJob)->delay(now()->addMinutes(2)); // Chờ 2 phút để VM boot hoàn toàn
|
||||
}
|
||||
// VM started — SSH vào vSphere host để đổi mật khẩu qua PS1 script
|
||||
|
||||
try {
|
||||
$customer = $this->item->order->customer;
|
||||
@@ -232,20 +243,19 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
$firstPayment = (int) $this->item->price * ($months ?: 1);
|
||||
$nextDueDate = $months > 0 ? now()->addMonths($months)->timestamp : null;
|
||||
|
||||
$initialPassword = 'TGS@' . \Illuminate\Support\Str::random(8);
|
||||
|
||||
$moduleVmware = ModuleVmware::create([
|
||||
'name' => $serverName,
|
||||
'module_ip_address' => $moduleIpAddress->id,
|
||||
'port' => 22,
|
||||
'ip' => $availableIP,
|
||||
'port' => $vmPort,
|
||||
'order_id' => $this->item->order->id,
|
||||
'first_payment' => $firstPayment,
|
||||
'next_payment' => $firstPayment,
|
||||
'next_due_date' => $nextDueDate,
|
||||
'next_invoice' => $nextDueDate,
|
||||
'user' => 'administrator',
|
||||
'password' => $initialPassword,
|
||||
'plain_password' => $initialPassword,
|
||||
'user' => $vmUser,
|
||||
'password' => VmProvisionService::TEMPLATE_PASSWORD,
|
||||
'plain_password' => VmProvisionService::TEMPLATE_PASSWORD,
|
||||
'hostname' => $serverName,
|
||||
'vmware_id' => $vmId,
|
||||
'vcenter_id' => $vcenter->id,
|
||||
@@ -254,11 +264,21 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
'status' => 1,
|
||||
]);
|
||||
|
||||
// Explicit sync: update services table directly (belt + suspenders vs observer)
|
||||
// Sync services table
|
||||
$this->syncServiceRecord($moduleVmware);
|
||||
|
||||
AssignIPJob::dispatch($vmId, $moduleVmware->id, $moduleIpAddress->ip)
|
||||
->delay(now()->addMinutes(5));
|
||||
// SSH → vSphere host → PS1 → change password → send email
|
||||
ChangePasswordViaVsphereJob::dispatch(
|
||||
$moduleVmware->id,
|
||||
$vmId,
|
||||
$isWindows ? VmProvisionService::OS_WINDOWS : VmProvisionService::OS_LINUX,
|
||||
);
|
||||
|
||||
Log::info('ChangePasswordViaVsphereJob dispatched', [
|
||||
'module_vmware_id' => $moduleVmware->id,
|
||||
'vm_id' => $vmId,
|
||||
'os_family' => $isWindows ? 'WINDOWS' : 'LINUX',
|
||||
]);
|
||||
} catch (\Exception $e) {
|
||||
Log::error('❌ Lỗi khi lưu dữ liệu VM và IP address: ' . $e->getMessage(), [
|
||||
'vmware_id' => $vmId,
|
||||
@@ -380,26 +400,31 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
|
||||
private function getAvailableIPFromPool(int $networkId): string
|
||||
{
|
||||
// Lấy tất cả IP từ IPPool theo network_id, order by ip_address
|
||||
$ipPoolList = IpPool::where('module_network_id', $networkId)
|
||||
->orderBy('ip_address')
|
||||
->get();
|
||||
|
||||
if ($ipPoolList->isEmpty()) {
|
||||
// Nếu không có IP trong pool, trả về IP default
|
||||
return '0.0.0.0';
|
||||
}
|
||||
|
||||
// Lấy tất cả IPs đã được assign trong network này
|
||||
$assignedIPs = ModuleIpAddress::where('module_network_id', $networkId)
|
||||
->pluck('ip')
|
||||
->toArray();
|
||||
|
||||
foreach ($ipPoolList as $ipPool) {
|
||||
if (!in_array($ipPool->ip_address, $assignedIPs)) {
|
||||
return $ipPool->ip_address;
|
||||
}
|
||||
// Lấy ngẫu nhiên 1 IP từ pool chưa được assign
|
||||
$available = IpPool::where('module_network_id', $networkId)
|
||||
->when(!empty($assignedIPs), fn ($q) => $q->whereNotIn('ip_address', $assignedIPs))
|
||||
->inRandomOrder()
|
||||
->first();
|
||||
|
||||
if (!$available) {
|
||||
Log::warning('getAvailableIPFromPool: không còn IP trống trong pool', [
|
||||
'network_id' => $networkId,
|
||||
'assigned_count' => count($assignedIPs),
|
||||
]);
|
||||
return '0.0.0.0';
|
||||
}
|
||||
return '0.0.0.0';
|
||||
|
||||
Log::info('getAvailableIPFromPool: IP được chọn', [
|
||||
'network_id' => $networkId,
|
||||
'ip' => $available->ip_address,
|
||||
]);
|
||||
|
||||
return $available->ip_address;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -504,4 +529,20 @@ class CreateVirtualMachineJob implements ShouldQueue
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gửi email thông báo VM đã khởi tạo thành công cho khách hàng.
|
||||
* Gọi ngay sau khi tạo module_vmware — cho cả Linux lẫn Windows.
|
||||
*/
|
||||
private function getBillingCycleLabel(?int $months): string
|
||||
{
|
||||
return match ($months) {
|
||||
1 => 'Hàng tháng',
|
||||
3 => '3 Tháng',
|
||||
6 => '6 Tháng',
|
||||
12 => 'Hàng năm',
|
||||
24 => '2 Năm',
|
||||
default => $months . ' Tháng',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user