Files
pbao9 5043bea79a 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.
2026-04-16 23:21:27 +07:00

209 lines
7.8 KiB
PHP

<?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(),
]);
}
}
}