diff --git a/web/app/Controllers/CloudAdminInstanceController.php b/web/app/Controllers/CloudAdminInstanceController.php index 379aeb15..da00fa19 100644 --- a/web/app/Controllers/CloudAdminInstanceController.php +++ b/web/app/Controllers/CloudAdminInstanceController.php @@ -3,8 +3,12 @@ namespace App\Controllers; use App\Models\CloudHost; +use App\Models\CloudHostNetworkAttachment; use App\Models\CloudJob; use App\Models\CloudPublicIp; +use App\Models\CloudPublicIpPool; +use App\Models\CloudResourceReservation; +use App\Models\CloudResourcePool; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudAdminInstanceService; use App\Services\Cloud\CloudError; @@ -19,6 +23,9 @@ use App\Services\Cloud\CloudSSHKeys; /** Administrator inventory snapshots plus explicitly queued VM mutations. */ final class CloudAdminInstanceController { + private const MAX_PUBLIC_POOLS = 32; + private const MAX_AVAILABLE_IPS_PER_POOL = 254; + public function index($request, $response) { return $response->withJson(CloudAdminInstanceService::page( @@ -57,47 +64,176 @@ final class CloudAdminInstanceController if ($host === null) { throw new CloudError('虚拟机所属宿主机不存在,无法读取地址池', 409); } + $reservation = $instance->reservation_id === null ? null + : CloudResourceReservation::find((int) $instance->reservation_id); + $currentPool = $reservation === null ? null + : CloudPublicIpPool::find((int) ($reservation->public_ip_pool_id ?? 0)); + $attachment = $reservation === null ? null + : CloudHostNetworkAttachment::find( + (int) ($reservation->network_attachment_id ?? 0) + ); + $currentIp = $reservation === null ? null + : CloudPublicIp::find((int) $reservation->public_ip_id); + $reservationPool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + if ($reservation === null || $currentPool === null || $attachment === null + || $currentIp === null || $reservationPool === null + || (string) $reservation->state !== 'committed' + || (int) $reservation->host_id !== (int) $host->id + || (int) ($reservation->instance_id ?? 0) !== (int) $instance->id + || (int) $reservation->resource_pool_id + !== (int) ($instance->resource_pool_id ?? 0) + || (int) $attachment->line_id !== (int) $reservationPool->line_id + || (int) $currentPool->host_id !== (int) $host->id + || (int) $currentPool->network_attachment_id !== (int) $attachment->id + || (int) $currentIp->host_id !== (int) $host->id + || (int) ($currentIp->public_ip_pool_id ?? 0) + !== (int) $currentPool->id + || (string) $currentIp->state !== 'assigned' + || (int) ($currentIp->reservation_id ?? 0) !== (int) $reservation->id + || (int) ($currentIp->instance_id ?? 0) !== (int) $instance->id + || preg_match('/^[a-f0-9]{32}$/D', + (string) $currentPool->pool_key) !== 1 + || (int) $attachment->host_id !== (int) $host->id + || (string) $attachment->network_selector + !== (string) $host->default_network + || (string) $attachment->state !== 'active' + || (string) $attachment->sync_state !== 'fresh' + || (int) $attachment->observed_revision + < (int) $attachment->desired_revision) { + throw new CloudError('虚拟机公网 IP 资源预留不完整,暂不能更换地址', 409); + } $profile = (new CloudEngineClient())->host( (int) $host->id, 'GET', 'host/network-options', $actor ); $gateway = self::safeIpv4($profile['gateway'] ?? null); $dnsServers = self::safeIpv4List($profile['dns_servers'] ?? null, 4); $guestPrefix = self::safePrefix($profile['guest_prefix'] ?? null); - $blocked = array_values(array_filter([$gateway, ...$dnsServers])); - $rawAvailable = $profile['available_ips'] ?? null; - $availableOverflow = is_array($rawAvailable) && count($rawAvailable) > 254; + + $rawPools = $profile['pools'] ?? null; + $profileMalformed = !is_array($rawPools) + || count($rawPools) > self::MAX_PUBLIC_POOLS; + $databasePools = CloudPublicIpPool::where('host_id', (int) $host->id) + ->where('network_attachment_id', (int) $attachment->id) + ->where('state', 'active')->where('sync_state', 'fresh') + ->whereColumn('observed_revision', '>=', 'desired_revision') + ->orderBy('id')->limit(self::MAX_PUBLIC_POOLS + 1)->get(); + if ($databasePools->count() > self::MAX_PUBLIC_POOLS) { + $profileMalformed = true; + } + $databaseByKey = []; + foreach ($databasePools as $databasePool) { + if (preg_match('/^[a-f0-9]{32}$/D', + (string) $databasePool->pool_key) === 1) { + $databaseByKey[(string) $databasePool->pool_key] = $databasePool; + } + } $ledgerAvailable = []; - if (is_array($rawAvailable) && !$availableOverflow) { + if (!$profileMalformed && $databaseByKey !== []) { foreach (CloudPublicIp::where('host_id', (int) $host->id) + ->whereIn('public_ip_pool_id', array_map( + static fn ($pool): int => (int) $pool->id, + array_values($databaseByKey) + )) ->where('state', 'available') - ->get(['address', 'prefix_length']) as $ip) { - $ledgerAvailable[(string) $ip->address . '/' . (int) $ip->prefix_length] = true; + ->whereNull('reservation_id')->whereNull('instance_id') + ->whereNull('operation_id') + ->get(['address', 'prefix_length', 'public_ip_pool_id']) as $ip) { + $databasePool = $databasePools->firstWhere( + 'id', (int) $ip->public_ip_pool_id + ); + if ($databasePool !== null) { + $ledgerAvailable[ + (string) $ip->address . '/' . (int) $ip->prefix_length + ] = (string) $databasePool->pool_key; + } } } - $available = []; - foreach (is_array($rawAvailable) ? array_slice($rawAvailable, 0, 254) : [] as $value) { - $cidr = self::safePublicIpCidr($value); - $address = $cidr === null ? null : explode('/', $cidr, 2)[0]; - $parts = $cidr === null ? [] : explode('/', $cidr, 2); - if ($cidr !== null && $guestPrefix !== null - && (int) ($parts[1] ?? 0) === $guestPrefix - && self::cidrInPool($cidr, $profile['pool_cidr'] ?? null) - && !in_array($address, $blocked, true) - && isset($ledgerAvailable[$cidr])) { - $available[] = $cidr; + + $availableOptions = []; + $safePools = []; + $availableOverflow = false; + $scanned = 0; + foreach (is_array($rawPools) ? $rawPools : [] as $rawPool) { + if (!is_array($rawPool) || array_is_list($rawPool)) { + $profileMalformed = true; + continue; } + $poolKey = $rawPool['pool_key'] ?? null; + if (!is_string($poolKey) + || preg_match('/^[a-f0-9]{32}$/D', $poolKey) !== 1 + || !isset($databaseByKey[$poolKey]) + || ($rawPool['state'] ?? null) !== 'active' + || ($rawPool['configuration_state'] ?? null) !== 'ready' + || ($rawPool['network_selector'] ?? null) + !== (string) $attachment->network_selector) { + continue; + } + $databasePool = $databaseByKey[$poolKey]; + $poolCidr = self::safeText($rawPool['pool_cidr'] ?? null, 18); + $poolPrefix = self::safePrefix($rawPool['guest_prefix'] ?? null); + $poolGateway = self::safeIpv4($rawPool['gateway'] ?? null); + $poolDns = self::safeIpv4List($rawPool['dns_servers'] ?? null, 4); + $rawAvailable = $rawPool['available_ips'] ?? null; + if ($poolCidr === null || $poolPrefix === null || $poolGateway === null + || !is_array($rawAvailable) + || $poolCidr !== (string) $databasePool->cidr + || $poolPrefix !== (int) $databasePool->guest_prefix_length + || $poolGateway !== (string) $databasePool->gateway) { + $profileMalformed = true; + continue; + } + $poolAvailableCount = count($rawAvailable); + $scanned += $poolAvailableCount; + if ($poolAvailableCount > self::MAX_AVAILABLE_IPS_PER_POOL + || $scanned > self::MAX_PUBLIC_POOLS + * self::MAX_AVAILABLE_IPS_PER_POOL) { + $availableOverflow = true; + break; + } + $blocked = array_values(array_filter([$poolGateway, ...$poolDns])); + $poolAvailable = 0; + foreach ($rawAvailable as $value) { + $cidr = self::safePublicIpCidr($value); + $address = $cidr === null ? null : explode('/', $cidr, 2)[0]; + $parts = $cidr === null ? [] : explode('/', $cidr, 2); + if ($cidr !== null && (int) ($parts[1] ?? 0) === $poolPrefix + && self::cidrInPool($cidr, $poolCidr) + && !in_array($address, $blocked, true) + && ($ledgerAvailable[$cidr] ?? null) === $poolKey) { + $availableOptions[$poolKey . ':' . $cidr] = [ + 'public_pool_key' => $poolKey, + 'public_ip_cidr' => $cidr, + ]; + $poolAvailable++; + } + } + $safePools[] = [ + 'public_pool_key' => $poolKey, + 'pool_cidr' => $poolCidr, + 'guest_prefix' => $poolPrefix, + 'gateway' => $poolGateway, + 'dns_servers' => $poolDns, + 'available_count' => $poolAvailable, + ]; } - $available = array_values(array_unique($available)); + $availableOptions = array_values($availableOptions); + $available = array_values(array_map( + static fn (array $option): string => $option['public_ip_cidr'], + $availableOptions + )); $configurationState = in_array($profile['configuration_state'] ?? null, ['ready', 'not_configured', 'invalid', 'drift'], true) ? $profile['configuration_state'] : 'unavailable'; - if (!is_array($rawAvailable) || $availableOverflow) { + if ($profileMalformed || $availableOverflow) { $configurationState = 'unavailable'; $available = []; + $availableOptions = []; + $safePools = []; } $currentCidr = self::safePublicIpCidr($spec['public_ip_cidr']); - $message = !is_array($rawAvailable) - ? '宿主机返回的可用公网 IP 列表格式异常,请先检查引擎状态。' + $message = $profileMalformed + ? '宿主机返回的公网地址池格式异常或与本地账本不一致,请先同步配置。' : ($availableOverflow ? '宿主机返回的可用公网 IP 列表超出安全上限,请先检查地址池配置。' : (CloudOperationErrorCatalog::adminSummary(null, null, @@ -112,12 +248,15 @@ final class CloudAdminInstanceController 'host_name' => (string) $host->name, 'region' => (string) $host->region, 'current_ip_cidr' => $currentCidr, + 'current_public_pool_key' => (string) $currentPool->pool_key, 'pool_cidr' => self::safeText($profile['pool_cidr'] ?? null, 32), 'guest_prefix' => $guestPrefix, 'gateway' => $gateway, 'dns_servers' => $dnsServers, 'available_ips' => $available, + 'available_ip_options' => $availableOptions, 'available_count' => count($available), + 'pools' => $safePools, 'configuration_state' => $configurationState, 'active_job' => $activeJob === null ? null : [ 'id' => (string) $activeJob->id, @@ -150,11 +289,15 @@ final class CloudAdminInstanceController throw new CloudError('只有处于活动状态的虚拟机可以更换公网 IP', 409); } $body = CloudInput::object($request); - CloudInput::only($body, ['public_ip_cidr', 'confirm_restart']); + CloudInput::only($body, + ['public_ip_cidr', 'public_pool_key', 'confirm_restart']); if (($body['confirm_restart'] ?? false) !== true) { throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); } $cidr = CloudInput::publicIpCidr($body['public_ip_cidr'] ?? null); + $publicPoolKey = CloudInput::publicPoolKey( + $body['public_pool_key'] ?? null + ); $spec = json_decode((string) $instance->spec_json, true); if (!is_array($spec) || array_is_list($spec) || ($spec['managed'] ?? false) !== true @@ -167,11 +310,16 @@ final class CloudAdminInstanceController throw new CloudError('新公网 IP 与当前配置相同', 409); } $job = CloudJobService::enqueue($instance, $actor, 'network_change', 'POST', - '/network', ['public_ip_cidr' => $cidr, 'confirm_restart' => true]); + '/network', [ + 'public_ip_cidr' => $cidr, + 'public_pool_key' => $publicPoolKey, + 'confirm_restart' => true, + ]); return $response->withJson([ 'job_id' => (string) $job->id, 'status_url' => '/api/v1/jobs/' . $job->id, 'public_ip_cidr' => $cidr, + 'public_pool_key' => $publicPoolKey, ], 202)->withHeader('Cache-Control', 'no-store'); } diff --git a/web/app/Models/CloudResourceReservation.php b/web/app/Models/CloudResourceReservation.php index abddedc8..03e7394b 100644 --- a/web/app/Models/CloudResourceReservation.php +++ b/web/app/Models/CloudResourceReservation.php @@ -26,4 +26,23 @@ final class CloudResourceReservation extends Model 'created_at' => 'int', 'updated_at' => 'int', ]; + + /** + * Nullable columns permit an in-place legacy schema upgrade, but every + * reservation created by current code must carry a complete immutable + * network allocation boundary. + */ + protected static function booted(): void + { + static::creating(static function (self $reservation): void { + foreach (['network_attachment_id', 'public_ip_pool_id', + 'public_ip_id'] as $field) { + if ((int) ($reservation->{$field} ?? 0) < 1) { + throw new \LogicException( + 'New reservations require complete network allocation references.' + ); + } + } + }); + } } diff --git a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php index e36ffdcf..2d8a14b1 100644 --- a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php +++ b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php @@ -8,6 +8,7 @@ use App\Models\CloudHostCapacitySnapshot; use App\Models\CloudNetworkLine; use App\Models\CloudRegion; use App\Models\CloudResourcePool; +use App\Models\CloudResourceReservation; use App\Services\Config; /** Database-owned administrator settings for one compute host. */ @@ -127,6 +128,7 @@ final class CloudAdminHostSchedulingService if ($schedulerState === 'active') { self::validateActive($host, $pool, $line, $region, $values); } + self::assertReservationLine($host, $pool, $line); $now = time(); CloudHostPoolMembershipService::replaceLocked( @@ -184,6 +186,34 @@ final class CloudAdminHostSchedulingService } } + /** Keep existing instances on the line captured by their sales pool. */ + private static function assertReservationLine(CloudHost $host, $pool, + $line): void + { + $reservations = CloudResourceReservation::where('host_id', (int) $host->id) + ->whereIn('state', ['held', 'uncertain', 'committed']) + ->orderBy('id')->lockForUpdate()->get(['id', 'resource_pool_id']); + if ($reservations->isEmpty()) { + return; + } + if ($pool === null || $line === null) { + throw new CloudError('宿主机仍有实例或资源预留,不能移除所属资源池', 409); + } + $poolIds = $reservations->pluck('resource_pool_id')->map( + static fn ($id): int => (int) $id + )->unique()->values()->all(); + $reservationPools = CloudResourcePool::whereIn('id', $poolIds) + ->orderBy('id')->get(['id', 'line_id'])->keyBy('id'); + if ($reservationPools->count() !== count($poolIds)) { + throw new CloudError('宿主机现有资源预留的线路关系不完整', 409); + } + foreach ($poolIds as $poolId) { + if ((int) $reservationPools->get($poolId)->line_id !== (int) $line->id) { + throw new CloudError('宿主机仍有其他线路的实例或资源预留,不能跨线路更换资源池', 409); + } + } + } + private static function poolOptions(): array { $lines = []; diff --git a/web/app/Services/Cloud/CloudInput.php b/web/app/Services/Cloud/CloudInput.php index 71dd08fd..6b29f3d0 100644 --- a/web/app/Services/Cloud/CloudInput.php +++ b/web/app/Services/Cloud/CloudInput.php @@ -162,6 +162,16 @@ final class CloudInput return $parts[0] . '/' . (int) $parts[1]; } + /** Validate the stable, non-secret identifier of one native public pool. */ + public static function publicPoolKey($value): string + { + if (!is_string($value) + || preg_match('/^[a-f0-9]{32}$/D', $value) !== 1) { + throw new CloudError('请选择有效的公网地址池'); + } + return $value; + } + public static function safeResult(array $value): array { foreach ($value as $key => $item) { diff --git a/web/app/Services/Cloud/CloudJobService.php b/web/app/Services/Cloud/CloudJobService.php index ee9b552b..1ca0b36b 100644 --- a/web/app/Services/Cloud/CloudJobService.php +++ b/web/app/Services/Cloud/CloudJobService.php @@ -2,9 +2,12 @@ namespace App\Services\Cloud; use App\Models\CloudHost; +use App\Models\CloudHostNetworkAttachment; use App\Models\CloudInstance; use App\Models\CloudJob; use App\Models\CloudPublicIp; +use App\Models\CloudPublicIpPool; +use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; final class CloudJobService @@ -20,13 +23,17 @@ final class CloudJobService ); } if ($kind === 'network_change') { - CloudInput::only($body, ['public_ip_cidr', 'confirm_restart']); + CloudInput::only($body, + ['public_ip_cidr', 'public_pool_key', 'confirm_restart']); if (($body['confirm_restart'] ?? false) !== true) { throw new CloudError('更换公网 IP 前必须确认虚拟机会短暂重启'); } $body['public_ip_cidr'] = CloudInput::publicIpCidr( $body['public_ip_cidr'] ?? null ); + $body['public_pool_key'] = CloudInput::publicPoolKey( + $body['public_pool_key'] ?? null + ); } if ($kind === 'instance_settings') { CloudInput::only($body, ['hostname', 'root_password', 'ssh_public_key', 'confirm_restart']); @@ -83,21 +90,51 @@ final class CloudJobService if ($kind === 'network_change') { $host = CloudHost::where('id', (int) $locked->host_id) ->lockForUpdate()->first(); - $reservation = $locked->reservation_id === null ? null + // The host row is the sentinel for all of these references. + // Read their identifiers first, then lock attachment/pools, + // reservation and IP rows in the scheduler's fixed order. + $reservationRef = $locked->reservation_id === null ? null : CloudResourceReservation::where('id', (int) $locked->reservation_id) - ->lockForUpdate()->first(); - if ($host === null || $reservation === null - || (int) $reservation->host_id !== (int) $host->id - || (int) ($reservation->instance_id ?? 0) !== (int) $locked->id - || (string) $reservation->state !== 'committed') { + ->first(); + if ($host === null || $reservationRef === null + || (int) $reservationRef->host_id !== (int) $host->id + || (int) ($reservationRef->network_attachment_id ?? 0) < 1 + || (int) ($reservationRef->public_ip_pool_id ?? 0) < 1) { throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409); } $parts = explode('/', (string) $body['public_ip_cidr'], 2); + $targetPoolRef = CloudPublicIpPool::where('host_id', (int) $host->id) + ->where('pool_key', (string) $body['public_pool_key'])->first(); + if ($targetPoolRef === null) { + throw new CloudError('所选公网地址池已不可用,请刷新后重试', 409); + } $targetRef = CloudPublicIp::where('host_id', (int) $host->id) + ->where('public_ip_pool_id', (int) $targetPoolRef->id) ->where('address', $parts[0]) - ->where('prefix_length', (int) $parts[1])->first(['id']); + ->where('prefix_length', (int) $parts[1])->first(); if ($targetRef === null) { - throw new CloudError('所选公网 IP 不在当前宿主机的可用账本中', 409); + throw new CloudError('所选公网 IP 不在指定地址池的可用账本中', 409); + } + + $networkAttachmentId = (int) $reservationRef->network_attachment_id; + $sourcePoolId = (int) $reservationRef->public_ip_pool_id; + $targetPoolId = (int) $targetPoolRef->id; + $attachment = CloudHostNetworkAttachment::where( + 'id', $networkAttachmentId + )->lockForUpdate()->first(); + $poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId])); + sort($poolIds, SORT_NUMERIC); + $pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id') + ->lockForUpdate()->get()->keyBy('id'); + $sourcePool = $pools->get($sourcePoolId); + $targetPool = $pools->get($targetPoolId); + $reservation = CloudResourceReservation::where( + 'id', (int) $reservationRef->id + )->lockForUpdate()->first(); + $reservationPool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + if ($reservation === null) { + throw new CloudError('虚拟机缺少有效的公网 IP 资源预留', 409); } $ipIds = array_values(array_unique([ (int) $reservation->public_ip_id, (int) $targetRef->id, @@ -107,8 +144,48 @@ final class CloudJobService ->lockForUpdate()->get()->keyBy('id'); $source = $ips->get((int) $reservation->public_ip_id); $target = $ips->get((int) $targetRef->id); - if ($source === null || $target === null + if ($attachment === null || $sourcePool === null + || $targetPool === null || $source === null || $target === null + || $reservationPool === null + || (int) $attachment->host_id !== (int) $host->id + || (int) $reservation->resource_pool_id + !== (int) ($locked->resource_pool_id ?? 0) + || (int) $attachment->line_id + !== (int) $reservationPool->line_id + || (string) $attachment->state !== 'active' + || (string) $attachment->sync_state !== 'fresh' + || (int) $attachment->observed_revision + < (int) $attachment->desired_revision + || (string) $attachment->network_selector + !== (string) $host->default_network + || (int) $sourcePool->host_id !== (int) $host->id + || (int) $targetPool->host_id !== (int) $host->id + || preg_match('/^[a-f0-9]{32}$/D', + (string) $sourcePool->pool_key) !== 1 + || (int) $sourcePool->network_attachment_id + !== $networkAttachmentId + || (int) $targetPool->network_attachment_id + !== $networkAttachmentId + || (string) $targetPool->pool_key + !== (string) $body['public_pool_key'] + || (string) $targetPool->state !== 'active' + || (string) $targetPool->sync_state !== 'fresh' + || (int) $targetPool->observed_revision + < (int) $targetPool->desired_revision + || (int) $reservation->host_id !== (int) $host->id + || (int) ($reservation->instance_id ?? 0) !== (int) $locked->id + || (string) $reservation->state !== 'committed' + || (int) ($reservation->network_attachment_id ?? 0) + !== $networkAttachmentId + || (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId || (int) $source->host_id !== (int) $host->id + || (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId + || (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId + || (int) $target->prefix_length + !== (int) $targetPool->guest_prefix_length + || !self::publicIpBelongsToPool($source, $sourcePool) + || !self::publicIpBelongsToPool($target, $targetPool) + || !self::instancePublicIpMatches($locked, $source) || (string) $source->state !== 'assigned' || (int) ($source->reservation_id ?? 0) !== (int) $reservation->id || (int) ($source->instance_id ?? 0) !== (int) $locked->id @@ -123,7 +200,13 @@ final class CloudJobService || $target->operation_id !== null) { throw new CloudError('所选公网 IP 已不可分配,请刷新后重试', 409); } - $networkLedger = [$source, $target]; + $networkLedger = [ + 'source' => $source, + 'target' => $target, + 'network_attachment_id' => $networkAttachmentId, + 'source_public_ip_pool_id' => $sourcePoolId, + 'target_public_ip_pool_id' => $targetPoolId, + ]; } $job = new CloudJob(); $job->operation_id = bin2hex(random_bytes(16)); @@ -137,9 +220,16 @@ final class CloudJobService 'credential' => $credential, 'owner_id' => (int) $locked->user_id, 'can_manage' => (bool) ($actor['can_manage'] ?? false)]; if ($networkLedger !== null) { - [$source, $target] = $networkLedger; + $source = $networkLedger['source']; + $target = $networkLedger['target']; $jobPayload['source_public_ip_id'] = (int) $source->id; $jobPayload['target_public_ip_id'] = (int) $target->id; + $jobPayload['network_attachment_id'] = + $networkLedger['network_attachment_id']; + $jobPayload['source_public_ip_pool_id'] = + $networkLedger['source_public_ip_pool_id']; + $jobPayload['target_public_ip_pool_id'] = + $networkLedger['target_public_ip_pool_id']; // reservation_id is deliberately left NULL until the swap // succeeds because cloud_public_ips enforces one current IP // per reservation. @@ -312,4 +402,52 @@ final class CloudJobService 'to' => $from === 0 ? 0 : $from + count($items) - 1, ]]; } + + private static function publicIpBelongsToPool(CloudPublicIp $ip, + CloudPublicIpPool $pool): bool + { + $parts = explode('/', (string) $pool->cidr, 2); + if (count($parts) !== 2 || !ctype_digit($parts[1])) { + return false; + } + $prefix = (int) $parts[1]; + if ($prefix < 24 || $prefix > 30 + || (int) $ip->prefix_length !== (int) $pool->guest_prefix_length) { + return false; + } + $address = self::ipv4Number((string) $ip->address); + $network = self::ipv4Number($parts[0]); + if ($address === null || $network === null) { + return false; + } + $block = 2 ** (32 - $prefix); + $base = (int) (floor($network / $block) * $block); + return $address > $base && $address < $base + $block - 1; + } + + private static function instancePublicIpMatches(CloudInstance $instance, + CloudPublicIp $ip): bool + { + $spec = json_decode((string) $instance->spec_json, true); + $recorded = is_array($spec) && !array_is_list($spec) + ? ($spec['public_ip_cidr'] ?? null) : null; + return is_string($recorded) && hash_equals( + (string) $ip->address . '/' . (int) $ip->prefix_length, + trim($recorded) + ); + } + + private static function ipv4Number(string $value): ?int + { + if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return null; + } + $packed = inet_pton($value); + if ($packed === false || strlen($packed) !== 4) { + return null; + } + $parts = unpack('Nnumber', $packed); + return is_array($parts) && isset($parts['number']) + ? (int) sprintf('%u', $parts['number']) : null; + } } diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index 5fcb2236..2d756201 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -5,10 +5,13 @@ namespace App\Services\Cloud; use App\Models\CloudHost; use App\Models\CloudHostCapacityPolicy; use App\Models\CloudHostCapacitySnapshot; +use App\Models\CloudHostNetworkAttachment; +use App\Models\CloudHostResourcePoolMembership; use App\Models\CloudInstance; use App\Models\CloudNetworkLine; use App\Models\CloudOffer; use App\Models\CloudPublicIp; +use App\Models\CloudPublicIpPool; use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; @@ -26,6 +29,7 @@ use App\Services\Config; final class CloudPlacementService { private const GIB = 1073741824; + private const MAX_PUBLIC_IPS_PER_POOL = 254; private const ACTIVE_RESERVATIONS = ['held', 'uncertain']; /** @@ -82,15 +86,7 @@ final class CloudPlacementService continue; } $pendingByHost = self::pendingUsageByHost($candidateRows); - $availableIpHosts = array_fill_keys( - CloudPublicIp::query()->whereIn('host_id', - $candidateRows->pluck('id')->all()) - ->where('state', 'available')->distinct() - ->pluck('host_id')->map( - static fn ($id): int => (int) $id - )->all(), - true - ); + $availableIpHosts = self::availableIpHosts($candidateRows); foreach ($poolRequests as $key => $resources) { foreach ($candidateRows as $candidate) { $hostId = (int) $candidate->id; @@ -191,6 +187,7 @@ final class CloudPlacementService $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) ->lockForUpdate()->first(); if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id + || !self::reservationNetworkMatches($reservation, $ip) || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id || !hash_equals((string) $reservation->operation_id, (string) ($ip->operation_id ?? '')) @@ -238,6 +235,7 @@ final class CloudPlacementService $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) ->lockForUpdate()->first(); if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id + || !self::reservationNetworkMatches($reservation, $ip) || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id || !hash_equals((string) $reservation->operation_id, (string) ($ip->operation_id ?? ''))) { @@ -281,6 +279,7 @@ final class CloudPlacementService $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) ->lockForUpdate()->first(); if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id + || !self::reservationNetworkMatches($reservation, $ip) || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id || !hash_equals((string) $reservation->operation_id, (string) ($ip->operation_id ?? '')) @@ -318,22 +317,55 @@ final class CloudPlacementService /** Atomically settle the PHP-side address ledger for a network-change job. */ public static function finishNetworkChange(CloudInstance $instance, - string $operationId, int $sourceIpId, int $targetIpId, string $outcome): void + string $operationId, int $sourceIpId, int $targetIpId, + int $networkAttachmentId, int $sourcePoolId, int $targetPoolId, + string $outcome): void { if (!in_array($outcome, ['succeeded', 'failed', 'uncertain'], true) || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1 - || $sourceIpId < 1 || $targetIpId < 1 || $sourceIpId === $targetIpId) { + || min($sourceIpId, $targetIpId, $networkAttachmentId, + $sourcePoolId, $targetPoolId) < 1 + || $sourceIpId === $targetIpId) { throw new CloudError('公网 IP 变更账本参数无效', 409); } $host = CloudHost::where('id', (int) $instance->host_id) ->lockForUpdate()->first(); + + // Host is the sentinel for every host-scoped writer. Lock attachment + // and pool rows in numeric order before the reservation/IP ledger so + // placement and network changes cannot invert their lock hierarchy. + $attachment = CloudHostNetworkAttachment::where('id', $networkAttachmentId) + ->lockForUpdate()->first(); + $poolIds = array_values(array_unique([$sourcePoolId, $targetPoolId])); + sort($poolIds, SORT_NUMERIC); + $pools = CloudPublicIpPool::whereIn('id', $poolIds)->orderBy('id') + ->lockForUpdate()->get()->keyBy('id'); + $sourcePool = $pools->get($sourcePoolId); + $targetPool = $pools->get($targetPoolId); $reservation = $instance->reservation_id === null ? null : CloudResourceReservation::where('id', (int) $instance->reservation_id) ->lockForUpdate()->first(); - if ($host === null || $reservation === null + $reservationPool = $reservation === null ? null + : CloudResourcePool::find((int) $reservation->resource_pool_id); + if ($host === null || $attachment === null + || $sourcePool === null || $targetPool === null + || $reservationPool === null + || (int) $attachment->host_id !== (int) $host->id + || (int) $reservation->resource_pool_id + !== (int) ($instance->resource_pool_id ?? 0) + || (int) $attachment->line_id !== (int) $reservationPool->line_id + || (int) $sourcePool->host_id !== (int) $host->id + || (int) $targetPool->host_id !== (int) $host->id + || (int) $sourcePool->network_attachment_id !== $networkAttachmentId + || (int) $targetPool->network_attachment_id !== $networkAttachmentId + || preg_match('/^[a-f0-9]{32}$/D', (string) $targetPool->pool_key) !== 1 + || $reservation === null || (string) $reservation->state !== 'committed' || (int) $reservation->host_id !== (int) $host->id || (int) ($reservation->instance_id ?? 0) !== (int) $instance->id + || (int) ($reservation->network_attachment_id ?? 0) + !== $networkAttachmentId + || (int) ($reservation->public_ip_pool_id ?? 0) !== $sourcePoolId || (int) $reservation->public_ip_id !== $sourceIpId) { throw new CloudError('虚拟机公网 IP 资源预留不一致', 409); } @@ -347,6 +379,8 @@ final class CloudPlacementService if ($source === null || $target === null || (int) $source->host_id !== (int) $host->id || (int) $target->host_id !== (int) $host->id + || (int) ($source->public_ip_pool_id ?? 0) !== $sourcePoolId + || (int) ($target->public_ip_pool_id ?? 0) !== $targetPoolId || (string) $source->state !== 'assigned' || (int) ($source->reservation_id ?? 0) !== (int) $reservation->id || (int) ($source->instance_id ?? 0) !== (int) $instance->id @@ -358,6 +392,11 @@ final class CloudPlacementService || !hash_equals($operationId, (string) ($target->operation_id ?? ''))) { throw new CloudError('公网 IP 变更账本关联不一致', 409); } + if ($outcome === 'succeeded' + && (!self::publicIpBelongsToPool($source, $sourcePool) + || !self::publicIpBelongsToPool($target, $targetPool))) { + throw new CloudError('公网 IP 变更结果与地址池账本不一致', 409); + } $now = time(); if ($outcome === 'uncertain') { @@ -386,7 +425,8 @@ final class CloudPlacementService $source->save(); $reservation->public_ip_id = $targetIpId; - $reservation->updated_at = $now; + $reservation->network_attachment_id = $networkAttachmentId; + $reservation->public_ip_pool_id = $targetPoolId; $reservation->save(); $target->state = 'assigned'; @@ -405,20 +445,59 @@ final class CloudPlacementService // placement, inventory refresh and administrator policy changes before // any snapshot or concrete IP row is locked. $host = CloudHost::where('id', $hostId)->lockForUpdate()->first(); + $membership = CloudHostResourcePoolMembership::where('host_id', $hostId) + ->where('resource_pool_id', (int) $pool->id) + ->lockForUpdate()->first(); $policy = CloudHostCapacityPolicy::where('host_id', $hostId) ->lockForUpdate()->first(); $snapshot = CloudHostCapacitySnapshot::where('host_id', $hostId) ->lockForUpdate()->first(); - if ($policy === null || $host === null || $snapshot === null - || (int) $host->resource_pool_id !== (int) $pool->id + if ($host === null || $membership === null || $policy === null + || $snapshot === null + || (string) $membership->scheduler_state !== 'active' || !(bool) $host->enabled - || (string) $host->scheduler_state !== 'active' || (string) $host->health_state !== 'healthy' || (string) $snapshot->sync_state !== 'fresh' || (int) $snapshot->last_attempt_at < time() - self::freshnessSeconds()) { return null; } + $attachments = CloudHostNetworkAttachment::where('host_id', $hostId) + ->where('line_id', (int) $pool->line_id) + ->where('network_selector', (string) $host->default_network) + ->where('state', 'active')->where('sync_state', 'fresh') + ->whereColumn('observed_revision', '>=', 'desired_revision') + ->orderBy('id')->lockForUpdate()->get(); + if ($attachments->isEmpty()) { + return null; + } + $attachmentById = $attachments->keyBy('id'); + $publicPools = CloudPublicIpPool::where('host_id', $hostId) + ->whereIn('network_attachment_id', $attachments->pluck('id')->all()) + ->where('state', 'active')->where('sync_state', 'fresh') + ->whereColumn('observed_revision', '>=', 'desired_revision') + // Lock pool rows in primary-key order. Selection preference is + // applied in memory only after the complete row set is locked. + ->orderBy('id')->lockForUpdate()->get(); + $eligiblePools = []; + foreach ($publicPools as $publicPool) { + if (preg_match('/^[a-f0-9]{32}$/D', + (string) $publicPool->pool_key) === 1) { + $eligiblePools[] = $publicPool; + } + } + usort($eligiblePools, static function ($left, $right) use ($attachmentById): int { + $leftAttachment = $attachmentById->get((int) $left->network_attachment_id); + $rightAttachment = $attachmentById->get((int) $right->network_attachment_id); + return ((int) $leftAttachment->priority <=> (int) $rightAttachment->priority) + ?: ((int) $left->priority <=> (int) $right->priority) + ?: ((int) $leftAttachment->id <=> (int) $rightAttachment->id) + ?: ((int) $left->id <=> (int) $right->id); + }); + if ($eligiblePools === []) { + return null; + } + // This must be a current locking read, not an aggregate consistent // read. Under InnoDB REPEATABLE READ a transaction may have opened its // snapshot while waiting for the host sentinel; a normal SUM could @@ -439,10 +518,33 @@ final class CloudPlacementService return null; } - $ip = self::availablePublicIpQuery($hostId)->lockForUpdate()->first(); - if ($ip === null) { + $ip = null; + $selectedPool = null; + foreach ($eligiblePools as $publicPool) { + $candidateIps = self::availablePublicIpQuery( + $hostId, (int) $publicPool->id, + (int) $publicPool->guest_prefix_length + )->limit(self::MAX_PUBLIC_IPS_PER_POOL + 1)->lockForUpdate()->get(); + if ($candidateIps->count() > self::MAX_PUBLIC_IPS_PER_POOL) { + continue; + } + foreach ($candidateIps as $candidateIp) { + if (self::publicIpBelongsToPool($candidateIp, $publicPool)) { + $ip = $candidateIp; + $selectedPool = $publicPool; + break 2; + } + } + } + if ($ip === null || $selectedPool === null) { return null; } + $selectedAttachment = $attachmentById->get( + (int) $selectedPool->network_attachment_id + ); + if ($selectedAttachment === null) { + throw new CloudError('公网地址池与网络接入关联不一致', 409); + } $operationId = bin2hex(random_bytes(16)); $reservation = new CloudResourceReservation(); $reservation->reservation_key = bin2hex(random_bytes(16)); @@ -453,6 +555,8 @@ final class CloudPlacementService $reservation->host_id = $hostId; $reservation->user_id = $order->user_id; $reservation->instance_id = null; + $reservation->network_attachment_id = $selectedAttachment->id; + $reservation->public_ip_pool_id = $selectedPool->id; $reservation->public_ip_id = $ip->id; $reservation->cpu_cores = $resources['cpu_cores']; $reservation->memory_mib = $resources['memory_mib']; @@ -481,11 +585,14 @@ final class CloudPlacementService 'host' => $host, 'reservation' => $reservation, 'public_ip' => $ip, - 'payload' => self::placementPayload($payload, $host, $ip), + 'payload' => self::placementPayload( + $payload, $selectedAttachment, $selectedPool, $ip + ), ]; } - private static function placementPayload(array $payload, CloudHost $host, + private static function placementPayload(array $payload, + CloudHostNetworkAttachment $attachment, CloudPublicIpPool $publicPool, CloudPublicIp $ip): array { if (($payload['method'] ?? null) !== 'POST' @@ -493,7 +600,8 @@ final class CloudPlacementService || !is_array($payload['body'] ?? null)) { throw new CloudError('开通订单的加密请求无效', 409); } - $payload['body']['network'] = (string) $host->default_network; + $payload['body']['network'] = (string) $attachment->network_selector; + $payload['body']['public_pool_key'] = (string) $publicPool->pool_key; $payload['body']['public_ip_cidr'] = (string) $ip->address . '/' . (int) $ip->prefix_length; // For a configured host pool the engine owns these trusted values. @@ -577,22 +685,31 @@ final class CloudPlacementService { $freshAfter = time() - self::freshnessSeconds(); return CloudHost::query()->join( + 'cloud_host_resource_pool_memberships as pool_membership', + 'pool_membership.host_id', '=', 'cloud_hosts.id' + )->join( + 'cloud_resource_pools as membership_pool', + 'membership_pool.id', '=', 'pool_membership.resource_pool_id' + )->join( 'cloud_host_capacity_policies as capacity_policy', 'capacity_policy.host_id', '=', 'cloud_hosts.id' )->join( 'cloud_host_capacity_snapshots as capacity_snapshot', 'capacity_snapshot.host_id', '=', 'cloud_hosts.id' - )->where('cloud_hosts.resource_pool_id', $poolId) + )->where('pool_membership.resource_pool_id', $poolId) + ->where('pool_membership.scheduler_state', 'active') ->where('cloud_hosts.enabled', 1) - ->where('cloud_hosts.scheduler_state', 'active') ->where('cloud_hosts.health_state', 'healthy') ->where('capacity_snapshot.sync_state', 'fresh') ->where('capacity_snapshot.last_attempt_at', '>=', $freshAfter) ->where('capacity_policy.configured_cpu_cores', '>', 0) ->where('capacity_policy.configured_memory_mib', '>', 0) ->where('capacity_policy.configured_disk_gib', '>', 0) + ->distinct() ->get([ 'cloud_hosts.id', + 'cloud_hosts.default_network', + 'membership_pool.line_id as resource_pool_line_id', 'capacity_policy.configured_cpu_cores', 'capacity_policy.configured_memory_mib', 'capacity_policy.configured_disk_gib', @@ -650,6 +767,71 @@ final class CloudPlacementService return $usage; } + /** + * Return hosts with at least one concrete address in an eligible pool. + * + * This remains an advisory, non-locking read. The payment path repeats + * every predicate under the host, attachment, pool and IP row locks. + * + * @return array + */ + private static function availableIpHosts($candidateRows): array + { + $hostIds = $candidateRows->pluck('id')->map( + static fn ($id): int => (int) $id + )->unique()->values()->all(); + if ($hostIds === []) { + return []; + } + $lineId = (int) ($candidateRows->first()->resource_pool_line_id ?? 0); + if ($lineId < 1) { + return []; + } + $rows = CloudPublicIp::query()->join( + 'cloud_public_ip_pools as public_pool', + 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id' + )->join( + 'cloud_host_network_attachments as network_attachment', + 'network_attachment.id', '=', 'public_pool.network_attachment_id' + )->join( + 'cloud_hosts as eligible_host', + 'eligible_host.id', '=', 'cloud_public_ips.host_id' + )->whereIn('cloud_public_ips.host_id', $hostIds) + ->where('cloud_public_ips.state', 'available') + ->whereNull('cloud_public_ips.reservation_id') + ->whereNull('cloud_public_ips.instance_id') + ->whereNull('cloud_public_ips.operation_id') + ->whereColumn('cloud_public_ips.host_id', 'public_pool.host_id') + ->whereColumn('cloud_public_ips.prefix_length', + 'public_pool.guest_prefix_length') + ->whereColumn('cloud_public_ips.host_id', 'network_attachment.host_id') + ->whereColumn('network_attachment.network_selector', + 'eligible_host.default_network') + ->where('network_attachment.line_id', $lineId) + ->where('network_attachment.state', 'active') + ->where('network_attachment.sync_state', 'fresh') + ->whereColumn('network_attachment.observed_revision', '>=', + 'network_attachment.desired_revision') + ->where('public_pool.state', 'active') + ->where('public_pool.sync_state', 'fresh') + ->whereColumn('public_pool.observed_revision', '>=', + 'public_pool.desired_revision') + ->distinct()->get([ + 'cloud_public_ips.host_id', 'cloud_public_ips.address', + 'public_pool.pool_key', 'public_pool.cidr', + ]); + $available = []; + foreach ($rows as $row) { + if (preg_match('/^[a-f0-9]{32}$/D', (string) $row->pool_key) === 1 + && self::ipv4BelongsToCidr( + (string) $row->address, (string) $row->cidr + )) { + $available[(int) $row->host_id] = true; + } + } + return $available; + } + private static function reservationUsage($reservationRows, int $lastAttemptAt): array { @@ -734,10 +916,75 @@ final class CloudPlacementService ); } - private static function availablePublicIpQuery(int $hostId) + private static function availablePublicIpQuery(int $hostId, int $publicPoolId, + int $prefixLength) { return CloudPublicIp::query()->where('host_id', $hostId) - ->where('state', 'available')->orderBy('id'); + ->where('public_ip_pool_id', $publicPoolId) + ->where('prefix_length', $prefixLength) + ->where('state', 'available') + ->whereNull('reservation_id')->whereNull('instance_id') + ->whereNull('operation_id')->orderBy('id'); + } + + /** + * Nullable identities keep pre-migration in-flight jobs operable. A row + * that has started adopting the new identity must be complete and exact. + */ + private static function reservationNetworkMatches( + CloudResourceReservation $reservation, CloudPublicIp $ip): bool + { + if ($reservation->network_attachment_id === null + && $reservation->public_ip_pool_id === null) { + return true; + } + return (int) ($reservation->network_attachment_id ?? 0) > 0 + && (int) ($reservation->public_ip_pool_id ?? 0) > 0 + && (int) ($ip->public_ip_pool_id ?? 0) + === (int) $reservation->public_ip_pool_id; + } + + private static function publicIpBelongsToPool(CloudPublicIp $ip, + CloudPublicIpPool $pool): bool + { + if ((int) $ip->prefix_length !== (int) $pool->guest_prefix_length) { + return false; + } + return self::ipv4BelongsToCidr( + (string) $ip->address, (string) $pool->cidr + ); + } + + private static function ipv4BelongsToCidr(string $addressValue, + string $cidr): bool + { + $parts = explode('/', $cidr, 2); + if (count($parts) !== 2 || !ctype_digit($parts[1])) { + return false; + } + $prefix = (int) $parts[1]; + $address = self::ipv4Number($addressValue); + $network = self::ipv4Number($parts[0]); + if ($address === null || $network === null || $prefix < 24 || $prefix > 30) { + return false; + } + $block = 2 ** (32 - $prefix); + $base = (int) (floor($network / $block) * $block); + return $address > $base && $address < $base + $block - 1; + } + + private static function ipv4Number(string $value): ?int + { + if (filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return null; + } + $packed = inet_pton($value); + if ($packed === false || strlen($packed) !== 4) { + return null; + } + $parts = unpack('Nnumber', $packed); + return is_array($parts) && isset($parts['number']) + ? (int) sprintf('%u', $parts['number']) : null; } private static function freshnessSeconds(): int diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index 98133efe..393946fd 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -317,8 +317,26 @@ final class CloudWorkerService FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] ); + $networkAttachmentId = filter_var( + $payload['network_attachment_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $sourcePoolId = filter_var( + $payload['source_public_ip_pool_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); + $targetPoolId = filter_var( + $payload['target_public_ip_pool_id'] ?? null, + FILTER_VALIDATE_INT, + ['options' => ['min_range' => 1]] + ); if ($instance === null || $sourceIpId === false - || $targetIpId === false) { + || $targetIpId === false + || $networkAttachmentId === false + || $sourcePoolId === false + || $targetPoolId === false) { throw new CloudError( '公网 IP 变更任务缺少账本关联', 409 ); @@ -326,6 +344,8 @@ final class CloudWorkerService CloudPlacementService::finishNetworkChange( $instance, (string) $job->operation_id, (int) $sourceIpId, (int) $targetIpId, + (int) $networkAttachmentId, + (int) $sourcePoolId, (int) $targetPoolId, 'uncertain' ); }, 3 @@ -403,17 +423,40 @@ final class CloudWorkerService FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); $targetIpId = filter_var($payload['target_public_ip_id'] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]); - if ($instance === null || $sourceIpId === false || $targetIpId === false) { + $networkAttachmentId = filter_var( + $payload['network_attachment_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] + ); + $sourcePoolId = filter_var( + $payload['source_public_ip_pool_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] + ); + $targetPoolId = filter_var( + $payload['target_public_ip_pool_id'] ?? null, + FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]] + ); + if ($instance === null || $sourceIpId === false + || $targetIpId === false || $networkAttachmentId === false + || $sourcePoolId === false || $targetPoolId === false) { throw new CloudError('公网 IP 变更任务缺少账本关联', 409); } if ($status === 'succeeded') { $requested = is_array($payload['body'] ?? null) ? ($payload['body']['public_ip_cidr'] ?? null) : null; + $requestedPoolKey = is_array($payload['body'] ?? null) + ? ($payload['body']['public_pool_key'] ?? null) : null; $confirmed = is_array($result) ? ($result['public_ip_cidr'] ?? null) : null; + $confirmedPoolKey = is_array($result) + ? ($result['public_pool_key'] ?? null) : null; if (!is_string($requested) || !is_string($confirmed) - || $requested !== $confirmed) { - throw new CloudError('引擎成功结果缺少已确认的公网 IP', 502); + || !is_string($requestedPoolKey) + || !is_string($confirmedPoolKey) + || $requested !== $confirmed + || !hash_equals($requestedPoolKey, $confirmedPoolKey)) { + throw new CloudError( + '引擎成功结果缺少已确认的公网 IP 或地址池', 502 + ); } $decoded = json_decode((string) $instance->spec_json, true); if (!is_array($decoded) || array_is_list($decoded)) { @@ -421,7 +464,8 @@ final class CloudWorkerService } CloudPlacementService::finishNetworkChange($instance, (string) $job->operation_id, (int) $sourceIpId, - (int) $targetIpId, 'succeeded'); + (int) $targetIpId, (int) $networkAttachmentId, + (int) $sourcePoolId, (int) $targetPoolId, 'succeeded'); $decoded['public_ip_cidr'] = $confirmed; $instance->spec_json = json_encode($decoded, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES @@ -433,7 +477,8 @@ final class CloudWorkerService } else { CloudPlacementService::finishNetworkChange($instance, (string) $job->operation_id, (int) $sourceIpId, - (int) $targetIpId, $status); + (int) $targetIpId, (int) $networkAttachmentId, + (int) $sourcePoolId, (int) $targetPoolId, $status); } } elseif ($status === 'succeeded' && $job->kind === 'create') { $vm = is_array($result) ? ($result['vm'] ?? $result) : []; @@ -444,11 +489,24 @@ final class CloudWorkerService } $requestedPublicIpCidr = is_array($payload['body'] ?? null) ? ($payload['body']['public_ip_cidr'] ?? null) : null; + $requestedPublicPoolKey = is_array($payload['body'] ?? null) + ? ($payload['body']['public_pool_key'] ?? null) : null; $confirmedPublicIpCidr = $vm['public_ip_cidr'] ?? null; + $confirmedPublicPoolKey = $vm['public_pool_key'] ?? null; + // Jobs queued before the multi-pool rollout have no key; the + // engine's unique-IP inference remains their compatibility + // path. Every newly queued placement includes a key and must + // receive the same identity back before PHP commits it. + $poolIdentityMatches = $requestedPublicPoolKey === null + || (is_string($requestedPublicPoolKey) + && is_string($confirmedPublicPoolKey) + && hash_equals($requestedPublicPoolKey, + $confirmedPublicPoolKey)); if (!is_string($requestedPublicIpCidr) || !is_string($confirmedPublicIpCidr) || !hash_equals($requestedPublicIpCidr, - $confirmedPublicIpCidr)) { + $confirmedPublicIpCidr) + || !$poolIdentityMatches) { // A recovered create result may describe a VM whose // network was changed out of band after the original // response was lost. Never commit the original address in diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index 8a7b2ae5..8172bc2c 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -82,6 +82,11 @@ function cidrContains(cidr, address) { return (ipv4Number(parseIPv4(network.address)) & mask) === (ipv4Number(ip) & mask); } +function publicPoolKey(value) { + const key = String(value ?? '').trim(); + return /^[a-f0-9]{32}$/.test(key) ? key : ''; +} + function networkOptionsFromVm(vm) { const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24); const prefix = current?.prefix || 24; @@ -91,9 +96,12 @@ function networkOptionsFromVm(vm) { guest_prefix: prefix, gateway: vm.gateway || '', dns_servers: Array.isArray(vm.dns_servers) ? vm.dns_servers : [], + current_public_pool_key: '', public_pool_cidr: '', available_count: 0, available_ips: [], + available_ip_options: [], + pools: [], configuration_state: 'not_configured', can_change: false, }; @@ -107,38 +115,77 @@ function networkOptionsPayload(payload, vm) { const dns = Array.isArray(source.dns_servers) ? source.dns_servers.filter(value => parseIPv4(value)) : fallback.dns_servers; const normalizedGuestPrefix = Number.isInteger(guestPrefix) && guestPrefix >= 24 && guestPrefix <= 30 ? guestPrefix : fallback.guest_prefix; - const available = Array.isArray(source.available_ips) ? source.available_ips : []; - const availableIps = available.map(value => { - if (value && typeof value === 'object') return value.cidr || value.public_ip_cidr || value.ip || ''; - return value; - }).map(value => normalizeCidr(value, normalizedGuestPrefix)) - .filter(value => value && value.prefix === normalizedGuestPrefix) - .map(value => value.value); + const pools = []; + const poolsByKey = new Map(); + for (const value of Array.isArray(source.pools) ? source.pools : []) { + if (!value || typeof value !== 'object' || Array.isArray(value)) continue; + const key = publicPoolKey(value.public_pool_key || value.pool_key); + const poolCidr = normalizeCidr(value.pool_cidr, null); + const poolPrefix = Number(value.guest_prefix); + const poolGateway = parseIPv4(value.gateway)?.join('.') || ''; + if (!key || !poolCidr || !Number.isInteger(poolPrefix) + || poolPrefix < 24 || poolPrefix > 30 || !poolGateway) continue; + const pool = { + public_pool_key: key, + pool_cidr: poolCidr.value, + guest_prefix: poolPrefix, + gateway: poolGateway, + dns_servers: Array.isArray(value.dns_servers) + ? value.dns_servers.map(item => parseIPv4(item)?.join('.')).filter(Boolean) : [], + available_count: Math.max(0, Number(value.available_count) || 0), + }; + pools.push(pool); + poolsByKey.set(key, pool); + } + const availableOptions = []; + const seenOptions = new Set(); + for (const value of Array.isArray(source.available_ip_options) ? source.available_ip_options : []) { + if (!value || typeof value !== 'object' || Array.isArray(value)) continue; + const key = publicPoolKey(value.public_pool_key || value.pool_key); + const pool = poolsByKey.get(key); + const cidr = normalizeCidr(value.public_ip_cidr || value.cidr, pool?.guest_prefix); + const optionKey = cidr ? `${key}:${cidr.value}` : ''; + if (!pool || !cidr || cidr.prefix !== pool.guest_prefix + || !cidrContains(pool.pool_cidr, cidr.address) || seenOptions.has(optionKey)) continue; + seenOptions.add(optionKey); + availableOptions.push({ public_pool_key: key, public_ip_cidr: cidr.value }); + } + const availableIps = availableOptions.map(value => value.public_ip_cidr); return { ...fallback, ...source, current_ip_cidr: current?.value || fallback.current_ip_cidr, + current_public_pool_key: publicPoolKey(source.current_public_pool_key), guest_prefix: normalizedGuestPrefix, public_pool_cidr: String(source.public_pool_cidr || source.pool_cidr || '').trim(), gateway: String(source.gateway || fallback.gateway || '').trim(), dns_servers: dns, available_count: Number.isFinite(Number(source.available_count)) ? Math.max(0, Number(source.available_count)) : availableIps.length, - available_ips: [...new Set(availableIps)], + available_ips: availableIps, + available_ip_options: availableOptions, + pools, configuration_state: ['ready', 'not_configured', 'invalid', 'drift', 'unavailable'] .includes(source.configuration_state) ? source.configuration_state : 'unavailable', can_change: source.can_change === true, }; } -function networkOptionSummary(options) { - const pool = options.public_pool_cidr - || (options.configuration_state === 'not_configured' ? '未配置' : '提交时由引擎校验'); - const prefix = options.guest_prefix ? `/${options.guest_prefix}` : '未记录'; - const gateway = options.gateway || '提交时由宿主机配置决定'; - const dns = options.dns_servers?.length ? options.dns_servers.join('、') : '宿主机默认 DNS'; - const available = options.available_ips?.length - ? `${options.available_ips.length} 个` : '暂无可用地址'; +function networkOptionSummary(options, selectedPool = null) { + const pools = Array.isArray(options.pools) ? options.pools : []; + const selected = selectedPool || (pools.length === 1 ? pools[0] : null); + const pool = selected?.pool_cidr || (pools.length > 1 ? `${pools.length} 个启用地址池` + : (options.public_pool_cidr + || (options.configuration_state === 'not_configured' ? '未配置' : '提交时由引擎校验'))); + const prefix = selected?.guest_prefix ? `/${selected.guest_prefix}` + : (pools.length > 1 ? '按所选地址池' : (options.guest_prefix ? `/${options.guest_prefix}` : '未记录')); + const gateway = selected?.gateway || (pools.length > 1 ? '按所选地址池' + : (options.gateway || '提交时由宿主机配置决定')); + const dnsValues = selected?.dns_servers || (pools.length > 1 ? [] : options.dns_servers); + const dns = dnsValues?.length ? dnsValues.join('、') + : (pools.length > 1 ? '按所选地址池' : '宿主机默认 DNS'); + const available = options.available_ip_options?.length + ? `${options.available_ip_options.length} 个` : '暂无可用地址'; return { pool, prefix, gateway, dns, available }; } @@ -731,12 +778,21 @@ function networkOptionsView(section, options, fallback = false, fallbackMessage }); const select = section.querySelector('[name="public_ip_cidr"]'); const submit = section.querySelector('button[type="submit"]'); - const hasAvailable = options.available_ips?.length > 0; + const hasAvailable = options.available_ip_options?.length > 0; const canChange = options.can_change === true && options.configuration_state === 'ready' && hasAvailable; if (select instanceof HTMLSelectElement) { select.replaceChildren(new Option( hasAvailable ? '请选择新的公网 IP' : '当前没有可用公网 IP', '')); - for (const value of options.available_ips || []) select.add(new Option(value, value)); + const poolsByKey = new Map((options.pools || []) + .map(pool => [pool.public_pool_key, pool])); + for (const value of options.available_ip_options || []) { + const pool = poolsByKey.get(value.public_pool_key); + const label = options.pools?.length > 1 && pool?.pool_cidr + ? `${value.public_ip_cidr} · ${pool.pool_cidr}` : value.public_ip_cidr; + const option = new Option(label, value.public_ip_cidr); + option.dataset.publicPoolKey = value.public_pool_key; + select.add(option); + } select.disabled = !canChange; if (!hasAvailable || !canChange) select.setAttribute('aria-describedby', 'network-options-empty'); else select.removeAttribute('aria-describedby'); @@ -790,30 +846,40 @@ async function loadNetworkOptions(vm, section) { function targetNetworkValue(section, vm) { const options = section._networkOptions || networkOptionsFromVm(vm); const input = section.querySelector('[name="public_ip_cidr"]'); - const fallbackPrefix = Number(options.guest_prefix) || normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24)?.prefix || 24; if (options.can_change === false || options.configuration_state !== 'ready') { throw new Error('宿主机网络配置尚未就绪,暂不能更换公网 IP。'); } - if (!Array.isArray(options.available_ips) || options.available_ips.length === 0) { + if (!Array.isArray(options.available_ip_options) || options.available_ip_options.length === 0) { throw new Error('当前宿主机没有可用公网 IP,请先补充地址池或释放地址后重试。'); } if (!input?.value) throw new Error('请选择新的公网 IP。'); - const parsed = normalizeCidr(input?.value, fallbackPrefix); - if (!parsed || !options.available_ips.includes(parsed.value)) { + const selectedOption = input instanceof HTMLSelectElement ? input.selectedOptions[0] : null; + const selectedPoolKey = publicPoolKey(selectedOption?.dataset.publicPoolKey); + const selectedPool = (options.pools || []) + .find(pool => pool.public_pool_key === selectedPoolKey); + const parsed = normalizeCidr(input.value, selectedPool?.guest_prefix); + const available = parsed && options.available_ip_options.some(option => ( + option.public_ip_cidr === parsed.value && option.public_pool_key === selectedPoolKey + )); + if (!parsed || !selectedPool || !available) { throw new Error('请选择列表中的可用公网 IP,不支持手动填写。'); } - if (Number(options.guest_prefix) && parsed.prefix !== Number(options.guest_prefix)) { - throw new Error(`地址前缀必须为 /${options.guest_prefix},请不要修改宿主机分配的前缀。`); + if (parsed.prefix !== Number(selectedPool.guest_prefix)) { + throw new Error(`地址前缀必须为 /${selectedPool.guest_prefix},请不要修改宿主机分配的前缀。`); } - if (options.public_pool_cidr && !cidrContains(options.public_pool_cidr, parsed.address)) { - throw new Error(`目标地址不在宿主机地址池 ${options.public_pool_cidr} 内。`); + if (!cidrContains(selectedPool.pool_cidr, parsed.address)) { + throw new Error(`目标地址不在宿主机地址池 ${selectedPool.pool_cidr} 内。`); } const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, parsed.prefix); if (current?.value === parsed.value) throw new Error('新公网 IP 与当前配置相同。'); - const blocked = [options.gateway, ...(options.dns_servers || []), ...(options.public_reserved_ips || options.reserved_ips || [])] + const blocked = [selectedPool.gateway, ...(selectedPool.dns_servers || [])] .map(value => parseIPv4(value)?.join('.')).filter(Boolean); if (blocked.includes(parsed.address)) throw new Error('目标地址是网关、DNS 或保留地址,不能分配给虚拟机。'); - return parsed.value; + return { + public_ip_cidr: parsed.value, + public_pool_key: selectedPoolKey, + pool: selectedPool, + }; } function makeNetworkConfirmation(section, vm, target, options) { @@ -823,8 +889,8 @@ function makeNetworkConfirmation(section, vm, target, options) { const check = confirmation?.querySelector('[data-network-confirm-check]'); const submit = confirmation?.querySelector('[data-network-confirm-submit]'); if (!confirmation || !summary || !check || !submit) return null; - const network = networkOptionSummary(options); - summary.textContent = `公网地址将从 ${current} 更换为 ${target}。运行中的实例会受控关机并重新启动,已关机实例保持关机;网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`; + const network = networkOptionSummary(options, target.pool); + summary.textContent = `公网地址将从 ${current} 更换为 ${target.public_ip_cidr}。运行中的实例会受控关机并重新启动,已关机实例保持关机;地址池 ${network.pool}、网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`; check.checked = false; submit.disabled = true; confirmation.hidden = false; @@ -1050,7 +1116,9 @@ function networkEditor(vm) { setNetworkFeedback(section, '正在创建网络变更任务,请勿重复提交…', 'muted'); try { const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, { - public_ip_cidr: target, confirm_restart: true, + public_ip_cidr: target.public_ip_cidr, + public_pool_key: target.public_pool_key, + confirm_restart: true, }, controller); const jobId = result?.job_id ?? result?.job?.id ?? result?.operation_id; if (!jobId) throw new Error('服务器未返回网络变更任务编号,请在任务记录中核对。'); diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 4f766883..89d201d2 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100314' scope='global'} +{assign var=venix_asset_version value='2026100315' scope='global'} diff --git a/web/tests/AdminHostSchedulingContractTest.php b/web/tests/AdminHostSchedulingContractTest.php index e0cd7d88..e7d0fab0 100644 --- a/web/tests/AdminHostSchedulingContractTest.php +++ b/web/tests/AdminHostSchedulingContractTest.php @@ -69,6 +69,12 @@ $assert(str_contains($service, "\$schedulerState === 'active'") && str_contains($service, "(string) \$region->status !== 'active'") && str_contains($service, '$safety >= $configured'), 'Active scheduling must validate the host, pool hierarchy and safety reserves.'); +$assert(str_contains($service, 'assertReservationLine($host, $pool, $line)') + && str_contains($service, + "->whereIn('state', ['held', 'uncertain', 'committed'])") + && str_contains($service, + '宿主机仍有其他线路的实例或资源预留,不能跨线路更换资源池'), + 'Hosts with live reservations must not move their network inventory across sales lines.'); $assert(str_contains($service, 'CloudHostInventorySyncService())->syncOne($hostId)') && str_contains($service, '可以保存配置,但调度器会拒绝放置实例'), 'Manual sync and non-blocking health/staleness warnings must remain explicit.'); diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index 4aa35f2e..551d98c4 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -24,6 +24,8 @@ namespace { use App\Models\CloudHost; use App\Models\CloudHostCapacityPolicy; use App\Models\CloudHostCapacitySnapshot; + use App\Models\CloudHostNetworkAttachment; + use App\Models\CloudHostResourcePoolMembership; use App\Models\CloudInstance; use App\Models\CloudInvoice; use App\Models\CloudInvoicePayment; @@ -33,6 +35,7 @@ namespace { use App\Models\CloudOrder; use App\Models\CloudJob; use App\Models\CloudPublicIp; + use App\Models\CloudPublicIpPool; use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; @@ -67,14 +70,17 @@ namespace { $schema->create('cloud_network_lines', function (Blueprint $t) { $t->increments('id'); $t->integer('region_id'); $t->string('code'); $t->string('name'); $t->integer('is_default')->default(0); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_resource_pools', function (Blueprint $t) { $t->increments('id'); $t->integer('line_id'); $t->string('code'); $t->string('name'); $t->string('status'); $t->string('scheduling_policy')->default('balanced'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->string('country_code')->default(''); $t->integer('enabled'); $t->integer('resource_pool_id')->nullable(); $t->string('scheduler_state')->default('disabled'); $t->string('health_state')->default('unknown'); $t->integer('last_seen_at')->nullable(); $t->integer('health_checked_at')->nullable(); $t->string('health_error_code')->default(''); $t->string('default_network'); $t->integer('created_at')->default(0); $t->integer('updated_at')->default(0); }); + $schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); }); + $schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('bridge'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } }); $schema->create('cloud_host_capacity_snapshots', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['cpu_total_cores', 'cpu_allocated_cores', 'cpu_available_cores', 'memory_total_mib', 'memory_allocated_mib', 'memory_available_mib', 'storage_total_bytes', 'storage_allocated_bytes', 'storage_available_bytes', 'instance_total_count', 'instance_running_count', 'public_ip_configured', 'public_ip_total_count', 'public_ip_reserved_count', 'public_ip_allocated_count', 'public_ip_available_count'] as $v) { $t->integer($v)->default(0); } $t->string('sync_state')->default('never'); foreach (['observed_at', 'last_attempt_at', 'revision', 'attempt_generation'] as $v) { $t->integer($v)->default(0); } $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); - $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); }); $schema->create('cloud_template_retirements', function (Blueprint $t) { $t->string('template_id')->primary(); $t->string('state')->default('deleting'); $t->integer('template_created_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_template_catalog_locks', function (Blueprint $t) { $t->integer('id')->primary(); $t->integer('updated_at'); $t->string('lease_token')->nullable(); $t->string('lease_kind')->nullable(); $t->integer('lease_until')->default(0); }); $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('payload_cipher')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); - $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); foreach (['order_id', 'offer_id', 'resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); + $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); foreach (['order_id', 'offer_id', 'resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); $schema->create('cloud_jobs', function (Blueprint $t) { $t->increments('id'); $t->string('operation_id')->unique(); foreach (['order_id', 'instance_id'] as $v) { $t->integer($v)->nullable(); } foreach (['user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('kind'); $t->string('status'); $t->text('payload_cipher'); $t->integer('attempts')->default(0); $t->integer('dispatched_at')->nullable(); $t->string('lease_token')->nullable(); $t->integer('lease_until')->default(0); $t->integer('available_at'); $t->string('error_code')->nullable(); $t->text('result_json')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); }); $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'offer_id', 'resource_pool_id', 'reservation_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('credential_cipher')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); }); $schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); }); @@ -89,9 +95,15 @@ namespace { $line = new CloudNetworkLine(); $line->region_id = $region->id; $line->code = 'default'; $line->name = 'Default'; $line->is_default = true; $line->status = 'active'; $line->sort = 0; $line->created_at = $line->updated_at = $now; $line->save(); $pool = new CloudResourcePool(); $pool->line_id = $line->id; $pool->code = 'general'; $pool->name = 'General'; $pool->status = 'active'; $pool->scheduling_policy = 'balanced'; $pool->sort = 0; $pool->created_at = $pool->updated_at = $now; $pool->save(); $host = new CloudHost(); $host->name = 'host'; $host->enabled = true; $host->resource_pool_id = $pool->id; $host->scheduler_state = 'active'; $host->health_state = 'healthy'; $host->last_seen_at = $now; $host->health_checked_at = $now; $host->health_error_code = ''; $host->default_network = 'bridge:br0'; $host->created_at = $host->updated_at = $now; $host->save(); + $membership = new CloudHostResourcePoolMembership(); $membership->host_id = $host->id; $membership->resource_pool_id = $pool->id; $membership->scheduler_state = 'active'; $membership->priority = 0; $membership->weight = 100; $membership->created_at = $membership->updated_at = $now; $membership->save(); + $attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary bridge'; $attachment->network_mode = 'bridge'; $attachment->network_selector = 'bridge:br0'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'fresh'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save(); + $sourcePoolKey = str_repeat('1', 32); $targetPoolKey = str_repeat('2', 32); + $sourcePublicPool = new CloudPublicIpPool(); $sourcePublicPool->pool_key = $sourcePoolKey; $sourcePublicPool->host_id = $host->id; $sourcePublicPool->network_attachment_id = $attachment->id; $sourcePublicPool->name = 'Primary public pool'; $sourcePublicPool->cidr = '203.0.113.16/29'; $sourcePublicPool->gateway = '203.0.113.17'; $sourcePublicPool->guest_prefix_length = 28; $sourcePublicPool->dns_servers_json = '["1.1.1.1"]'; $sourcePublicPool->reserved_ips_json = '[]'; $sourcePublicPool->state = 'active'; $sourcePublicPool->priority = 0; $sourcePublicPool->desired_revision = 1; $sourcePublicPool->observed_revision = 1; $sourcePublicPool->sync_state = 'fresh'; $sourcePublicPool->last_error_code = ''; $sourcePublicPool->created_at = $sourcePublicPool->updated_at = $now; $sourcePublicPool->save(); + $targetPublicPool = new CloudPublicIpPool(); $targetPublicPool->pool_key = $targetPoolKey; $targetPublicPool->host_id = $host->id; $targetPublicPool->network_attachment_id = $attachment->id; $targetPublicPool->name = 'Secondary public pool'; $targetPublicPool->cidr = '203.0.113.32/29'; $targetPublicPool->gateway = '203.0.113.33'; $targetPublicPool->guest_prefix_length = 28; $targetPublicPool->dns_servers_json = '["1.0.0.1"]'; $targetPublicPool->reserved_ips_json = '[]'; $targetPublicPool->state = 'active'; $targetPublicPool->priority = 10; $targetPublicPool->desired_revision = 1; $targetPublicPool->observed_revision = 1; $targetPublicPool->sync_state = 'fresh'; $targetPublicPool->last_error_code = ''; $targetPublicPool->created_at = $targetPublicPool->updated_at = $now; $targetPublicPool->save(); $policy = new CloudHostCapacityPolicy(); $policy->host_id = $host->id; $policy->configured_cpu_cores = 64; $policy->configured_memory_mib = 131072; $policy->configured_disk_gib = 4096; $policy->safety_cpu_cores = 2; $policy->safety_memory_mib = 2048; $policy->safety_disk_gib = 64; $policy->max_instances = 100; $policy->created_at = $policy->updated_at = $now; $policy->save(); $snapshot = new CloudHostCapacitySnapshot(); $snapshot->host_id = $host->id; $snapshot->cpu_total_cores = 64; $snapshot->cpu_allocated_cores = 0; $snapshot->cpu_available_cores = 64; $snapshot->memory_total_mib = 131072; $snapshot->memory_allocated_mib = 0; $snapshot->memory_available_mib = 131072; $snapshot->storage_total_bytes = 4096 * 1073741824; $snapshot->storage_allocated_bytes = 0; $snapshot->storage_available_bytes = 4096 * 1073741824; $snapshot->instance_total_count = 0; $snapshot->instance_running_count = 0; $snapshot->public_ip_configured = true; $snapshot->public_ip_total_count = 4; $snapshot->public_ip_reserved_count = 0; $snapshot->public_ip_allocated_count = 0; $snapshot->public_ip_available_count = 4; $snapshot->sync_state = 'fresh'; $snapshot->observed_at = $now; $snapshot->last_attempt_at = $now; $snapshot->revision = 1; $snapshot->last_error_code = ''; $snapshot->created_at = $snapshot->updated_at = $now; $snapshot->save(); - foreach (['203.0.113.18', '203.0.113.19', '203.0.113.20', '203.0.113.21'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); } + foreach (['203.0.113.18', '203.0.113.19'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $sourcePublicPool->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); } + foreach (['203.0.113.34', '203.0.113.35'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $targetPublicPool->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); } $plan = new Shop(); $plan->name = 'plan'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->sort = 0; $plan->save(); $soldOutPlan = new Shop(); $soldOutPlan->name = 'sold-out-plan'; $soldOutPlan->cpu_cores = 2; $soldOutPlan->memory_mib = 2048; $soldOutPlan->bandwidth_mbps = 100; $soldOutPlan->disk_gib = 20; $soldOutPlan->validity_days = 30; $soldOutPlan->traffic_quota_bytes = 1024 * 1024 * 1024; $soldOutPlan->status = 1; $soldOutPlan->sort = 0; $soldOutPlan->save(); $offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save(); @@ -142,6 +154,24 @@ namespace { $host->health_state = 'healthy'; $host->updated_at = time(); $host->save(); + $membership->scheduler_state = 'disabled'; + $membership->updated_at = time(); + $membership->save(); + $membershipUnavailable = CloudDeploymentPageService::saleCatalog(); + $assert(($membershipUnavailable['offers'][0]['sellable'] ?? null) === false, + 'Legacy host scheduling fields bypassed the canonical pool membership.'); + $membership->scheduler_state = 'active'; + $membership->updated_at = time(); + $membership->save(); + $attachment->sync_state = 'failed'; + $attachment->updated_at = time(); + $attachment->save(); + $staleNetworkCatalog = CloudDeploymentPageService::saleCatalog(); + $assert(($staleNetworkCatalog['offers'][0]['sellable'] ?? null) === false, + 'A pool on a stale network attachment remained sellable.'); + $attachment->sync_state = 'fresh'; + $attachment->updated_at = time(); + $attachment->save(); CloudPublicIp::query()->update(['state' => 'reserved', 'updated_at' => time()]); $noAddressCatalog = CloudDeploymentPageService::saleCatalog(); $assert(($noAddressCatalog['offers'][0]['sellable'] ?? null) === false, @@ -263,6 +293,9 @@ namespace { && (int) $openingReservation->cpu_cores === 2 && (int) $openingReservation->memory_mib === 2048 && (int) $openingReservation->disk_gib === 20 + && (int) $openingReservation->network_attachment_id === (int) $attachment->id + && (int) $openingReservation->public_ip_pool_id + === (int) $sourcePublicPool->id && (string) $openingJob->operation_id === (string) $openingReservation->operation_id && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'reserved' && CloudJob::where('order_id', $first->id)->count() === 1 @@ -286,6 +319,7 @@ namespace { ]], 'autostart' => true, 'managed' => true, + 'public_pool_key' => $sourcePoolKey, 'public_ip_cidr' => '203.0.113.18/28', 'os_source' => 'cloud_template', 'os_name' => 'AlmaLinux 10', @@ -314,6 +348,22 @@ namespace { $openingJob->available_at = 0; $openingJob->save(); unset($createdVm['status']); + $poolMismatchedVm = array_replace($createdVm, [ + 'public_pool_key' => str_repeat('f', 32), + ]); + $mock->append(new Response(200, [], json_encode([ + 'status' => 'succeeded', 'result' => $poolMismatchedVm, + ]))); + $worker->tick(); + $openingJob->refresh(); + $openingReservation->refresh(); + $assert($openingJob->status === 'uncertain' + && $openingReservation->state === 'uncertain' + && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'uncertain' + && CloudInstance::count() === 0, + 'A create result with a mismatched public pool was committed.'); + $openingJob->available_at = 0; + $openingJob->save(); $mock->append(new Response(200, [], json_encode([ 'status' => 'succeeded', 'result' => $createdVm, ]))); @@ -342,7 +392,9 @@ namespace { 'User-visible creation progress lacks safe timing or attempt metadata.'); $posted = json_decode((string) $history[0]['request']->getBody(), true); $signedActor = json_decode(base64_decode(strtr($history[0]['request']->getHeaderLine('X-Cloud-Actor'), '-_', '+/')), true); - $assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 && $posted['network'] === 'bridge:br0' + $assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 + && $posted['network'] === 'bridge:br0' + && $posted['public_pool_key'] === $sourcePoolKey && $signedActor['can_provision'] === true && $signedActor['can_manage'] === true, 'Plan or provisioning authority lost.'); $assert(!str_contains(CloudJob::first()->result_json, 'must-not-persist'), 'Plain password saved in result.'); $terminalPayload = \App\Services\Cloud\CloudSecrets::decrypt( @@ -925,10 +977,51 @@ namespace { // job keeps both ledger IDs, while the engine receives only its existing // request body. An ambiguous response keeps both addresses unavailable and // a reconciled success atomically moves the reservation to the target. - $networkTarget = CloudPublicIp::where('address', '203.0.113.20')->first(); + try { + CloudJobService::enqueue($instance->fresh(), $actor, + 'network_change', 'POST', '/network', [ + 'public_ip_cidr' => '203.0.113.34/28', + 'confirm_restart' => true, + ]); + throw new RuntimeException('Network change accepted an implicit public pool.'); + } catch (CloudError $expected) { + $assert($expected->httpStatus === 422, + 'Missing public pool key returned the wrong status.'); + } + try { + CloudJobService::enqueue($instance->fresh(), $actor, + 'network_change', 'POST', '/network', [ + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $sourcePoolKey, + 'confirm_restart' => true, + ]); + throw new RuntimeException('Network change accepted an IP from another pool.'); + } catch (CloudError $expected) { + $assert($expected->httpStatus === 409, + 'Pool/IP mismatch returned the wrong status.'); + } + $attachment->line_id = (int) $line->id + 100; + $attachment->save(); + try { + CloudJobService::enqueue($instance->fresh(), $actor, + 'network_change', 'POST', '/network', [ + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $targetPoolKey, + 'confirm_restart' => true, + ]); + throw new RuntimeException('Network change crossed the instance sales line.'); + } catch (CloudError $expected) { + $assert($expected->httpStatus === 409, + 'Sales-line mismatch returned the wrong status.'); + } + $attachment->line_id = $line->id; + $attachment->save(); + $reservationUpdatedAtBeforeNetwork = (int) $openingReservation->fresh()->updated_at; + $networkTarget = CloudPublicIp::where('address', '203.0.113.34')->first(); $networkChange = CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.20/28', 'confirm_restart' => true, + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true, ]); $networkPayload = \App\Services\Cloud\CloudSecrets::decrypt( $networkChange->payload_cipher @@ -938,6 +1031,12 @@ namespace { === (int) $openingReservation->public_ip_id && (int) ($networkPayload['target_public_ip_id'] ?? 0) === (int) $networkTarget->id + && (int) ($networkPayload['network_attachment_id'] ?? 0) + === (int) $attachment->id + && (int) ($networkPayload['source_public_ip_pool_id'] ?? 0) + === (int) $sourcePublicPool->id + && (int) ($networkPayload['target_public_ip_pool_id'] ?? 0) + === (int) $targetPublicPool->id && $networkTarget->state === 'changing' && $networkTarget->reservation_id === null && (int) $networkTarget->instance_id === (int) $instance->id @@ -952,9 +1051,13 @@ namespace { $networkBody = json_decode((string) $networkRequest->getBody(), true); $networkTarget->refresh(); $assert($networkBody === [ - 'public_ip_cidr' => '203.0.113.20/28', 'confirm_restart' => true, + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true, ] && $networkTarget->state === 'uncertain' + && (int) CloudResourceReservation::find( + $openingReservation->id + )->public_ip_pool_id === (int) $sourcePublicPool->id && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'assigned', 'Ambiguous network change exposed ledger metadata to the engine or released either address.'); $networkChange->refresh(); @@ -962,7 +1065,25 @@ namespace { $networkChange->save(); $mock->append(new Response(200, [], json_encode([ 'status' => 'succeeded', 'result' => [ - 'public_ip_cidr' => '203.0.113.20/28', 'network_changed' => true, + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $sourcePoolKey, 'network_changed' => true, + ], + ]))); + $worker->tick(); + $networkChange->refresh(); + $networkTarget->refresh(); + $assert($networkChange->status === 'uncertain' + && $networkTarget->state === 'uncertain' + && (int) CloudResourceReservation::find( + $openingReservation->id + )->public_ip_pool_id === (int) $sourcePublicPool->id, + 'A network success for another public pool moved the local ledger.'); + $networkChange->available_at = 0; + $networkChange->save(); + $mock->append(new Response(200, [], json_encode([ + 'status' => 'succeeded', 'result' => [ + 'public_ip_cidr' => '203.0.113.34/28', + 'public_pool_key' => $targetPoolKey, 'network_changed' => true, ], ]))); $worker->tick(); @@ -970,18 +1091,24 @@ namespace { $networkTarget->refresh(); $assert(CloudJob::find($networkChange->id)->status === 'succeeded' && (int) $networkReservation->public_ip_id === (int) $networkTarget->id + && (int) $networkReservation->network_attachment_id === (int) $attachment->id + && (int) $networkReservation->public_ip_pool_id + === (int) $targetPublicPool->id + && (int) $networkReservation->updated_at + === $reservationUpdatedAtBeforeNetwork && $networkTarget->state === 'assigned' && (int) $networkTarget->reservation_id === (int) $networkReservation->id && (int) $networkTarget->instance_id === (int) $instance->id && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'available' && (json_decode((string) $instance->fresh()->spec_json, true)['public_ip_cidr'] ?? null) - === '203.0.113.20/28', + === '203.0.113.34/28', 'Reconciled network success did not atomically swap the reservation and instance metadata.'); - $failedNetworkTarget = CloudPublicIp::where('address', '203.0.113.21')->first(); + $failedNetworkTarget = CloudPublicIp::where('address', '203.0.113.35')->first(); $failedNetwork = CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.21/28', 'confirm_restart' => true, + 'public_ip_cidr' => '203.0.113.35/28', + 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true, ]); $mock->append(new Response(422, [], json_encode([ 'operation_id' => $failedNetwork->operation_id, 'status' => 'failed', @@ -997,7 +1124,10 @@ namespace { && $failedNetworkTarget->operation_id === null && $networkTarget->state === 'assigned' && (int) CloudResourceReservation::find($openingReservation->id)->public_ip_id - === (int) $networkTarget->id, + === (int) $networkTarget->id + && (int) CloudResourceReservation::find( + $openingReservation->id + )->public_ip_pool_id === (int) $targetPublicPool->id, 'Explicit network failure changed the source assignment or retained its target hold.'); $delete = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE', '?delete_disks=true', []); diff --git a/web/tests/CloudInventoryRelationshipContractTest.php b/web/tests/CloudInventoryRelationshipContractTest.php new file mode 100644 index 00000000..ff6e4b8a --- /dev/null +++ b/web/tests/CloudInventoryRelationshipContractTest.php @@ -0,0 +1,63 @@ +get()') + && str_contains($membership, '$row->priority = self::SAFE_PRIORITY;') + && str_contains($membership, '$row->weight = self::SAFE_WEIGHT;') + && str_contains($membership, '$host->resource_pool_id =') + && str_contains($membership, '$host->scheduler_state ='), + 'Membership authority does not lock, normalize and mirror safely.'); + +$assert(str_contains($publicIp, 'protected static function booted(): void') + && str_contains($publicIp, 'static::creating(') + && str_contains($publicIp, "\$row->public_ip_pool_id ?? 0") + && str_contains($reservation, 'protected static function booted(): void') + && str_contains($reservation, 'static::creating(') + && str_contains($reservation, "'network_attachment_id', 'public_ip_pool_id'") + && str_contains($reservation, "'public_ip_id'") + && str_contains($inventory, + "\$publicPool->network_attachment_id = (int) \$attachment->id;") + && str_contains($inventory, + "\$row->public_ip_pool_id = \$identity['public_ip_pool_id'];"), + 'New reservation, pool or concrete-IP writes can omit a required relation.'); + +$assert(str_contains($schema, + 'network_attachment_id BIGINT UNSIGNED DEFAULT NULL') + && str_contains($schema, + 'public_ip_pool_id BIGINT UNSIGNED DEFAULT NULL') + && str_contains($schema, + 'public_ip_pool_id BIGINT UNSIGNED NULL AFTER host_id'), + 'Legacy upgrade columns must remain nullable until existing rows are backfilled.'); + +echo "Cloud inventory relationship write contracts passed.\n"; diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 150daace..f050ab3a 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -5,6 +5,26 @@ $controller = file_get_contents($root . '/app/Controllers/CloudAdminInstanceCont $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); $placement = file_get_contents($root . '/app/Services/Cloud/CloudPlacementService.php'); $worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php'); +$input = file_get_contents($root . '/app/Services/Cloud/CloudInput.php'); +$adminInstances = file_get_contents($root . '/public/cloud/admin-instances.js'); +$pendingStart = is_string($placement) + ? strpos($placement, 'private static function pendingUsageByHost') : false; +$pendingEnd = is_string($placement) + ? strpos($placement, 'private static function availableIpHosts') : false; +$pendingMethod = $pendingStart !== false && $pendingEnd !== false + ? substr($placement, $pendingStart, $pendingEnd - $pendingStart) : ''; +$availableStart = is_string($placement) + ? strpos($placement, 'private static function availablePublicIpQuery') : false; +$availableEnd = is_string($placement) + ? strpos($placement, 'private static function reservationNetworkMatches') : false; +$availableMethod = $availableStart !== false && $availableEnd !== false + ? substr($placement, $availableStart, $availableEnd - $availableStart) : ''; +$finishStart = is_string($placement) + ? strpos($placement, 'public static function finishNetworkChange') : false; +$finishEnd = is_string($placement) + ? strpos($placement, 'private static function tryHost', $finishStart ?: 0) : false; +$finishMethod = $finishStart !== false && $finishEnd !== false + ? substr($placement, $finishStart, $finishEnd - $finishStart) : ''; $assert = static function ($condition, string $message): void { if (!$condition) { @@ -14,31 +34,83 @@ $assert = static function ($condition, string $message): void { $assert(is_string($controller) && str_contains($controller, "->where('state', 'available')") - && str_contains($controller, 'isset($ledgerAvailable[$cidr])'), - 'Network choices no longer intersect the engine free-list with the local available-IP ledger.'); + && str_contains($controller, + '($ledgerAvailable[$cidr] ?? null) === $poolKey') + && str_contains($controller, 'available_ip_options') + && str_contains($controller, 'current_public_pool_key') + && str_contains($controller, + '(int) $attachment->line_id !== (int) $reservationPool->line_id') + && str_contains($controller, "['public_ip_cidr', 'public_pool_key', 'confirm_restart']"), + 'Network choices no longer intersect per-pool engine availability with the local ledger or require a pool key.'); +$assert(is_string($adminInstances) + && str_contains($adminInstances, 'available_ip_options') + && str_contains($adminInstances, 'option.dataset.publicPoolKey') + && str_contains($adminInstances, 'public_pool_key: target.public_pool_key') + && str_contains($adminInstances, 'networkOptionSummary(options, target.pool)'), + 'Admin network changes no longer preserve the selected pool identity and pool-specific network summary.'); +$assert(is_string($input) + && str_contains($input, 'function publicPoolKey') + && str_contains($input, '/^[a-f0-9]{32}$/D'), + 'Public pool keys no longer have a fixed lowercase-hex input boundary.'); $assert(is_string($jobs) && str_contains($jobs, '(string) $reservation->state !== \'committed\'') && str_contains($jobs, '(string) $source->state !== \'assigned\'') && str_contains($jobs, '(string) $target->state !== \'available\'') + && str_contains($jobs, '(string) $targetPool->state !== \'active\'') + && str_contains($jobs, '(string) $targetPool->sync_state !== \'fresh\'') + && str_contains($jobs, '$targetPool->network_attachment_id') + && str_contains($jobs, + '(int) $attachment->line_id') + && str_contains($jobs, '(int) $reservationPool->line_id') + && str_contains($jobs, 'self::instancePublicIpMatches($locked, $source)') && str_contains($jobs, '$target->state = \'changing\'') && str_contains($jobs, '$target->operation_id = $job->operation_id') && str_contains($jobs, '$jobPayload[\'source_public_ip_id\']') - && str_contains($jobs, '$jobPayload[\'target_public_ip_id\']'), - 'Network-change enqueue no longer locks and persists the source/target ledger identity.'); + && str_contains($jobs, '$jobPayload[\'target_public_ip_id\']') + && str_contains($jobs, '$jobPayload[\'network_attachment_id\']') + && str_contains($jobs, '$jobPayload[\'source_public_ip_pool_id\']') + && str_contains($jobs, '$jobPayload[\'target_public_ip_pool_id\']'), + 'Network-change enqueue no longer locks and persists the attachment/pool/address ledger identity.'); $assert(is_string($worker) && str_contains($worker, "['succeeded', 'failed', 'uncertain']") && str_contains($worker, 'CloudPlacementService::finishNetworkChange') + && str_contains($worker, '$confirmedPublicPoolKey') + && str_contains($worker, '$confirmedPoolKey') && str_contains($worker, '$markedUncertain !== 1') && str_contains($worker, "'uncertain'"), - 'Worker no longer settles every terminal or ambiguous network-change outcome.'); + 'Worker no longer confirms pool identity or settles every terminal/ambiguous network-change outcome.'); $assert(is_string($placement) + && str_contains($placement, 'cloud_host_resource_pool_memberships as pool_membership') + && !str_contains($placement, "->where('cloud_hosts.resource_pool_id', \$poolId)") + && str_contains($placement, '$reservation->network_attachment_id = $selectedAttachment->id') + && str_contains($placement, '$reservation->public_ip_pool_id = $selectedPool->id') + && str_contains($placement, '$payload[\'body\'][\'public_pool_key\']') && str_contains($placement, '$reservation->public_ip_id = $targetIpId') + && str_contains($placement, '$reservation->public_ip_pool_id = $targetPoolId') + && str_contains($placement, + '(int) $attachment->line_id !== (int) $reservationPool->line_id') + && str_contains($placement, + '(int) $ip->prefix_length !== (int) $pool->guest_prefix_length') && str_contains($placement, '$target->state = \'assigned\'') && str_contains($placement, '$target->state = \'uncertain\'') && str_contains($placement, '$source->state = \'available\'') && str_contains($placement, 'lockedHostAndReservation') && str_contains($placement, '(string) $reservation->state === \'committed\'') && str_contains($placement, '$ip->instance_id ?? 0'), - 'Placement ledger no longer enforces atomic swaps, conservative uncertainty, and committed-state monotonicity.'); + 'Placement no longer uses membership/pool-scoped allocation or enforce atomic multi-pool ledger swaps.'); +$assert(str_contains($placement, 'MAX_PUBLIC_IPS_PER_POOL + 1') + && str_contains($placement, 'foreach ($candidateIps as $candidateIp)'), + 'A malformed first address can still hide the rest of an otherwise usable pool.'); +$assert($finishMethod !== '' + && !str_contains($finishMethod, '$reservation->updated_at = $now'), + 'Network-only changes must not make committed capacity look newly pending.'); +$assert(str_contains($pendingMethod, "->whereIn('host_id', \$candidateIds)") + && !str_contains($pendingMethod, 'resource_pool_id'), + 'Advisory pending usage is no longer deducted once per physical host across memberships.'); +$assert(str_contains($availableMethod, "->where('state', 'available')") + && str_contains($availableMethod, "->whereNull('reservation_id')") + && str_contains($availableMethod, "->whereNull('instance_id')") + && str_contains($availableMethod, "->whereNull('operation_id')"), + 'Placement no longer rejects stale ownership fields on an apparently available address.'); echo "Cloud network IP ledger contract tests passed\n";