Files
portal-api/app/Services/VirtualMachine/VmIpReservationService.php
T

95 lines
3.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
{
/**
* @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) {
// Exclude IPs that have any active reservation (real VM or pending).
// Also accept status='reserved' in ip_pools so stale reservations
// (ip_pool row stuck as 'reserved' with no matching module_ip_addresses row)
// are recoverable without manual DB cleanup.
$allUsedIps = ModuleIpAddress::where('module_network_id', $networkId)
->lockForUpdate()
->pluck('ip')
->toArray();
$ipPool = IpPool::where('module_network_id', $networkId)
->whereIn('status', ['free', 'reserved'])
->whereNotIn('ip_address', $allUsedIps)
->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));
}
}