Files
baodev0andClaude Sonnet 5.5 1d40dfbb44 fix(vm): khôi phục lọc network khi giữ IP cho VM
reserve() không còn lấy IP ngoài network được chọn hoặc IP chưa gán network.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 11:56:35 +07:00

159 lines
5.2 KiB
PHP

<?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
{
public function hasFreeIp(): bool
{
return $this->availableIps()->exists();
}
/**
* @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) {
// ip_pools.status is the single source of truth for availability.
$ipPool = $this->availableIps()
->where('module_network_id', $networkId)
->lockForUpdate()
->inRandomOrder()
->first();
if (!$ipPool) {
return null;
}
$ipPool->update(['status' => 'reserved']);
$cidr = (int) ($ipPool->cidr ?: 24);
$gateway = (string) ($ipPool->gateway ?? '');
$netmask = $ipPool->netmask ?: $this->cidrToNetmask($cidr);
// module_ip_address mirrors ip_pools — update the existing synced row
// (created when the IP was added to ip_pools) instead of inserting a new one.
$reservation = ModuleIpAddress::where('ip', $ipPool->ip_address)
->where('module_network_id', $networkId)
->lockForUpdate()
->first();
$attrs = [
'vm_name' => '__pending__',
'module_host_id' => $hostId,
'module_network_id' => $networkId,
'ip' => $ipPool->ip_address,
'gateway' => $gateway,
'netmask' => $netmask,
'dns' => $dns,
'status' => 0,
];
if ($reservation) {
$reservation->update($attrs);
} else {
$reservation = ModuleIpAddress::create($attrs);
}
return [
'reservation' => $reservation,
'ip_pool_id' => $ipPool->id,
'gateway' => $gateway,
'cidr' => $cidr,
];
});
}
/**
* Reserve a specific, still-free IP within a network (customer-picked change-IP flow).
*
* @return array{ip_pool_id:int, gateway:string}|null
*/
public function reserveInNetwork(int $networkId, string $ipAddress, int $serviceId): ?array
{
return DB::transaction(function () use ($networkId, $ipAddress, $serviceId) {
$ipPool = IpPool::where('module_network_id', $networkId)
->where('ip_address', $ipAddress)
->where('status', 'free')
->lockForUpdate()
->first();
if (!$ipPool) {
return null;
}
$ipPool->update(['status' => 'assigned', 'service_id' => $serviceId]);
return [
'ip_pool_id' => $ipPool->id,
'gateway' => (string) ($ipPool->gateway ?? ''),
];
});
}
private function availableIps()
{
return IpPool::whereIn('status', ['free', 'reserved'])
->whereNotNull('module_network_id')
->whereNotNull('gateway')
->where('gateway', '!=', '');
}
public function freeIpsInNetwork(int $networkId)
{
return IpPool::where('module_network_id', $networkId)
->where('status', 'free')
->orderBy('ip_address')
->get(['id', 'ip_address', 'gateway']);
}
public function releaseByPoolId(int $ipPoolId): void
{
try {
IpPool::where('id', $ipPoolId)->update(['status' => 'free', 'service_id' => null]);
} catch (\Throwable $e) {
Log::warning('VmIpReservationService: releaseByPoolId failed', [
'ip_pool_id' => $ipPoolId,
'error' => $e->getMessage(),
]);
}
}
public function release(ModuleIpAddress $reservation, ?int $ipPoolId): void
{
try {
$reservation->update(['vm_name' => null, 'status' => 0]);
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));
}
}