This commit is contained in:
baodev0
2026-06-22 08:43:32 +07:00
parent 3243473843
commit 0c436153c6
22 changed files with 1389 additions and 95 deletions
@@ -9,6 +9,7 @@ use App\Jobs\VirtualMachine\Provision\AssignIpToGuestJob;
use App\Models\OrderItem;
use App\Services\VirtualMachine\VmAddonResolver;
use App\Services\VirtualMachine\VmInfrastructureResolver;
use App\Services\VirtualMachine\VmIpReservationService;
use App\Services\VirtualMachine\VmModuleService;
use App\Services\VirtualMachine\VmNotificationService;
use App\Services\VirtualMachine\VmPowerService;
@@ -50,7 +51,11 @@ class CreateVirtualMachineJob implements ShouldQueue
VmServiceSyncService $serviceSync,
VmNotificationService $notification,
VmVcenterErrorTranslator $errorTranslator,
VmIpReservationService $ipReservation,
): bool {
$reservation = null;
$ipPoolId = null;
try {
$vmLogger->step('Create VM job started', [
'order_item_id' => $this->item->id,
@@ -66,6 +71,39 @@ class CreateVirtualMachineJob implements ShouldQueue
$infra = $infraResolver->resolve($this->item, $product);
$addonData = $addonResolver->resolve($this->item);
// Reserve IP BEFORE clone so VM name on vCenter, ModuleVmware.name
// and services.server_name all carry the format {ip}_{server_name}.
// Network comes from the active chain (active host → active network);
// product->ipAddress is no longer consulted for network selection.
if (!$infra->network) {
throw new RuntimeException("Active host id={$infra->host->id} chưa có network active.");
}
$networkId = $infra->network->id;
$dns = $product->ipAddress->dns ?? '8.8.8.8';
$picked = $ipReservation->reserve($networkId, $infra->host->id, $dns);
if (!$picked) {
throw new RuntimeException(
"Không còn IP free trong pool (network_id={$networkId}) để tạo VM."
);
}
$reservation = $picked['reservation'];
$ipPoolId = $picked['ip_pool_id'];
$reservedIp = $reservation->ip;
$originalName = $this->item->server_name ?? ('VM-' . $this->item->id);
$combinedName = "{$reservedIp}_{$originalName}";
$this->item->server_name = $combinedName;
$vmLogger->step('IP reserved for VM', [
'order_item_id' => $this->item->id,
'ip' => $reservedIp,
'ip_pool_id' => $ipPoolId,
'server_name' => $combinedName,
]);
if (!$vCenter->loginServer($infra->vcenter)) {
throw new RuntimeException("Login vào vCenter thất bại với host: {$infra->vcenter->host}");
}
@@ -142,6 +180,8 @@ class CreateVirtualMachineJob implements ShouldQueue
(string) $vmId,
$infra->isWindows ? VmProvisionService::OS_WINDOWS : VmProvisionService::OS_LINUX,
VmProvisionService::TEMPLATE_PASSWORD,
$reservation->id,
$ipPoolId,
)->onQueue('default');
$vmLogger->success('AssignIpToGuestJob dispatched', [
@@ -160,6 +200,10 @@ class CreateVirtualMachineJob implements ShouldQueue
return true;
} catch (Throwable $e) {
if ($reservation) {
$ipReservation->release($reservation, $ipPoolId);
}
$vmLogger->exception('Create VM job failed', $e, [
'order_item_id' => $this->item->id,
'is_retry' => $this->isRetry,
@@ -58,6 +58,8 @@ class AssignIpToGuestJob implements ShouldQueue
public readonly string $vmId,
public readonly string $osFamily, // VmProvisionService::OS_LINUX | OS_WINDOWS
public readonly string $guestPassword = VmProvisionService::TEMPLATE_PASSWORD,
public readonly ?int $reservationId = null,
public readonly ?int $reservedIpPoolId = null,
) {}
// ─────────────────────────────────────────────────────────────────────────
@@ -103,16 +105,22 @@ class AssignIpToGuestJob implements ShouldQueue
$guestUser = strtoupper($this->osFamily) === 'WINDOWS' ? 'Administrator' : 'root';
// ─── Attempt loop ────────────────────────────────────────────────────
// If reservationId is supplied, the IP was reserved upstream (CreateVirtualMachineJob)
// and baked into the VM name — we can't swap IPs on retry, so we run a single attempt.
$maxAttempts = $this->reservationId ? 1 : self::MAX_ATTEMPTS;
for ($attempt = 1; $attempt <= self::MAX_ATTEMPTS; $attempt++) {
for ($attempt = 1; $attempt <= $maxAttempts; $attempt++) {
Log::info('AssignIpToGuestJob: attempt', [
'attempt' => $attempt,
'module_vmware_id' => $this->moduleVmwareId,
'network_id' => $networkId,
'preserved' => (bool) $this->reservationId,
]);
// [3] Reserve a free IP with transaction + row lock
$picked = $this->reserveIp($networkId, $hostId, $dns);
// [3] Use upstream reservation if provided, else reserve a fresh IP.
$picked = $this->reservationId
? $this->loadReservation($this->reservationId, $this->reservedIpPoolId)
: $this->reserveIp($networkId, $hostId, $dns);
if (!$picked) {
Log::error('AssignIpToGuestJob: no free IPs in pool', [
@@ -220,7 +228,7 @@ class AssignIpToGuestJob implements ShouldQueue
Log::error('AssignIpToGuestJob: all attempts failed — marking VM inactive', [
'module_vmware_id' => $this->moduleVmwareId,
'vm_id' => $this->vmId,
'attempts' => self::MAX_ATTEMPTS,
'attempts' => $maxAttempts,
]);
ModuleVmware::where('id', $this->moduleVmwareId)->update(['status' => 0]);
@@ -336,6 +344,34 @@ class AssignIpToGuestJob implements ShouldQueue
});
}
/**
* 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): ?array
{
$reservation = ModuleIpAddress::find($reservationId);
if (!$reservation) {
Log::error('AssignIpToGuestJob: 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 deleting the pending ModuleIpAddress row.
* This returns the IP to the available pool.