diff --git a/web/app/Command/CloudSetup.php b/web/app/Command/CloudSetup.php index a87044a2..f590b986 100644 --- a/web/app/Command/CloudSetup.php +++ b/web/app/Command/CloudSetup.php @@ -20,7 +20,8 @@ final class CloudSetup 'cloud_user_iso_replicas', 'cloud_rescue_templates', 'cloud_rescue_template_artifacts', 'cloud_rescue_template_replicas', 'cloud_host_resource_pool_memberships', - 'cloud_host_network_attachments', 'cloud_public_ip_pools', + 'cloud_host_network_attachments', + 'cloud_public_ip_pool_catalog_mutex', 'cloud_public_ip_pools', 'cloud_public_ip_pool_replacement_batches', 'cloud_public_ip_pool_replacement_batch_items', 'cloud_host_vpc_transports', 'cloud_vpc_cidr_pools', @@ -36,7 +37,8 @@ final class CloudSetup 'cloud_backup_restores', 'cloud_backup_recoveries', 'cloud_instance_migrations', 'cloud_peer_migration_artifacts', 'cloud_instance_runtime', 'cloud_orders', 'cloud_order_items', - 'cloud_resource_reservations', 'cloud_service_periods', + 'cloud_resource_reservations', 'cloud_resource_reservation_ips', + 'cloud_service_periods', 'cloud_traffic_pools', 'cloud_traffic_entitlements', 'cloud_traffic_ledger_events', 'cloud_traffic_instance_cursors', 'cloud_traffic_scan_failures', @@ -59,9 +61,13 @@ final class CloudSetup 'engine_vm_traffic_checkpoints', 'engine_vm_traffic_totals', ]; private const REQUIRED_MAIN_COLUMNS = [ + 'cloud_public_ip_pool_catalog_mutex' => [ + 'id', 'updated_at', + ], 'cloud_host_agents' => [ 'host_id', 'revision', 'tested_revision', - 'network_selectors_json', 'last_tested_at', + 'network_selectors_json', 'public_network_capabilities_json', + 'last_tested_at', ], 'cloud_host_network_attachments' => [ 'id', 'attachment_key', 'host_id', 'line_id', 'name', @@ -76,6 +82,21 @@ final class CloudSetup 'id', 'host_id', 'resource_pool_id', 'scheduler_state', 'priority', 'weight', 'revision', 'created_at', 'updated_at', ], + 'cloud_public_ip_pools' => [ + 'id', 'pool_key', 'host_id', 'network_attachment_id', + 'address_family', 'name', 'cidr', 'gateway', 'gateway_on_link', + 'guest_prefix_length', 'dns_servers_json', 'reserved_ips_json', + 'allocation_start', 'allocation_end', 'allocation_cursor', + 'max_allocations', 'state', 'priority', 'desired_revision', + 'observed_revision', 'sync_state', 'last_error_code', + 'created_at', 'updated_at', + ], + 'cloud_public_ips' => [ + 'id', 'host_id', 'public_ip_pool_id', 'address_family', + 'address', 'address_binary', 'prefix_length', 'state', + 'reservation_id', 'instance_id', 'operation_id', + 'created_at', 'updated_at', + ], 'cloud_traffic_pool_groups' => [ 'id', 'code', 'name', 'mode', 'revision', 'created_at', 'updated_at', @@ -301,6 +322,12 @@ final class CloudSetup 'disk_gib', 'state', 'expires_at', 'released_at', 'release_reason', 'created_at', 'updated_at', ], + 'cloud_resource_reservation_ips' => [ + 'id', 'reservation_id', 'address_family', + 'network_attachment_id', 'public_ip_pool_id', 'public_ip_id', + 'operation_id', 'state', 'released_at', 'release_reason', + 'created_at', 'updated_at', + ], 'cloud_service_periods' => [ 'id', 'instance_id', 'user_id', 'plan_id', 'order_id', 'renewal_id', 'traffic_pool_group_id', 'traffic_quota_mode', @@ -378,11 +405,23 @@ final class CloudSetup ], ]; private const REQUIRED_CHECKS = [ + 'cloud_public_ip_pool_catalog_mutex' => [ + 'chk_cloud_public_ip_pool_catalog_mutex', + ], 'cloud_host_network_attachments' => [ 'chk_cloud_network_attachment_state', 'chk_cloud_network_attachment_verification', 'chk_cloud_network_attachment_config_revision', ], + 'cloud_public_ip_pools' => [ + 'chk_cloud_public_ip_pool_family', + 'chk_cloud_public_ip_pool_prefix', + 'chk_cloud_public_ip_pool_gateway', + 'chk_cloud_public_ip_pool_allocation', + ], + 'cloud_public_ips' => [ + 'chk_cloud_public_ip_family', 'chk_cloud_public_ip_prefix', + ], 'cloud_traffic_pool_groups' => [ 'chk_cloud_traffic_pool_group_mode', ], @@ -486,12 +525,20 @@ final class CloudSetup 'cloud_resource_reservations' => [ 'chk_cloud_resource_reservation_source', ], + 'cloud_resource_reservation_ips' => [ + 'chk_cloud_reservation_ip_family', + 'chk_cloud_reservation_ip_state', + 'chk_cloud_reservation_ip_release', + ], 'cloud_agent_completion_events' => [ 'chk_cloud_completion_outcome', 'chk_cloud_completion_disposition', ], ]; private const REQUIRED_INDEXES = [ + 'cloud_public_ip_pool_catalog_mutex' => [ + 'PRIMARY', + ], 'cloud_host_network_attachments' => [ 'PRIMARY', 'cloud_host_network_attachment_key', 'cloud_host_network_selector', @@ -499,6 +546,18 @@ final class CloudSetup 'cloud_network_attachment_sync', 'cloud_network_attachment_verification', ], + 'cloud_public_ip_pools' => [ + 'PRIMARY', 'cloud_public_ip_pool_key', + 'cloud_public_ip_pool_cidr', + 'cloud_public_ip_pool_attachment', + 'cloud_public_ip_pool_sync', + ], + 'cloud_public_ips' => [ + 'PRIMARY', 'cloud_public_ip_address', + 'cloud_public_ip_available', 'cloud_public_ip_pool_available', + 'cloud_public_ip_reservation', 'cloud_public_ip_instance', + 'cloud_public_ip_operation', + ], 'cloud_traffic_pool_groups' => [ 'PRIMARY', 'cloud_traffic_pool_group_code', 'cloud_traffic_pool_group_mode', @@ -636,6 +695,12 @@ final class CloudSetup 'cloud_agent_completion_events' => [ 'PRIMARY', 'uniq_cloud_completion_operation', ], + 'cloud_resource_reservation_ips' => [ + 'PRIMARY', 'cloud_reservation_ip_family', + 'cloud_reservation_ip_operation', + 'cloud_reservation_ip_address', 'cloud_reservation_ip_pool', + 'cloud_reservation_ip_attachment', + ], 'cloud_backup_subscriptions' => [ 'PRIMARY', 'cloud_backup_subscription_instance', 'cloud_backup_subscription_due', @@ -821,6 +886,8 @@ final class CloudSetup /** Seed only immutable/default control rows in an otherwise fresh schema. */ private static function ensureMultiHostDefaults($connection): void { + $connection->table('cloud_public_ip_pool_catalog_mutex') + ->insertOrIgnore(['id' => 1, 'updated_at' => 0]); $connection->table('configurations')->insertOrIgnore([ 'name' => 'cloud_network_lines_enabled', 'value' => 'false', diff --git a/web/app/Controllers/CloudAdminHostNetworkController.php b/web/app/Controllers/CloudAdminHostNetworkController.php index 795b0e02..ac6bd6ed 100644 --- a/web/app/Controllers/CloudAdminHostNetworkController.php +++ b/web/app/Controllers/CloudAdminHostNetworkController.php @@ -36,9 +36,10 @@ final class CloudAdminHostNetworkController } else { $body = CloudInput::object($request); CloudInput::only($body, [ - 'network_attachment_id', 'name', 'cidr', 'gateway', - 'dns_servers', 'reserved_ips', 'guest_prefix_length', - 'state', 'request_key', + 'network_attachment_id', 'address_family', 'name', 'cidr', + 'gateway', 'gateway_on_link', 'dns_servers', 'reserved_ips', + 'allocation_start', 'allocation_end', 'max_allocations', + 'guest_prefix_length', 'state', 'request_key', ]); $result = $service->create($hostId, $actor, $body); $status = 201; @@ -53,9 +54,10 @@ final class CloudAdminHostNetworkController $actor = $this->actor($request, true); $body = CloudInput::object($request); CloudInput::only($body, [ - 'network_attachment_id', 'name', 'cidr', 'gateway', - 'dns_servers', 'reserved_ips', 'guest_prefix_length', - 'state', 'expected_revision', + 'network_attachment_id', 'address_family', 'name', 'cidr', + 'gateway', 'gateway_on_link', 'dns_servers', 'reserved_ips', + 'allocation_start', 'allocation_end', 'max_allocations', + 'guest_prefix_length', 'state', 'expected_revision', ]); $result = (new CloudAdminHostNetworkService())->update( (int) ($args['id'] ?? 0), diff --git a/web/app/Models/CloudHostAgent.php b/web/app/Models/CloudHostAgent.php index d07b872d..e37d1e06 100644 --- a/web/app/Models/CloudHostAgent.php +++ b/web/app/Models/CloudHostAgent.php @@ -11,6 +11,7 @@ final class CloudHostAgent extends Model protected $hidden = ['sealed_api_secret']; protected $attributes = [ 'network_selectors_json' => '[]', + 'public_network_capabilities_json' => '{}', ]; protected $casts = [ 'host_id' => 'int', diff --git a/web/app/Models/CloudPublicIpPoolCatalogMutex.php b/web/app/Models/CloudPublicIpPoolCatalogMutex.php new file mode 100644 index 00000000..55471785 --- /dev/null +++ b/web/app/Models/CloudPublicIpPoolCatalogMutex.php @@ -0,0 +1,16 @@ + 'int', + 'updated_at' => 'int', + ]; +} diff --git a/web/app/Services/Cloud/CloudAdminHostNetworkService.php b/web/app/Services/Cloud/CloudAdminHostNetworkService.php index 57134766..a2c54ffa 100644 --- a/web/app/Services/Cloud/CloudAdminHostNetworkService.php +++ b/web/app/Services/Cloud/CloudAdminHostNetworkService.php @@ -9,12 +9,13 @@ use App\Models\CloudHostResourcePoolMembership; use App\Models\CloudNetworkLine; use App\Models\CloudPublicIp; use App\Models\CloudPublicIpPool; +use App\Models\CloudPublicIpPoolCatalogMutex; use App\Models\CloudPublicIpPoolReplacementBatch; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; /** - * Administrator-owned desired state for one host's public IPv4 pools. + * Administrator-owned desired state for one host's public IPv4/IPv6 pools. * * PHP is the sole authority for public-pool configuration and IP allocation. * VM create/change-network jobs carry a signed immutable pool snapshot to the @@ -23,6 +24,7 @@ use App\Models\CloudResourceReservation; final class CloudAdminHostNetworkService { private const MAX_POOLS = 32; + private const MAX_IPV6_ALLOCATIONS = 65535; private const STATES = ['active', 'draining', 'disabled']; private const OCCUPIED_IP_STATES = [ 'reserved', 'assigned', 'changing', 'uncertain', @@ -122,6 +124,14 @@ final class CloudAdminHostNetworkService $host, $poolKey, $desired, $catalogItems, $creating, $expectedRevision ): array { + $catalogMutex = CloudPublicIpPoolCatalogMutex::where('id', 1) + ->lockForUpdate()->first(); + if ($catalogMutex === null) { + throw new CloudError( + '公网地址池全局目录锁未初始化,请先完成数据库结构更新', + 503 + ); + } $lockedHost = CloudHost::where('id', (int) $host->id) ->lockForUpdate()->first(); if ($lockedHost === null) { @@ -241,14 +251,24 @@ final class CloudAdminHostNetworkService 409 ); } + if ($pool !== null + && (int) $pool->address_family + !== $desired['address_family']) { + throw new CloudError( + '公网地址池地址族创建后不能修改,请新建目标地址族的地址池', + 409 + ); + } self::assertNoOverlap( $poolKey, + $desired['address_family'], $desired['cidr'], $poolRows ); self::assertNoGlobalOverlap( (int) $lockedHost->id, + $desired['address_family'], $desired['cidr'] ); @@ -323,8 +343,10 @@ final class CloudAdminHostNetworkService $pool->created_at = $now; } $pool->name = $desired['name']; + $pool->address_family = $desired['address_family']; $pool->cidr = $desired['cidr']; $pool->gateway = $desired['gateway']; + $pool->gateway_on_link = $desired['gateway_on_link']; $pool->guest_prefix_length = $desired['guest_prefix_length']; $pool->dns_servers_json = json_encode( $desired['dns_servers'], @@ -334,6 +356,12 @@ final class CloudAdminHostNetworkService $desired['reserved_ips'], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES ); + $pool->allocation_start = $desired['allocation_start']; + $pool->allocation_end = $desired['allocation_end']; + $pool->allocation_cursor = $pool->address_family === 6 + ? ($pool->allocation_cursor ?? $desired['allocation_start']) + : null; + $pool->max_allocations = $desired['max_allocations']; $pool->state = $desired['state']; $pool->desired_revision = $revision; // Public-pool configuration is PHP-owned. Desired state, the @@ -356,10 +384,15 @@ final class CloudAdminHostNetworkService 'state' => $desired['state'], 'network_attachment_id' => (int) $attachment->id, 'network_selector' => (string) $attachment->network_selector, + 'address_family' => $desired['address_family'], 'cidr' => $desired['cidr'], 'gateway' => $desired['gateway'], + 'gateway_on_link' => $desired['gateway_on_link'], 'dns_servers' => $desired['dns_servers'], 'reserved_ips' => $desired['reserved_ips'], + 'allocation_start' => $desired['allocation_start'], + 'allocation_end' => $desired['allocation_end'], + 'max_allocations' => $desired['max_allocations'], 'guest_prefix_length' => $desired['guest_prefix_length'], ], ]; @@ -380,8 +413,6 @@ final class CloudAdminHostNetworkService $lines = $lineIds === [] ? collect() : CloudNetworkLine::whereIn('id', $lineIds)->get()->keyBy('id'); $agent = CloudHostAgent::find((int) $host->id); - $testedSelectors = $agent === null ? [] - : CloudAgentSettingsService::testedNetworkSelectors($agent); $activePoolIds = CloudHostResourcePoolMembership::where( 'host_id', (int) $host->id )->where('scheduler_state', 'active') @@ -400,7 +431,6 @@ final class CloudAdminHostNetworkService $attachmentRow, $lines->get((int) $attachmentRow->line_id), $agent, - $testedSelectors, $activeLineIds ); $attachments[] = $dto; @@ -412,6 +442,7 @@ final class CloudAdminHostNetworkService } $occupied = []; $assigned = []; + $available = []; if (!$dbRows->isEmpty()) { foreach (CloudPublicIp::whereIn( 'public_ip_pool_id', $dbRows->pluck('id')->all() @@ -424,13 +455,21 @@ final class CloudAdminHostNetworkService })->groupBy('public_ip_pool_id')->get() as $count) { $occupied[(int) $count->public_ip_pool_id] = (int) $count->aggregate; } - foreach (CloudResourceReservation::whereIn( + foreach (CloudPublicIp::whereIn( + 'public_ip_pool_id', $dbRows->pluck('id')->all() + )->where('state', 'assigned') + ->selectRaw('public_ip_pool_id, COUNT(*) AS aggregate') + ->groupBy('public_ip_pool_id')->get() as $count) { + $assigned[(int) $count->public_ip_pool_id] = (int) $count->aggregate; + } + foreach (CloudPublicIp::whereIn( 'public_ip_pool_id', $dbRows->pluck('id')->all() - )->where('state', 'committed')->whereNotNull('instance_id') + )->where('state', 'available') + ->whereNull('reservation_id')->whereNull('instance_id') + ->whereNull('operation_id') ->selectRaw('public_ip_pool_id, COUNT(*) AS aggregate') ->groupBy('public_ip_pool_id')->get() as $count) { - $assigned[(int) $count->public_ip_pool_id] = - (int) $count->aggregate; + $available[(int) $count->public_ip_pool_id] = (int) $count->aggregate; } } @@ -484,6 +523,11 @@ final class CloudAdminHostNetworkService $attachmentsById[$attachmentId] ?? self::missingAttachmentDto($attachmentId), $row === null ? 0 : ($assigned[(int) $row->id] ?? 0), + $row === null ? 0 : self::availableCount( + $row, + $occupied[(int) $row->id] ?? 0, + $available[(int) $row->id] ?? 0 + ), $row === null ? null : ($replacementByPool[(int) $row->id] ?? null), $row === null ? 0 @@ -505,11 +549,59 @@ final class CloudAdminHostNetworkService (int) $row->network_attachment_id ), $assigned[(int) $row->id] ?? 0, + self::availableCount( + $row, + $occupied[(int) $row->id] ?? 0, + $available[(int) $row->id] ?? 0 + ), $replacementByPool[(int) $row->id] ?? null, $replacementHistoryByPool[(int) $row->id] ?? 0 ); } + $familyCapacityByAttachment = []; + foreach ($items as $item) { + if ((string) ($item['state'] ?? '') !== 'active' + || (string) ($item['sync_state'] ?? '') !== 'applied') { + continue; + } + $attachmentId = (int) ($item['network_attachment_id'] ?? 0); + $family = (int) ($item['address_family'] ?? 0); + if ($attachmentId > 0 && in_array($family, [4, 6], true)) { + $familyCapacityByAttachment[$attachmentId][$family] = + ($familyCapacityByAttachment[$attachmentId][$family] ?? 0) + + max(0, (int) ($item['available_count'] ?? 0)); + } + } + foreach ($attachments as &$attachment) { + $capacity = $familyCapacityByAttachment[(int) $attachment['id']] ?? []; + $attachment['public_network_capacity'] = [ + 'ipv4' => max(0, (int) ($capacity[4] ?? 0)), + 'ipv6' => max(0, (int) ($capacity[6] ?? 0)), + 'bundles' => min( + max(0, (int) ($capacity[4] ?? 0)), + max(0, (int) ($capacity[6] ?? 0)) + ), + ]; + $attachment['dual_stack_ready'] = $attachment['ready'] === true + && $attachment['public_network_capacity']['bundles'] > 0; + $attachmentsById[(int) $attachment['id']] = $attachment; + } + unset($attachment); + foreach ($items as &$item) { + $attachment = $attachmentsById[ + (int) ($item['network_attachment_id'] ?? 0) + ] ?? null; + if ($attachment !== null) { + $item['attachment'] = $attachment; + $item['dual_stack_ready'] = + (bool) ($attachment['dual_stack_ready'] ?? false); + } else { + $item['dual_stack_ready'] = false; + } + } + unset($item); + return [ 'host' => [ 'id' => (int) $host->id, @@ -589,17 +681,13 @@ final class CloudAdminHostNetworkService if ((string) $attachment->state !== 'active') { throw new CloudError('所选网络接入未启用', 409); } - $testedSelectors = $agent === null ? [] - : CloudAgentSettingsService::testedNetworkSelectors($agent); - if ($agent === null || !$agent->isReady() + if ($agent === null || (string) $attachment->verification_state !== 'verified' - || (int) $attachment->verified_agent_revision - !== (int) $agent->revision || (int) $attachment->last_verified_at < 1 - || !in_array( + || !CloudAgentSettingsService::publicNetworkReady( + $agent, (string) $attachment->network_selector, - $testedSelectors, - true + (int) $attachment->verified_agent_revision )) { throw new CloudError( '所选网络接入没有当前 Agent 版本的有效验证证据,请重新测试', @@ -611,15 +699,20 @@ final class CloudAdminHostNetworkService private static function normalizeInput(array $body, int $status = 422): array { $attachmentId = $body['network_attachment_id'] ?? null; + $family = $body['address_family'] ?? null; $name = $body['name'] ?? ''; $state = $body['state'] ?? null; $prefix = $body['guest_prefix_length'] ?? null; + $gatewayOnLink = $body['gateway_on_link'] ?? null; $dns = $body['dns_servers'] ?? null; $reserved = $body['reserved_ips'] ?? null; if (is_bool($attachmentId) || !is_int($attachmentId) || $attachmentId < 1) { throw new CloudError('请选择有效的宿主机网络接入', $status); } + if (!is_int($family) || !in_array($family, [4, 6], true)) { + throw new CloudError('请选择有效的公网地址族', $status); + } if (!is_string($name) || trim($name) === '' || mb_strlen(trim($name)) > 80 || preg_match('//u', $name) !== 1 @@ -632,130 +725,205 @@ final class CloudAdminHostNetworkService if (is_bool($prefix) || !is_int($prefix)) { throw new CloudError('客户机网络前缀无效', $status); } + if (!is_bool($gatewayOnLink)) { + throw new CloudError('网关 on-link 标记无效', $status); + } if (!is_array($dns) || !array_is_list($dns) || !is_array($reserved) || !array_is_list($reserved)) { throw new CloudError('公网地址列表格式无效', $status); } - $cidr = self::normalizeCidr($body['cidr'] ?? null, $status); - [, $networkPrefix] = explode('/', $cidr, 2); - $networkPrefix = (int) $networkPrefix; - if ($prefix < 24 || $prefix > $networkPrefix) { - throw new CloudError( - '客户机网络前缀必须介于 /24 和地址池前缀之间', - $status - ); + $network = self::normalizeNetworkPrefix( + $body['cidr'] ?? null, $family, $status + ); + $cidr = $network->networkCidr(); + if ($prefix !== $network->prefixLength()) { + throw new CloudError('客户机网络前缀必须与地址池前缀一致', $status); } - $gateway = self::normalizeIpv4( - $body['gateway'] ?? null, '公网网关', false, $status + $gateway = self::normalizePublicAddress( + $body['gateway'] ?? null, $family, '公网网关', $status ); - if (!self::containsUsable($cidr, $gateway)) { - throw new CloudError('公网网关必须位于地址池的可用范围内', $status); + $gatewayInPool = self::addressUsableInPrefix($network, $gateway); + if ($family === 4 && ($gatewayOnLink || !$gatewayInPool)) { + throw new CloudError('IPv4 网关必须位于地址池可用范围内且不能启用 on-link', $status); + } + if ($family === 6 && !$gatewayInPool && !$gatewayOnLink) { + throw new CloudError('地址池外的 IPv6 网关必须启用 on-link', $status); } if (count($dns) < 1 || count($dns) > 4) { throw new CloudError('公网 DNS 必须填写 1 至 4 个地址', $status); } - if (count($reserved) > 254) { - throw new CloudError('保留 IP 最多可填写 254 个地址', $status); + if (count($reserved) > 256) { + throw new CloudError('保留 IP 最多可填写 256 个地址', $status); } - $dns = self::normalizeIpList( - $dns, '公网 DNS', false, null, $status + $dns = self::normalizePublicAddressList( + $dns, null, '公网 DNS', null, $status ); - $reserved = self::normalizeIpList( - $reserved, '保留 IP', true, $cidr, $status + $reserved = self::normalizePublicAddressList( + $reserved, $family, '保留 IP', $network, $status ); + $allocationStart = null; + $allocationEnd = null; + $maxAllocations = $body['max_allocations'] ?? null; + if ($family === 4) { + if (($body['allocation_start'] ?? null) !== null + || ($body['allocation_end'] ?? null) !== null + || $maxAllocations !== 0) { + throw new CloudError('IPv4 地址池不使用稀疏分配范围', $status); + } + $maxAllocations = 0; + } else { + if (is_bool($maxAllocations) || !is_int($maxAllocations) + || $maxAllocations < 1 + || $maxAllocations > self::MAX_IPV6_ALLOCATIONS) { + throw new CloudError( + 'IPv6 最大分配数量必须为 1 至 ' + . self::MAX_IPV6_ALLOCATIONS, + $status + ); + } + $start = self::normalizePublicAddress( + $body['allocation_start'] ?? null, + 6, + 'IPv6 分配起始地址', + $status + ); + $end = self::normalizePublicAddress( + $body['allocation_end'] ?? null, + 6, + 'IPv6 分配结束地址', + $status + ); + if (!self::addressUsableInPrefix($network, $start) + || !self::addressUsableInPrefix($network, $end) + || $start->compare($end) > 0) { + throw new CloudError('IPv6 稀疏分配范围必须位于地址池内且顺序有效', $status); + } + $blocked = []; + foreach (array_merge( + [$gateway->text()], $dns, $reserved + ) as $blockedText) { + $blockedAddress = CloudIpAddress::parse($blockedText); + if ($blockedAddress->family() === 6 + && $blockedAddress->compare($start) >= 0 + && $blockedAddress->compare($end) <= 0) { + $blocked[$blockedAddress->text()] = true; + } + } + $candidate = $start; + $usable = 0; + while (true) { + if (!isset($blocked[$candidate->text()])) { + $usable++; + if ($usable >= $maxAllocations) { + break; + } + } + if ($candidate->equals($end)) { + throw new CloudError( + 'IPv6 稀疏分配范围扣除网关、DNS 和保留地址后小于最大分配数量', + $status + ); + } + $candidate = $candidate->next(); + } + $allocationStart = $start->text(); + $allocationEnd = $end->text(); + } return [ 'network_attachment_id' => $attachmentId, + 'address_family' => $family, 'name' => trim($name), 'cidr' => $cidr, - 'gateway' => $gateway, + 'gateway' => $gateway->text(), + 'gateway_on_link' => $gatewayOnLink, 'dns_servers' => $dns, 'reserved_ips' => $reserved, + 'allocation_start' => $allocationStart, + 'allocation_end' => $allocationEnd, + 'max_allocations' => $maxAllocations, 'guest_prefix_length' => $prefix, 'state' => $state, ]; } - private static function normalizeCidr($value, int $status): string + private static function normalizeNetworkPrefix($value, int $family, + int $status): CloudIpPrefix { - if (!is_string($value) - || preg_match('/^([^\/]+)\/([0-9]{1,2})$/D', trim($value), $match) !== 1) { - throw new CloudError('公网地址池必须填写有效的 IPv4 CIDR', $status); + try { + $prefix = CloudIpPrefix::network($value); + } catch (\Throwable) { + throw new CloudError('公网地址池 CIDR 格式无效', $status); } - $address = self::normalizeIpv4( - $match[1], '公网地址池', false, $status - ); - $prefix = (int) $match[2]; - if ($prefix < 24 || $prefix > 30) { - throw new CloudError('公网地址池前缀必须为 /24 至 /30', $status); + if ($prefix->family() !== $family + || !$prefix->networkAddress()->isPublicUnicast()) { + throw new CloudError('公网地址池必须使用所选地址族的可路由网段', $status); } - $network = self::uint($address) & self::mask($prefix); - $networkAddress = long2ip($network); - $broadcastAddress = long2ip($network | (~self::mask($prefix) & 0xffffffff)); - if (!self::isPublicIpv4($networkAddress) - || !self::isPublicIpv4($broadcastAddress)) { - throw new CloudError('公网地址池必须是可路由的 IPv4 网段', $status); + $length = $prefix->prefixLength(); + if (($family === 4 && ($length < 24 || $length > 30)) + || ($family === 6 && ($length < 48 || $length > 120))) { + throw new CloudError( + $family === 4 + ? 'IPv4 地址池前缀必须为 /24 至 /30' + : 'IPv6 地址池前缀必须为 /48 至 /120', + $status + ); } - return $networkAddress . '/' . $prefix; + return $prefix; } - private static function normalizeIpList(array $values, string $label, - bool $allowReservedRange, ?string $cidr, int $status): array + private static function normalizePublicAddressList(array $values, + ?int $family, string $label, ?CloudIpPrefix $prefix, + int $status): array { $result = []; foreach ($values as $value) { - $address = self::normalizeIpv4( - $value, $label, $allowReservedRange, $status + $address = self::normalizePublicAddress( + $value, $family, $label, $status ); - if ($cidr !== null && !self::containsUsable($cidr, $address)) { + if ($prefix !== null + && !self::addressUsableInPrefix($prefix, $address)) { throw new CloudError($label . '必须位于地址池的可用范围内', $status); } - $result[$address] = true; + $result[$address->text()] = true; } return array_keys($result); } - private static function normalizeIpv4($value, string $label, - bool $allowReservedRange, int $status): string + private static function normalizePublicAddress($value, ?int $family, + string $label, int $status): CloudIpAddress { - if (!is_string($value) || trim($value) !== $value - || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false - || (!$allowReservedRange && !self::isPublicIpv4($value))) { - throw new CloudError($label . '必须是有效的公网 IPv4 地址', $status); + try { + $address = CloudIpAddress::parse($value); + } catch (\Throwable) { + throw new CloudError($label . '必须是有效的公网 IP 地址', $status); } - return long2ip(self::uint($value)); - } - - private static function isPublicIpv4(string $address): bool - { - return filter_var( - $address, - FILTER_VALIDATE_IP, - FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE - ) !== false; + if (($family !== null && $address->family() !== $family) + || !$address->isPublicUnicast()) { + throw new CloudError($label . '必须是有效的公网 IP 地址', $status); + } + return $address; } - private static function containsUsable(string $cidr, string $address): bool + private static function addressUsableInPrefix(CloudIpPrefix $prefix, + CloudIpAddress $address): bool { - [$networkAddress, $prefix] = explode('/', $cidr, 2); - $network = self::uint($networkAddress); - $broadcast = $network | (~self::mask((int) $prefix) & 0xffffffff); - $candidate = self::uint($address); - return $candidate > $network && $candidate < $broadcast; + return $address->isPublicUnicast() + && $prefix->contains($address) + && !$address->equals($prefix->networkAddress()) + && ($address->family() !== 4 + || !$address->equals($prefix->lastAddress())); } private static function overlaps(string $left, string $right): bool { - [$leftStart, $leftEnd] = self::bounds($left); - [$rightStart, $rightEnd] = self::bounds($right); - return $leftStart <= $rightEnd && $rightStart <= $leftEnd; - } - - private static function bounds(string $cidr): array - { - [$address, $prefix] = explode('/', $cidr, 2); - $start = self::uint($address) & self::mask((int) $prefix); - return [$start, $start | (~self::mask((int) $prefix) & 0xffffffff)]; + try { + return CloudIpPrefix::network($left)->overlaps( + CloudIpPrefix::network($right) + ); + } catch (\Throwable) { + return true; + } } private static function uint(string $address): int @@ -772,14 +940,17 @@ final class CloudAdminHostNetworkService return (0xffffffff << (32 - $prefix)) & 0xffffffff; } - private static function assertNoOverlap(string $poolKey, string $cidr, - $poolRows): void + private static function assertNoOverlap(string $poolKey, int $family, + string $cidr, $poolRows): void { $checked = []; foreach ($poolRows as $row) { if ((string) $row->pool_key === $poolKey) { continue; } + if ((int) $row->address_family !== $family) { + continue; + } $checked[(string) $row->pool_key] = (string) $row->cidr; } foreach ($checked as $other) { @@ -790,9 +961,11 @@ final class CloudAdminHostNetworkService } /** Public addresses are globally unique in cloud_public_ips. */ - private static function assertNoGlobalOverlap(int $hostId, string $cidr): void + private static function assertNoGlobalOverlap(int $hostId, int $family, + string $cidr): void { foreach (CloudPublicIpPool::where('host_id', '<>', $hostId) + ->where('address_family', $family) ->get(['pool_key', 'cidr']) as $row) { if (self::overlaps($cidr, (string) $row->cidr)) { throw new CloudError( @@ -827,6 +1000,7 @@ final class CloudAdminHostNetworkService { return (string) $pool->name === $desired['name'] && (string) $pool->state === $desired['state'] + && (int) $pool->address_family === $desired['address_family'] && (int) $pool->network_attachment_id === $desired['network_attachment_id'] && !self::runtimeChanged(self::poolConfig($pool), $desired); @@ -835,10 +1009,17 @@ final class CloudAdminHostNetworkService private static function poolConfig(CloudPublicIpPool $pool): array { return [ + 'address_family' => (int) $pool->address_family, 'cidr' => (string) $pool->cidr, 'gateway' => (string) $pool->gateway, + 'gateway_on_link' => (bool) $pool->gateway_on_link, 'dns_servers' => self::decodeIpList($pool->dns_servers_json), 'reserved_ips' => self::decodeIpList($pool->reserved_ips_json), + 'allocation_start' => $pool->allocation_start === null + ? null : (string) $pool->allocation_start, + 'allocation_end' => $pool->allocation_end === null + ? null : (string) $pool->allocation_end, + 'max_allocations' => (int) $pool->max_allocations, 'guest_prefix_length' => (int) $pool->guest_prefix_length, ]; } @@ -856,8 +1037,18 @@ final class CloudAdminHostNetworkService array $desired): bool { return (string) ($current['cidr'] ?? '') !== $desired['cidr'] + || (int) ($current['address_family'] ?? 0) + !== $desired['address_family'] || (string) ($current['gateway'] ?? '') !== $desired['gateway'] + || (bool) ($current['gateway_on_link'] ?? false) + !== $desired['gateway_on_link'] || array_values($current['dns_servers'] ?? []) !== $desired['dns_servers'] + || ($current['allocation_start'] ?? null) + !== $desired['allocation_start'] + || ($current['allocation_end'] ?? null) + !== $desired['allocation_end'] + || (int) ($current['max_allocations'] ?? 0) + !== $desired['max_allocations'] || (int) ($current['guest_prefix_length'] ?? 0) !== $desired['guest_prefix_length']; } @@ -866,9 +1057,7 @@ final class CloudAdminHostNetworkService private static function materializeIpLedger(CloudPublicIpPool $pool): void { $config = self::poolConfig($pool); - [$network, $prefix] = explode('/', $config['cidr'], 2); - $networkValue = self::uint($network); - $broadcast = $networkValue | (~self::mask((int) $prefix) & 0xffffffff); + $family = (int) $config['address_family']; $blocked = array_fill_keys(array_merge( [$config['gateway']], $config['dns_servers'], $config['reserved_ips'] ), true); @@ -876,8 +1065,22 @@ final class CloudAdminHostNetworkService CloudHost::find((int) $pool->host_id) ); if ($managementAddress !== null) { - $blocked[$managementAddress] = true; + try { + $management = CloudIpAddress::parse($managementAddress); + if ($management->family() === $family) { + $blocked[$management->text()] = true; + } + } catch (\Throwable) { + // Host usage validation owns malformed management metadata. + } } + if ($family === 6) { + self::refreshSparseIpv6Ledger($pool, $config, $blocked); + return; + } + [$network, $prefix] = explode('/', $config['cidr'], 2); + $networkValue = self::uint($network); + $broadcast = $networkValue | (~self::mask((int) $prefix) & 0xffffffff); $wanted = []; for ($value = $networkValue + 1; $value < $broadcast; $value++) { $address = long2ip($value); @@ -898,7 +1101,9 @@ final class CloudAdminHostNetworkService $row = new CloudPublicIp(); $row->host_id = (int) $pool->host_id; $row->public_ip_pool_id = (int) $pool->id; + $row->address_family = 4; $row->address = $address; + $row->address_binary = inet_pton($address); $row->created_at = $now; } $row->prefix_length = (int) $config['guest_prefix_length']; @@ -920,22 +1125,55 @@ final class CloudAdminHostNetworkService } } + /** IPv6 pools materialize only addresses that were actually claimed. */ + private static function refreshSparseIpv6Ledger(CloudPublicIpPool $pool, + array $config, array $blocked): void + { + $start = CloudIpAddress::parse((string) $config['allocation_start']); + $end = CloudIpAddress::parse((string) $config['allocation_end']); + $now = time(); + foreach (CloudPublicIp::where( + 'public_ip_pool_id', (int) $pool->id + )->orderBy('id')->lockForUpdate()->get() as $row) { + try { + $address = CloudIpAddress::parse((string) $row->address); + $inRange = $address->family() === 6 + && $address->compare($start) >= 0 + && $address->compare($end) <= 0; + } catch (\Throwable) { + $inRange = false; + $address = null; + } + $row->address_family = 6; + if ($address !== null) { + $row->address = $address->text(); + $row->address_binary = $address->binary(); + } + $row->prefix_length = (int) $config['guest_prefix_length']; + if ($row->reservation_id === null && $row->instance_id === null + && $row->operation_id === null) { + $row->state = $inRange && $address !== null + && !isset($blocked[$address->text()]) + ? 'available' : 'disabled'; + } + $row->updated_at = $now; + $row->save(); + } + } + private static function attachmentDto( CloudHostNetworkAttachment $attachment, ?CloudNetworkLine $line, ?CloudHostAgent $agent, - array $testedSelectors, array $activeLineIds ): array { $storedVerification = (string) $attachment->verification_state; - $currentEvidence = $agent !== null && $agent->isReady() - && (int) $attachment->verified_agent_revision - === (int) $agent->revision + $currentEvidence = $agent !== null && (int) $attachment->last_verified_at > 0 - && in_array( + && CloudAgentSettingsService::publicNetworkReady( + $agent, (string) $attachment->network_selector, - $testedSelectors, - true + (int) $attachment->verified_agent_revision ); $verification = $storedVerification === 'verified' && !$currentEvidence ? 'stale' : $storedVerification; @@ -990,6 +1228,7 @@ final class CloudAdminHostNetworkService private static function poolDto(?CloudPublicIpPool $row, ?array $live, int $occupied, ?array $attachment, int $assigned = 0, + int $available = 0, ?array $activeReplacement = null, int $replacementHistoryCount = 0): array { @@ -1006,8 +1245,21 @@ final class CloudAdminHostNetworkService ), 'cidr' => (string) ($desired['cidr'] ?? $live['cidr']), 'gateway' => (string) ($desired['gateway'] ?? $live['gateway']), + 'address_family' => (int) ( + $desired['address_family'] ?? $live['address_family'] ?? 0 + ), + 'gateway_on_link' => (bool) ( + $desired['gateway_on_link'] ?? $live['gateway_on_link'] ?? false + ), 'dns_servers' => $desired['dns_servers'] ?? $live['dns_servers'], 'reserved_ips' => $desired['reserved_ips'] ?? $live['reserved_ips'], + 'allocation_start' => $desired['allocation_start'] + ?? $live['allocation_start'] ?? null, + 'allocation_end' => $desired['allocation_end'] + ?? $live['allocation_end'] ?? null, + 'max_allocations' => (int) ( + $desired['max_allocations'] ?? $live['max_allocations'] ?? 0 + ), 'guest_prefix_length' => (int) ( $desired['guest_prefix_length'] ?? $live['guest_prefix_length'] ), @@ -1031,6 +1283,7 @@ final class CloudAdminHostNetworkService (string) ($row?->sync_state ?? 'untracked') ), 'occupied_count' => max(0, $occupied), + 'available_count' => max(0, $available), 'assigned_instance_count' => max(0, $assigned), 'replacement_locked' => $activeReplacement !== null, 'active_replacement' => $activeReplacement, @@ -1043,6 +1296,15 @@ final class CloudAdminHostNetworkService ]; } + private static function availableCount(CloudPublicIpPool $pool, + int $occupied, int $concreteAvailable): int + { + if ((int) $pool->address_family === 6) { + return max(0, (int) $pool->max_allocations - $occupied); + } + return max(0, $concreteAvailable); + } + private static function decodeIpList($value): array { try { diff --git a/web/app/Services/Cloud/CloudAdminHostProjectionService.php b/web/app/Services/Cloud/CloudAdminHostProjectionService.php index fd19dd18..467ef4bb 100644 --- a/web/app/Services/Cloud/CloudAdminHostProjectionService.php +++ b/web/app/Services/Cloud/CloudAdminHostProjectionService.php @@ -559,64 +559,125 @@ final class CloudAdminHostProjectionService if ($hostIds === []) { return $result; } - $rows = CloudPublicIp::query() - ->join('cloud_public_ip_pools as public_pool', - 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id') + $pools = CloudPublicIp::query()->from('cloud_public_ip_pools as public_pool') ->join('cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id') - ->whereIn('cloud_public_ips.host_id', $hostIds) - ->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.host_id', - 'cloud_public_ips.host_id') + ->whereIn('public_pool.host_id', $hostIds) + ->whereColumn('network_attachment.host_id', 'public_pool.host_id') ->get([ - 'cloud_public_ips.host_id', + 'public_pool.id', 'public_pool.host_id', + 'public_pool.address_family', 'public_pool.max_allocations', + 'public_pool.state as pool_state', + 'public_pool.sync_state as pool_sync_state', + 'public_pool.observed_revision as pool_observed_revision', + 'public_pool.desired_revision as pool_desired_revision', + 'network_attachment.id as attachment_id', 'network_attachment.line_id', - 'cloud_public_ips.state', - 'cloud_public_ips.reservation_id', - 'cloud_public_ips.instance_id', - 'cloud_public_ips.operation_id', 'network_attachment.network_selector', 'network_attachment.state as attachment_state', 'network_attachment.verification_state', 'network_attachment.verified_agent_revision', - 'public_pool.state as pool_state', - 'public_pool.sync_state as pool_sync_state', - 'public_pool.observed_revision as pool_observed_revision', - 'public_pool.desired_revision as pool_desired_revision', ]); - foreach ($rows as $row) { - $hostId = (int) $row->host_id; - $lineId = (int) $row->line_id; + $poolById = []; + foreach ($pools as $pool) { + $poolById[(int) $pool->id] = $pool; + } + $addresses = $poolById === [] ? collect() : CloudPublicIp::whereIn( + 'public_ip_pool_id', array_keys($poolById) + )->get(); + $occupiedByPool = []; + $availableByPool = []; + $identities = []; + foreach ($addresses as $row) { + $pool = $poolById[(int) $row->public_ip_pool_id] ?? null; + if ($pool === null) { + continue; + } + $hostId = (int) $pool->host_id; + $lineId = (int) $pool->line_id; $result[$hostId][$lineId] ??= self::emptyIpStats(); - $result[$hostId][$lineId]['total']++; + $occupied = in_array((string) $row->state, + ['reserved', 'assigned', 'changing', 'uncertain'], true) + || $row->reservation_id !== null || $row->instance_id !== null + || $row->operation_id !== null; + if ($occupied) { + $occupiedByPool[(int) $pool->id] = + ($occupiedByPool[(int) $pool->id] ?? 0) + 1; + } + if ((string) $row->state === 'available' && !$occupied) { + $availableByPool[(int) $pool->id] = + ($availableByPool[(int) $pool->id] ?? 0) + 1; + } $state = (string) $row->state; if ($state === 'assigned') { - $result[$hostId][$lineId]['allocated']++; + $key = 'instance:' . (int) ($row->instance_id ?? 0); + $identities[$hostId][$lineId]['allocated'][$key] = true; } elseif (in_array($state, ['reserved', 'changing', 'uncertain'], true)) { - $result[$hostId][$lineId]['reserved']++; + $identity = (int) ($row->reservation_id ?? 0) > 0 + ? 'reservation:' . (int) $row->reservation_id + : 'operation:' . (string) ($row->operation_id ?? $row->id); + $identities[$hostId][$lineId]['reserved'][$identity] = true; } elseif ($state === 'disabled') { $result[$hostId][$lineId]['disabled']++; } - $available = $state === 'available' - && $row->reservation_id === null - && $row->instance_id === null - && $row->operation_id === null - && (string) $row->attachment_state === 'active' - && (string) $row->verification_state === 'verified' - && (string) $row->pool_state === 'active' - && (string) $row->pool_sync_state === 'applied' - && (int) $row->pool_observed_revision - >= (int) $row->pool_desired_revision + } + $capacity = []; + foreach ($pools as $pool) { + $hostId = (int) $pool->host_id; + $lineId = (int) $pool->line_id; + $result[$hostId][$lineId] ??= self::emptyIpStats(); + $ready = (string) $pool->attachment_state === 'active' + && (string) $pool->verification_state === 'verified' + && (string) $pool->pool_state === 'active' + && (string) $pool->pool_sync_state === 'applied' + && (int) $pool->pool_observed_revision + >= (int) $pool->pool_desired_revision && self::agentSelectorEvidenceReady( $agents[$hostId] ?? null, - (string) $row->network_selector, - (int) $row->verified_agent_revision + (string) $pool->network_selector, + (int) $pool->verified_agent_revision + ); + if (!$ready) { + continue; + } + $family = (int) $pool->address_family; + $available = $family === 6 + ? max(0, (int) $pool->max_allocations + - (int) ($occupiedByPool[(int) $pool->id] ?? 0)) + : (int) ($availableByPool[(int) $pool->id] ?? 0); + $capacity[$hostId][$lineId][(int) $pool->attachment_id][$family] = + ($capacity[$hostId][$lineId][(int) $pool->attachment_id][$family] + ?? 0) + $available; + } + foreach ($capacity as $hostId => $lines) { + foreach ($lines as $lineId => $attachments) { + foreach ($attachments as $families) { + $result[$hostId][$lineId]['available'] += min( + (int) ($families[4] ?? 0), + (int) ($families[6] ?? 0) + ); + } + } + } + foreach ($identities as $hostId => $lines) { + foreach ($lines as $lineId => $states) { + $result[$hostId][$lineId]['allocated'] = count( + $states['allocated'] ?? [] ); - if ($available) { - $result[$hostId][$lineId]['available']++; + $result[$hostId][$lineId]['reserved'] = count( + $states['reserved'] ?? [] + ); + } + } + foreach ($result as &$lines) { + foreach ($lines as &$stats) { + $stats['total'] = $stats['available'] + $stats['allocated'] + + $stats['reserved'] + $stats['disabled']; } + unset($stats); } + unset($lines); return $result; } @@ -624,13 +685,10 @@ final class CloudAdminHostProjectionService string $selector, int $verifiedRevision): bool { return $agent !== null - && $agent->isReady() - && $verifiedRevision === (int) $agent->revision - && $verifiedRevision === (int) $agent->tested_revision - && in_array( + && CloudAgentSettingsService::publicNetworkReady( + $agent, $selector, - CloudAgentSettingsService::testedNetworkSelectors($agent), - true + $verifiedRevision ); } diff --git a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php index f68d0924..b9d9a381 100644 --- a/web/app/Services/Cloud/CloudAdminHostSchedulingService.php +++ b/web/app/Services/Cloud/CloudAdminHostSchedulingService.php @@ -414,30 +414,23 @@ final class CloudAdminHostSchedulingService { $usage = CloudPanelUsageService::forHost($hostId); $byLine = []; - $ipQuery = CloudPublicIp::where('cloud_public_ips.host_id', $hostId) - ->join( - 'cloud_public_ip_pools as public_pool', - 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id' - )->join( + $pools = CloudPublicIp::query() + ->from('cloud_public_ip_pools as public_pool')->join( 'cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_id' )->leftJoin( 'cloud_host_agents as host_agent', - 'host_agent.host_id', '=', 'cloud_public_ips.host_id' - )->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.host_id', 'cloud_public_ips.host_id') + 'host_agent.host_id', '=', 'public_pool.host_id' + )->where('public_pool.host_id', $hostId) + ->whereColumn('network_attachment.host_id', 'public_pool.host_id') ->select([ - 'cloud_public_ips.state', - 'cloud_public_ips.reservation_id', - 'cloud_public_ips.instance_id', - 'cloud_public_ips.operation_id', + 'public_pool.id', 'public_pool.address_family', + 'public_pool.max_allocations', + 'network_attachment.id as attachment_id', 'network_attachment.line_id', 'network_attachment.host_id as attachment_host_id', 'network_attachment.network_selector as attachment_network_selector', 'network_attachment.state as attachment_state', - 'network_attachment.sync_state as attachment_sync_state', - 'network_attachment.observed_revision as attachment_observed_revision', - 'network_attachment.desired_revision as attachment_desired_revision', 'network_attachment.verification_state as attachment_verification_state', 'network_attachment.verified_agent_revision as attachment_verified_agent_revision', 'network_attachment.last_verified_at as attachment_last_verified_at', @@ -447,33 +440,91 @@ final class CloudAdminHostSchedulingService 'host_agent.tested_revision as agent_tested_revision', 'host_agent.last_test_status as agent_last_test_status', 'host_agent.network_selectors_json as agent_network_selectors_json', + 'host_agent.public_network_capabilities_json as agent_public_network_capabilities_json', 'public_pool.state as pool_state', 'public_pool.sync_state as pool_sync_state', 'public_pool.observed_revision as pool_observed_revision', 'public_pool.desired_revision as pool_desired_revision', - ]); - foreach ($ipQuery->get() as $row) { - if ((string) $row->state === 'available' - && ((int) ($row->reservation_id ?? 0) > 0 - || (int) ($row->instance_id ?? 0) > 0 - || (string) ($row->operation_id ?? '') !== '' - || (string) ($row->attachment_state ?? '') !== 'active' - || (string) ($row->attachment_sync_state ?? '') !== 'applied' - || (int) ($row->attachment_observed_revision ?? 0) - < (int) ($row->attachment_desired_revision ?? 0) - || !self::attachmentEvidenceReady($row) - || (string) ($row->pool_state ?? '') !== 'active' - || (string) ($row->pool_sync_state ?? '') !== 'applied' - || (int) ($row->pool_observed_revision ?? 0) - < (int) ($row->pool_desired_revision ?? 0))) { + ])->get(); + $poolById = []; + foreach ($pools as $pool) { + $poolById[(int) $pool->id] = $pool; + } + $rows = $poolById === [] ? collect() : CloudPublicIp::whereIn( + 'public_ip_pool_id', array_keys($poolById) + )->get(); + $occupiedByPool = []; + $availableByPool = []; + $identities = []; + foreach ($rows as $row) { + $pool = $poolById[(int) $row->public_ip_pool_id] ?? null; + if ($pool === null) { continue; } - $lineId = (int) $row->line_id; + $lineId = (int) $pool->line_id; if ($lineId < 1) { continue; } - $key = (string) $row->state; - $byLine[$lineId][$key] = ($byLine[$lineId][$key] ?? 0) + 1; + $occupied = in_array((string) $row->state, + ['reserved', 'assigned', 'changing', 'uncertain'], true) + || $row->reservation_id !== null || $row->instance_id !== null + || $row->operation_id !== null; + if ($occupied) { + $occupiedByPool[(int) $pool->id] = + ($occupiedByPool[(int) $pool->id] ?? 0) + 1; + } elseif ((string) $row->state === 'available') { + $availableByPool[(int) $pool->id] = + ($availableByPool[(int) $pool->id] ?? 0) + 1; + } + if ((string) $row->state === 'assigned') { + $identities[$lineId]['assigned']['instance:' + . (int) ($row->instance_id ?? 0)] = true; + } elseif (in_array((string) $row->state, + ['reserved', 'changing', 'uncertain'], true)) { + $identity = (int) ($row->reservation_id ?? 0) > 0 + ? 'reservation:' . (int) $row->reservation_id + : 'operation:' . (string) ($row->operation_id ?? $row->id); + $identities[$lineId][(string) $row->state][$identity] = true; + } elseif ((string) $row->state === 'disabled') { + $byLine[$lineId]['disabled'] = + ($byLine[$lineId]['disabled'] ?? 0) + 1; + } + } + $capacity = []; + foreach ($pools as $pool) { + $ready = (string) ($pool->attachment_state ?? '') === 'active' + && self::attachmentEvidenceReady($pool) + && (string) ($pool->pool_state ?? '') === 'active' + && (string) ($pool->pool_sync_state ?? '') === 'applied' + && (int) ($pool->pool_observed_revision ?? 0) + >= (int) ($pool->pool_desired_revision ?? 0); + if (!$ready) { + continue; + } + $family = (int) $pool->address_family; + $count = $family === 6 + ? max(0, (int) $pool->max_allocations + - (int) ($occupiedByPool[(int) $pool->id] ?? 0)) + : (int) ($availableByPool[(int) $pool->id] ?? 0); + $capacity[(int) $pool->line_id][ + (int) $pool->attachment_id + ][$family] = ($capacity[(int) $pool->line_id][ + (int) $pool->attachment_id + ][$family] ?? 0) + $count; + } + foreach ($capacity as $lineId => $attachments) { + foreach ($attachments as $families) { + $byLine[$lineId]['available'] = + ($byLine[$lineId]['available'] ?? 0) + min( + (int) ($families[4] ?? 0), + (int) ($families[6] ?? 0) + ); + } + } + foreach ($identities as $lineId => $states) { + foreach ($states as $state => $values) { + $byLine[$lineId][$state] = count($values); + } } $usage['ip'] = []; foreach ($byLine as $states) { @@ -513,11 +564,17 @@ final class CloudAdminHostSchedulingService (string) ($row->agent_last_test_status ?? ''), 'network_selectors_json' => (string) ($row->agent_network_selectors_json ?? '[]'), + 'public_network_capabilities_json' => + (string) ($row->agent_public_network_capabilities_json ?? '{}'), ], true); - return CloudPlacementNetworkService::attachmentReadyForAgent( - $attachment, - $agent - ); + return (string) $attachment->state === 'active' + && (string) $attachment->verification_state === 'verified' + && (int) $attachment->last_verified_at > 0 + && CloudAgentSettingsService::publicNetworkReady( + $agent, + (string) $attachment->network_selector, + (int) $attachment->verified_agent_revision + ); } private static function capacityDto($policy, array $usage): array diff --git a/web/app/Services/Cloud/CloudAdminResourceService.php b/web/app/Services/Cloud/CloudAdminResourceService.php index 92c31d9a..ae6fee18 100644 --- a/web/app/Services/Cloud/CloudAdminResourceService.php +++ b/web/app/Services/Cloud/CloudAdminResourceService.php @@ -530,90 +530,142 @@ final class CloudAdminResourceService ]; } $ipAgg = []; - if ($hostIds !== []) { - foreach (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' - )->whereIn('cloud_public_ips.host_id', $hostIds) - ->whereColumn('public_pool.host_id', 'cloud_public_ips.host_id') - ->whereColumn('network_attachment.host_id', - 'cloud_public_ips.host_id') - // Gateway, DNS and management addresses are disabled while - // materializing the pool's reserved_ips ledger. - ->where(function ($query): void { - $query->where('cloud_public_ips.state', '<>', 'available') - ->orWhere(function ($available): void { - $available->where('cloud_public_ips.state', 'available') - ->whereNull('cloud_public_ips.reservation_id') - ->whereNull('cloud_public_ips.instance_id') - ->whereNull('cloud_public_ips.operation_id'); - }); - }) - ->selectRaw( - 'cloud_public_ips.host_id, network_attachment.line_id, ' - . 'cloud_public_ips.state, COUNT(*) AS row_count' - )->groupBy('cloud_public_ips.host_id', - 'network_attachment.line_id', 'cloud_public_ips.state')->get() as $row) { - $ipAgg[(int) $row->host_id][(int) $row->line_id][(string) $row->state] - = (int) $row->row_count; - } - } - // Only addresses whose attachment and public pool are applied at - // their desired revisions can be advertised as sellable capacity. + // Public capacity is a dual-stack bundle. IPv6 pools are sparse and + // therefore contribute their bounded maximum without materializing a + // /64-sized address ledger; IPv4 continues to use concrete rows. $networkReadyByHostLine = []; $networkReadyIpCountByHostLine = []; if ($hostIds !== []) { - $networkRows = CloudPublicIp::query()->join( - 'cloud_public_ip_pools as public_pool', - 'public_pool.id', '=', 'cloud_public_ips.public_ip_pool_id' - )->join( + $publicPools = CloudPublicIp::query() + ->from('cloud_public_ip_pools as public_pool')->join( 'cloud_host_network_attachments as network_attachment', 'network_attachment.id', '=', 'public_pool.network_attachment_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') + )->whereIn('public_pool.host_id', $hostIds) ->whereColumn('network_attachment.host_id', - 'cloud_public_ips.host_id') - ->where('network_attachment.state', 'active') - ->where('network_attachment.verification_state', 'verified') - ->where('public_pool.state', 'active') - ->where('public_pool.sync_state', 'applied') - ->whereColumn('public_pool.observed_revision', '>=', - 'public_pool.desired_revision') + 'public_pool.host_id') ->get([ - 'cloud_public_ips.id as ip_id', - 'cloud_public_ips.host_id', 'cloud_public_ips.address', + 'public_pool.id', 'public_pool.host_id', + 'public_pool.address_family', + 'public_pool.max_allocations', 'public_pool.pool_key', + 'public_pool.cidr', 'public_pool.guest_prefix_length', + 'public_pool.state as pool_state', + 'public_pool.sync_state as pool_sync_state', + 'public_pool.observed_revision as pool_observed_revision', + 'public_pool.desired_revision as pool_desired_revision', + 'network_attachment.id as attachment_id', 'network_attachment.line_id', 'network_attachment.network_selector', + 'network_attachment.state as attachment_state', + 'network_attachment.verification_state', 'network_attachment.verified_agent_revision', - 'public_pool.pool_key', - 'public_pool.cidr', ]); - foreach ($networkRows as $row) { - if (preg_match('/^[a-f0-9]{32}$/D', - (string) $row->pool_key) !== 1 - || !self::ipv4BelongsToCidr( - (string) $row->address, (string) $row->cidr - ) || !self::agentSelectorEvidenceReady( - $agentByHost[(int) $row->host_id] ?? null, - (string) $row->network_selector, - (int) $row->verified_agent_revision + $poolById = []; + foreach ($publicPools as $pool) { + $poolById[(int) $pool->id] = $pool; + } + $addresses = $poolById === [] ? collect() + : CloudPublicIp::whereIn( + 'public_ip_pool_id', array_keys($poolById) + )->get(); + $occupiedByPool = []; + $availableByPool = []; + $identities = []; + foreach ($addresses as $address) { + $pool = $poolById[(int) $address->public_ip_pool_id] ?? null; + if ($pool === null) { + continue; + } + $hostId = (int) $pool->host_id; + $lineId = (int) $pool->line_id; + $occupied = in_array((string) $address->state, + ['reserved', 'assigned', 'changing', 'uncertain'], true) + || $address->reservation_id !== null + || $address->instance_id !== null + || $address->operation_id !== null; + if ($occupied) { + $occupiedByPool[(int) $pool->id] = + ($occupiedByPool[(int) $pool->id] ?? 0) + 1; + } elseif ((string) $address->state === 'available' + && (int) $pool->address_family === 4 + && (int) $address->prefix_length + === (int) $pool->guest_prefix_length + && self::ipv4BelongsToCidr( + (string) $address->address, (string) $pool->cidr )) { + $availableByPool[(int) $pool->id] = + ($availableByPool[(int) $pool->id] ?? 0) + 1; + } + $state = (string) $address->state; + if ($state === 'assigned') { + $identities[$hostId][$lineId]['assigned']['instance:' + . (int) ($address->instance_id ?? 0)] = true; + } elseif (in_array($state, + ['reserved', 'changing', 'uncertain'], true)) { + $identity = (int) ($address->reservation_id ?? 0) > 0 + ? 'reservation:' . (int) $address->reservation_id + : 'operation:' . (string) ($address->operation_id + ?? $address->id); + $identities[$hostId][$lineId][$state][$identity] = true; + } elseif ($state === 'disabled') { + $ipAgg[$hostId][$lineId]['disabled'] = + ($ipAgg[$hostId][$lineId]['disabled'] ?? 0) + 1; + } + } + $capacity = []; + foreach ($publicPools as $pool) { + $ready = preg_match('/^[a-f0-9]{32}$/D', + (string) $pool->pool_key) === 1 + && (string) $pool->attachment_state === 'active' + && (string) $pool->verification_state === 'verified' + && (string) $pool->pool_state === 'active' + && (string) $pool->pool_sync_state === 'applied' + && (int) $pool->pool_observed_revision + >= (int) $pool->pool_desired_revision + && self::agentSelectorEvidenceReady( + $agentByHost[(int) $pool->host_id] ?? null, + (string) $pool->network_selector, + (int) $pool->verified_agent_revision + ); + if (!$ready) { continue; } - $networkReadyByHostLine[(int) $row->host_id][(int) $row->line_id] = true; - $hostId = (int) $row->host_id; - $lineId = (int) $row->line_id; - $networkReadyIpCountByHostLine[$hostId][$lineId] = - ($networkReadyIpCountByHostLine[$hostId][$lineId] ?? 0) + 1; + $family = (int) $pool->address_family; + $available = $family === 6 + ? max(0, (int) $pool->max_allocations + - (int) ($occupiedByPool[(int) $pool->id] ?? 0)) + : (int) ($availableByPool[(int) $pool->id] ?? 0); + $capacity[(int) $pool->host_id][(int) $pool->line_id] + [(int) $pool->attachment_id][$family] = + ($capacity[(int) $pool->host_id][(int) $pool->line_id] + [(int) $pool->attachment_id][$family] ?? 0) + + $available; + } + foreach ($capacity as $hostId => $lineCapacities) { + foreach ($lineCapacities as $lineId => $attachments) { + foreach ($attachments as $families) { + $bundles = min( + (int) ($families[4] ?? 0), + (int) ($families[6] ?? 0) + ); + if ($bundles < 1) { + continue; + } + $networkReadyByHostLine[$hostId][$lineId] = true; + $networkReadyIpCountByHostLine[$hostId][$lineId] = + ($networkReadyIpCountByHostLine[$hostId][$lineId] + ?? 0) + $bundles; + $ipAgg[$hostId][$lineId]['available'] = + ($ipAgg[$hostId][$lineId]['available'] ?? 0) + + $bundles; + } + } + } + foreach ($identities as $hostId => $lines) { + foreach ($lines as $lineId => $states) { + foreach ($states as $state => $values) { + $ipAgg[$hostId][$lineId][$state] = count($values); + } + } } } @@ -1485,13 +1537,10 @@ final class CloudAdminResourceService string $selector, int $verifiedRevision): bool { return $agent !== null - && $agent->isReady() - && $verifiedRevision === (int) $agent->revision - && $verifiedRevision === (int) $agent->tested_revision - && in_array( + && CloudAgentSettingsService::publicNetworkReady( + $agent, $selector, - CloudAgentSettingsService::testedNetworkSelectors($agent), - true + $verifiedRevision ); } diff --git a/web/app/Services/Cloud/CloudAgentSettingsService.php b/web/app/Services/Cloud/CloudAgentSettingsService.php index 6b845557..2be1f2f6 100644 --- a/web/app/Services/Cloud/CloudAgentSettingsService.php +++ b/web/app/Services/Cloud/CloudAgentSettingsService.php @@ -9,6 +9,7 @@ use App\Models\CloudHostStorageConfiguration; final class CloudAgentSettingsService { private const MAX_NETWORK_SELECTORS = 64; + private const PUBLIC_NETWORK_CONTRACT = 1; private const REQUIRED_FEATURES = [ 'create_vm', 'delete_vm', 'power', 'resources', 'settings', 'network', @@ -190,7 +191,8 @@ final class CloudAgentSettingsService ); $summary = self::capabilitySummary($capabilities); self::recordTest($hostId, $expectedRevision, 'healthy', '', - $health['version'], $summary['network_selectors']); + $health['version'], $summary['network_selectors'], + $summary['public_network']); self::scheduleTemplateBackfill($hostId, $actor, 'agent_ready'); self::scheduleRescueBackfill($hostId, $actor, 'agent_ready'); $fresh = CloudHostAgent::find($hostId); @@ -230,6 +232,9 @@ final class CloudAgentSettingsService 'agent_invalid_capabilities', false, 200); } $selectors = self::networkSelectorsFromCapabilities($capabilities); + $publicNetwork = self::normalizePublicNetworkCapabilities( + $capabilities['public_network'] ?? null + ); $known = array_merge(self::REQUIRED_FEATURES, ['uefi', 'secure_boot']); foreach ($known as $feature) { @@ -263,6 +268,7 @@ final class CloudAgentSettingsService 'secure_boot' => false, 'storage_configuration' => true, 'network_selectors' => $selectors, + 'public_network' => $publicNetwork, 'required_feature_count' => count(self::REQUIRED_FEATURES), 'available_features' => self::REQUIRED_FEATURES, 'unavailable_features' => [], @@ -278,6 +284,7 @@ final class CloudAgentSettingsService $setting->last_error_code = ''; $setting->last_agent_version = ''; $setting->network_selectors_json = '[]'; + $setting->public_network_capabilities_json = '{}'; $setting->last_tested_at = 0; $setting->updated_at = time(); $setting->save(); @@ -384,6 +391,37 @@ final class CloudAgentSettingsService } } + /** Current-revision proof for one selector's guarded dual-stack contract. */ + public static function publicNetworkReady( + CloudHostAgent $setting, + string $selector, + int $verifiedRevision + ): bool { + if (!$setting->isReady() + || $verifiedRevision < 1 + || $verifiedRevision !== (int) $setting->revision + || $verifiedRevision !== (int) $setting->tested_revision + || !in_array( + $selector, + self::testedNetworkSelectors($setting), + true + )) { + return false; + } + try { + $decoded = json_decode( + (string) $setting->public_network_capabilities_json, + true, + 8, + JSON_THROW_ON_ERROR + ); + self::normalizePublicNetworkCapabilities($decoded); + return true; + } catch (\Throwable) { + return false; + } + } + private static function client( CloudHostAgent $setting, float $timeoutSeconds = 20.0 @@ -406,7 +444,8 @@ final class CloudAgentSettingsService string $status, string $errorCode, string $version, - array $networkSelectors = [] + array $networkSelectors = [], + array $publicNetworkCapabilities = [] ): void { $encodedSelectors = $status === 'healthy' ? json_encode( @@ -414,6 +453,14 @@ final class CloudAgentSettingsService JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES ) : '[]'; + $encodedPublicNetwork = $status === 'healthy' + ? json_encode( + self::normalizePublicNetworkCapabilities( + $publicNetworkCapabilities + ), + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ) + : '{}'; $updated = CloudHostAgent::query()->where('host_id', $hostId) ->where('revision', $expectedRevision)->update([ 'last_test_status' => $status, @@ -422,6 +469,7 @@ final class CloudAgentSettingsService 'last_error_code' => substr($errorCode, 0, 64), 'last_agent_version' => substr($version, 0, 64), 'network_selectors_json' => $encodedSelectors, + 'public_network_capabilities_json' => $encodedPublicNetwork, 'last_tested_at' => time(), 'updated_at' => time(), ]); @@ -438,6 +486,31 @@ final class CloudAgentSettingsService ); } + /** Persist only the four security properties consumed by placement. */ + private static function normalizePublicNetworkCapabilities( + mixed $value + ): array { + if (!is_array($value) || array_is_list($value) + || ($value['contract'] ?? null) !== self::PUBLIC_NETWORK_CONTRACT + || ($value['dual_stack_required'] ?? null) !== true + || ($value['project_owned_filter'] ?? null) !== true + || ($value['ndp_guard'] ?? null) !== true) { + throw new CloudAgentError( + '宿主机 Agent 未满足双栈公网网络安全合同', + 409, + 'agent_capability_mismatch', + false, + 200 + ); + } + return [ + 'contract' => self::PUBLIC_NETWORK_CONTRACT, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ]; + } + private static function normalizeNetworkSelectors(mixed $selectors): array { if (!is_array($selectors) || !array_is_list($selectors) diff --git a/web/public/cloud/admin-hosts.js b/web/public/cloud/admin-hosts.js index 5ddbeea7..89608f5a 100644 --- a/web/public/cloud/admin-hosts.js +++ b/web/public/cloud/admin-hosts.js @@ -859,6 +859,7 @@ async function testHostNetworkAttachment(attachmentKey, expectedRevision, button } finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; if (button?.isConnected) button.disabled = false; syncNetworkAttachmentButtons(); } } } function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; } +function networkPoolFamilyLabel(value) { return Number(value) === 6 ? 'IPv6' : 'IPv4'; } function networkPoolInput(type, name, value, options = {}) { const control = document.createElement(type === 'textarea' ? 'textarea' : type === 'select' ? 'select' : 'input'); control.className = type === 'select' ? 'form-select' : 'form-control'; @@ -917,16 +918,25 @@ function networkPoolAttachmentField(select, detail, wide = true) { } function networkPoolBody(form) { const value = name => form.elements.namedItem(name)?.value ?? ''; + const family = Number(value('address_family')); const prefix = Number(value('guest_prefix_length')); + const maxAllocations = Number(value('max_allocations')); const expectedRevision = Number(value('expected_revision')); const networkAttachmentId = Number(value('network_attachment_id')); - if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。'); + if (![4, 6].includes(family)) throw new Error('请选择 IPv4 或 IPv6 地址族。'); + if (!Number.isInteger(prefix) || (family === 4 ? prefix < 24 || prefix > 30 : prefix < 48 || prefix > 120)) throw new Error(family === 4 ? 'IPv4 前缀必须是 24 至 30 的整数。' : 'IPv6 前缀必须是 48 至 120 的整数。'); + if (family === 6 && (!Number.isInteger(maxAllocations) || maxAllocations < 1 || maxAllocations > 65535)) throw new Error('IPv6 最大分配数量必须是 1 至 65535 的整数。'); if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new Error('地址池版本无效,请刷新后重试。'); if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择有效的宿主机网络接入。'); return { network_attachment_id: networkAttachmentId, + address_family: family, name: value('name').trim(), cidr: value('cidr').trim(), gateway: value('gateway').trim(), + gateway_on_link: value('gateway_on_link') === '1', dns_servers: formList(value('dns_servers')), reserved_ips: formList(value('reserved_ips')), + allocation_start: family === 6 ? value('allocation_start').trim() : null, + allocation_end: family === 6 ? value('allocation_end').trim() : null, + max_allocations: family === 6 ? maxAllocations : 0, guest_prefix_length: prefix, state: value('state'), expected_revision: expectedRevision, }; } @@ -936,7 +946,7 @@ function renderNetworkPoolForm(pool) { const expectedRevision = networkPoolInput('hidden', 'expected_revision', Number(pool.expected_revision || pool.revision || 0)); const heading = element('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap mb-3'); const copy = element('div', 'min-w-0'); - copy.append(element('h6', 'mb-1', pool.name || pool.cidr), element('div', 'text-muted admin-mono fs-13', pool.pool_key)); + copy.append(element('h6', 'mb-1', `${networkPoolFamilyLabel(pool.address_family)} · ${pool.name || pool.cidr}`), element('div', 'text-muted admin-mono fs-13', pool.pool_key)); const badge = element('span', 'badge bg-light text-dark', `${networkPoolStateLabel(pool.state)} · ${pool.sync_message || '等待应用'}`); heading.append(copy, badge); const grid = element('div', 'cloud-admin-form-grid'); @@ -945,15 +955,24 @@ function renderNetworkPoolForm(pool) { const attachmentDetail = element('div', 'form-text', networkPoolAttachmentDetail(pool.network_attachment_id, pool.attachment)); attachment.addEventListener('change', () => { attachmentDetail.textContent = networkPoolAttachmentDetail(attachment.value, pool.attachment); }); const name = networkPoolInput('text', 'name', pool.name, { required: true, maxLength: 80 }); + const family = networkPoolInput('select', 'address_family', ''); family.replaceChildren(); family.append(new Option('IPv4', '4'), new Option('IPv6', '6')); family.value = String(Number(pool.address_family || 4)); + family.disabled = true; const cidr = networkPoolInput('text', 'cidr', pool.cidr, { required: true, mono: true }); const gateway = networkPoolInput('text', 'gateway', pool.gateway, { required: true, mono: true }); - const prefix = networkPoolInput('number', 'guest_prefix_length', pool.guest_prefix_length, { required: true, min: 24, max: 30 }); + const gatewayOnLink = networkPoolInput('select', 'gateway_on_link', ''); gatewayOnLink.replaceChildren(); gatewayOnLink.append(new Option('网关位于地址池内', '0'), new Option('网关在链路上(on-link)', '1')); gatewayOnLink.value = pool.gateway_on_link === true ? '1' : '0'; + const prefix = networkPoolInput('number', 'guest_prefix_length', pool.guest_prefix_length, { required: true, min: Number(pool.address_family) === 6 ? 48 : 24, max: Number(pool.address_family) === 6 ? 120 : 30 }); const status = networkPoolInput('select', 'state', pool.state); const dns = networkPoolInput('text', 'dns_servers', Array.isArray(pool.dns_servers) ? pool.dns_servers.join(', ') : '', { required: true, mono: true }); const reserved = networkPoolInput('textarea', 'reserved_ips', Array.isArray(pool.reserved_ips) ? pool.reserved_ips.join(', ') : '', { mono: true, rows: 3 }); - for (const [control, suffix] of [[attachment, 'attachment'], [name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`; - grid.append(networkPoolAttachmentField(attachment, attachmentDetail), networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true)); - const metadata = element('p', 'form-text mb-0', `面板版本 ${Number(pool.revision || 0)} · 已应用版本 ${pool.live_revision === null ? '未确认' : Number(pool.live_revision)} · 占用 ${Number(pool.occupied_count || 0)} 个地址`); + const allocationStart = networkPoolInput('text', 'allocation_start', pool.allocation_start || '', { mono: true }); + const allocationEnd = networkPoolInput('text', 'allocation_end', pool.allocation_end || '', { mono: true }); + const maxAllocations = networkPoolInput('number', 'max_allocations', Number(pool.max_allocations || 0), { min: 1, max: 65535 }); + for (const [control, suffix] of [[attachment, 'attachment'], [name, 'name'], [family, 'family'], [cidr, 'cidr'], [gateway, 'gateway'], [gatewayOnLink, 'gateway-on-link'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved'], [allocationStart, 'allocation-start'], [allocationEnd, 'allocation-end'], [maxAllocations, 'max-allocations']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`; + const sparseFields = [networkPoolField('IPv6 分配起始地址', allocationStart), networkPoolField('IPv6 分配结束地址', allocationEnd), networkPoolField('IPv6 最大分配数量', maxAllocations)]; + const syncFamily = () => { const ipv6 = family.value === '6'; prefix.min = ipv6 ? '48' : '24'; prefix.max = ipv6 ? '120' : '30'; for (const field of sparseFields) field.hidden = !ipv6; allocationStart.required = ipv6; allocationEnd.required = ipv6; maxAllocations.required = ipv6; gatewayOnLink.disabled = !canManage || !ipv6; if (!ipv6) { allocationStart.value = ''; allocationEnd.value = ''; maxAllocations.value = '0'; gatewayOnLink.value = '0'; } }; + family.addEventListener('change', syncFamily); syncFamily(); + grid.append(networkPoolAttachmentField(attachment, attachmentDetail), networkPoolField('地址池名称', name, true), networkPoolField('地址族', family), networkPoolField('网关方式', gatewayOnLink), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true), ...sparseFields); + const metadata = element('p', 'form-text mb-0', `面板版本 ${Number(pool.revision || 0)} · 已应用版本 ${pool.live_revision === null ? '未确认' : Number(pool.live_revision)} · 占用 ${Number(pool.occupied_count || 0)} · 可分配 ${Number(pool.available_count || 0)}`); const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3'); actions.append(metadata); const actionButtons = element('div', 'd-flex gap-2 flex-wrap'); @@ -978,11 +997,11 @@ function renderNetworkPoolForm(pool) { const replacementLocked = pool.replacement_locked === true || (pool.active_replacement && typeof pool.active_replacement === 'object'); if (runtimeLocked) { - for (const control of [attachment, cidr, gateway, prefix, dns]) control.disabled = true; + for (const control of [attachment, family, cidr, gateway, gatewayOnLink, prefix, dns, allocationStart, allocationEnd, maxAllocations]) control.disabled = true; form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;网络接入、CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。')); } if (replacementLocked) { - for (const control of [attachment, name, cidr, gateway, prefix, status, dns, reserved, save]) control.disabled = true; + for (const control of [attachment, name, family, cidr, gateway, gatewayOnLink, prefix, status, dns, reserved, allocationStart, allocationEnd, maxAllocations, save]) control.disabled = true; form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池正在执行受控换池,配置保持锁定;请查看批次进度或前往任务中心核对。')); } if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true; @@ -1314,7 +1333,7 @@ function showNetworkPoolCreate() { const form = byId('host-network-pool-create-form'); form.reset(); try { form.dataset.requestKey = newNetworkPoolRequestKey(); } catch (error) { hostNetworkPoolNotice(error.message, true); return; } - byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-state').value = 'active'; form.hidden = false; + byId('host-network-pool-new-family').value = '4'; byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-gateway-on-link').value = '0'; byId('host-network-pool-new-state').value = 'active'; syncNewNetworkPoolFamily(); form.hidden = false; fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment')); const firstReady = networkPoolAttachments().find(attachment => attachment.ready === true); if (firstReady) byId('host-network-pool-new-attachment').value = String(networkPoolAttachmentId(firstReady)); @@ -1322,14 +1341,26 @@ function showNetworkPoolCreate() { byId('host-network-pool-new-name').focus({ preventScroll: true }); form.scrollIntoView({ behavior: 'smooth', block: 'start' }); } function hideNetworkPoolCreate() { const form = byId('host-network-pool-create-form'); form.hidden = true; delete form.dataset.requestKey; } +function syncNewNetworkPoolFamily() { + const ipv6 = byId('host-network-pool-new-family').value === '6'; + const prefix = byId('host-network-pool-new-prefix'); prefix.min = ipv6 ? '48' : '24'; prefix.max = ipv6 ? '120' : '30'; prefix.value = ipv6 ? '64' : '28'; + for (const id of ['host-network-pool-new-allocation-start', 'host-network-pool-new-allocation-end', 'host-network-pool-new-max-allocations']) { const control = byId(id); control.required = ipv6; control.disabled = !canManage || !ipv6; } + const gatewayOnLink = byId('host-network-pool-new-gateway-on-link'); gatewayOnLink.disabled = !canManage || !ipv6; + for (const field of document.querySelectorAll?.('[data-network-pool-ipv6-only]') || []) field.hidden = !ipv6; + if (!ipv6) gatewayOnLink.value = '0'; +} function newNetworkPoolBody(form) { + const family = Number(byId('host-network-pool-new-family').value); const prefix = Number(byId('host-network-pool-new-prefix').value); + const maxAllocations = Number(byId('host-network-pool-new-max-allocations').value); const networkAttachmentId = Number(byId('host-network-pool-new-attachment').value); - if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。'); + if (![4, 6].includes(family)) throw new Error('请选择 IPv4 或 IPv6 地址族。'); + if (!Number.isInteger(prefix) || (family === 4 ? prefix < 24 || prefix > 30 : prefix < 48 || prefix > 120)) throw new Error(family === 4 ? 'IPv4 前缀必须是 24 至 30 的整数。' : 'IPv6 前缀必须是 48 至 120 的整数。'); + if (family === 6 && (!Number.isInteger(maxAllocations) || maxAllocations < 1 || maxAllocations > 65535)) throw new Error('IPv6 最大分配数量必须是 1 至 65535 的整数。'); if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择已验证的宿主机网络接入。'); const requestKey = form.dataset.requestKey || ''; if (!/^[0-9a-f]{32}$/.test(requestKey)) throw new Error('创建请求标识已失效,请取消后重新添加。'); - return { network_attachment_id: networkAttachmentId, name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey }; + return { network_attachment_id: networkAttachmentId, address_family: family, name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), gateway_on_link: byId('host-network-pool-new-gateway-on-link').value === '1', dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), allocation_start: family === 6 ? byId('host-network-pool-new-allocation-start').value.trim() : null, allocation_end: family === 6 ? byId('host-network-pool-new-allocation-end').value.trim() : null, max_allocations: family === 6 ? maxAllocations : 0, guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey }; } async function createHostNetworkPool(event) { event.preventDefault(); if (!canManage || state.networkPoolBusy) return; @@ -1512,6 +1543,7 @@ async function initialize() { const attachmentDrawer = byId('host-network-attachments-drawer'); attachmentDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkAttachments(); }); attachmentDrawer.addEventListener('click', event => { if (event.target === attachmentDrawer) closeHostNetworkAttachments(); }); byId('host-network-pools-close').addEventListener('click', closeHostNetworkPools); byId('host-network-pool-add')?.addEventListener('click', showNetworkPoolCreate); byId('host-network-pool-create-cancel').addEventListener('click', hideNetworkPoolCreate); byId('host-network-pool-create-form').addEventListener('submit', createHostNetworkPool); byId('host-network-pool-new-attachment').addEventListener('change', event => { byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(event.currentTarget.value); }); + byId('host-network-pool-new-family').addEventListener('change', syncNewNetworkPoolFamily); syncNewNetworkPoolFamily(); const networkDrawer = byId('host-network-pools-drawer'); networkDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkPools(); }); networkDrawer.addEventListener('click', event => { if (event.target === networkDrawer) closeHostNetworkPools(); }); byId('host-vpc-transport-close').addEventListener('click', closeHostVpcTransport); byId('host-vpc-transport-form').addEventListener('submit', saveHostVpcTransport); byId('host-vpc-transport-discover').addEventListener('click', discoverHostVpcTransport); byId('host-vpc-transport-test').addEventListener('click', testHostVpcTransport); byId('host-vpc-transport-candidate').addEventListener('change', selectHostVpcTransportCandidate); const vpcTransportDrawer = byId('host-vpc-transport-drawer'); vpcTransportDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostVpcTransport(); }); vpcTransportDrawer.addEventListener('click', event => { if (event.target === vpcTransportDrawer) closeHostVpcTransport(); }); diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index d5858f18..6a58220c 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -248,7 +248,7 @@
-

Public IPv4 Pools

+

Public IPv4 / IPv6 Pools

公网地址池

diff --git a/web/sql/cloud.sql b/web/sql/cloud.sql index 262c7f2e..febf6386 100644 --- a/web/sql/cloud.sql +++ b/web/sql/cloud.sql @@ -95,6 +95,7 @@ CREATE TABLE cloud_host_agents ( last_error_code VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', last_agent_version VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '', network_selectors_json LONGTEXT NOT NULL, + public_network_capabilities_json LONGTEXT NOT NULL, last_tested_at BIGINT UNSIGNED NOT NULL DEFAULT 0, created_at BIGINT UNSIGNED NOT NULL, updated_at BIGINT UNSIGNED NOT NULL, @@ -251,6 +252,17 @@ CREATE TABLE cloud_vpc_cidr_pools ( ) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +-- Pool CIDRs are globally unique across hosts. Every administrator pool +-- mutation locks this singleton before host, attachment, pool and address +-- rows so concurrent cross-host overlap checks cannot both commit. +CREATE TABLE cloud_public_ip_pool_catalog_mutex ( + id TINYINT UNSIGNED NOT NULL PRIMARY KEY, + updated_at BIGINT UNSIGNED NOT NULL DEFAULT 0, + CONSTRAINT chk_cloud_public_ip_pool_catalog_mutex CHECK (id = 1) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +INSERT IGNORE INTO cloud_public_ip_pool_catalog_mutex + (id, updated_at) VALUES (1, 0); + -- A public pool is an allocation boundary, not a compute resource pool. The -- child cloud_public_ips rows remain the authoritative concrete-address -- ledger used by payment-time placement and reconciliation. diff --git a/web/tests/AdminHostNetworkBehaviorTest.mjs b/web/tests/AdminHostNetworkBehaviorTest.mjs index b68f0fd9..581d5b41 100644 --- a/web/tests/AdminHostNetworkBehaviorTest.mjs +++ b/web/tests/AdminHostNetworkBehaviorTest.mjs @@ -7,13 +7,13 @@ const requestRuntimeSource = await readFile( new URL('../public/cloud/admin-request-runtime.js', import.meta.url), 'utf8'); const source = adminSource.slice(adminSource.indexOf('const root =')) .replace('void initialize();', '') - + '\nglobalThis.hostUI = { initialize, fillHost, saveHost, renderHostNetworkAttachments, createHostNetworkAttachment, networkAttachmentBody, renderHostNetworkPools, renderNetworkPoolReplacementPanel, networkPoolReplacementRequest, state };'; + + '\nglobalThis.hostUI = { initialize, fillHost, saveHost, renderHostNetworkAttachments, createHostNetworkAttachment, networkAttachmentBody, renderHostNetworkPools, renderNetworkPoolReplacementPanel, networkPoolReplacementRequest, newNetworkPoolBody, syncNewNetworkPoolFamily, state };'; const submit = { preventDefault() {} }; const descendants = node => [node, ...(node?.children || []).flatMap(descendants)]; function fixture(canManage = true) { const elements = new Map(); - const selectIds = new Set(['host-country-code', 'host-network-type', 'host-network-attachment-new-line', 'host-network-attachment-new-selector', 'host-network-attachment-new-state', 'host-network-pool-new-attachment', 'host-network-pool-new-state']); + const selectIds = new Set(['host-country-code', 'host-network-type', 'host-network-attachment-new-line', 'host-network-attachment-new-selector', 'host-network-attachment-new-state', 'host-network-pool-new-attachment', 'host-network-pool-new-state', 'host-network-pool-new-family', 'host-network-pool-new-gateway-on-link']); class Element { constructor(tag = 'input') { this.tag = tag; this.value = ''; this.textContent = ''; this.dataset = {}; @@ -195,6 +195,8 @@ function fixture(canManage = true) { network_attachment_id: 11, attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'China optimized', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, gateway: '8.8.8.1', guest_prefix_length: 29, + address_family: 4, gateway_on_link: false, + allocation_start: null, allocation_end: null, max_allocations: 0, dns_servers: ['1.1.1.1'], reserved_ips: [], state: 'active', revision: 1, expected_revision: 1, live_revision: 1, sync_message: '已应用', occupied_count: 1, @@ -213,6 +215,80 @@ function fixture(canManage = true) { 'The occupied-pool warning did not explain the per-address safety rule.'); } +{ + const test = fixture(); + const get = test.get; + get('host-network-pool-new-family').value = '4'; + get('host-network-pool-new-gateway-on-link').value = '1'; + test.syncNewNetworkPoolFamily(); + assert.equal(get('host-network-pool-new-gateway-on-link').value, '0'); + assert.equal(get('host-network-pool-new-gateway-on-link').disabled, true, + 'IPv4 create mode exposed the unsupported on-link control.'); + get('host-network-pool-new-attachment').value = '11'; + get('host-network-pool-new-family').value = '6'; + test.syncNewNetworkPoolFamily(); + assert.equal(get('host-network-pool-new-gateway-on-link').disabled, false, + 'IPv6 create mode did not enable on-link selection.'); + get('host-network-pool-new-name').value = 'Public IPv6'; + get('host-network-pool-new-cidr').value = '2404:c140:156:3a::/64'; + get('host-network-pool-new-gateway').value = '2404:c140:156::1'; + get('host-network-pool-new-gateway-on-link').value = '1'; + get('host-network-pool-new-dns').value = '2606:4700:4700::1111'; + get('host-network-pool-new-reserved').value = '2404:c140:156:3a::2'; + get('host-network-pool-new-allocation-start').value = '2404:c140:156:3a::1000'; + get('host-network-pool-new-allocation-end').value = '2404:c140:156:3a::1fff'; + get('host-network-pool-new-max-allocations').value = '100'; + get('host-network-pool-new-prefix').value = '64'; + get('host-network-pool-new-state').value = 'active'; + const form = get('host-network-pool-create-form'); form.dataset.requestKey = 'f'.repeat(32); + const body = test.newNetworkPoolBody(form); + assert.equal(body.address_family, 6); + assert.equal(body.gateway_on_link, true); + assert.equal(body.max_allocations, 100); + assert.equal(body.allocation_start, '2404:c140:156:3a::1000'); +} + +{ + const test = fixture(false); + test.get('host-network-pool-new-family').value = '6'; + test.syncNewNetworkPoolFamily(); + assert.equal(test.get('host-network-pool-new-gateway-on-link').disabled, true, + 'Read-only IPv6 create mode enabled the on-link control.'); +} + +for (const [family, enabled] of [[4, false], [6, true]]) { + const test = fixture(); + test.state.hosts = [{ id: 7, default_network: 'bridge:br0' }]; + test.state.networkPoolHostId = '7'; + test.get('host-network-pools-drawer').open = true; + test.renderHostNetworkPools({ + host: { id: 7, name: 'Host' }, + attachments: [{ id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }], + maximum: 32, + items: [{ + pool_key: String(family).repeat(32), name: `Public IPv${family}`, + cidr: family === 4 ? '8.8.8.0/29' : '2404:c140:156:3a::/64', + network_attachment_id: 11, + attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, + gateway: family === 4 ? '8.8.8.1' : '2404:c140:156::1', + guest_prefix_length: family === 4 ? 29 : 64, + address_family: family, gateway_on_link: family === 6, + allocation_start: family === 6 ? '2404:c140:156:3a::1000' : null, + allocation_end: family === 6 ? '2404:c140:156:3a::1fff' : null, + max_allocations: family === 6 ? 100 : 0, + dns_servers: [family === 4 ? '1.1.1.1' : '2606:4700:4700::1111'], + reserved_ips: [], state: 'active', revision: 1, + expected_revision: 1, live_revision: 1, sync_message: '已应用', + occupied_count: 0, + }], + }, 7, 0); + const gatewayOnLink = descendants(test.get('host-network-pools-list')) + .find(node => node.name === 'gateway_on_link'); + assert.equal(gatewayOnLink?.disabled, !enabled, + `IPv${family} edit mode exposed the wrong on-link state.`); + if (family === 4) assert.equal(gatewayOnLink?.value, '0'); +} + { const test = fixture(); const sourceKey = 'a'.repeat(32); const targetKey = 'b'.repeat(32); @@ -291,6 +367,9 @@ function fixture(canManage = true) { network_attachment_id: 11, attachment: { id: 11, name: 'Public uplink', line_id: 3, line_name: 'International', network_selector: 'bridge:br-public', state: 'active', verification_state: 'verified', ready: true }, gateway: '203.0.113.1', guest_prefix_length: 29, + address_family: 6, gateway_on_link: true, + allocation_start: '2404:c140:156:3a::1000', + allocation_end: '2404:c140:156:3a::1fff', max_allocations: 100, dns_servers: ['1.1.1.1'], reserved_ips: [], state: 'disabled', revision: 5, expected_revision: 5, live_revision: 5, sync_message: '已应用', occupied_count: 0, @@ -300,6 +379,10 @@ function fixture(canManage = true) { }, 7, 0); const buttons = descendants(test.get('host-network-pools-list')) .filter(node => node.tag === 'button'); + const gatewayOnLink = descendants(test.get('host-network-pools-list')) + .find(node => node.name === 'gateway_on_link'); + assert.equal(gatewayOnLink?.disabled, true, + 'Read-only IPv6 edit mode enabled the on-link control.'); const history = buttons.find(node => node.textContent === '查看换池记录'); assert.ok(history && history.hidden !== true, 'A completed replacement history became unreachable after source occupancy reached zero.'); diff --git a/web/tests/AdminHostNetworkPoolsContractTest.php b/web/tests/AdminHostNetworkPoolsContractTest.php index 3d51dfe0..7369523e 100644 --- a/web/tests/AdminHostNetworkPoolsContractTest.php +++ b/web/tests/AdminHostNetworkPoolsContractTest.php @@ -9,6 +9,15 @@ $controller = file_get_contents( $service = file_get_contents( $root . '/app/Services/Cloud/CloudAdminHostNetworkService.php' ); +$projectionService = file_get_contents( + $root . '/app/Services/Cloud/CloudAdminHostProjectionService.php' +); +$schedulingService = file_get_contents( + $root . '/app/Services/Cloud/CloudAdminHostSchedulingService.php' +); +$resourceService = file_get_contents( + $root . '/app/Services/Cloud/CloudAdminResourceService.php' +); $usage = file_get_contents( $root . '/app/Services/Cloud/CloudPanelUsageService.php' ); @@ -44,9 +53,11 @@ $assert(str_contains($controller, 'CloudAccess::manage($actor);') && str_contains($controller, '$write = $method !== \'GET\';') && substr_count($controller, "'network_attachment_id'") === 2 && substr_count($controller, - "'network_attachment_id', 'name', 'cidr', 'gateway'") === 2 + "'network_attachment_id', 'address_family', 'name', 'cidr'") === 2 + && substr_count($controller, + "'gateway', 'gateway_on_link', 'dns_servers', 'reserved_ips'") === 2 && substr_count($controller, - "'dns_servers', 'reserved_ips', 'guest_prefix_length'") === 2 + "'allocation_start', 'allocation_end', 'max_allocations'") === 2 && str_contains($controller, "'state', 'request_key'") && str_contains($controller, @@ -76,7 +87,7 @@ $assert(str_contains($service, 'private const MAX_POOLS = 32;') && str_contains($service, '(int) $attachment->verified_agent_revision') && str_contains($service, - 'CloudAgentSettingsService::testedNetworkSelectors($agent)') + 'CloudAgentSettingsService::publicNetworkReady(') && str_contains($service, 'assertMembershipLine(') && str_contains($service, 'CloudPublicIpPool') && str_contains($service, 'desired_revision') @@ -85,6 +96,13 @@ $assert(str_contains($service, 'private const MAX_POOLS = 32;') && !str_contains($service, 'refreshAttachmentAggregate') && !str_contains($service, '$attachment->save();'), 'Pools must bind verified attachments without rewriting attachment state.'); +$assert(str_contains($projectionService, + 'CloudAgentSettingsService::publicNetworkReady(') + && str_contains($schedulingService, + 'CloudAgentSettingsService::publicNetworkReady(') + && str_contains($resourceService, + 'CloudAgentSettingsService::publicNetworkReady('), + 'Every administrator readiness projection must require the tested public-network contract.'); $assert(str_contains($service, "preg_match('/^[0-9a-f]{32}$/D', \$requestKey)") @@ -109,6 +127,15 @@ $assert(str_contains($service, 'assertNoOverlap(') && str_contains($service, 'catalogCount(') && str_contains($service, '一台宿主机最多配置 32 个公网地址池') && str_contains($service, 'OCCUPIED_IP_STATES') + && str_contains($service, 'MAX_IPV6_ALLOCATIONS') + && str_contains($service, "'address_family'") + && str_contains($service, "'gateway_on_link'") + && str_contains($service, "'allocation_start'") + && str_contains($service, "'allocation_end'") + && str_contains($service, "'max_allocations'") + && str_contains($service, 'refreshSparseIpv6Ledger') + && str_contains($service, "'dual_stack_ready'") + && str_contains($service, "'available_count'") && str_contains($service, '该地址池仍有实例或任务占用,只能修改名称、运行状态和未占用的保留 / 禁用 IP') && str_contains($service, @@ -122,6 +149,15 @@ $assert(str_contains($service, 'assertNoOverlap(') && str_contains($service, "'line' => \$attachment['line']") && !str_contains($service, '->delete()'), 'Pool limits, overlap checks, occupied runtime locks and soft lifecycle states are required.'); +$catalogLockAt = strpos($service, + 'CloudPublicIpPoolCatalogMutex::where('); +$hostLockAt = strpos($service, + "CloudHost::where('id', (int) \$host->id)"); +$assert($catalogLockAt !== false && $hostLockAt !== false + && $catalogLockAt < $hostLockAt + && str_contains(substr($service, $catalogLockAt, + $hostLockAt - $catalogLockAt), '->lockForUpdate()'), + 'Public-pool mutations must lock the global catalog before any host-scoped row.'); $assert(str_contains($service, 'materializeIpLedger(') && str_contains((string) $usage, "CloudInstance::where('cloud_instances.host_id', \$hostId)") @@ -168,18 +204,28 @@ $assert(str_contains($template, 'id="host-network-pools-drawer"') && str_contains($client, 'expected_revision: expectedRevision') && str_contains($client, 'network_attachment_id: networkAttachmentId') + && str_contains($client, 'address_family: family') + && str_contains($client, 'gateway_on_link:') + && str_contains($client, 'allocation_start:') + && str_contains($client, 'max_allocations:') && str_contains($client, 'networkPoolAttachmentDetail(') && str_contains($client, 'const readyAttachments = networkPoolAttachments()') && str_contains($client, 'const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools`);') && str_contains($client, 'save.disabled = !canManage') - && str_contains($client, 'for (const control of [attachment, cidr, gateway, prefix, dns]) control.disabled = true;') + && str_contains($client, 'for (const control of [attachment, family, cidr, gateway, gatewayOnLink, prefix, dns, allocationStart, allocationEnd, maxAllocations]) control.disabled = true;') && !str_contains($client, '[cidr, gateway, prefix, dns, reserved]') && str_contains($client, '已分配或任务占用的 IP 会被拒绝') && !file_exists($root . '/public/cloud/admin-host-network.css'), 'The responsive pool editor must lock network identity while allowing unoccupied disabled-IP edits.'); $assert(str_contains($template, '受控迁移占用地址') + && str_contains($template, 'Public IPv4 / IPv6 Pools') + && str_contains($template, 'id="host-network-pool-new-family"') + && str_contains($template, 'id="host-network-pool-new-gateway-on-link"') + && str_contains($template, 'id="host-network-pool-new-allocation-start"') + && str_contains($template, 'id="host-network-pool-new-allocation-end"') + && str_contains($template, 'id="host-network-pool-new-max-allocations"') && str_contains($client, 'function networkPoolReplacementPath(') && str_contains($client, '/replacement-batches`') diff --git a/web/tests/CloudAdminHostListProjectionTest.php b/web/tests/CloudAdminHostListProjectionTest.php index 4a65cf51..965f94f7 100644 --- a/web/tests/CloudAdminHostListProjectionTest.php +++ b/web/tests/CloudAdminHostListProjectionTest.php @@ -99,6 +99,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_error_code'); $table->string('last_agent_version'); $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); $table->integer('last_tested_at'); $table->integer('created_at'); $table->integer('updated_at'); @@ -160,6 +161,8 @@ $schema->create('cloud_public_ip_pools', $table->increments('id'); $table->integer('host_id'); $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->integer('max_allocations')->default(0); $table->string('state'); $table->string('sync_state'); $table->integer('observed_revision'); @@ -169,6 +172,7 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); $table->integer('public_ip_pool_id'); + $table->integer('address_family'); $table->string('state'); $table->integer('reservation_id')->nullable(); $table->integer('instance_id')->nullable(); @@ -226,6 +230,8 @@ Capsule::table('cloud_host_agents')->insert([ 'last_test_status' => 'healthy', 'last_error_code' => '', 'last_agent_version' => 'v3', 'last_tested_at' => 100, 'network_selectors_json' => '["bridge:br0"]', + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', 'created_at' => 1, 'updated_at' => 100, ]); Capsule::table('cloud_host_storage_configurations')->insert([ @@ -254,18 +260,26 @@ Capsule::table('cloud_host_network_attachments')->insert([ 'desired_revision' => 1, ]); Capsule::table('cloud_public_ip_pools')->insert([ - 'id' => 1, 'host_id' => 1, 'network_attachment_id' => 1, - 'state' => 'active', 'sync_state' => 'applied', - 'observed_revision' => 1, 'desired_revision' => 1, + ['id' => 1, 'host_id' => 1, 'network_attachment_id' => 1, + 'address_family' => 4, 'max_allocations' => 0, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], + ['id' => 2, 'host_id' => 1, 'network_attachment_id' => 1, + 'address_family' => 6, 'max_allocations' => 100, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], ]); Capsule::table('cloud_public_ips')->insert([ ['id' => 1, 'host_id' => 1, 'public_ip_pool_id' => 1, + 'address_family' => 4, 'state' => 'assigned', 'reservation_id' => 1, 'instance_id' => 1, 'operation_id' => null], ['id' => 2, 'host_id' => 1, 'public_ip_pool_id' => 1, + 'address_family' => 4, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ['id' => 3, 'host_id' => 1, 'public_ip_pool_id' => 1, + 'address_family' => 4, 'state' => 'disabled', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ]); diff --git a/web/tests/CloudAdminHostMultiMembershipProjectionTest.php b/web/tests/CloudAdminHostMultiMembershipProjectionTest.php index 15737a6d..d996302c 100644 --- a/web/tests/CloudAdminHostMultiMembershipProjectionTest.php +++ b/web/tests/CloudAdminHostMultiMembershipProjectionTest.php @@ -109,6 +109,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_error_code'); $table->string('last_agent_version'); $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); $table->integer('last_tested_at'); $table->integer('created_at'); $table->integer('updated_at'); @@ -164,9 +165,11 @@ $schema->create('cloud_public_ip_pools', $table->increments('id'); $table->integer('host_id'); $table->integer('network_attachment_id'); + $table->integer('address_family'); $table->string('pool_key'); $table->string('cidr'); $table->integer('guest_prefix_length'); + $table->integer('max_allocations')->default(0); $table->string('state'); $table->string('sync_state'); $table->integer('observed_revision'); @@ -176,6 +179,7 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); $table->integer('public_ip_pool_id'); + $table->integer('address_family'); $table->string('address'); $table->integer('prefix_length'); $table->string('state'); @@ -244,6 +248,8 @@ Capsule::table('cloud_host_agents')->insert([ 'network_selectors_json' => json_encode([ 'bridge:br-premium', 'bridge:br-standard', ], JSON_THROW_ON_ERROR), + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', 'created_at' => 1, 'updated_at' => 1, ]); Capsule::table('cloud_host_storage_configurations')->insert([ @@ -264,22 +270,40 @@ Capsule::table('cloud_host_network_attachments')->insert([ ]); Capsule::table('cloud_public_ip_pools')->insert([ ['id' => 50, 'host_id' => 1, 'network_attachment_id' => 40, + 'address_family' => 4, 'pool_key' => str_repeat('a', 32), 'cidr' => '203.0.113.0/29', - 'guest_prefix_length' => 29, + 'guest_prefix_length' => 29, 'max_allocations' => 0, 'state' => 'active', 'sync_state' => 'applied', 'observed_revision' => 2, 'desired_revision' => 2], ['id' => 51, 'host_id' => 1, 'network_attachment_id' => 41, + 'address_family' => 4, 'pool_key' => str_repeat('b', 32), 'cidr' => '198.51.100.0/29', - 'guest_prefix_length' => 29, + 'guest_prefix_length' => 29, 'max_allocations' => 0, 'state' => 'active', 'sync_state' => 'applied', 'observed_revision' => 3, 'desired_revision' => 3], + ['id' => 52, 'host_id' => 1, 'network_attachment_id' => 40, + 'address_family' => 6, + 'pool_key' => str_repeat('c', 32), + 'cidr' => '2404:c140:156:3a::/64', + 'guest_prefix_length' => 64, 'max_allocations' => 100, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], + ['id' => 53, 'host_id' => 1, 'network_attachment_id' => 41, + 'address_family' => 6, + 'pool_key' => str_repeat('d', 32), + 'cidr' => '2404:c140:156:3b::/64', + 'guest_prefix_length' => 64, 'max_allocations' => 100, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], ]); Capsule::table('cloud_public_ips')->insert([ ['id' => 60, 'host_id' => 1, 'public_ip_pool_id' => 50, + 'address_family' => 4, 'address' => '203.0.113.2', 'prefix_length' => 29, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ['id' => 61, 'host_id' => 1, 'public_ip_pool_id' => 51, + 'address_family' => 4, 'address' => '198.51.100.2', 'prefix_length' => 29, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], @@ -306,6 +330,46 @@ $assert($host['capacity']['cpu']['configured'] === 16 && $projection['summary']['capacity']['cpu']['configured'] === 16, 'Physical capacity was duplicated across active memberships.'); +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => '{}', +]); +$missingPublicNetworkContract = + CloudAdminHostProjectionService::listing()['hosts'][0]; +$missingPublicNetworkResources = CloudAdminResourceService::page(); +$assert($missingPublicNetworkContract['readiness']['network_ready'] === false + && $missingPublicNetworkContract['capacity']['ip']['available'] === 0 + && count(array_filter( + $missingPublicNetworkResources['hosts'], + static fn (array $row): bool => $row['network_ready'] + )) === 0, + 'Host projection accepted missing public-network capability evidence.'); +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', +]); + +Capsule::table('cloud_public_ip_pools')->where('id', 53)->update([ + 'state' => 'disabled', +]); +$oneIncompletePair = CloudAdminHostProjectionService::listing()['hosts'][0]; +$assert($oneIncompletePair['capacity']['ip']['available'] === 1 + && count(array_filter( + $oneIncompletePair['memberships'], + static fn (array $row): bool => $row['network_ready'] + )) === 1, + 'A line without an active IPv6 companion pool remained placement-ready.'); +$oneIncompletePairResources = CloudAdminResourceService::page(); +$readyResourceMemberships = array_values(array_filter( + $oneIncompletePairResources['hosts'], + static fn (array $row): bool => $row['network_ready'] +)); +$assert(count($readyResourceMemberships) === 1 + && (int) $readyResourceMemberships[0]['resource_pool_id'] === 20, + 'Resource capacity accepted a line without its IPv6 companion pool.'); +Capsule::table('cloud_public_ip_pools')->where('id', 53)->update([ + 'state' => 'active', +]); + $resources = CloudAdminResourceService::page(); $pools = []; foreach ($resources['pools'] as $pool) { diff --git a/web/tests/CloudAdminHostMultiMembershipServiceTest.php b/web/tests/CloudAdminHostMultiMembershipServiceTest.php index 96071b98..df8004d6 100644 --- a/web/tests/CloudAdminHostMultiMembershipServiceTest.php +++ b/web/tests/CloudAdminHostMultiMembershipServiceTest.php @@ -66,6 +66,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->integer('tested_revision'); $table->string('last_test_status'); $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); }); $schema->create('cloud_regions', static function (Blueprint $table): void { $table->increments('id'); @@ -166,6 +167,8 @@ $schema->create('cloud_public_ip_pools', $table->increments('id'); $table->integer('host_id'); $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->integer('max_allocations')->default(0); $table->string('state'); $table->string('sync_state'); $table->integer('observed_revision'); @@ -175,6 +178,7 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); $table->integer('public_ip_pool_id'); + $table->integer('address_family'); $table->string('state'); $table->integer('reservation_id')->nullable(); $table->integer('instance_id')->nullable(); @@ -194,6 +198,8 @@ Capsule::table('cloud_host_agents')->insert([ 'host_id' => 1, 'enabled' => 1, 'revision' => 1, 'tested_revision' => 1, 'last_test_status' => 'healthy', 'network_selectors_json' => '["bridge:line-a","bridge:line-b"]', + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', ]); Capsule::table('cloud_regions')->insert([ ['id' => 1, 'code' => 'hkg', 'name' => 'Hong Kong', @@ -228,8 +234,8 @@ Capsule::table('cloud_resource_pools')->insert([ Capsule::table('cloud_host_network_attachments')->insert([ ['id' => 1, 'host_id' => 1, 'line_id' => 10, 'state' => 'active', 'network_selector' => 'bridge:line-a', - 'sync_state' => 'applied', 'observed_revision' => 1, - 'desired_revision' => 1, 'verification_state' => 'verified', + 'sync_state' => 'never', 'observed_revision' => 0, + 'desired_revision' => 9, 'verification_state' => 'verified', 'verified_agent_revision' => 1, 'last_verified_at' => time()], ['id' => 2, 'host_id' => 1, 'line_id' => 11, 'state' => 'active', 'network_selector' => 'bridge:line-b', @@ -239,20 +245,33 @@ Capsule::table('cloud_host_network_attachments')->insert([ ]); Capsule::table('cloud_public_ip_pools')->insert([ ['id' => 1, 'host_id' => 1, 'network_attachment_id' => 1, + 'address_family' => 4, 'max_allocations' => 0, 'state' => 'active', 'sync_state' => 'applied', 'observed_revision' => 1, 'desired_revision' => 1], ['id' => 2, 'host_id' => 1, 'network_attachment_id' => 2, + 'address_family' => 4, 'max_allocations' => 0, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], + ['id' => 3, 'host_id' => 1, 'network_attachment_id' => 1, + 'address_family' => 6, 'max_allocations' => 100, + 'state' => 'active', 'sync_state' => 'applied', + 'observed_revision' => 1, 'desired_revision' => 1], + ['id' => 4, 'host_id' => 1, 'network_attachment_id' => 2, + 'address_family' => 6, 'max_allocations' => 100, 'state' => 'active', 'sync_state' => 'applied', 'observed_revision' => 1, 'desired_revision' => 1], ]); Capsule::table('cloud_public_ips')->insert([ ['id' => 1, 'host_id' => 1, 'public_ip_pool_id' => 1, + 'address_family' => 4, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ['id' => 2, 'host_id' => 1, 'public_ip_pool_id' => 2, + 'address_family' => 4, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ['id' => 3, 'host_id' => 1, 'public_ip_pool_id' => 2, + 'address_family' => 4, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null], ]); @@ -289,7 +308,32 @@ $assert(count($second['memberships']) === 2 && $poolA['ip_capacity']['available'] === 1 && $poolB['ip_capacity']['available'] === 2 && $second['capacity']['ip']['available'] === 3, - 'Read did not expose complete enriched same-region memberships and IP capacity.'); + 'Verified current Agent evidence did not make an otherwise unsynchronized attachment schedulable.'); + +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true}', +]); +$missingNdpGuard = CloudAdminHostSchedulingService::read(1); +$assert($membership($missingNdpGuard, 100)['ip_capacity']['available'] === 0 + && $membership($missingNdpGuard, 101)['ip_capacity']['available'] === 0, + 'Scheduling accepted public-network evidence without ndp_guard.'); +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', +]); + +Capsule::table('cloud_public_ip_pools')->where('id', 3)->update([ + 'state' => 'disabled', +]); +$missingIpv6Pair = CloudAdminHostSchedulingService::read(1); +$assert($membership($missingIpv6Pair, 100)['ip_capacity']['available'] === 0 + && $membership($missingIpv6Pair, 100)['placement_ready'] === false + && $membership($missingIpv6Pair, 101)['ip_capacity']['available'] === 2, + 'Scheduling accepted IPv4 capacity without its same-attachment IPv6 pool.'); +Capsule::table('cloud_public_ip_pools')->where('id', 3)->update([ + 'state' => 'active', +]); Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ 'revision' => 2, 'tested_revision' => 2, diff --git a/web/tests/CloudAdminHostNetworkServiceTest.php b/web/tests/CloudAdminHostNetworkServiceTest.php index 3bfd8985..c27fb6ba 100644 --- a/web/tests/CloudAdminHostNetworkServiceTest.php +++ b/web/tests/CloudAdminHostNetworkServiceTest.php @@ -56,10 +56,16 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_error_code'); $table->string('last_agent_version'); $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); $table->integer('last_tested_at'); $table->integer('created_at'); $table->integer('updated_at'); }); +$schema->create('cloud_public_ip_pool_catalog_mutex', + static function (Blueprint $table): void { + $table->integer('id')->primary(); + $table->integer('updated_at')->default(0); + }); $schema->create('cloud_network_lines', static function (Blueprint $table): void { $table->increments('id'); $table->string('name'); @@ -113,12 +119,18 @@ $schema->create('cloud_public_ip_pools', $table->string('pool_key'); $table->integer('host_id'); $table->integer('network_attachment_id'); + $table->integer('address_family'); $table->string('name'); $table->string('cidr'); $table->string('gateway'); + $table->boolean('gateway_on_link')->default(false); $table->integer('guest_prefix_length'); $table->text('dns_servers_json'); $table->text('reserved_ips_json'); + $table->string('allocation_start')->nullable(); + $table->string('allocation_end')->nullable(); + $table->string('allocation_cursor')->nullable(); + $table->integer('max_allocations')->default(0); $table->string('state'); $table->integer('priority'); $table->integer('desired_revision'); @@ -132,7 +144,9 @@ $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->increments('id'); $table->integer('host_id'); $table->integer('public_ip_pool_id'); - $table->string('address')->unique(); + $table->integer('address_family'); + $table->string('address'); + $table->binary('address_binary'); $table->integer('prefix_length'); $table->string('state'); $table->integer('reservation_id')->nullable()->unique(); @@ -177,6 +191,9 @@ $schema->create('cloud_public_ip_pool_replacement_batch_items', }); $now = time(); +Capsule::table('cloud_public_ip_pool_catalog_mutex')->insert([ + 'id' => 1, 'updated_at' => 0, +]); $hostId = Capsule::table('cloud_hosts')->insertGetId([ 'name' => 'Host 1', 'enabled' => 1, 'created_at' => $now, 'updated_at' => $now, @@ -206,6 +223,8 @@ Capsule::table('cloud_host_agents')->insert([ 'last_test_status' => 'healthy', 'last_error_code' => '', 'last_agent_version' => 'test', 'network_selectors_json' => json_encode($selectors, JSON_THROW_ON_ERROR), + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true,"ndp_guard":true}', 'last_tested_at' => $now, 'created_at' => $now, 'updated_at' => $now, ]); $selector = 'bridge:br0'; @@ -270,10 +289,14 @@ $foreignAttachmentId = Capsule::table( $poolKey = str_repeat('a', 32); $poolId = Capsule::table('cloud_public_ip_pools')->insertGetId([ 'pool_key' => $poolKey, 'host_id' => $hostId, - 'network_attachment_id' => $attachmentId, 'name' => 'Public pool', + 'network_attachment_id' => $attachmentId, 'address_family' => 4, + 'name' => 'Public pool', 'cidr' => '8.8.8.0/29', 'gateway' => '8.8.8.1', + 'gateway_on_link' => 0, 'guest_prefix_length' => 29, 'dns_servers_json' => '["1.1.1.1"]', - 'reserved_ips_json' => '[]', 'state' => 'active', 'priority' => 0, + 'reserved_ips_json' => '[]', 'allocation_start' => null, + 'allocation_end' => null, 'allocation_cursor' => null, + 'max_allocations' => 0, 'state' => 'active', 'priority' => 0, 'desired_revision' => 1, 'observed_revision' => 1, 'sync_state' => 'applied', 'last_error_code' => '', 'created_at' => $now, 'updated_at' => $now, @@ -281,14 +304,16 @@ $poolId = Capsule::table('cloud_public_ip_pools')->insertGetId([ Capsule::table('cloud_public_ips')->insert([ [ 'host_id' => $hostId, 'public_ip_pool_id' => $poolId, - 'address' => '8.8.8.2', 'prefix_length' => 29, + 'address_family' => 4, 'address' => '8.8.8.2', + 'address_binary' => inet_pton('8.8.8.2'), 'prefix_length' => 29, 'state' => 'assigned', 'reservation_id' => 41, 'instance_id' => 51, 'operation_id' => str_repeat('b', 32), 'created_at' => $now, 'updated_at' => $now, ], [ 'host_id' => $hostId, 'public_ip_pool_id' => $poolId, - 'address' => '8.8.8.3', 'prefix_length' => 29, + 'address_family' => 4, 'address' => '8.8.8.3', + 'address_binary' => inet_pton('8.8.8.3'), 'prefix_length' => 29, 'state' => 'available', 'reservation_id' => null, 'instance_id' => null, 'operation_id' => null, 'created_at' => $now, 'updated_at' => $now, @@ -307,9 +332,11 @@ $body = static fn ( string $state = 'active' ) => [ 'network_attachment_id' => $targetAttachmentId ?? $attachmentId, - 'name' => 'Public pool', 'cidr' => '8.8.8.0/29', + 'address_family' => 4, 'name' => 'Public pool', 'cidr' => '8.8.8.0/29', 'gateway' => '8.8.8.1', 'dns_servers' => [$dns], 'reserved_ips' => $reserved, 'guest_prefix_length' => 29, + 'gateway_on_link' => false, 'allocation_start' => null, + 'allocation_end' => null, 'max_allocations' => 0, 'state' => $state, 'expected_revision' => $revision, ]; $service = new CloudAdminHostNetworkService(); @@ -422,12 +449,17 @@ $expectCloudError( $createBody = [ 'network_attachment_id' => $attachmentBId, + 'address_family' => 4, 'name' => 'Second public pool', 'cidr' => '8.8.4.0/29', 'gateway' => '8.8.4.1', 'dns_servers' => ['1.0.0.1'], 'reserved_ips' => [], 'guest_prefix_length' => 29, + 'gateway_on_link' => false, + 'allocation_start' => null, + 'allocation_end' => null, + 'max_allocations' => 0, 'state' => 'active', 'request_key' => str_repeat('f', 32), ]; @@ -445,6 +477,192 @@ $assert($createdPool !== null && (string) $replayed['saved_pool_key'] === $createdPoolKey && CloudPublicIpPool::where('pool_key', $createdPoolKey)->count() === 1, 'Create/replay did not preserve one applied attachment-bound pool.'); + +Capsule::table('cloud_public_ip_pools')->insert([ + 'pool_key' => str_repeat('e', 32), 'host_id' => $foreignHostId, + 'network_attachment_id' => $foreignAttachmentId, 'address_family' => 4, + 'name' => 'Foreign public pool', 'cidr' => '9.9.8.0/29', + 'gateway' => '9.9.8.1', 'gateway_on_link' => 0, + 'guest_prefix_length' => 29, 'dns_servers_json' => '["1.1.1.1"]', + 'reserved_ips_json' => '[]', 'allocation_start' => null, + 'allocation_end' => null, 'allocation_cursor' => null, + 'max_allocations' => 0, 'state' => 'active', 'priority' => 0, + 'desired_revision' => 1, 'observed_revision' => 1, + 'sync_state' => 'applied', 'last_error_code' => '', + 'created_at' => $now, 'updated_at' => $now, +]); +$expectCloudError( + static fn () => $service->create( + $hostId, + $actor, + array_replace($createBody, [ + 'request_key' => str_repeat('d', 32), + 'cidr' => '9.9.8.0/29', + 'gateway' => '9.9.8.1', + ]) + ), + 409, + '地址段已被其他宿主机占用' +); + +$ipv6Body = [ + 'network_attachment_id' => $attachmentId, + 'address_family' => 6, + 'name' => 'Public IPv6 pool', + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + 'dns_servers' => ['2606:4700:4700::1111'], + 'reserved_ips' => ['2404:c140:156:3a::2'], + 'allocation_start' => '2404:c140:156:3a::1000', + 'allocation_end' => '2404:c140:156:3a::1fff', + 'max_allocations' => 100, + 'guest_prefix_length' => 64, + 'state' => 'active', + 'request_key' => str_repeat('6', 32), +]; +$ipv6Created = $service->create($hostId, $actor, $ipv6Body); +$ipv6Pool = CloudPublicIpPool::where( + 'pool_key', (string) $ipv6Created['saved_pool_key'] +)->first(); +$ipv6Item = array_values(array_filter( + $ipv6Created['items'], + static fn (array $item): bool => + (string) $item['pool_key'] === (string) $ipv6Created['saved_pool_key'] +))[0] ?? null; +$assert($ipv6Pool !== null + && (int) $ipv6Pool->address_family === 6 + && (bool) $ipv6Pool->gateway_on_link === true + && (string) $ipv6Pool->allocation_start === '2404:c140:156:3a::1000' + && (string) $ipv6Pool->allocation_end === '2404:c140:156:3a::1fff' + && (int) $ipv6Pool->max_allocations === 100 + && CloudPublicIp::where('public_ip_pool_id', (int) $ipv6Pool->id)->count() === 0 + && is_array($ipv6Item) + && (int) $ipv6Item['available_count'] === 100 + && $ipv6Item['dual_stack_ready'] === true + && $ipv6Item['attachment']['dual_stack_ready'] === true, + 'IPv6 /64 was materialized or its bounded sparse capacity was not exposed.'); + +$blockedRangeBody = array_replace($ipv6Body, [ + 'name' => 'Blocked sparse range', + 'cidr' => '2404:c140:156:3b::/120', + 'gateway' => '2404:c140:156:3b::10', + 'dns_servers' => [ + '2404:c140:156:3b::10', + '2404:c140:156:3b:0:0:0:10', + ], + 'reserved_ips' => ['2404:c140:156:3b::10'], + 'allocation_start' => '2404:c140:156:3b::10', + 'allocation_end' => '2404:c140:156:3b::13', + 'max_allocations' => 4, + 'guest_prefix_length' => 120, + 'request_key' => str_repeat('b', 32), +]); +$expectCloudError( + static fn () => $service->create($hostId, $actor, $blockedRangeBody), + 422, + '扣除网关、DNS 和保留地址后小于最大分配数量' +); +$deduplicatedBlockers = $service->create( + $hostId, + $actor, + array_replace($blockedRangeBody, ['max_allocations' => 3]) +); +$deduplicatedPool = CloudPublicIpPool::where( + 'pool_key', (string) $deduplicatedBlockers['saved_pool_key'] +)->first(); +$assert($deduplicatedPool !== null + && (int) $deduplicatedPool->max_allocations === 3, + 'The same blocked IPv6 address was deducted more than once across lists.'); + +$outsideRange = $service->create($hostId, $actor, array_replace( + $blockedRangeBody, + [ + 'name' => 'External gateway and DNS', + 'cidr' => '2404:c140:156:3c::/120', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + 'dns_servers' => ['1.1.1.1'], + 'reserved_ips' => ['2404:c140:156:3c::20'], + 'allocation_start' => '2404:c140:156:3c::10', + 'allocation_end' => '2404:c140:156:3c::13', + 'max_allocations' => 4, + 'request_key' => str_repeat('c', 32), + ] +)); +$outsideRangePool = CloudPublicIpPool::where( + 'pool_key', (string) $outsideRange['saved_pool_key'] +)->first(); +$assert($outsideRangePool !== null + && (int) $outsideRangePool->max_allocations === 4, + 'An off-prefix gateway, other-family DNS or out-of-range reservation reduced sparse capacity.'); +Capsule::table('cloud_public_ips')->insert([ + [ + 'host_id' => $hostId, 'public_ip_pool_id' => (int) $ipv6Pool->id, + 'address_family' => 6, 'address' => '2404:c140:156:3a::1000', + 'address_binary' => inet_pton('2404:c140:156:3a::1000'), + 'prefix_length' => 64, 'state' => 'reserved', + 'reservation_id' => 61, 'instance_id' => null, + 'operation_id' => str_repeat('7', 32), + 'created_at' => $now, 'updated_at' => $now, + ], + [ + 'host_id' => $hostId, 'public_ip_pool_id' => (int) $ipv6Pool->id, + 'address_family' => 6, 'address' => '2404:c140:156:3a::1001', + 'address_binary' => inet_pton('2404:c140:156:3a::1001'), + 'prefix_length' => 64, 'state' => 'changing', + 'reservation_id' => 62, 'instance_id' => 62, + 'operation_id' => str_repeat('8', 32), + 'created_at' => $now, 'updated_at' => $now, + ], + [ + 'host_id' => $hostId, 'public_ip_pool_id' => (int) $ipv6Pool->id, + 'address_family' => 6, 'address' => '2404:c140:156:3a::1002', + 'address_binary' => inet_pton('2404:c140:156:3a::1002'), + 'prefix_length' => 64, 'state' => 'uncertain', + 'reservation_id' => 63, 'instance_id' => null, + 'operation_id' => str_repeat('9', 32), + 'created_at' => $now, 'updated_at' => $now, + ], + [ + 'host_id' => $hostId, 'public_ip_pool_id' => (int) $ipv6Pool->id, + 'address_family' => 6, 'address' => '2404:c140:156:3a::1003', + 'address_binary' => inet_pton('2404:c140:156:3a::1003'), + 'prefix_length' => 64, 'state' => 'available', + 'reservation_id' => null, 'instance_id' => null, + 'operation_id' => str_repeat('a', 32), + 'created_at' => $now, 'updated_at' => $now, + ], +]); +$occupiedIpv6Read = $service->read($hostId, $actor); +$occupiedIpv6Item = array_values(array_filter( + $occupiedIpv6Read['items'], + static fn (array $item): bool => + (string) $item['pool_key'] === (string) $ipv6Created['saved_pool_key'] +))[0] ?? null; +$assert(is_array($occupiedIpv6Item) + && (int) $occupiedIpv6Item['occupied_count'] === 4 + && (int) $occupiedIpv6Item['available_count'] === 96, + 'IPv6 sparse capacity did not deduct every occupied state or pointer.'); +$expectCloudError( + static fn () => $service->update( + $hostId, + (string) $ipv6Created['saved_pool_key'], + $actor, + array_replace($ipv6Body, [ + 'reserved_ips' => [ + '2404:c140:156:3a::2', + '2404:c140:156:3a::1000', + '2404:c140:156:3a::1001', + '2404:c140:156:3a::1002', + '2404:c140:156:3a::1003', + ], + 'expected_revision' => 1, + ]) + ), + 409, + '已分配或任务占用的公网 IP 不能加入保留 / 禁用列表' +); $expectCloudError( static fn () => $service->create( $hostId, @@ -472,6 +690,28 @@ $assert((int) $createdPool->network_attachment_id === $attachmentId && (int) $createdPool->desired_revision === 2 && (int) $switched['items'][1]['attachment']['id'] === $attachmentId, 'An unoccupied pool could not switch its explicit attachment.'); +$expectCloudError( + static fn () => $service->update( + $hostId, + $createdPoolKey, + $actor, + array_replace($ipv6Body, [ + 'name' => 'Converted IPv6 pool', + 'cidr' => '2404:c140:156:3b::/64', + 'reserved_ips' => ['2404:c140:156:3b::2'], + 'allocation_start' => '2404:c140:156:3b::1000', + 'allocation_end' => '2404:c140:156:3b::1fff', + 'expected_revision' => 2, + ]) + ), + 409, + '地址族创建后不能修改' +); +$createdPool->refresh(); +$assert((int) $createdPool->address_family === 4 + && CloudPublicIp::where('public_ip_pool_id', (int) $createdPool->id) + ->where('address_family', 4)->count() > 0, + 'Rejecting an address-family change damaged the concrete ledger.'); Capsule::table('cloud_public_ip_pools')->where('id', $createdPool->id) ->update(['network_attachment_id' => 999999]); $missingRead = $service->read($hostId, $actor); @@ -588,4 +828,30 @@ $assert(is_array($historyItem) && $historyItem['has_replacement_history'] === true, 'Terminal replacement history was not exposed on the pool DTO.'); +Capsule::table('cloud_host_agents')->where('host_id', $hostId)->update([ + 'public_network_capabilities_json' => + '{"contract":1,"dual_stack_required":true,"project_owned_filter":true}', +]); +$missingNdpCapability = $service->read($hostId, $actor); +$assert(count(array_filter( + $missingNdpCapability['attachments'], + static fn (array $attachment): bool => $attachment['ready'] === true + )) === 0, + 'Administrator pool attachments remained ready without ndp_guard.'); + +Capsule::table('cloud_public_ip_pool_catalog_mutex')->delete(); +$expectCloudError( + static fn () => $service->create( + $hostId, + $actor, + array_replace($createBody, [ + 'request_key' => str_repeat('5', 32), + 'cidr' => '9.9.10.0/29', + 'gateway' => '9.9.10.1', + ]) + ), + 503, + '公网地址池全局目录锁未初始化' +); + echo "Public pools bind explicit, verified host attachments safely.\n"; diff --git a/web/tests/CloudAgentActivationGateTest.php b/web/tests/CloudAgentActivationGateTest.php index 819fd40f..63e2cdd3 100644 --- a/web/tests/CloudAgentActivationGateTest.php +++ b/web/tests/CloudAgentActivationGateTest.php @@ -60,6 +60,7 @@ $schema->create('cloud_host_agents', static function (Blueprint $table): void { $table->string('last_error_code')->default(''); $table->string('last_agent_version')->default(''); $table->text('network_selectors_json')->default('[]'); + $table->text('public_network_capabilities_json')->default('{}'); $table->integer('last_tested_at')->default(0); $table->integer('created_at'); $table->integer('updated_at'); @@ -107,8 +108,14 @@ Capsule::table('cloud_host_storage_configurations')->insert([ $recordTest = new ReflectionMethod(CloudAgentSettingsService::class, 'recordTest'); +$publicNetwork = [ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, +]; $recordTest->invoke(null, (int) $host->id, 1, 'healthy', '', 'test-1', - ['bridge:br0']); + ['bridge:br0'], $publicNetwork); $ready = CloudAgentSettingsService::read((int) $host->id); $assert($ready['ready'] === true && $ready['tested_revision'] === 1 && (string) CloudHostAgent::find((int) $host->id) @@ -156,7 +163,7 @@ $assert($rotated['revision'] === 2 && CloudAgentSettingsService::enabledHostIds() === [], 'Rotating an Agent secret retained the prior readiness result.'); $recordTest->invoke(null, (int) $host->id, 2, 'healthy', '', 'test-2', - ['bridge:br0']); + ['bridge:br0'], $publicNetwork); $changed = CloudAgentSettingsService::save((int) $host->id, [ 'enabled' => false, @@ -171,7 +178,7 @@ $assert($changed['revision'] === 3 && $changed['enabled'] === false 'Changing an Agent setting retained the prior revision readiness.'); $recordTest->invoke(null, (int) $host->id, 3, 'healthy', '', 'test-3', - ['bridge:br0']); + ['bridge:br0'], $publicNetwork); $recordTest->invoke(null, (int) $host->id, 3, 'unhealthy', 'agent_unavailable', ''); $failed = CloudHostAgent::find((int) $host->id); @@ -209,7 +216,7 @@ foreach (['bridge:br9', 'network:default'] as $network) { $setting->enabled = true; $setting->save(); $recordTest->invoke(null, (int) $host->id, $revision, 'healthy', '', - 'test-current', [$network]); + 'test-current', [$network], $publicNetwork); $saveHostNetwork($network); $setting->refresh(); $assert($host->fresh()->default_network === $network diff --git a/web/tests/CloudAgentPanelContractTest.php b/web/tests/CloudAgentPanelContractTest.php index 5169313e..7b904800 100644 --- a/web/tests/CloudAgentPanelContractTest.php +++ b/web/tests/CloudAgentPanelContractTest.php @@ -32,6 +32,8 @@ $assert(str_contains($schema, 'CREATE TABLE cloud_host_agents') && str_contains($schema, 'revision BIGINT UNSIGNED NOT NULL DEFAULT 1') && str_contains($schema, 'tested_revision BIGINT UNSIGNED NOT NULL DEFAULT 0') && str_contains($schema, 'network_selectors_json LONGTEXT NOT NULL') + && str_contains($schema, + 'public_network_capabilities_json LONGTEXT NOT NULL') && str_contains($schema, 'CREATE TABLE cloud_templates') && str_contains($schema, 'startup_script MEDIUMTEXT NOT NULL') && str_contains($schema, 'generation_token CHAR(32)') @@ -82,6 +84,13 @@ $assert(str_contains($cipher, "CloudSecrets::key('host-agent-secret')") $assert(str_contains($service, '$setting->tested_revision = 0') && str_contains($service, "'tested_revision' => \$status === 'healthy'") && str_contains($service, "'network_selectors_json' => \$encodedSelectors") + && str_contains($service, + "'public_network_capabilities_json' => \$encodedPublicNetwork") + && str_contains($service, 'public static function publicNetworkReady(') + && str_contains($service, 'private const PUBLIC_NETWORK_CONTRACT = 1;') + && str_contains($service, "'dual_stack_required' => true") + && str_contains($service, "'project_owned_filter' => true") + && str_contains($service, "'ndp_guard' => true") && str_contains($service, 'if (!$setting->isReady())') && str_contains($service, "'agent_not_tested'") && str_contains($service, "'ready' => \$ready") diff --git a/web/tests/CloudAgentPublicNetworkCapabilityTest.php b/web/tests/CloudAgentPublicNetworkCapabilityTest.php new file mode 100644 index 00000000..17e75e13 --- /dev/null +++ b/web/tests/CloudAgentPublicNetworkCapabilityTest.php @@ -0,0 +1,162 @@ +agentCode === 'agent_capability_mismatch' + || $error->agentCode === 'agent_invalid_capabilities', + 'Unexpected public-network capability error: ' . $error->agentCode); + return; + } + throw new RuntimeException($message); +}; + +$capsule = new Capsule(); +$capsule->addConnection([ + 'driver' => 'sqlite', 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); +$schema->create('cloud_host_agents', static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + $table->text('sealed_api_secret'); + $table->boolean('enabled'); + $table->integer('revision'); + $table->integer('tested_revision'); + $table->string('last_test_status'); + $table->string('last_error_code'); + $table->string('last_agent_version'); + $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); + $table->integer('last_tested_at'); + $table->integer('created_at'); + $table->integer('updated_at'); +}); + +$features = array_fill_keys([ + 'create_vm', 'delete_vm', 'power', 'resources', 'settings', 'network', + 'reinstall', 'snapshots', 'backups', 'firewall', 'rescue', 'metrics', + 'console', 'templates', 'user_iso', +], true); +$features['uefi'] = true; +$features['secure_boot'] = false; +$publicNetwork = [ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, +]; +$capabilities = [ + 'backend' => 'libvirt', + 'features' => $features, + 'network_selectors' => ['bridge:br0'], + 'public_network' => $publicNetwork + ['untrusted_extension' => true], + 'checks' => ['storage_configuration' => ['available' => true]], +]; +$summaryMethod = new ReflectionMethod( + CloudAgentSettingsService::class, + 'capabilitySummary' +); +$summary = $summaryMethod->invoke(null, $capabilities); +$assert(($summary['public_network'] ?? null) === $publicNetwork, + 'A valid public-network contract was not normalized into health evidence.'); +foreach (array_keys($publicNetwork) as $field) { + $broken = $capabilities; + unset($broken['public_network'][$field]); + $rejects( + static fn () => $summaryMethod->invoke(null, $broken), + 'A public-network capability with a missing field was accepted: ' . $field + ); +} +foreach (['dual_stack_required', 'project_owned_filter', 'ndp_guard'] as $field) { + $broken = $capabilities; + $broken['public_network'][$field] = false; + $rejects( + static fn () => $summaryMethod->invoke(null, $broken), + 'A false public-network safety capability was accepted: ' . $field + ); +} + +$now = time(); +Capsule::table('cloud_host_agents')->insert([ + 'host_id' => 1, 'sealed_api_secret' => 'sealed', 'enabled' => 1, + 'revision' => 4, 'tested_revision' => 0, + 'last_test_status' => 'never', 'last_error_code' => '', + 'last_agent_version' => '', 'network_selectors_json' => '[]', + 'public_network_capabilities_json' => '{}', 'last_tested_at' => 0, + 'created_at' => $now, 'updated_at' => $now, +]); +$recordTest = new ReflectionMethod(CloudAgentSettingsService::class, 'recordTest'); +$recordTest->invoke( + null, + 1, + 4, + 'healthy', + '', + 'test-agent', + ['bridge:br0'], + $publicNetwork +); +$agent = CloudHostAgent::find(1); +$assert($agent !== null + && json_decode( + (string) $agent->public_network_capabilities_json, + true, + 8, + JSON_THROW_ON_ERROR + ) === $publicNetwork + && CloudAgentSettingsService::publicNetworkReady( + $agent, 'bridge:br0', 4 + ) + && !CloudAgentSettingsService::publicNetworkReady( + $agent, 'bridge:br1', 4 + ) + && !CloudAgentSettingsService::publicNetworkReady( + $agent, 'bridge:br0', 3 + ), + 'Public-network readiness did not bind capability, selector and revision.'); + +$agent->public_network_capabilities_json = json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, +], JSON_THROW_ON_ERROR); +$agent->save(); +$agent->refresh(); +$assert(!CloudAgentSettingsService::publicNetworkReady( + $agent, 'bridge:br0', 4 + ), + 'Legacy capability evidence without ndp_guard remained ready.'); + +CloudAgentSettingsService::invalidateReadiness($agent); +$agent->refresh(); +$assert((string) $agent->public_network_capabilities_json === '{}' + && !CloudAgentSettingsService::publicNetworkReady( + $agent, 'bridge:br0', 5 + ), + 'Readiness invalidation retained prior public-network evidence.'); + +echo "Agent public-network capability gate passed.\n"; diff --git a/web/tests/CloudDualStackPublicNetworkSchemaTest.php b/web/tests/CloudDualStackPublicNetworkSchemaTest.php index f00b79d7..f366cd14 100644 --- a/web/tests/CloudDualStackPublicNetworkSchemaTest.php +++ b/web/tests/CloudDualStackPublicNetworkSchemaTest.php @@ -26,6 +26,16 @@ $table = static function (string $name) use ($schema): string { $pools = $table('cloud_public_ip_pools'); $ips = $table('cloud_public_ips'); $claims = $table('cloud_resource_reservation_ips'); +$catalogMutex = $table('cloud_public_ip_pool_catalog_mutex'); + +$assert($catalogMutex !== '' + && str_contains($catalogMutex, + 'id TINYINT UNSIGNED NOT NULL PRIMARY KEY') + && str_contains($catalogMutex, + 'CONSTRAINT chk_cloud_public_ip_pool_catalog_mutex CHECK (id = 1)') + && str_contains($schema, + 'INSERT IGNORE INTO cloud_public_ip_pool_catalog_mutex'), + 'Public-pool overlap checks lack a persistent singleton catalog mutex.'); $assert($pools !== '' && str_contains($pools, 'address_family TINYINT UNSIGNED NOT NULL') @@ -85,6 +95,10 @@ $ipModel = file_get_contents($root . '/app/Models/CloudPublicIp.php'); $claimModelPath = $root . '/app/Models/CloudResourceReservationIp.php'; $claimModel = is_file($claimModelPath) ? file_get_contents($claimModelPath) : false; +$setup = file_get_contents($root . '/app/Command/CloudSetup.php'); +$mutexModel = file_get_contents( + $root . '/app/Models/CloudPublicIpPoolCatalogMutex.php' +); $assert(is_string($poolModel) && str_contains($poolModel, "'address_family' => 'int'") && str_contains($poolModel, "'gateway_on_link' => 'bool'") @@ -98,5 +112,23 @@ $assert(is_string($claimModel) "protected \$table = 'cloud_resource_reservation_ips';") && str_contains($claimModel, "'address_family' => 'int'"), 'Reservation address-claim model is missing.'); +$assert(is_string($mutexModel) + && str_contains($mutexModel, + "protected \$table = 'cloud_public_ip_pool_catalog_mutex';"), + 'Public-pool catalog mutex model is missing.'); +$assert(is_string($setup) + && str_contains($setup, "'cloud_public_ip_pool_catalog_mutex'") + && str_contains($setup, "'cloud_resource_reservation_ips'") + && str_contains($setup, "'cloud_public_ip_pools' => [") + && str_contains($setup, "'address_family', 'name', 'cidr', 'gateway'") + && str_contains($setup, "'allocation_start', 'allocation_end'") + && str_contains($setup, "'cloud_public_ips' => [") + && str_contains($setup, "'address_binary', 'prefix_length'") + && str_contains($setup, "'cloud_resource_reservation_ips' => [") + && str_contains($setup, "'chk_cloud_reservation_ip_release'") + && str_contains($setup, "'cloud_reservation_ip_family'") + && str_contains($setup, "'cloud_public_ip_pool_attachment'") + && str_contains($setup, "'cloud_public_ip_address'"), + 'Cloud setup does not refuse an incomplete dual-stack schema.'); echo "Dual-stack public-network schema tests passed.\n"; diff --git a/web/tests/CloudSpecialTaskSingleDispatchTest.php b/web/tests/CloudSpecialTaskSingleDispatchTest.php index 8733e38a..7c2b70bb 100644 --- a/web/tests/CloudSpecialTaskSingleDispatchTest.php +++ b/web/tests/CloudSpecialTaskSingleDispatchTest.php @@ -100,10 +100,12 @@ $assert(str_contains($schema, 'parent_job_id BIGINT UNSIGNED DEFAULT NULL') 'Fresh schema lacks aggregate/child or single-dispatch links.'); $assert(str_contains($hostNetwork, - 'CloudAgentSettingsService::testedNetworkSelectors($agent)') + 'CloudAgentSettingsService::publicNetworkReady(') && !str_contains($hostNetwork, '->request(') && !str_contains($hostNetwork, 'markOutcome(') && str_contains($hostNetwork, '->transaction(') + && str_contains($hostNetwork, + 'CloudPublicIpPoolCatalogMutex::where(') && str_contains($hostNetwork, "->sync_state = 'applied'"), 'Host-network configuration is not a single local transaction.');