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:
pbao9
2026-04-16 23:21:27 +07:00
parent d68fda2cf0
commit 5043bea79a
16 changed files with 1599 additions and 172 deletions
+141
View File
@@ -0,0 +1,141 @@
<?php
declare(strict_types=1);
namespace App\Services;
use App\Http\Facade\SignRSA;
use App\Http\Services\vCenter as VCenterService;
use App\Models\ModuleVmware;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
final class VmProvisionService
{
/** Default password baked into every VM template */
public const TEMPLATE_PASSWORD = 'TGS@123';
public const OS_LINUX = 'LINUX';
public const OS_WINDOWS = 'WINDOWS';
// -------------------------------------------------------------------------
// vCenter REST helpers (used by WaitVmReadyJob if still in flow)
// -------------------------------------------------------------------------
public function loginVCenter(\App\Models\vCenter $vcenter, VCenterService $service): void
{
if (!$service->loginServer($vcenter)) {
throw new \RuntimeException("vCenter login failed for host={$vcenter->host}");
}
}
/**
* @return array{tools_running:bool,ip_address:string|null,os_family:string|null}
*/
public function getVmGuestInfo(VCenterService $service, string $vmId): array
{
try {
$response = Http::withoutVerifying()
->withHeaders(['vmware-api-session-id' => $service->token])
->timeout(10)
->get("https://{$service->apiUri}/rest/vcenter/vm/{$vmId}/guest/identity");
if (!$response->successful()) {
return ['tools_running' => false, 'ip_address' => null, 'os_family' => null];
}
$value = $response->json('value', []);
$ip = trim((string) ($value['ip_address'] ?? ''));
return [
'tools_running' => $ip !== '' && $ip !== '0.0.0.0',
'ip_address' => $ip ?: null,
'os_family' => isset($value['family']) ? strtoupper((string) $value['family']) : null,
];
} catch (\Throwable $e) {
Log::warning('VmProvisionService::getVmGuestInfo error', [
'vm_id' => $vmId, 'error' => $e->getMessage(),
]);
return ['tools_running' => false, 'ip_address' => null, 'os_family' => null];
}
}
// -------------------------------------------------------------------------
// Password
// -------------------------------------------------------------------------
/**
* Generate a cryptographically secure 16-char password.
* Charset deliberately excludes % (breaks cmd.exe env expansion)
* and " (breaks PowerShell argument quoting).
*/
public function generatePassword(int $length = 16): string
{
$sets = [
'ABCDEFGHJKLMNPQRSTUVWXYZ',
'abcdefghjkmnpqrstuvwxyz',
'23456789',
'!@#$*', // no % or " — safe in cmd.exe double-quoted arguments
];
$password = '';
$allChars = implode('', $sets);
foreach ($sets as $set) {
$password .= $set[random_int(0, strlen($set) - 1)];
}
for ($i = count($sets); $i < $length; $i++) {
$password .= $allChars[random_int(0, strlen($allChars) - 1)];
}
$chars = str_split($password);
for ($i = count($chars) - 1; $i > 0; $i--) {
$j = random_int(0, $i);
[$chars[$i], $chars[$j]] = [$chars[$j], $chars[$i]];
}
return implode('', $chars);
}
public function encryptPassword(string $plaintext): string
{
return SignRSA::EncryptFunc($plaintext);
}
// -------------------------------------------------------------------------
// Persistence
// -------------------------------------------------------------------------
/**
* Update password only — IP already set during VM creation.
*/
public function updatePassword(int $moduleVmwareId, string $plainPassword): void
{
ModuleVmware::where('id', $moduleVmwareId)->update([
'password' => $this->encryptPassword($plainPassword),
'plain_password' => $plainPassword,
]);
Log::info('VmProvisionService::updatePassword saved', [
'module_vmware_id' => $moduleVmwareId,
]);
}
/**
* Update password + overwrite IP (used when real guest IP differs from pool IP).
*/
public function savePassword(int $moduleVmwareId, string $ip, string $plainPassword): void
{
ModuleVmware::where('id', $moduleVmwareId)->update([
'ip' => $ip,
'password' => $this->encryptPassword($plainPassword),
'plain_password' => $plainPassword,
]);
Log::info('VmProvisionService::savePassword saved', [
'module_vmware_id' => $moduleVmwareId,
'ip' => $ip,
]);
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace App\Services;
use Illuminate\Support\Facades\Log;
/**
* VsphereHostSshService
*
* Executes pre-deployed PowerShell scripts on the vSphere Windows host
* via native SSH (sshpass). No phpseclib dependency.
*
* Scripts in C:/CLISave/ accept 5 positional params:
* VM_ID NEW_PASSWORD VCENTER_HOST VCENTER_USER VCENTER_PASSWORD
*
* Scripts only output "SUCCESS" or "FAIL".
*/
final class VsphereHostSshService
{
private const HOST = '10.10.10.173';
private const PORT = 22;
private const USER = 'administrator';
private const PASS = 'Thegioiso@123**$$8899TgTk2';
private const SCRIPT_DIR = 'C:\\CLISave'; // backslash required for Windows cmd.exe
private const SCRIPT_LINUX = 'changePasswordLinux.ps1';
private const SCRIPT_WINDOWS = 'changePasswordWindows.ps1';
private const CONNECT_TIMEOUT = 20;
private const MAX_RETRIES = 5;
private const RETRY_DELAY = 5;
// ─────────────────────────────────────────────────────────────────────────
/**
* Run the OS-appropriate PS1 script on the vSphere host.
*
* @throws \RuntimeException on SSH failure
*/
public function changePassword(
string $vmId,
string $newPassword,
string $osFamily,
string $vcenterHost,
string $vcenterUser,
string $vcenterPassword,
): string {
$script = strtoupper($osFamily) === VmProvisionService::OS_WINDOWS
? self::SCRIPT_WINDOWS
: self::SCRIPT_LINUX;
// Remote Windows cmd.exe command — all args double-quoted
$remoteCmd = sprintf(
'cd %s && powershell -ExecutionPolicy Bypass -NonInteractive -File %s %s %s %s %s %s',
self::SCRIPT_DIR,
$script,
$this->warg($vmId),
$this->warg($newPassword),
$this->warg($vcenterHost),
$this->warg($vcenterUser),
$this->warg($vcenterPassword),
);
Log::info('VsphereHostSshService: executing script', [
'vm_id' => $vmId,
'script' => $script,
'vcenter_host' => $vcenterHost,
]);
$output = $this->sshExec($remoteCmd);
Log::info('VsphereHostSshService: script output', [
'vm_id' => $vmId,
'output' => trim($output),
]);
return $output;
}
// ─────────────────────────────────────────────────────────────────────────
/**
* Run a command on the vSphere SSH host via sshpass.
* Retries up to MAX_RETRIES times on connection failure.
*
* @throws \RuntimeException
*/
private function sshExec(string $remoteCmd): string
{
// Full native SSH command executed on local shell
$sshCmd = sprintf(
'sshpass -p %s ssh -o StrictHostKeyChecking=no -o ConnectTimeout=%d -p %d %s@%s %s 2>&1',
escapeshellarg(self::PASS),
self::CONNECT_TIMEOUT,
self::PORT,
escapeshellarg(self::USER),
escapeshellarg(self::HOST),
escapeshellarg($remoteCmd),
);
for ($attempt = 1; $attempt <= self::MAX_RETRIES; $attempt++) {
$output = shell_exec($sshCmd);
if ($output === null) {
Log::warning('VsphereHostSshService: shell_exec returned null', [
'attempt' => $attempt,
]);
} else {
Log::info('VsphereHostSshService: SSH executed', ['attempt' => $attempt]);
return $output;
}
if ($attempt < self::MAX_RETRIES) {
sleep(self::RETRY_DELAY);
}
}
throw new \RuntimeException(
'SSH exec to ' . self::HOST . ' failed after ' . self::MAX_RETRIES . ' attempts',
);
}
/**
* Windows cmd.exe safe argument: wrap in double quotes, escape inner double quotes.
* Password charset excludes " and % so wrapping is always safe.
*/
private function warg(string $value): string
{
return '"' . str_replace('"', '\\"', $value) . '"';
}
}