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
@@ -4,7 +4,9 @@ declare(strict_types=1);
namespace App\Services\VirtualMachine\Dto;
use App\Models\ModuleDatastore;
use App\Models\ModuleHost;
use App\Models\ModuleNetwork;
use App\Models\Os;
use App\Models\vCenter;
@@ -19,6 +21,8 @@ class VmInfrastructureContext
public readonly bool $isWindows,
public readonly string $vmUser,
public readonly int $vmPort,
public readonly ?ModuleDatastore $datastore = null,
public readonly ?ModuleNetwork $network = null,
) {
}
}
@@ -0,0 +1,226 @@
<?php
declare(strict_types=1);
namespace App\Services\VirtualMachine;
use App\Models\ModuleDatacenter;
use App\Models\ModuleDatastore;
use App\Models\ModuleHost;
use App\Models\ModuleNetwork;
use App\Models\vCenter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use RuntimeException;
/**
* Single source of truth for the "active" provisioning chain:
*
* vCenter (status=1, global)
* └── ModuleDatacenter (status=1 per vCenter)
* └── ModuleHost (status=1 per datacenter)
* ├── ModuleDatastore (status=1 per host)
* └── ModuleNetwork (status=1 per host)
*
* Rules enforced here:
* - At most ONE row per parent scope may have status=1.
* - Setting status=1 on row X auto-deactivates all siblings in same parent.
* - Setting status=0 on row X cascade-deactivates ALL descendants below it.
* - resolveChain() returns the full active chain or throws if any layer is missing.
*
* Settings provider mirroring:
* - activate('vcenter', $id) also writes provider.active_vcenter_id into the
* setting table so the Settings → Provider page reflects the same value
* without owning the truth.
*/
class VmActiveProviderService
{
public const TYPE_VCENTER = 'vcenter';
public const TYPE_DATACENTER = 'datacenter';
public const TYPE_HOST = 'host';
public const TYPE_DATASTORE = 'datastore';
public const TYPE_NETWORK = 'network';
/** type → [modelClass, parentColumn|null (null = global), childTypes[]] */
private const MAP = [
self::TYPE_VCENTER => [vCenter::class, null, [self::TYPE_DATACENTER]],
self::TYPE_DATACENTER => [ModuleDatacenter::class, 'vcenter_id', [self::TYPE_HOST]],
self::TYPE_HOST => [ModuleHost::class, 'module_datacenter_id', [self::TYPE_DATASTORE, self::TYPE_NETWORK]],
self::TYPE_DATASTORE => [ModuleDatastore::class, 'module_host_id', []],
self::TYPE_NETWORK => [ModuleNetwork::class, 'module_host_id', []],
];
public function __construct(private readonly VmProviderSettingsService $providerSettings)
{
}
// ─────────────────────────────────────────────────────────────────────────
// Resolve helpers
// ─────────────────────────────────────────────────────────────────────────
public function activeVcenter(): ?vCenter
{
return vCenter::where('status', 1)->first();
}
public function activeDatacenter(int $vcenterId): ?ModuleDatacenter
{
return ModuleDatacenter::where('vcenter_id', $vcenterId)
->where('status', 1)
->first();
}
public function activeHost(int $datacenterId): ?ModuleHost
{
return ModuleHost::where('module_datacenter_id', $datacenterId)
->where('status', 1)
->first();
}
public function activeDatastore(int $hostId): ?ModuleDatastore
{
return ModuleDatastore::where('module_host_id', $hostId)
->where('status', 1)
->first();
}
public function activeNetwork(int $hostId): ?ModuleNetwork
{
return ModuleNetwork::where('module_host_id', $hostId)
->where('status', 1)
->first();
}
/**
* Return the full active chain. Throws if any layer has no active row.
*
* @return array{vcenter:vCenter,datacenter:ModuleDatacenter,host:ModuleHost,datastore:ModuleDatastore,network:ModuleNetwork}
*/
public function resolveChain(): array
{
$vcenter = $this->activeVcenter();
if (!$vcenter) {
throw new RuntimeException('Không có vCenter nào đang active. Vui lòng kích hoạt 1 vCenter trong admin.');
}
$datacenter = $this->activeDatacenter($vcenter->id);
if (!$datacenter) {
throw new RuntimeException("vCenter active id={$vcenter->id} chưa có Datacenter nào active.");
}
$host = $this->activeHost($datacenter->id);
if (!$host) {
throw new RuntimeException("Datacenter active id={$datacenter->id} chưa có Host nào active.");
}
$datastore = $this->activeDatastore($host->id);
if (!$datastore) {
throw new RuntimeException("Host active id={$host->id} chưa có Datastore nào active.");
}
$network = $this->activeNetwork($host->id);
if (!$network) {
throw new RuntimeException("Host active id={$host->id} chưa có Network nào active.");
}
return compact('vcenter', 'datacenter', 'host', 'datastore', 'network');
}
// ─────────────────────────────────────────────────────────────────────────
// Mutators
// ─────────────────────────────────────────────────────────────────────────
/**
* Set this row active, deactivating all siblings in the same parent scope.
*/
public function activate(string $type, int $id): Model
{
[$modelClass, $parentColumn] = $this->mapOrFail($type);
return DB::transaction(function () use ($modelClass, $parentColumn, $type, $id) {
/** @var Model $row */
$row = $modelClass::query()->lockForUpdate()->findOrFail($id);
// Deactivate siblings under same parent (or all rows if global scope)
$siblings = $modelClass::query()->where('id', '!=', $row->getKey());
if ($parentColumn) {
$siblings->where($parentColumn, $row->{$parentColumn});
}
$siblings->update(['status' => 0]);
$row->status = 1;
$row->save();
if ($type === self::TYPE_VCENTER) {
$this->providerSettings->setActiveVcenterId((int) $row->getKey());
}
return $row->refresh();
});
}
/**
* Set this row inactive AND cascade-deactivate every descendant beneath it.
*/
public function deactivate(string $type, int $id): Model
{
[$modelClass] = $this->mapOrFail($type);
return DB::transaction(function () use ($modelClass, $type, $id) {
/** @var Model $row */
$row = $modelClass::query()->lockForUpdate()->findOrFail($id);
$row->status = 0;
$row->save();
$this->cascadeDeactivate($type, (int) $row->getKey());
if ($type === self::TYPE_VCENTER) {
$this->providerSettings->setActiveVcenterId(null);
}
return $row->refresh();
});
}
/**
* Recursively set status=0 on every descendant of $parentId under $type.
*/
private function cascadeDeactivate(string $type, int $parentId): void
{
$childTypes = self::MAP[$type][2] ?? [];
foreach ($childTypes as $childType) {
[$childModel, $childParentColumn] = $this->mapOrFail($childType);
if (!$childParentColumn) {
continue;
}
$childIds = $childModel::query()
->where($childParentColumn, $parentId)
->pluck('id')
->all();
if (!$childIds) {
continue;
}
$childModel::query()->whereIn('id', $childIds)->update(['status' => 0]);
foreach ($childIds as $childId) {
$this->cascadeDeactivate($childType, (int) $childId);
}
}
}
/**
* @return array{0:class-string<Model>,1:?string,2:string[]}
*/
private function mapOrFail(string $type): array
{
if (!isset(self::MAP[$type])) {
throw new RuntimeException("Unknown infra type: {$type}");
}
return self::MAP[$type];
}
}
@@ -4,22 +4,31 @@ declare(strict_types=1);
namespace App\Services\VirtualMachine;
use App\Models\ModuleHost;
use App\Models\OrderItem;
use App\Models\Os;
use App\Services\VirtualMachine\Dto\VmInfrastructureContext;
use RuntimeException;
/**
* Resolves the provisioning target by walking the ACTIVE chain only:
*
* active vCenter → active Datacenter → active Host → active Datastore + Network
*
* Product / OS bindings are now informational only — the host/datacenter/vcenter
* configured per-product no longer drive VM creation. The whole platform clones
* onto whatever single chain is currently marked status=1.
*/
class VmInfrastructureResolver
{
public function __construct(private readonly VmProvisionLogger $logger)
{
public function __construct(
private readonly VmProvisionLogger $logger,
private readonly VmActiveProviderService $activeProvider,
) {
}
public function resolve(OrderItem $item, $product): VmInfrastructureContext
{
$os = Os::with(['host.datacenter.vCenter', 'osGroup.host.datacenter.vCenter'])
->find($item->os_id);
$os = Os::with('osGroup')->find($item->os_id);
if (!$os) {
throw new RuntimeException(
@@ -27,63 +36,31 @@ class VmInfrastructureResolver
);
}
// Priority 1: host attached directly to OS
$host = $os->host;
$datacenter = $host?->datacenter;
$vcenter = $datacenter?->vCenter;
$chain = $this->activeProvider->resolveChain();
// Priority 2: host from OS group fallback
if (!$host || !$datacenter || !$vcenter) {
$groupHost = $os->osGroup?->host;
$host = $host ?? $groupHost;
$datacenter = $datacenter ?? $groupHost?->datacenter;
$vcenter = $vcenter ?? $groupHost?->datacenter?->vCenter;
if ($groupHost) {
$this->logger->step('Infrastructure fallback: osGroup host', [
'os_id' => $os->id,
'os_group_id' => $os->os_group_id,
'host_id' => $groupHost->id,
]);
}
}
// Priority 3: host from product (Provisioning tab)
if ((!$host || !$datacenter || !$vcenter) && $product && $product->module_host_id) {
$productHost = ModuleHost::with('datacenter.vCenter')->find($product->module_host_id);
if ($productHost) {
$host = $host ?? $productHost;
$datacenter = $datacenter ?? $productHost->datacenter;
$vcenter = $vcenter ?? $productHost->datacenter?->vCenter;
$this->logger->step('Infrastructure fallback: product host', [
'product_id' => $product->id,
'host_id' => $productHost->id,
'datacenter_id' => $productHost->datacenter?->id,
]);
}
}
if (!$vcenter || !$host || !$datacenter) {
throw new RuntimeException(
"Thiếu thông tin host/datacenter/vcenter từ sản phẩm ID #" . ($product->id ?? 'unknown') . ". "
. "Vui lòng cấu hình vCenter trong tab Provisioning của sản phẩm, "
. "hoặc gán host cho OS group của OS được chọn."
);
}
$this->logger->step('Infrastructure resolved from active chain', [
'order_item_id' => $item->id,
'vcenter_id' => $chain['vcenter']->id,
'datacenter_id' => $chain['datacenter']->id,
'host_id' => $chain['host']->id,
'datastore_id' => $chain['datastore']->id,
'network_id' => $chain['network']->id,
]);
$osGroupName = $os->osGroup?->name ?? '';
$isWindows = str_contains(strtolower($osGroupName), 'windows');
return new VmInfrastructureContext(
os: $os,
host: $host,
datacenter: $datacenter,
vcenter: $vcenter,
host: $chain['host'],
datacenter: $chain['datacenter'],
vcenter: $chain['vcenter'],
template: $os->template_id,
isWindows: $isWindows,
vmUser: $isWindows ? 'administrator' : 'root',
vmPort: $isWindows ? 3389 : 22,
datastore: $chain['datastore'],
network: $chain['network'],
);
}
}
@@ -0,0 +1,92 @@
<?php
declare(strict_types=1);
namespace App\Services\VirtualMachine;
use App\Models\IpPool;
use App\Models\ModuleIpAddress;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
/**
* Reserves and releases IPs from ip_pools / module_ip_addresses with row-level locking.
*
* Extracted so CreateVirtualMachineJob can pick an IP BEFORE cloning the VM
* (the IP is baked into the VM name), and AssignIpToGuestJob can later use
* the same reservation instead of picking its own.
*/
class VmIpReservationService
{
/**
* @return array{reservation:ModuleIpAddress,ip_pool_id:int,gateway:string,cidr:int}|null
*/
public function reserve(int $networkId, int $hostId, string $dns): ?array
{
return DB::transaction(function () use ($networkId, $hostId, $dns) {
$usedIps = ModuleIpAddress::where('module_network_id', $networkId)
->lockForUpdate()
->pluck('ip')
->toArray();
$ipPool = IpPool::where('module_network_id', $networkId)
->where('status', 'free')
->whereNotNull('gateway')
->where('gateway', '!=', '')
->whereNotIn('ip_address', $usedIps)
->lockForUpdate()
->inRandomOrder()
->first();
if (!$ipPool) {
return null;
}
$ipPool->update(['status' => 'reserved']);
$cidr = (int) ($ipPool->cidr ?: 24);
$gateway = (string) ($ipPool->gateway ?? '');
$netmask = $this->cidrToNetmask($cidr);
$reservation = ModuleIpAddress::create([
'vm_name' => '__pending__',
'module_host_id' => $hostId,
'module_network_id' => $networkId,
'ip' => $ipPool->ip_address,
'gateway' => $gateway,
'netmask' => $netmask,
'dns' => $dns,
'status' => 0,
]);
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPool->id,
'gateway' => $gateway,
'cidr' => $cidr,
];
});
}
public function release(ModuleIpAddress $reservation, ?int $ipPoolId): void
{
try {
$reservation->delete();
if ($ipPoolId) {
IpPool::where('id', $ipPoolId)->update(['status' => 'free']);
}
Log::info('VmIpReservationService: IP released', ['ip' => $reservation->ip]);
} catch (\Throwable $e) {
Log::warning('VmIpReservationService: release failed', [
'ip' => $reservation->ip,
'error' => $e->getMessage(),
]);
}
}
public function cidrToNetmask(int $cidr): string
{
$cidr = max(0, min(32, $cidr));
return long2ip(-1 << (32 - $cidr));
}
}
@@ -0,0 +1,87 @@
<?php
declare(strict_types=1);
namespace App\Services\VirtualMachine;
use App\Repositories\Setting\SettingRepositoryInterface;
/**
* Reads / writes the provisioning "provider" config stored in setting table
* under the single key `provider`.
*
* Shape:
* {
* "active_vcenter_id": 1, // mirror of module_vcenter.status=1
* "default_folder": "group-v1008",
* "default_resource_pool": "resgroup-3002",
* "default_datastore": "datastore-3004", // fallback if active host has no active datastore
* "name": "Acme Cloud",
* "region": "HCM",
* "tags": ["prod"]
* }
*
* The active_vcenter_id field is mirrored from module_vcenter — module_vcenter
* remains the source of truth, this is just a convenience view for the UI.
*/
class VmProviderSettingsService
{
public const KEY = 'provider';
public const DEFAULTS = [
'active_vcenter_id' => null,
'default_folder' => 'group-v1008',
'default_resource_pool' => 'resgroup-3002',
'default_datastore' => 'datastore-3004',
'name' => null,
'region' => null,
'tags' => [],
];
public function __construct(private readonly SettingRepositoryInterface $settings)
{
}
/** @return array<string,mixed> */
public function all(): array
{
$raw = $this->settings->getByKey(self::KEY);
$data = is_string($raw) ? json_decode($raw, true) : [];
return array_merge(self::DEFAULTS, is_array($data) ? $data : []);
}
public function get(string $field, mixed $default = null): mixed
{
return $this->all()[$field] ?? $default;
}
/** Merge-write a subset of fields. */
public function merge(array $patch): array
{
$merged = array_merge($this->all(), $patch);
$this->settings->updateOrCreateByKey(self::KEY, [
'value' => json_encode($merged, JSON_UNESCAPED_UNICODE),
]);
return $merged;
}
public function setActiveVcenterId(?int $id): void
{
$this->merge(['active_vcenter_id' => $id]);
}
public function defaultFolder(): string
{
return (string) $this->get('default_folder', self::DEFAULTS['default_folder']);
}
public function defaultResourcePool(): string
{
return (string) $this->get('default_resource_pool', self::DEFAULTS['default_resource_pool']);
}
public function defaultDatastore(): string
{
return (string) $this->get('default_datastore', self::DEFAULTS['default_datastore']);
}
}