whereIn('status', ['free', 'reserved']) ->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, ]; }); } 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)); } }