From c0ee66f369ba00023c6ea84fb37b02a467cf62c2 Mon Sep 17 00:00:00 2001 From: codex Date: Tue, 3 Nov 2026 15:13:47 +0800 Subject: [PATCH] feat: provision dual-stack public networks --- web/app/Models/CloudResourceReservation.php | 21 +- .../CloudInstanceMigrationSettlement.php | 96 ++ .../Services/Cloud/CloudInvoiceService.php | 9 +- .../Cloud/CloudOperationRecoveryIdentity.php | 61 +- web/app/Services/Cloud/CloudOrderService.php | 36 +- .../Cloud/CloudPlacementNetworkService.php | 229 ++++- .../Services/Cloud/CloudPlacementService.php | 544 +++++++---- .../CloudPublicNetworkAllocationService.php | 424 +++++++-- .../CloudPublicNetworkCapacityUnavailable.php | 14 + web/app/Services/Cloud/CloudWorkerService.php | 103 +-- .../AdminResourceSchedulingContractTest.php | 15 +- ...CloudAdminOperationRecoveryServiceTest.php | 79 +- web/tests/CloudAgentMutationIdentityTest.php | 83 +- .../CloudDefaultNetworkNonAuthorityTest.php | 7 +- .../CloudDualStackPlacementAdvisoryTest.php | 251 +++++ web/tests/CloudFinancialWorkflowTest.php | 864 +++++++++++++----- web/tests/CloudMailOutboxDispatchTest.php | 33 +- .../CloudNetworkIpLedgerContractTest.php | 14 +- .../CloudOperationRecoveryMatrixTest.php | 90 +- ...dProvisioningPublicNetworkContractTest.php | 121 +++ ...oudProvisioningPublicNetworkLedgerTest.php | 379 ++++++++ ...loudPublicNetworkAllocationServiceTest.php | 739 ++++++++++++++- ...CloudUndispatchedFinalizerRecoveryTest.php | 193 +++- 23 files changed, 3720 insertions(+), 685 deletions(-) create mode 100644 web/app/Services/Cloud/CloudPublicNetworkCapacityUnavailable.php create mode 100644 web/tests/CloudDualStackPlacementAdvisoryTest.php create mode 100644 web/tests/CloudProvisioningPublicNetworkContractTest.php create mode 100644 web/tests/CloudProvisioningPublicNetworkLedgerTest.php diff --git a/web/app/Models/CloudResourceReservation.php b/web/app/Models/CloudResourceReservation.php index 740bf207..9fc2b324 100644 --- a/web/app/Models/CloudResourceReservation.php +++ b/web/app/Models/CloudResourceReservation.php @@ -28,7 +28,10 @@ final class CloudResourceReservation extends Model 'updated_at' => 'int', ]; - /** Every reservation carries a complete immutable network allocation. */ + /** + * Address ownership lives in cloud_resource_reservation_ips. The legacy + * singular columns remain schema-only until the final clean-break cleanup. + */ public function save(array $options = []) { if (!$this->exists) { @@ -41,15 +44,15 @@ final class CloudResourceReservation extends Model 'New reservations require exactly one order or backup restore source.' ); } - foreach (['network_attachment_id', 'public_ip_pool_id', - 'public_ip_id'] as $field) { - if ((int) ($this->{$field} ?? 0) < 1) { - throw new \LogicException( - 'New reservations require complete network allocation references.' - ); - } - } } return parent::save($options); } + + public function publicIpClaims() + { + return $this->hasMany( + CloudResourceReservationIp::class, + 'reservation_id' + ); + } } diff --git a/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php b/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php index e374ff73..53a9b7bb 100644 --- a/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php +++ b/web/app/Services/Cloud/CloudInstanceMigrationSettlement.php @@ -16,6 +16,102 @@ use App\Models\CloudResourceReservation; */ final class CloudInstanceMigrationSettlement { + /** + * Lock the exact maintenance-migration evidence that accounts for a + * stopped source duplicate on one host. + * + * The caller already owns the host and public-pool locks. Migration rows + * are locked before their restore reservations, matching every migration + * finalizer before the allocator later locks concrete IP rows. + * + * @param list $candidatePoolIds + * @return array + */ + public static function lockRetainedSourcePublicIpEvidence( + int $hostId, + array $candidatePoolIds + ): array { + $candidatePoolIds = array_values(array_unique(array_map( + static fn ($id): int => (int) $id, + $candidatePoolIds + ))); + sort($candidatePoolIds, SORT_NUMERIC); + if ($hostId < 1 || $candidatePoolIds === [] + || $candidatePoolIds[0] < 1) { + throw new CloudError('保留源副本公网账本范围无效', 409); + } + + $migrations = CloudInstanceMigration::where('source_host_id', $hostId) + ->whereIn('state', ['source_retained', 'cleanup_running']) + ->orderBy('id')->lockForUpdate()->get(); + if ($migrations->isEmpty()) { + return []; + } + $reservationIds = $migrations->pluck('source_reservation_id')->map( + static fn ($id): int => (int) $id + )->unique()->sort()->values()->all(); + if ($reservationIds === [] || $reservationIds[0] < 1) { + throw new CloudError('保留源副本缺少资源预留证据', 409); + } + $reservations = CloudResourceReservation::whereIn('id', $reservationIds) + ->orderBy('id')->lockForUpdate()->get()->keyBy('id'); + if ($reservations->count() !== count($reservationIds)) { + throw new CloudError('保留源副本资源预留证据不完整', 409); + } + + $candidatePools = array_fill_keys($candidatePoolIds, true); + $evidence = []; + foreach ($migrations as $migration) { + $reservationId = (int) $migration->source_reservation_id; + $reservation = $reservations->get($reservationId); + $operationId = (string) ($reservation?->operation_id ?? ''); + if (!$reservation instanceof CloudResourceReservation + || (int) $migration->instance_id < 1 + || (int) $migration->restore_id < 1 + || (int) $migration->source_host_id !== $hostId + || (int) $migration->target_host_id < 1 + || (int) $migration->target_reservation_id < 1 + || (int) $reservation->host_id !== $hostId + || (int) ($reservation->backup_restore_id ?? 0) + !== (int) $migration->restore_id + || $reservation->order_id !== null + || (string) $reservation->state !== 'committed' + || $reservation->instance_id !== null + || (int) ($reservation->network_attachment_id ?? 0) < 1 + || (int) ($reservation->public_ip_pool_id ?? 0) < 1 + || (int) ($reservation->public_ip_id ?? 0) < 1 + || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) { + throw new CloudError( + '保留源副本迁移与资源预留证据不一致', + 409 + ); + } + $poolId = (int) $reservation->public_ip_pool_id; + if (!isset($candidatePools[$poolId])) { + continue; + } + $publicIpId = (int) $reservation->public_ip_id; + if (isset($evidence[$publicIpId])) { + throw new CloudError('保留源副本公网地址证据重复', 409); + } + $evidence[$publicIpId] = [ + 'migration_id' => (int) $migration->id, + 'migration_state' => (string) $migration->state, + 'reservation_id' => $reservationId, + 'host_id' => (int) $reservation->host_id, + 'network_attachment_id' => + (int) $reservation->network_attachment_id, + 'public_ip_pool_id' => $poolId, + 'public_ip_id' => $publicIpId, + 'operation_id' => $operationId, + ]; + } + ksort($evidence, SORT_NUMERIC); + return $evidence; + } + /** * Make the order-linked reservation authoritative on the target while a * separate restore reservation accounts for the stopped source duplicate. diff --git a/web/app/Services/Cloud/CloudInvoiceService.php b/web/app/Services/Cloud/CloudInvoiceService.php index 88a90915..363f802a 100644 --- a/web/app/Services/Cloud/CloudInvoiceService.php +++ b/web/app/Services/Cloud/CloudInvoiceService.php @@ -657,8 +657,13 @@ final class CloudInvoiceService } else { $spec = json_decode((string) $instance->spec_json, true); $spec = is_array($spec) && !array_is_list($spec) ? $spec : []; - $cidr = is_string($spec['public_ip_cidr'] ?? null) - ? trim($spec['public_ip_cidr']) : ''; + try { + $cidr = CloudPublicNetworkSnapshot::fromArray( + $spec['public_network'] ?? null + )->address(4); + } catch (\InvalidArgumentException) { + $cidr = ''; + } $ip = explode('/', $cidr, 2)[0]; if (filter_var($ip, FILTER_VALIDATE_IP) === false) { $ip = '—'; diff --git a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php index a7246c42..0340ceee 100644 --- a/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php +++ b/web/app/Services/Cloud/CloudOperationRecoveryIdentity.php @@ -860,13 +860,31 @@ final class CloudOperationRecoveryIdentity self::expectRequest($method, $target, 'POST', '/v1/vms'); self::assertAllowedBody($body, [ 'operation_id', 'uuid', 'source', 'name', 'description', 'vcpu', - 'memory_mib', 'disk_gib', 'bandwidth_mbps', 'network', + 'memory_mib', 'disk_gib', 'bandwidth_mbps', 'public_network', 'template_id', 'template_revision', 'template_generation_token', 'startup_script', 'hostname', 'guest_ssh_public_key', - 'root_password', 'public_pool_key', 'public_pool_cidr', - 'public_ip_cidr', 'gateway', 'dns_servers', + 'root_password', 'platform_network_policy_snapshot', ]); + $order = $job->order_id === null ? null + : CloudOrder::find((int) $job->order_id); + $orderSpec = $order === null ? null + : json_decode((string) $order->spec_json, true); + $reservation = $order === null || $order->reservation_id === null + ? null : CloudResourceReservation::find( + (int) $order->reservation_id + ); + try { + $frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray( + is_array($orderSpec) + ? ($orderSpec['public_network'] ?? null) : null + ); + $requestedPublicNetwork = CloudPublicNetworkSnapshot::fromArray( + $body['public_network'] ?? null + ); + } catch (\InvalidArgumentException) { + self::invalidPayload('创建实例的双栈公网快照无效'); + } $resourceId = self::operationUuid((string) $job->operation_id); $requestedUuid = $body['uuid'] ?? null; $integers = ['vcpu', 'memory_mib', 'disk_gib', 'bandwidth_mbps', @@ -892,17 +910,6 @@ final class CloudOperationRecoveryIdentity || !is_string($body['template_generation_token'] ?? null) || preg_match(self::CATALOG_ID_PATTERN, $body['template_generation_token']) !== 1 - || !is_string($body['network'] ?? null) - || trim($body['network']) === '' - || !is_string($body['public_pool_key'] ?? null) - || preg_match(self::CATALOG_ID_PATTERN, - $body['public_pool_key']) !== 1 - || !is_string($body['public_pool_cidr'] ?? null) - || !is_string($body['public_ip_cidr'] ?? null) - || !is_string($body['gateway'] ?? null) - || !is_array($body['dns_servers'] ?? null) - || !array_is_list($body['dns_servers']) - || $body['dns_servers'] === [] || !is_array($body['platform_network_policy_snapshot'] ?? null) || array_is_list($body['platform_network_policy_snapshot']) || ($requestedUuid !== null @@ -910,8 +917,30 @@ final class CloudOperationRecoveryIdentity || !hash_equals($resourceId, strtolower($requestedUuid)))) || (int) $job->user_id < 1 - || $job->order_id === null - || (int) $job->order_id < 1 + || $order === null || !is_array($orderSpec) + || array_is_list($orderSpec) + || ($orderSpec['source'] ?? null) !== 'cloud' + || (int) $order->user_id !== (int) $job->user_id + || (int) ($order->host_id ?? 0) !== (int) $job->host_id + || $reservation === null + || (int) $reservation->id !== (int) $order->reservation_id + || (int) ($reservation->order_id ?? 0) !== (int) $order->id + || (int) ($reservation->user_id ?? 0) !== (int) $order->user_id + || (int) ($reservation->host_id ?? 0) !== (int) $job->host_id + || (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id + || (int) ($reservation->resource_pool_id ?? 0) + !== (int) $order->resource_pool_id + || (int) ($reservation->backup_restore_id ?? 0) !== 0 + || !hash_equals( + (string) $job->operation_id, + (string) ($reservation->operation_id ?? '') + ) + || !in_array((string) $reservation->state, + ['held', 'uncertain', 'committed'], true) + || !hash_equals( + $frozenPublicNetwork->fingerprint(), + $requestedPublicNetwork->fingerprint() + ) || array_key_exists('owner_id', $payload)) { self::invalidPayload('创建实例请求与任务账本不匹配'); } diff --git a/web/app/Services/Cloud/CloudOrderService.php b/web/app/Services/Cloud/CloudOrderService.php index 3d73081b..f9928c12 100644 --- a/web/app/Services/Cloud/CloudOrderService.php +++ b/web/app/Services/Cloud/CloudOrderService.php @@ -51,6 +51,16 @@ final class CloudOrderService if (!in_array($source, ['cloud', 'deployment_snapshot'], true)) { throw new CloudError('实例来源无效'); } + // The C7 provisioning contract is dual-stack end to end. Backup and + // cloud-snapshot restores keep their legacy identity contract until + // C11, so reject them before creating an order or invoice rather than + // accepting payment for work that cannot be recovered safely. + if ($source === 'deployment_snapshot') { + throw new CloudError( + '云快照创建实例正在升级双栈网络,暂不可用', + 503 + ); + } $template = ''; $snapshotKey = null; if ($source === 'cloud') { @@ -152,7 +162,7 @@ final class CloudOrderService $payload = ['source' => $source === 'cloud' ? 'cloud' : '', 'name' => $name, 'vcpu' => (int) $plan->cpu_cores, 'memory_mib' => (int) $plan->memory_mib, 'disk_gib' => (int) $plan->disk_gib, - 'bandwidth_mbps' => (int) $plan->bandwidth_mbps, 'network' => '']; + 'bandwidth_mbps' => (int) $plan->bandwidth_mbps]; $credential = null; if ($source === 'cloud') { $key = CloudSSHKeys::owned( @@ -166,9 +176,6 @@ final class CloudOrderService 'template_id' => $template, 'guest_ssh_public_key' => $key?->public_key ?? '', 'root_password' => $password, - 'public_pool_key' => '', 'public_pool_cidr' => '', - 'public_ip_cidr' => '', 'gateway' => '', - 'dns_servers' => [], ]; $credential = [ 'password' => $password, @@ -186,9 +193,6 @@ final class CloudOrderService 'hostname' => CloudInput::hostname($name), 'guest_ssh_public_key' => '', 'root_password' => '', - 'public_pool_key' => '', 'public_pool_cidr' => '', - 'public_ip_cidr' => '', 'gateway' => '', - 'dns_servers' => [], 'debian_12_network_fix' => $backupSpec['debian_12_network_fix'], 'backup_key' => (string) $sourceBackup->backup_key, @@ -505,6 +509,16 @@ final class CloudOrderService CloudPlatformTestNetworkPolicy::snapshotForProvisioning(); $payload['body']['platform_network_policy_snapshot'] = $platformPolicy; $source = $orderSpec['source'] ?? null; + // Also fence orders created before this deployment. The surrounding + // payment transaction will roll back, so no wallet debit or provider + // payment can produce an order that the current recovery contract + // cannot reconcile safely. + if ($source === 'deployment_snapshot') { + throw new CloudError( + '云快照创建实例正在升级双栈网络,暂不可用', + 503 + ); + } $sourceBackup = null; if ($source === 'cloud') { if ($order->deployment_snapshot_id !== null @@ -623,6 +637,14 @@ final class CloudOrderService $placement = CloudPlacementService::reserve( $order, $offer, $plan, $payload ); + $orderSpec['public_network'] = + $placement['public_network']->toArray(); + if ($orderSpec['public_network'] + !== $placement['payload']['body']['public_network']) { + throw new CloudError('开通订单与任务的双栈公网快照不一致', 409); + } + $order->spec_json = json_encode($orderSpec, JSON_THROW_ON_ERROR + | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); if ($sourceBackup !== null) { $uuid = CloudOperationRecoveryIdentity::operationUuid( (string) $placement['reservation']->operation_id diff --git a/web/app/Services/Cloud/CloudPlacementNetworkService.php b/web/app/Services/Cloud/CloudPlacementNetworkService.php index dde4ff0f..f18d1dd8 100644 --- a/web/app/Services/Cloud/CloudPlacementNetworkService.php +++ b/web/app/Services/Cloud/CloudPlacementNetworkService.php @@ -39,6 +39,114 @@ final class CloudPlacementNetworkService return $available; } + /** + * New-instance catalog hint for one IPv4 + one sparse IPv6 pool on the + * same currently verified attachment. Exact admission is repeated by the + * bundle allocator under locks after payment. + * + * @return array + */ + public static function advisoryDualStackAvailableHosts( + $candidateRows + ): array { + $hostLines = []; + foreach ($candidateRows as $candidate) { + $hostId = (int) ($candidate->id ?? 0); + $lineId = (int) ($candidate->resource_pool_line_id ?? 0); + if ($hostId > 0 && $lineId > 0) { + $hostLines[$hostId][$lineId] = true; + } + } + if ($hostLines === []) { + return []; + } + $agents = CloudHostAgent::whereIn('host_id', array_keys($hostLines)) + ->get()->keyBy('host_id'); + $attachments = CloudHostNetworkAttachment::whereIn( + 'host_id', + array_keys($hostLines) + )->where('state', 'active')->where('verification_state', 'verified') + ->orderBy('id')->get(); + if ($attachments->isEmpty()) { + return []; + } + $eligible = []; + foreach ($attachments as $attachment) { + $hostId = (int) $attachment->host_id; + $lineId = (int) $attachment->line_id; + $agent = $agents->get($hostId); + if ($agent instanceof CloudHostAgent + && isset($hostLines[$hostId][$lineId]) + && self::attachmentReadyForAgent($attachment, $agent) + && CloudAgentSettingsService::publicNetworkReady( + $agent, + (string) $attachment->network_selector, + (int) $attachment->verified_agent_revision + )) { + $eligible[(int) $attachment->id] = $attachment; + } + } + if ($eligible === []) { + return []; + } + $pools = CloudPublicIpPool::whereIn( + 'network_attachment_id', + array_keys($eligible) + )->where('state', 'active')->where('sync_state', 'applied') + ->whereColumn('observed_revision', 'desired_revision') + ->orderBy('id')->get(); + $poolIds = $pools->pluck('id')->map( + static fn ($id): int => (int) $id + )->all(); + $ipsByPool = []; + if ($poolIds !== []) { + $ipRows = CloudPublicIp::whereIn('public_ip_pool_id', $poolIds) + ->whereIn('state', [ + 'available', 'reserved', 'changing', 'uncertain', + 'assigned', + ])->orderBy('id')->get(); + foreach ($ipRows as $ip) { + $ipsByPool[(int) $ip->public_ip_pool_id][] = $ip; + } + } + $hosts = CloudHost::whereIn('id', array_keys($hostLines)) + ->get()->keyBy('id'); + $capacity = []; + foreach ($pools as $pool) { + $attachment = $eligible[(int) $pool->network_attachment_id] + ?? null; + $family = (int) $pool->address_family; + if ($attachment === null + || (int) $pool->host_id !== (int) $attachment->host_id + || !in_array($family, [4, 6], true) + || preg_match('/^[a-f0-9]{32}$/D', + (string) $pool->pool_key) !== 1) { + continue; + } + $poolIps = $ipsByPool[(int) $pool->id] ?? []; + $hasCapacity = $family === 4 + ? self::advisoryIpv4PoolHasCapacity( + $pool, + $poolIps, + $hosts->get((int) $pool->host_id) + ) + : self::advisoryIpv6PoolHasCapacity($pool, $poolIps); + if ($hasCapacity) { + $capacity[(int) $attachment->id][$family] = true; + } + } + $available = []; + foreach ($capacity as $attachmentId => $families) { + if (!isset($families[4], $families[6])) { + continue; + } + $attachment = $eligible[(int) $attachmentId]; + $available[(int) $attachment->host_id] = true; + } + ksort($available, SORT_NUMERIC); + return $available; + } + /** @return array> keyed by host ID then line ID. */ public static function advisoryAvailableHostLines($candidateRows): array { @@ -109,7 +217,6 @@ final class CloudPlacementNetworkService ->where('public_pool.sync_state', 'applied') ->whereColumn( 'public_pool.observed_revision', - '>=', 'public_pool.desired_revision' ) ->get([ @@ -215,7 +322,7 @@ final class CloudPlacementNetworkService ->whereIn('network_attachment_id', array_keys($eligibleAttachments)) ->where('state', 'active') ->where('sync_state', 'applied') - ->whereColumn('observed_revision', '>=', 'desired_revision') + ->whereColumn('observed_revision', 'desired_revision') ->orderBy('id')->lockForUpdate()->get(); $candidates = []; foreach ($pools as $pool) { @@ -250,6 +357,42 @@ final class CloudPlacementNetworkService return $candidates; } + /** + * New-instance admission requires one IPv4 and one IPv6 pool on the exact + * same verified attachment. Address allocation remains owned by the + * atomic bundle allocator after the resource reservation row is created. + */ + public static function hasCompleteDualStackCandidate(array $candidates, + CloudHostAgent $agent): bool + { + $familiesByAttachment = []; + foreach ($candidates as $candidate) { + $attachment = $candidate['attachment'] ?? null; + $pool = $candidate['public_pool'] ?? null; + if (!$attachment instanceof CloudHostNetworkAttachment + || !$pool instanceof CloudPublicIpPool + || (int) $pool->network_attachment_id + !== (int) $attachment->id + || !in_array((int) $pool->address_family, [4, 6], true) + || !CloudAgentSettingsService::publicNetworkReady( + $agent, + (string) $attachment->network_selector, + (int) $attachment->verified_agent_revision + )) { + continue; + } + $familiesByAttachment[(int) $attachment->id][ + (int) $pool->address_family + ] = true; + } + foreach ($familiesByAttachment as $families) { + if (isset($families[4], $families[6])) { + return true; + } + } + return false; + } + /** Current-revision Agent evidence for one already-loaded attachment. */ public static function attachmentReadyForAgent( CloudHostNetworkAttachment $attachment, @@ -354,8 +497,86 @@ final class CloudPlacementNetworkService ->orderBy('id'); } + private static function advisoryIpv4PoolHasCapacity( + CloudPublicIpPool $pool, + array $ips, + ?CloudHost $host + ): bool { + try { + $network = CloudIpPrefix::network((string) $pool->cidr); + $gateway = CloudIpAddress::parse((string) $pool->gateway); + } catch (\InvalidArgumentException) { + return false; + } + if ($network->family() !== 4 || $network->prefixLength() > 30 + || (int) $pool->guest_prefix_length + !== $network->prefixLength() + || !$gateway->isPublicUnicast() + || !$network->contains($gateway)) { + return false; + } + $available = array_values(array_filter( + $ips, + static fn (CloudPublicIp $ip): bool => + (string) $ip->state === 'available' + && $ip->reservation_id === null + && $ip->instance_id === null + && $ip->operation_id === null + )); + if (count($available) > self::MAX_PUBLIC_IPS_PER_POOL) { + return false; + } + foreach ($available as $ip) { + try { + $address = CloudIpAddress::parse((string) $ip->address); + } catch (\InvalidArgumentException) { + continue; + } + if ($address->isPublicUnicast() + && self::publicIpBelongsToPool($ip, $pool, $host)) { + return true; + } + } + return false; + } + + private static function advisoryIpv6PoolHasCapacity( + CloudPublicIpPool $pool, + array $ips + ): bool { + try { + $network = CloudIpPrefix::network((string) $pool->cidr); + $gateway = CloudIpAddress::parse((string) $pool->gateway); + $start = CloudIpAddress::parse((string) $pool->allocation_start); + $end = CloudIpAddress::parse((string) $pool->allocation_end); + } catch (\InvalidArgumentException) { + return false; + } + if ($network->family() !== 6 || $network->prefixLength() > 120 + || (int) $pool->guest_prefix_length + !== $network->prefixLength() + || !$gateway->isPublicUnicast() + || (!$network->contains($gateway) + && !(bool) $pool->gateway_on_link) + || $start->family() !== 6 || $end->family() !== 6 + || !$start->isPublicUnicast() || !$end->isPublicUnicast() + || !$network->contains($start) || !$network->contains($end) + || $start->compare($end) > 0 + || (int) $pool->max_allocations < 1) { + return false; + } + $active = count(array_filter( + $ips, + static fn (CloudPublicIp $ip): bool => + (int) $ip->address_family === 6 + && in_array((string) $ip->state, + ['reserved', 'changing', 'uncertain', 'assigned'], true) + )); + return $active < (int) $pool->max_allocations; + } + private static function publicIpBelongsToPool(CloudPublicIp $ip, - CloudPublicIpPool $pool): bool + CloudPublicIpPool $pool, ?CloudHost $host = null): bool { return (int) $ip->host_id === (int) $pool->host_id && (int) $ip->public_ip_pool_id === (int) $pool->id @@ -366,7 +587,7 @@ final class CloudPlacementNetworkService ) && self::addressAllowedByPool( (string) $ip->address, $pool, - CloudHost::find((int) $pool->host_id) + $host ?? CloudHost::find((int) $pool->host_id) ); } diff --git a/web/app/Services/Cloud/CloudPlacementService.php b/web/app/Services/Cloud/CloudPlacementService.php index 56f70535..d8a8f474 100644 --- a/web/app/Services/Cloud/CloudPlacementService.php +++ b/web/app/Services/Cloud/CloudPlacementService.php @@ -17,6 +17,7 @@ use App\Models\CloudPublicIpPool; use App\Models\CloudRegion; use App\Models\CloudResourcePool; use App\Models\CloudResourceReservation; +use App\Models\CloudResourceReservationIp; use App\Models\CloudOrder; use App\Models\CloudTemplate; use App\Models\CloudTemplateReplica; @@ -239,10 +240,10 @@ final class CloudPlacementService } /** - * Select a host and reserve one concrete public IP exactly once. + * Select a host and atomically reserve one IPv4+IPv6 public network. * * @return array{host: CloudHost, reservation: CloudResourceReservation, - * public_ip: CloudPublicIp, payload: array} + * public_network: CloudPublicNetworkSnapshot, payload: array} */ public static function reserve(CloudOrder $order, CloudOffer $offer, Shop $plan, array $payload): array @@ -313,51 +314,55 @@ final class CloudPlacementService } public static function commit(CloudOrder $order, int $instanceId, - string $confirmedPublicIpCidr): void + array $confirmedPublicNetwork): void { - [, $reservation] = self::lockedHostAndReservation($order); - if ($reservation === null || (string) $reservation->state === 'released') { - throw new CloudError('开通任务缺少有效的资源预留', 409); + if ($instanceId < 1) { + throw new CloudError('开通任务实例归属无效', 409); } - $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) - ->lockForUpdate()->first(); - if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id - || !self::reservationNetworkMatches($reservation, $ip) - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) ($ip->operation_id ?? '')) - || !hash_equals( - (string) $ip->address . '/' . (int) $ip->prefix_length, - $confirmedPublicIpCidr - ) - || !in_array((string) $reservation->state, - ['held', 'uncertain', 'committed'], true) - || ((string) $reservation->state === 'held' - && (string) $ip->state !== 'reserved') - || ((string) $reservation->state === 'uncertain' - && (string) $ip->state !== 'uncertain') - || ((string) $reservation->state === 'committed' - && (string) $ip->state !== 'assigned')) { - throw new CloudError('开通任务的公网 IP 预留不一致', 409); - } - if ((string) $reservation->state === 'committed') { - if ((string) $ip->state !== 'assigned' - || (int) ($reservation->instance_id ?? 0) !== $instanceId - || (int) ($ip->instance_id ?? 0) !== $instanceId) { - throw new CloudError('已交付实例的公网 IP 账本不一致', 409); - } - return; - } - $now = time(); - $reservation->state = 'committed'; - $reservation->instance_id = $instanceId; - $reservation->expires_at = null; - $reservation->updated_at = $now; - $reservation->save(); - $ip->state = 'assigned'; - $ip->instance_id = $instanceId; - $ip->updated_at = $now; - $ip->save(); + $confirmed = CloudPublicNetworkSnapshot::fromArray( + $confirmedPublicNetwork + ); + (new CloudResourceReservation())->getConnection()->transaction( + static function () use ($order, $instanceId, $confirmed): void { + $hint = CloudResourceReservation::where( + 'order_id', + (int) $order->id + )->first(); + if ($hint === null) { + throw new CloudError('开通任务缺少有效的资源预留', 409); + } + $allocated = CloudPublicNetworkAllocationService::commitBundle( + (int) $hint->id, + $instanceId, + (string) $hint->operation_id + ); + if (!hash_equals( + $confirmed->fingerprint(), + $allocated->fingerprint() + )) { + throw new CloudError('开通回执与双栈公网预留不一致', 409); + } + $reservation = CloudResourceReservation::where( + 'id', + (int) $hint->id + )->lockForUpdate()->first(); + self::assertOrderReservation($order, $reservation, [ + 'held', 'uncertain', 'committed', + ]); + if ((string) $reservation->state === 'committed') { + if ((int) ($reservation->instance_id ?? 0) !== $instanceId) { + throw new CloudError('已交付实例的资源账本不一致', 409); + } + return; + } + $reservation->state = 'committed'; + $reservation->instance_id = $instanceId; + $reservation->expires_at = null; + $reservation->updated_at = time(); + $reservation->save(); + }, + 3 + ); } /** @@ -805,58 +810,102 @@ final class CloudPlacementService $ip->save(); } - /** Keep an ambiguous create and its address unavailable for reconciliation. */ + /** Keep an ambiguous create and both addresses unavailable for reconciliation. */ public static function markUncertain(CloudOrder $order): void { - [, $reservation] = self::lockedHostAndReservation($order); - if ($reservation === null || (string) $reservation->state === 'released') { - return; - } - $ip = CloudPublicIp::where('id', (int) $reservation->public_ip_id) - ->lockForUpdate()->first(); - if ($ip === null || (int) $ip->host_id !== (int) $reservation->host_id - || !self::reservationNetworkMatches($reservation, $ip) - || (int) ($ip->reservation_id ?? 0) !== (int) $reservation->id - || !hash_equals((string) $reservation->operation_id, - (string) ($ip->operation_id ?? ''))) { - throw new CloudError('开通任务的公网 IP 预留不一致', 409); - } - // A late exception after a successful commit must never roll a live - // instance and its address back to an ambiguous creation state. - if ((string) $reservation->state === 'committed') { - if ((string) $ip->state !== 'assigned' - || (int) ($reservation->instance_id ?? 0) < 1 - || (int) ($ip->instance_id ?? 0) !== (int) $reservation->instance_id) { - throw new CloudError('已交付实例的公网 IP 账本不一致', 409); - } - return; - } - if (!in_array((string) $reservation->state, ['held', 'uncertain'], true) - || !in_array((string) $ip->state, ['reserved', 'uncertain'], true)) { - throw new CloudError('开通任务的资源预留状态无效', 409); - } - $now = time(); - $reservation->state = 'uncertain'; - $reservation->expires_at = null; - $reservation->updated_at = $now; - $reservation->save(); - $ip->state = 'uncertain'; - $ip->updated_at = $now; - $ip->save(); + (new CloudResourceReservation())->getConnection()->transaction( + static function () use ($order): void { + $hint = CloudResourceReservation::where( + 'order_id', + (int) $order->id + )->first(); + if ($hint === null || (string) $hint->state === 'released') { + return; + } + if ((string) $hint->state === 'committed') { + $instanceId = (int) ($hint->instance_id ?? 0); + if ($instanceId < 1) { + throw new CloudError('已交付实例的资源账本不一致', 409); + } + CloudPublicNetworkAllocationService::commitBundle( + (int) $hint->id, + $instanceId, + (string) $hint->operation_id + ); + $reservation = CloudResourceReservation::where( + 'id', + (int) $hint->id + )->lockForUpdate()->first(); + self::assertOrderReservation( + $order, + $reservation, + ['committed'] + ); + if ((int) ($reservation->instance_id ?? 0) + !== $instanceId) { + throw new CloudError( + '已交付实例的资源账本不一致', + 409 + ); + } + return; + } + CloudPublicNetworkAllocationService::fenceBundle( + (int) $hint->id, + (string) $hint->operation_id + ); + $reservation = CloudResourceReservation::where( + 'id', + (int) $hint->id + )->lockForUpdate()->first(); + self::assertOrderReservation( + $order, + $reservation, + ['held', 'uncertain'] + ); + $reservation->state = 'uncertain'; + $reservation->expires_at = null; + $reservation->updated_at = time(); + $reservation->save(); + }, + 3 + ); } - /** Release only when the Agent outcome proves that no guest owns the IP. */ - public static function release(CloudOrder $order, string $reason, - bool $includeCommitted = false): void + /** Release only when the Agent proves that no guest owns either address. */ + public static function release(CloudOrder $order, string $reason): void { - [, $reservation] = self::lockedHostAndReservation($order); - if ($reservation === null || (string) $reservation->state === 'released') { - return; - } - self::releaseLockedReservation( - $reservation, - $reason, - $includeCommitted + (new CloudResourceReservation())->getConnection()->transaction( + static function () use ($order, $reason): void { + $hint = CloudResourceReservation::where( + 'order_id', + (int) $order->id + )->first(); + if ($hint === null || (string) $hint->state === 'released') { + return; + } + if ((string) $hint->state === 'committed') { + throw new CloudError('已交付实例的资源不能按失败任务释放', 409); + } + $releaseReason = self::releaseReason($reason); + CloudPublicNetworkAllocationService::releaseBundle( + (int) $hint->id, + (string) $hint->operation_id, + $releaseReason, + true + ); + $reservation = CloudResourceReservation::where( + 'id', + (int) $hint->id + )->lockForUpdate()->first(); + self::assertOrderReservation( + $order, + $reservation, + ['held', 'uncertain'] + ); + self::markReservationReleased($reservation, $releaseReason); + }, + 3 ); } @@ -872,60 +921,115 @@ final class CloudPlacementService if ($instance->order_id === null) { return; } - $order = CloudOrder::where('id', (int) $instance->order_id) - ->lockForUpdate()->first(); - if ($order === null) { - throw new CloudError('已删除实例的开通订单不存在', 409); - } - self::release($order, $reason, true); - return; - } - - $host = CloudHost::where('id', (int) $instance->host_id) - ->lockForUpdate()->first(); - $reservation = CloudResourceReservation::where('id', $reservationId) - ->lockForUpdate()->first(); - if ($host === null || $reservation === null - || (int) $reservation->host_id !== (int) $host->id - || (int) $reservation->instance_id !== (int) $instance->id - || (int) $reservation->resource_pool_id - !== (int) ($instance->resource_pool_id ?? 0)) { - throw new CloudError('已删除实例的资源预留账本不一致', 409); - } - - $orderId = (int) ($reservation->order_id ?? 0); - $restoreId = (int) ($reservation->backup_restore_id ?? 0); - if ($orderId > 0 && $restoreId === 0 - && (int) ($reservation->offer_id ?? 0) > 0) { - $order = CloudOrder::where('id', $orderId) - ->lockForUpdate()->first(); - if ($order === null - || (int) ($instance->order_id ?? 0) !== (int) $order->id - || (int) ($order->reservation_id ?? 0) - !== (int) $reservation->id - || (int) ($order->host_id ?? 0) !== (int) $instance->host_id) { - throw new CloudError('已删除实例的订单资源账本不一致', 409); - } - } elseif ($orderId === 0 && $restoreId > 0 - && (int) ($reservation->offer_id ?? 0) === 0) { - $restore = CloudBackupRestore::where('id', $restoreId) - ->lockForUpdate()->first(); - if ($restore === null || $instance->order_id !== null - || (int) $restore->target_host_id !== (int) $instance->host_id - || (int) $restore->target_instance_id !== (int) $instance->id - || (int) $restore->reservation_id !== (int) $reservation->id - || (string) $restore->state !== 'ready' - || !hash_equals( - (string) $restore->operation_id, - (string) $reservation->operation_id - )) { - throw new CloudError('已删除恢复实例的资源账本不一致', 409); - } - } else { - throw new CloudError('已删除实例的资源来源无效', 409); - } + throw new CloudError('已删除实例缺少资源预留账本', 409); + } + (new CloudResourceReservation())->getConnection()->transaction( + static function () use ($instance, $reservationId, $reason): void { + // Read only enough source identity to choose the writer. The + // dual-stack allocator then acquires host -> attachment/pool + // -> reservation -> claims/IP in its canonical lock order. + $hint = CloudResourceReservation::where( + 'id', + $reservationId + )->first(); + if ($hint === null) { + throw new CloudError('已删除实例的资源预留账本不存在', 409); + } + $orderId = (int) ($hint->order_id ?? 0); + $restoreId = (int) ($hint->backup_restore_id ?? 0); + if ($orderId > 0 && $restoreId === 0 + && (int) ($hint->offer_id ?? 0) > 0) { + $order = CloudOrder::where('id', $orderId)->first(); + if ($order === null + || (int) ($instance->order_id ?? 0) !== $orderId + || (int) ($order->reservation_id ?? 0) + !== $reservationId + || (int) ($order->host_id ?? 0) + !== (int) $instance->host_id + || (int) $hint->host_id !== (int) $instance->host_id + || (int) ($hint->instance_id ?? 0) + !== (int) $instance->id + || (int) $hint->resource_pool_id + !== (int) ($instance->resource_pool_id ?? 0)) { + throw new CloudError( + '已删除实例的订单资源账本不一致', + 409 + ); + } + if ((string) $hint->state === 'released') { + return; + } + $releaseReason = self::releaseReason($reason); + CloudPublicNetworkAllocationService:: + releaseCommittedBundle( + $reservationId, + (int) $instance->id, + (string) $hint->operation_id, + $releaseReason, + true + ); + $reservation = CloudResourceReservation::where( + 'id', + $reservationId + )->lockForUpdate()->first(); + self::assertOrderReservation( + $order, + $reservation, + ['committed'] + ); + if ((int) ($reservation->instance_id ?? 0) + !== (int) $instance->id) { + throw new CloudError( + '已删除实例的资源归属不一致', + 409 + ); + } + self::markReservationReleased( + $reservation, + $releaseReason + ); + return; + } - self::releaseLockedReservation($reservation, $reason, true); + // Backup restores retain their pre-C11 single-address ledger. + if ($orderId !== 0 || $restoreId < 1 + || (int) ($hint->offer_id ?? 0) !== 0) { + throw new CloudError('已删除实例的资源来源无效', 409); + } + $host = CloudHost::where('id', (int) $instance->host_id) + ->lockForUpdate()->first(); + $reservation = CloudResourceReservation::where( + 'id', + $reservationId + )->lockForUpdate()->first(); + $restore = CloudBackupRestore::where('id', $restoreId) + ->lockForUpdate()->first(); + if ($host === null || $reservation === null + || (int) $reservation->host_id !== (int) $host->id + || (int) $reservation->instance_id !== (int) $instance->id + || (int) $reservation->resource_pool_id + !== (int) ($instance->resource_pool_id ?? 0) + || $restore === null || $instance->order_id !== null + || (int) $restore->target_host_id + !== (int) $instance->host_id + || (int) $restore->target_instance_id + !== (int) $instance->id + || (int) $restore->reservation_id + !== (int) $reservation->id + || (string) $restore->state !== 'ready' + || !hash_equals( + (string) $restore->operation_id, + (string) $reservation->operation_id + )) { + throw new CloudError( + '已删除恢复实例的资源账本不一致', + 409 + ); + } + self::releaseLockedReservation($reservation, $reason, true); + }, + 3 + ); } private static function releaseLockedReservation( @@ -1179,15 +1283,6 @@ final class CloudPlacementService return null; } - $networkCandidates = CloudPlacementNetworkService::lockedCandidates( - $hostId, - (int) $pool->line_id, - $agent - ); - if ($networkCandidates === []) { - return null; - } - // This must be a current locking read, not an aggregate consistent // read. Every reservation writer locks the host first, so after this // host lock is acquired the row set is stable and the locking read @@ -1203,16 +1298,6 @@ final class CloudPlacementService return null; } - $network = CloudPlacementNetworkService::lockAvailableSelection( - $hostId, - $networkCandidates - ); - if ($network === null) { - return null; - } - $selectedAttachment = $network['attachment']; - $selectedPool = $network['public_pool']; - $ip = $network['public_ip']; $operationId = bin2hex(random_bytes(16)); $reservation = new CloudResourceReservation(); $reservation->reservation_key = bin2hex(random_bytes(16)); @@ -1223,9 +1308,9 @@ final class CloudPlacementService $reservation->host_id = $hostId; $reservation->user_id = $order->user_id; $reservation->instance_id = null; - $reservation->network_attachment_id = $selectedAttachment->id; - $reservation->public_ip_pool_id = $selectedPool->id; - $reservation->public_ip_id = $ip->id; + $reservation->network_attachment_id = null; + $reservation->public_ip_pool_id = null; + $reservation->public_ip_id = null; $reservation->cpu_cores = $resources['cpu_cores']; $reservation->memory_mib = $resources['memory_mib']; $reservation->disk_gib = $resources['disk_gib']; @@ -1235,13 +1320,33 @@ final class CloudPlacementService $reservation->release_reason = ''; $reservation->created_at = $reservation->updated_at = time(); $reservation->save(); - - $ip->state = 'reserved'; - $ip->reservation_id = $reservation->id; - $ip->instance_id = null; - $ip->operation_id = $operationId; - $ip->updated_at = time(); - $ip->save(); + try { + $publicNetwork = CloudPublicNetworkAllocationService::reserveBundle( + $hostId, + (int) $pool->line_id, + (int) $reservation->id, + $operationId + ); + } catch (CloudPublicNetworkCapacityUnavailable) { + // This is the only allocation outcome that means "try another + // host". The allocator selected and locked the complete network + // context before returning it, so a capacity miss must not have + // created either family claim. Any residue is a ledger fault and + // must abort the payment transaction instead of being hidden as + // ordinary scheduler exhaustion. + $claims = CloudResourceReservationIp::where( + 'reservation_id', + (int) $reservation->id + )->orderBy('id')->lockForUpdate()->get(); + if (!$claims->isEmpty()) { + throw new CloudError( + '公网地址容量回退存在残留账本,必须人工核查', + 409 + ); + } + $reservation->delete(); + return null; + } $order->resource_pool_id = $pool->id; $order->host_id = $hostId; @@ -1252,29 +1357,24 @@ final class CloudPlacementService return [ 'host' => $host, 'reservation' => $reservation, - 'public_ip' => $ip, - 'payload' => self::placementPayload( - $payload, $selectedAttachment, $selectedPool, $ip - ), + 'public_network' => $publicNetwork, + 'payload' => self::placementPayload($payload, $publicNetwork), ]; } private static function placementPayload(array $payload, - CloudHostNetworkAttachment $attachment, CloudPublicIpPool $publicPool, - CloudPublicIp $ip): array + CloudPublicNetworkSnapshot $publicNetwork): array { if (($payload['method'] ?? null) !== 'POST' || ($payload['request_target'] ?? null) !== '/v1/vms' || !is_array($payload['body'] ?? null)) { throw new CloudError('开通订单的加密请求无效', 409); } - $payload['body']['network'] = (string) $attachment->network_selector; - $payload['body']['public_pool_key'] = (string) $publicPool->pool_key; - $payload['body']['public_pool_cidr'] = (string) $publicPool->cidr; - $payload['body']['public_ip_cidr'] = (string) $ip->address . '/' - . (int) $ip->prefix_length; - $payload['body']['gateway'] = (string) $publicPool->gateway; - $payload['body']['dns_servers'] = self::poolDnsServers($publicPool); + foreach (['network', 'public_pool_key', 'public_pool_cidr', + 'public_ip_cidr', 'gateway', 'dns_servers'] as $retired) { + unset($payload['body'][$retired]); + } + $payload['body']['public_network'] = $publicNetwork->toArray(); return $payload; } @@ -1317,6 +1417,60 @@ final class CloudPlacementService } } + private static function assertOrderReservation(CloudOrder $order, + ?CloudResourceReservation $reservation, array $allowedStates): void + { + if ($reservation === null + || (int) ($reservation->order_id ?? 0) !== (int) $order->id + || (int) ($reservation->user_id ?? 0) !== (int) $order->user_id + || (int) ($reservation->offer_id ?? 0) !== (int) $order->offer_id + || (int) ($reservation->resource_pool_id ?? 0) + !== (int) $order->resource_pool_id + || (int) ($reservation->host_id ?? 0) + !== (int) $order->host_id + || (int) ($order->reservation_id ?? 0) + !== (int) ($reservation->id ?? 0) + || (int) ($reservation->backup_restore_id ?? 0) !== 0 + || preg_match( + '/^[a-f0-9]{32}$/D', + (string) ($reservation->operation_id ?? '') + ) !== 1 + || !in_array( + (string) ($reservation->state ?? ''), + $allowedStates, + true + )) { + throw new CloudError('开通订单的资源预留账本不一致', 409); + } + } + + private static function releaseReason(string $reason): string + { + $reason = strtolower(trim($reason)); + $reason = preg_replace('/[^a-z0-9_]+/', '_', $reason) ?? ''; + $reason = trim($reason, '_'); + if ($reason === '' || preg_match('/^[a-z]/D', $reason) !== 1) { + $reason = 'released' . ($reason === '' ? '' : '_' . $reason); + } + if (strlen($reason) < 3) { + $reason = 'released'; + } + return substr($reason, 0, 64); + } + + private static function markReservationReleased( + CloudResourceReservation $reservation, + string $reason + ): void { + $now = time(); + $reservation->state = 'released'; + $reservation->released_at = $now; + $reservation->release_reason = $reason; + $reservation->expires_at = null; + $reservation->updated_at = $now; + $reservation->save(); + } + /** * Capacity must follow the immutable order snapshot, never the mutable * current plan. The sealed Agent request is checked against the same @@ -1372,20 +1526,6 @@ final class CloudPlacementService return $resources; } - /** @return array{0: ?CloudHost, 1: ?CloudResourceReservation} */ - private static function lockedHostAndReservation(CloudOrder $order): array - { - $host = $order->host_id === null ? null - : CloudHost::where('id', (int) $order->host_id)->lockForUpdate()->first(); - $reservation = CloudResourceReservation::where('order_id', (int) $order->id) - ->lockForUpdate()->first(); - if ($reservation !== null - && ($host === null || (int) $reservation->host_id !== (int) $host->id)) { - throw new CloudError('订单的宿主机与资源预留不一致', 409); - } - return [$host, $reservation]; - } - private static function candidateHostRows(int $poolId) { return CloudHost::query()->join( @@ -1450,7 +1590,7 @@ final class CloudPlacementService */ private static function availableIpHosts($candidateRows): array { - return CloudPlacementNetworkService::advisoryAvailableHosts( + return CloudPlacementNetworkService::advisoryDualStackAvailableHosts( $candidateRows ); } diff --git a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php index 4ae2b856..b3f15a83 100644 --- a/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php +++ b/web/app/Services/Cloud/CloudPublicNetworkAllocationService.php @@ -2,6 +2,7 @@ namespace App\Services\Cloud; +use App\Models\CloudHostAgent; use Illuminate\Database\Capsule\Manager as DB; use Illuminate\Database\Connection; @@ -28,11 +29,19 @@ final class CloudPublicNetworkAllocationService $reservationId, $operationId ): CloudPublicNetworkSnapshot { - $claimHints = self::unlockedClaims($reservationId); self::lockHost($hostId); - $selection = $claimHints === [] - ? self::lockPoolPair($hostId, $lineId) - : self::lockClaimNetworkContext($claimHints, $hostId, $lineId); + $claimHints = self::unlockedClaims($reservationId); + $catalog = null; + $selection = null; + if ($claimHints === []) { + $catalog = self::lockPoolCatalog($hostId, $lineId); + } else { + $selection = self::lockClaimNetworkContext( + $claimHints, + $hostId, + $lineId + ); + } $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, ['held', 'committed', 'uncertain']); @@ -41,9 +50,12 @@ final class CloudPublicNetworkAllocationService self::assertClaimSet($existing, $operationId, [ 'reserved', 'committed', 'uncertain', ]); + if ($selection === null) { + throw new CloudError('公网网络资源预留状态不明确', 409); + } self::assertClaimsUseSelection($existing, $selection); $addresses = self::lockClaimAddresses($existing); - self::assertClaimAddresses($existing, $addresses, + self::assertClaimAddresses($existing, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'committed' => ['assigned'], @@ -54,6 +66,10 @@ final class CloudPublicNetworkAllocationService if ($claimHints !== [] || (string) $reservation->state !== 'held') { throw new CloudError('公网网络资源预留状态不明确', 409); } + if ($catalog === null) { + throw new CloudError('公网网络候选目录不完整', 409); + } + $selection = self::selectAvailablePoolPair($catalog); $now = time(); $claims = []; foreach (self::FAMILIES as $family) { @@ -96,12 +112,15 @@ final class CloudPublicNetworkAllocationService $operationId ): CloudPublicNetworkSnapshot { $reservationHint = self::unlockedReservation($reservationId); - $claimHints = self::unlockedClaims($reservationId); - if ($reservationHint === null || $claimHints === []) { + if ($reservationHint === null) { throw new CloudError('双栈公网地址账本不完整', 409); } $hostId = (int) $reservationHint->host_id; self::lockHost($hostId); + $claimHints = self::unlockedClaims($reservationId); + if ($claimHints === []) { + throw new CloudError('双栈公网地址账本不完整', 409); + } $selection = self::lockClaimNetworkContext($claimHints, $hostId); $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, @@ -111,7 +130,8 @@ final class CloudPublicNetworkAllocationService ['reserved', 'uncertain', 'committed']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); - self::assertClaimAddresses($claims, $addresses, $operationId, [ + self::assertClaimAddresses($claims, $addresses, $selection, + $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], 'committed' => ['assigned'], @@ -146,12 +166,15 @@ final class CloudPublicNetworkAllocationService $operationId ): void { $reservationHint = self::unlockedReservation($reservationId); - $claimHints = self::unlockedClaims($reservationId); - if ($reservationHint === null || $claimHints === []) { + if ($reservationHint === null) { throw new CloudError('双栈公网地址账本不完整', 409); } $hostId = (int) $reservationHint->host_id; self::lockHost($hostId); + $claimHints = self::unlockedClaims($reservationId); + if ($claimHints === []) { + throw new CloudError('双栈公网地址账本不完整', 409); + } $selection = self::lockClaimNetworkContext($claimHints, $hostId); $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, @@ -161,7 +184,8 @@ final class CloudPublicNetworkAllocationService ['reserved', 'uncertain']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); - self::assertClaimAddresses($claims, $addresses, $operationId, [ + self::assertClaimAddresses($claims, $addresses, $selection, + $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); @@ -196,12 +220,15 @@ final class CloudPublicNetworkAllocationService $reason ): void { $reservationHint = self::unlockedReservation($reservationId); - $claimHints = self::unlockedClaims($reservationId); - if ($reservationHint === null || $claimHints === []) { + if ($reservationHint === null) { throw new CloudError('双栈公网地址账本不完整', 409); } $hostId = (int) $reservationHint->host_id; self::lockHost($hostId); + $claimHints = self::unlockedClaims($reservationId); + if ($claimHints === []) { + throw new CloudError('双栈公网地址账本不完整', 409); + } $selection = self::lockClaimNetworkContext($claimHints, $hostId); $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, @@ -211,7 +238,8 @@ final class CloudPublicNetworkAllocationService ['reserved', 'uncertain']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); - self::assertClaimAddresses($claims, $addresses, $operationId, [ + self::assertClaimAddresses($claims, $addresses, $selection, + $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); @@ -240,12 +268,15 @@ final class CloudPublicNetworkAllocationService $reason ): void { $reservationHint = self::unlockedReservation($reservationId); - $claimHints = self::unlockedClaims($reservationId); - if ($reservationHint === null || $claimHints === []) { + if ($reservationHint === null) { throw new CloudError('双栈公网地址账本不完整', 409); } $hostId = (int) $reservationHint->host_id; self::lockHost($hostId); + $claimHints = self::unlockedClaims($reservationId); + if ($claimHints === []) { + throw new CloudError('双栈公网地址账本不完整', 409); + } $selection = self::lockClaimNetworkContext($claimHints, $hostId); $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, @@ -254,7 +285,8 @@ final class CloudPublicNetworkAllocationService self::assertClaimSet($claims, $operationId, ['committed']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); - self::assertClaimAddresses($claims, $addresses, $operationId, [ + self::assertClaimAddresses($claims, $addresses, $selection, + $operationId, [ 'committed' => ['assigned'], ], $instanceId); self::releaseLockedClaims($claims, $operationId, $reason); @@ -385,15 +417,136 @@ final class CloudPublicNetworkAllocationService return $result; } + private static function assertPoolLedger(object $pool, array $rows, + array $retainedSourceEvidence): void + { + foreach ($rows as $row) { + self::assertConcreteAddress($row, $pool); + self::assertAddressOwnership( + $row, + $pool, + $retainedSourceEvidence + ); + } + } + + private static function assertConcreteAddress(object $row, + object $pool): CloudIpAddress + { + try { + $address = CloudIpAddress::parse((string) $row->address); + if ((int) $row->host_id !== (int) $pool->host_id + || (int) $row->public_ip_pool_id !== (int) $pool->id + || (int) $row->address_family + !== (int) $pool->address_family + || (int) $row->prefix_length + !== (int) $pool->guest_prefix_length + || !hash_equals($address->text(), (string) $row->address) + || !is_string($row->address_binary) + || !hash_equals($address->binary(), $row->address_binary) + || !self::rawAddressBelongsToPool($address, $pool) + || ((string) $row->state !== 'disabled' + && !self::rawAddressAllowedByPool($address, $pool))) { + throw new \InvalidArgumentException(); + } + if ($address->family() === 6 + && (string) $row->state !== 'disabled') { + $start = CloudIpAddress::parse($pool->allocation_start ?? null); + $end = CloudIpAddress::parse($pool->allocation_end ?? null); + if ($address->compare($start) < 0 + || $address->compare($end) > 0) { + throw new \InvalidArgumentException(); + } + } + return $address; + } catch (\Throwable) { + throw new CloudError('公网地址具体身份与地址池不一致', 409); + } + } + + private static function assertAddressOwnership(object $row, + ?object $pool = null, array $retainedSourceEvidence = []): void + { + $reservationId = $row->reservation_id === null + ? null : (int) $row->reservation_id; + $instanceId = $row->instance_id === null + ? null : (int) $row->instance_id; + $operationId = $row->operation_id; + $validOperation = is_string($operationId) + && preg_match('/^[a-f0-9]{32}$/D', $operationId) === 1; + $state = (string) $row->state; + $valid = match ($state) { + 'available', 'disabled' => $reservationId === null + && $instanceId === null && $operationId === null, + 'reserved' => $reservationId !== null && $reservationId > 0 + && $instanceId === null && $validOperation, + 'assigned' => $reservationId !== null && $reservationId > 0 + && $validOperation && ( + ($instanceId !== null && $instanceId > 0) + || self::matchesRetainedSourceEvidence( + $row, + $pool, + $retainedSourceEvidence + ) + ), + 'changing' => $reservationId === null + && $instanceId !== null && $instanceId > 0 + && $validOperation, + 'uncertain' => $validOperation && ( + ($reservationId !== null && $reservationId > 0 + && $instanceId === null) + || ($reservationId === null + && $instanceId !== null && $instanceId > 0) + ), + default => false, + }; + if (!$valid) { + throw new CloudError('公网地址占用账本形态不一致', 409); + } + } + + private static function matchesRetainedSourceEvidence(object $row, + ?object $pool, array $evidenceByPublicIpId): bool + { + if ($pool === null || $row->instance_id !== null) { + return false; + } + $evidence = $evidenceByPublicIpId[(int) ($row->id ?? 0)] ?? null; + return is_array($evidence) + && in_array( + $evidence['migration_state'] ?? null, + ['source_retained', 'cleanup_running'], + true + ) + && (int) ($evidence['reservation_id'] ?? 0) + === (int) ($row->reservation_id ?? 0) + && (int) ($evidence['host_id'] ?? 0) === (int) $row->host_id + && (int) ($evidence['host_id'] ?? 0) === (int) $pool->host_id + && (int) ($evidence['network_attachment_id'] ?? 0) + === (int) $pool->network_attachment_id + && (int) ($evidence['public_ip_pool_id'] ?? 0) + === (int) $row->public_ip_pool_id + && (int) ($evidence['public_ip_pool_id'] ?? 0) + === (int) $pool->id + && (int) ($evidence['public_ip_id'] ?? 0) === (int) $row->id + && is_string($evidence['operation_id'] ?? null) + && hash_equals( + (string) $evidence['operation_id'], + (string) ($row->operation_id ?? '') + ); + } + private static function assertClaimAddresses(array $claims, - array $addresses, string $operationId, array $allowedPairs, - ?int $instanceId = null): void + array $addresses, array $selection, string $operationId, + array $allowedPairs, ?int $instanceId = null): void { foreach ($claims as $claim) { $ip = $addresses[(int) $claim->public_ip_id] ?? null; $claimState = (string) $claim->state; $allowedIpStates = $allowedPairs[$claimState] ?? []; - if ($ip === null || $allowedIpStates === [] + $family = (int) $claim->address_family; + $pool = $selection['pools'][$family] ?? null; + if ($ip === null || $pool === null || $allowedIpStates === [] || !in_array((string) $ip->state, $allowedIpStates, true) || (int) $ip->reservation_id !== (int) $claim->reservation_id || (int) $ip->address_family !== (int) $claim->address_family @@ -403,6 +556,8 @@ final class CloudPublicNetworkAllocationService (string) ($ip->operation_id ?? ''))) { throw new CloudError('公网地址与预留账本不一致', 409); } + self::assertConcreteAddress($ip, $pool); + self::assertAddressOwnership($ip); if ((string) $ip->state === 'assigned') { $actualInstanceId = (int) ($ip->instance_id ?? 0); if ($actualInstanceId < 1 @@ -447,44 +602,165 @@ final class CloudPublicNetworkAllocationService } } - private static function lockPoolPair(int $hostId, int $lineId): array + /** + * Lock the exact current Agent proof and every configured pool candidate. + * Concrete address rows are deliberately not locked here: the reservation + * row must come before claims/IPs in the canonical hierarchy. + */ + private static function lockPoolCatalog(int $hostId, int $lineId): array { + $agent = CloudHostAgent::where('host_id', $hostId) + ->lockForUpdate()->first(); + if (!$agent instanceof CloudHostAgent || !$agent->isReady()) { + throw new CloudError('宿主机 Agent 双栈网络验证证据无效', 409); + } $attachments = DB::table('cloud_host_network_attachments') ->where('host_id', $hostId)->where('line_id', $lineId) - ->where('state', 'active')->orderBy('priority')->orderBy('id') - ->lockForUpdate()->get(); + ->where('state', 'active')->orderBy('id') + ->lockForUpdate()->get()->all(); + $eligible = []; foreach ($attachments as $attachment) { - $rows = DB::table('cloud_public_ip_pools') - ->where('host_id', $hostId) - ->where('network_attachment_id', (int) $attachment->id) - ->where('state', 'active')->where('sync_state', 'applied') - ->whereColumn('desired_revision', 'observed_revision') - ->whereIn('address_family', self::FAMILIES) - ->orderBy('address_family')->orderBy('priority')->orderBy('id') - ->lockForUpdate()->get(); - $pools = []; + if ((string) $attachment->verification_state !== 'verified' + || (int) $attachment->last_verified_at < 1 + || !CloudAgentSettingsService::publicNetworkReady( + $agent, + (string) $attachment->network_selector, + (int) $attachment->verified_agent_revision + )) { + continue; + } + $eligible[(int) $attachment->id] = $attachment; + } + if ($eligible === []) { + throw new CloudError('宿主机缺少当前双栈公网网络验证证据', 409); + } + uasort($eligible, static fn (object $left, object $right): int => [ + (int) $left->priority, + (int) $left->id, + ] <=> [ + (int) $right->priority, + (int) $right->id, + ]); + + $poolRows = DB::table('cloud_public_ip_pools') + ->where('host_id', $hostId) + ->whereIn('network_attachment_id', array_keys($eligible)) + ->where('state', 'active') + ->whereIn('address_family', self::FAMILIES) + ->orderBy('id')->lockForUpdate()->get()->all(); + $pools = []; + foreach ($poolRows as $pool) { + $attachmentId = (int) $pool->network_attachment_id; + $family = (int) $pool->address_family; + if (!isset($eligible[$attachmentId]) + || (int) $pool->host_id !== $hostId + || !in_array($family, self::FAMILIES, true) + || preg_match('/^[a-f0-9]{32}$/D', + (string) $pool->pool_key) !== 1 + || (string) $pool->sync_state !== 'applied' + || (int) $pool->observed_revision + !== (int) $pool->desired_revision) { + throw new CloudError('公网地址池目录尚未精确收敛', 409); + } + self::validatePool($pool, $family); + $pools[$attachmentId][] = $pool; + } + foreach ($pools as &$attachmentPools) { + usort($attachmentPools, + static fn (object $left, object $right): int => [ + (int) $left->priority, + (int) $left->id, + ] <=> [ + (int) $right->priority, + (int) $right->id, + ]); + } + unset($attachmentPools); + $complete = false; + foreach (array_keys($eligible) as $attachmentId) { + $families = []; + foreach ($pools[$attachmentId] ?? [] as $pool) { + $families[(int) $pool->address_family] = true; + } + if (isset($families[4], $families[6])) { + $complete = true; + break; + } + } + if (!$complete) { + throw new CloudError('宿主机双栈公网地址池目录不完整', 409); + } + $poolIds = array_map( + static fn (object $pool): int => (int) $pool->id, + $poolRows + ); + $retainedSourceEvidence = CloudInstanceMigrationSettlement:: + lockRetainedSourcePublicIpEvidence($hostId, $poolIds); + return [ + 'attachments' => $eligible, + 'pools' => $pools, + 'retained_source_evidence' => $retainedSourceEvidence, + ]; + } + + /** Called only after the reservation row is locked. */ + private static function selectAvailablePoolPair(array $catalog): array + { + $allPools = []; + foreach ($catalog['pools'] as $attachmentPools) { + foreach ($attachmentPools as $pool) { + $allPools[(int) $pool->id] = $pool; + } + } + ksort($allPools, SORT_NUMERIC); + $rowsByPool = array_fill_keys(array_keys($allPools), []); + $lockedRows = DB::table('cloud_public_ips') + ->whereIn('public_ip_pool_id', array_keys($allPools)) + ->orderBy('id')->lockForUpdate()->get()->all(); + foreach ($lockedRows as $row) { + $poolId = (int) $row->public_ip_pool_id; + if (!isset($rowsByPool[$poolId])) { + throw new CloudError('公网地址引用了候选目录之外的地址池', 409); + } + $rowsByPool[$poolId][] = $row; + } + foreach ($allPools as $poolId => $pool) { + self::assertPoolLedger( + $pool, + $rowsByPool[$poolId], + $catalog['retained_source_evidence'] ?? [] + ); + } + + foreach ($catalog['attachments'] as $attachmentId => $attachment) { + $selectedPools = []; $addressCandidates = []; - foreach ($rows as $row) { - $family = (int) $row->address_family; - self::validatePool($row, $family); - if (isset($pools[$family])) { + foreach ($catalog['pools'][$attachmentId] ?? [] as $pool) { + $family = (int) $pool->address_family; + if (isset($selectedPools[$family])) { continue; } - $candidate = self::lockReservableAddressCandidate($row); + $candidate = self::lockReservableAddressCandidate( + $pool, + $rowsByPool[(int) $pool->id] ?? [] + ); if ($candidate !== null) { - $pools[$family] = $row; + $selectedPools[$family] = $pool; $addressCandidates[$family] = $candidate; } } - if (isset($pools[4], $pools[6])) { + if (isset($selectedPools[4], $selectedPools[6])) { return [ 'attachment' => $attachment, - 'pools' => $pools, + 'pools' => $selectedPools, 'address_candidates' => $addressCandidates, ]; } } - throw new CloudError('宿主机没有完整可用的双栈公网地址池', 409); + throw new CloudPublicNetworkCapacityUnavailable( + '宿主机没有完整可用的双栈公网地址池', + 409 + ); } /** @@ -496,28 +772,26 @@ final class CloudPublicNetworkAllocationService * range_start:?CloudIpAddress,range_end:?CloudIpAddress} */ private static function lockReservableAddressCandidate( - object $pool + object $pool, + array $rows ): ?array { $family = (int) $pool->address_family; if ($family === 6) { - $activeCount = DB::table('cloud_public_ips') - ->where('public_ip_pool_id', (int) $pool->id) - ->whereIn('state', [ - 'reserved', 'assigned', 'changing', 'uncertain', - ])->count(); + $activeCount = count(array_filter( + $rows, + static fn (object $row): bool => in_array( + (string) $row->state, + ['reserved', 'assigned', 'changing', 'uncertain'], + true + ) + )); if ((int) $pool->max_allocations < 1 || $activeCount >= (int) $pool->max_allocations) { return null; } } - $available = DB::table('cloud_public_ips') - ->where('host_id', (int) $pool->host_id) - ->where('public_ip_pool_id', (int) $pool->id) - ->where('address_family', $family)->where('state', 'available') - ->whereNull('reservation_id')->whereNull('instance_id') - ->whereNull('operation_id')->orderBy('id')->lockForUpdate()->get(); - foreach ($available as $row) { - if (self::addressAllowedByPool($row, $pool)) { + foreach ($rows as $row) { + if ((string) $row->state === 'available') { return [ 'row' => $row, 'candidate' => null, @@ -537,8 +811,7 @@ final class CloudPublicNetworkAllocationService || $candidate->compare($rangeEnd) > 0) { $candidate = $rangeStart; } - $materializedCount = DB::table('cloud_public_ips') - ->where('public_ip_pool_id', (int) $pool->id)->count(); + $materializedCount = count($rows); $attempts = max(1, $materializedCount + (int) $pool->max_allocations + count(self::decodedAddresses( @@ -695,33 +968,10 @@ final class CloudPublicNetworkAllocationService } } - private static function addressAllowedByPool(object $row, - object $pool): bool - { - try { - if ((int) $row->address_family !== (int) $pool->address_family - || (int) $row->prefix_length - !== (int) $pool->guest_prefix_length) { - return false; - } - return self::rawAddressAllowedByPool( - CloudIpAddress::parse((string) $row->address), - $pool - ); - } catch (\Throwable) { - return false; - } - } - private static function rawAddressAllowedByPool(CloudIpAddress $address, object $pool): bool { - $prefix = CloudIpPrefix::network((string) $pool->cidr); - if ($address->family() !== (int) $pool->address_family - || !$address->isPublicUnicast() || !$prefix->contains($address) - || $address->equals($prefix->networkAddress()) - || ($address->family() === 4 - && $address->equals($prefix->lastAddress()))) { + if (!self::rawAddressBelongsToPool($address, $pool)) { return false; } $blocked = self::decodedAddresses( @@ -740,6 +990,18 @@ final class CloudPublicNetworkAllocationService return !isset($blocked[$address->text()]); } + private static function rawAddressBelongsToPool(CloudIpAddress $address, + object $pool): bool + { + $prefix = CloudIpPrefix::network((string) $pool->cidr); + return $address->family() === (int) $pool->address_family + && $address->isPublicUnicast() + && $prefix->contains($address) + && !$address->equals($prefix->networkAddress()) + && ($address->family() !== 4 + || !$address->equals($prefix->lastAddress())); + } + private static function decodedAddresses(string $json, bool $allowEmpty, int $maximum = 256): array { diff --git a/web/app/Services/Cloud/CloudPublicNetworkCapacityUnavailable.php b/web/app/Services/Cloud/CloudPublicNetworkCapacityUnavailable.php new file mode 100644 index 00000000..8b935c27 --- /dev/null +++ b/web/app/Services/Cloud/CloudPublicNetworkCapacityUnavailable.php @@ -0,0 +1,14 @@ +spec_json, true); + try { + $frozenPublicNetwork = CloudPublicNetworkSnapshot::fromArray( + is_array($orderSpec) + ? ($orderSpec['public_network'] ?? null) : null + ); + $requestedPublicNetwork = + CloudPublicNetworkSnapshot::fromArray( + is_array($payload['body'] ?? null) + ? ($payload['body']['public_network'] ?? null) + : null + ); + $confirmedPublicNetwork = + CloudPublicNetworkSnapshot::fromArray( + $vm['public_network'] ?? null + ); + } catch (\InvalidArgumentException) { + throw new CloudError( + 'Agent 成功结果缺少有效的双栈公网快照,必须人工核查', + 502 + ); + } + if (!hash_equals( + $frozenPublicNetwork->fingerprint(), + $requestedPublicNetwork->fingerprint() + ) || !hash_equals( + $requestedPublicNetwork->fingerprint(), + $confirmedPublicNetwork->fingerprint() + )) { // A completion result may describe a VM whose network was - // changed out of band after dispatch. Never commit the - // original address in that case. Finalization converts the - // task to a terminal failure and retains the resource lock. + // changed out of band after dispatch. Never commit either + // original address in that case; retain the whole bundle. throw new CloudError( - 'Agent 成功结果与预留公网 IP 不一致,必须人工核查', 502 + 'Agent 成功结果与预留双栈公网不一致,必须人工核查', + 502 ); } $provisionInvoice = CloudInvoice::where( 'order_id', (int) $order->id )->lockForUpdate()->first(); - $reservation = $order->reservation_id === null ? null - : \App\Models\CloudResourceReservation::where( - 'id', - (int) $order->reservation_id - )->lockForUpdate()->first(); - $publicIp = $reservation === null - || $reservation->public_ip_id === null ? null - : \App\Models\CloudPublicIp::where( - 'id', - (int) $reservation->public_ip_id - )->lockForUpdate()->first(); if (!in_array((string) $order->status, ['queued', 'failed', 'uncertain'], true) || $order->refunded_at !== null @@ -2720,36 +2722,7 @@ final class CloudWorkerService || strtoupper((string) $provisionInvoice->currency) !== strtoupper((string) $order->currency) || CloudMoney::cents((string) $provisionInvoice->amount) - !== CloudMoney::cents((string) $order->amount) - || $reservation === null - || (int) $reservation->order_id !== (int) $order->id - || (int) $reservation->user_id !== (int) $order->user_id - || (int) $reservation->offer_id !== (int) $order->offer_id - || (int) $reservation->resource_pool_id - !== (int) $order->resource_pool_id - || (int) $reservation->host_id !== (int) $order->host_id - || !hash_equals( - (string) $job->operation_id, - (string) $reservation->operation_id - ) - || !in_array((string) $reservation->state, - ['held', 'uncertain'], true) - || $reservation->instance_id !== null - || $publicIp === null - || (int) $publicIp->host_id !== (int) $reservation->host_id - || (int) ($publicIp->reservation_id ?? 0) - !== (int) $reservation->id - || !hash_equals( - (string) $reservation->operation_id, - (string) ($publicIp->operation_id ?? '') - ) - || !in_array((string) $publicIp->state, - ['reserved', 'uncertain'], true) - || !hash_equals( - (string) $publicIp->address . '/' - . (int) $publicIp->prefix_length, - $confirmedPublicIpCidr - )) { + !== CloudMoney::cents((string) $order->amount)) { throw new CloudRecoveryInstanceStateConflict( '开通成功回执与资金、库存或资源预留账本不一致', 409 @@ -2765,7 +2738,7 @@ final class CloudWorkerService $instance->offer_id = $order->offer_id; $instance->resource_pool_id = $order->resource_pool_id; $instance->reservation_id = $order->reservation_id; - $spec = json_decode((string) $order->spec_json, true) ?: []; + $spec = $orderSpec; $templateMetadata = self::trustedTemplateMetadata($payload); $spec = array_replace($spec, $templateMetadata); $now = time(); @@ -2825,6 +2798,8 @@ final class CloudWorkerService } // A VM is panel-managed only after the Agent's exact create // operation has returned the validated success above. + $instanceSpec['public_network'] = + $confirmedPublicNetwork->toArray(); $instanceSpec['managed'] = true; $instance->spec_json = json_encode( $instanceSpec, @@ -2852,7 +2827,9 @@ final class CloudWorkerService $instance->updated_at = time(); $instance->save(); CloudPlacementService::commit( - $order, (int) $instance->id, $confirmedPublicIpCidr + $order, + (int) $instance->id, + $confirmedPublicNetwork->toArray() ); // Seed the independent runtime observation immediately after // provisioning. If the Agent returned a trusted power diff --git a/web/tests/AdminResourceSchedulingContractTest.php b/web/tests/AdminResourceSchedulingContractTest.php index 2f0ac69e..44ff26dd 100644 --- a/web/tests/AdminResourceSchedulingContractTest.php +++ b/web/tests/AdminResourceSchedulingContractTest.php @@ -83,13 +83,16 @@ $assert(str_contains($placement, "CloudResourceReservation::where('order_id', (int) \$order->id)->exists()") && !str_contains($placement, 'restoreExisting('), 'Final placement capacity must use a current locking read after the host sentinel, not a repeatable-read aggregate snapshot.'); -$assert(str_contains($worker, '$requestedPublicIpCidr') - && str_contains($worker, '$confirmedPublicIpCidr') - && str_contains($worker, "'Agent 成功结果与预留公网 IP 不一致,必须人工核查'") +$assert(str_contains($worker, '$frozenPublicNetwork') + && str_contains($worker, '$requestedPublicNetwork') + && str_contains($worker, '$confirmedPublicNetwork') + && str_contains($worker, + "'Agent 成功结果与预留双栈公网不一致,必须人工核查'") && str_contains($placement, - '(string) $ip->address . \'/\' . (int) $ip->prefix_length') - && str_contains($placement, '$confirmedPublicIpCidr'), - 'Create reconciliation must match requested, confirmed, and reserved public IPs before committing the ledger.'); + 'CloudPublicNetworkAllocationService::commitBundle(') + && str_contains($placement, '$confirmed->fingerprint()') + && str_contains($placement, '$allocated->fingerprint()'), + 'Create reconciliation must match frozen, requested, confirmed, and reserved dual-stack networks before committing the ledger.'); $refundStart = strpos($createFinalizer, 'public static function refundAndReleaseLocked('); $refundEnd = $refundStart === false ? false diff --git a/web/tests/CloudAdminOperationRecoveryServiceTest.php b/web/tests/CloudAdminOperationRecoveryServiceTest.php index 04ad644a..c8b1039b 100644 --- a/web/tests/CloudAdminOperationRecoveryServiceTest.php +++ b/web/tests/CloudAdminOperationRecoveryServiceTest.php @@ -184,6 +184,29 @@ namespace { $table->integer('user_id'); $table->string('status'); }); + $capsule->schema('default')->create('cloud_orders', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('offer_id'); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('reservation_id'); + $table->text('spec_json'); + }); + $capsule->schema('default')->create('cloud_resource_reservations', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('order_id')->nullable(); + $table->integer('backup_restore_id')->nullable(); + $table->integer('offer_id')->nullable(); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('instance_id')->nullable(); + $table->string('operation_id'); + $table->string('state'); + }); $now = time(); foreach ([ 41 => 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', @@ -191,11 +214,58 @@ namespace { 43 => 'cccccccccccccccccccccccccccccccc', 44 => 'dddddddddddddddddddddddddddddddd', ] as $id => $operationId) { + $publicNetwork = [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.' . $id . '/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::' . $id . '/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => [ + '1.1.1.1', + '2606:4700:4700::1111', + ], + ]; + $reservationId = 1000 + $id; + Capsule::table('cloud_orders')->insert([ + 'id' => $id, + 'user_id' => 99, + 'offer_id' => 1, + 'resource_pool_id' => 1, + 'host_id' => 7, + 'reservation_id' => $reservationId, + 'spec_json' => json_encode([ + 'source' => 'cloud', + 'public_network' => $publicNetwork, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), + ]); + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => $reservationId, + 'order_id' => $id, + 'backup_restore_id' => null, + 'offer_id' => 1, + 'resource_pool_id' => 1, + 'host_id' => 7, + 'user_id' => 99, + 'instance_id' => null, + 'operation_id' => $operationId, + 'state' => 'uncertain', + ]); Capsule::table('cloud_jobs')->insert([ 'id' => $id, 'operation_id' => $operationId, 'host_id' => 7, 'request_idempotency_key' => $operationId, 'request_fingerprint' => hash('sha256', $operationId), - 'kind' => 'create', 'order_id' => 100, + 'kind' => 'create', 'order_id' => $id, 'phase' => 'terminal', 'outcome' => 'failed', 'status' => 'failed', 'dispatched_at' => $now - 90, 'dispatch_started_at' => $now - 100, @@ -215,16 +285,11 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', + 'public_network' => $publicNetwork, 'template_id' => 'debian-13', 'template_revision' => 1, 'template_generation_token' => str_repeat('1', 32), 'root_password' => 'StrongPassword!123', - 'public_pool_key' => str_repeat('2', 32), - 'public_pool_cidr' => '203.0.113.0/24', - 'public_ip_cidr' => '203.0.113.41/24', - 'gateway' => '203.0.113.1', - 'dns_servers' => ['1.1.1.1'], 'platform_network_policy_snapshot' => [ 'schema_version' => 1, ], diff --git a/web/tests/CloudAgentMutationIdentityTest.php b/web/tests/CloudAgentMutationIdentityTest.php index 6307fc2b..5393e21f 100644 --- a/web/tests/CloudAgentMutationIdentityTest.php +++ b/web/tests/CloudAgentMutationIdentityTest.php @@ -128,6 +128,29 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_orders', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('offer_id'); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('reservation_id'); + $table->text('spec_json'); + }); + $schema->create('cloud_resource_reservations', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('order_id')->nullable(); + $table->integer('backup_restore_id')->nullable(); + $table->integer('offer_id')->nullable(); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('instance_id')->nullable(); + $table->string('operation_id'); + $table->string('state'); + }); $now = time(); $createBody = static function (string $operationId, int $suffix): array { @@ -139,16 +162,33 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', + 'public_network' => [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.' . $suffix . '/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('3', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::' + . $suffix . '/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => [ + '1.1.1.1', + '2606:4700:4700::1111', + ], + ], 'template_id' => 'debian-13', 'template_revision' => 1, 'template_generation_token' => str_repeat('1', 32), 'root_password' => 'Identity-test9!Pass', - 'public_pool_key' => str_repeat('2', 32), - 'public_pool_cidr' => '203.0.113.0/24', - 'public_ip_cidr' => '203.0.113.' . $suffix . '/24', - 'gateway' => '203.0.113.1', - 'dns_servers' => ['1.1.1.1'], 'platform_network_policy_snapshot' => ['schema_version' => 1], ]; }; @@ -156,11 +196,38 @@ namespace { int $id, string $operationId ) use ($createBody, $now): void { + $orderId = 1000 + $id; + $reservationId = 2000 + $id; + $body = $createBody($operationId, 20 + $id); + Capsule::table('cloud_orders')->insert([ + 'id' => $orderId, + 'user_id' => 11, + 'offer_id' => 1, + 'resource_pool_id' => 1, + 'host_id' => 7, + 'reservation_id' => $reservationId, + 'spec_json' => json_encode([ + 'source' => 'cloud', + 'public_network' => $body['public_network'], + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), + ]); + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => $reservationId, + 'order_id' => $orderId, + 'backup_restore_id' => null, + 'offer_id' => 1, + 'resource_pool_id' => 1, + 'host_id' => 7, + 'user_id' => 11, + 'instance_id' => null, + 'operation_id' => $operationId, + 'state' => 'held', + ]); Capsule::table('cloud_jobs')->insert([ 'id' => $id, 'host_id' => 7, 'user_id' => 11, - 'order_id' => 1000 + $id, + 'order_id' => $orderId, 'operation_id' => $operationId, 'execution_mode' => 'agent', 'kind' => 'create', @@ -172,7 +239,7 @@ namespace { 'sealed_payload' => CloudSecrets::encrypt([ 'method' => 'POST', 'request_target' => '/v1/vms', - 'body' => $createBody($operationId, 20 + $id), + 'body' => $body, 'credential' => [ 'password' => 'Identity-test9!Pass', 'login_name' => 'root', diff --git a/web/tests/CloudDefaultNetworkNonAuthorityTest.php b/web/tests/CloudDefaultNetworkNonAuthorityTest.php index 22142221..40eff9c5 100644 --- a/web/tests/CloudDefaultNetworkNonAuthorityTest.php +++ b/web/tests/CloudDefaultNetworkNonAuthorityTest.php @@ -18,6 +18,9 @@ $storage = $read( $console = $read('app/Services/Cloud/CloudConsoleTicketService.php'); $hostController = $read('app/Controllers/CloudAdminController.php'); $placement = $read('app/Services/Cloud/CloudPlacementService.php'); +$publicNetwork = $read( + 'app/Services/Cloud/CloudPublicNetworkAllocationService.php' +); $restore = $read('app/Services/Cloud/CloudBackupService.php'); $migration = $read( 'app/Services/Cloud/CloudInstanceMigrationService.php' @@ -44,7 +47,9 @@ $assert(str_contains($hostController, "'default_network'") 'Compatibility host metadata is missing or still invalidates Agent state.'); $assert(str_contains($placement, - '$payload[\'body\'][\'network\'] = (string) $attachment->network_selector;') + "\$payload['body']['public_network'] = \$publicNetwork->toArray();") + && str_contains($publicNetwork, + "'network_selector' => (string) \$attachment->network_selector") && str_contains($restore, "'network' => (string) \$network['network']") && str_contains($migration, diff --git a/web/tests/CloudDualStackPlacementAdvisoryTest.php b/web/tests/CloudDualStackPlacementAdvisoryTest.php new file mode 100644 index 00000000..f12be858 --- /dev/null +++ b/web/tests/CloudDualStackPlacementAdvisoryTest.php @@ -0,0 +1,251 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('default_network')->default('bridge:br0'); + $table->string('endpoint')->default('https://host.invalid'); +}); +$schema->create('cloud_host_agents', static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + $table->boolean('enabled'); + $table->integer('revision'); + $table->integer('tested_revision'); + $table->string('last_test_status'); + $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); +}); +$schema->create('cloud_host_network_attachments', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('line_id'); + $table->string('network_selector'); + $table->string('state'); + $table->integer('priority'); + $table->string('verification_state'); + $table->integer('verified_agent_revision'); + $table->integer('last_verified_at'); +}); +$schema->create('cloud_public_ip_pools', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->string('pool_key'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->string('cidr'); + $table->string('gateway'); + $table->boolean('gateway_on_link'); + $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->integer('max_allocations'); + $table->string('state'); + $table->integer('priority'); + $table->integer('desired_revision'); + $table->integer('observed_revision'); + $table->string('sync_state'); +}); +$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'); + $table->integer('reservation_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->string('operation_id')->nullable(); +}); + +Capsule::table('cloud_hosts')->insert(['id' => 1]); +Capsule::table('cloud_host_agents')->insert([ + 'host_id' => 1, + 'enabled' => 1, + 'revision' => 5, + 'tested_revision' => 5, + 'last_test_status' => 'healthy', + 'network_selectors_json' => '["bridge:br0","bridge:br1"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_host_network_attachments')->insert([ + [ + 'id' => 10, + 'host_id' => 1, + 'line_id' => 7, + 'network_selector' => 'bridge:br0', + 'state' => 'active', + 'priority' => 0, + 'verification_state' => 'verified', + 'verified_agent_revision' => 5, + 'last_verified_at' => time(), + ], + [ + 'id' => 11, + 'host_id' => 1, + 'line_id' => 7, + 'network_selector' => 'bridge:br1', + 'state' => 'active', + 'priority' => 1, + 'verification_state' => 'verified', + 'verified_agent_revision' => 5, + 'last_verified_at' => time(), + ], +]); +$common = [ + 'host_id' => 1, + 'state' => 'active', + 'priority' => 0, + 'desired_revision' => 1, + 'observed_revision' => 1, + 'sync_state' => 'applied', + 'reserved_ips_json' => '[]', +]; +Capsule::table('cloud_public_ip_pools')->insert([ + array_merge($common, [ + 'id' => 100, + 'pool_key' => str_repeat('a', 32), + 'network_attachment_id' => 10, + 'address_family' => 4, + 'cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => 0, + 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + 'allocation_start' => null, + 'allocation_end' => null, + 'max_allocations' => 0, + ]), + array_merge($common, [ + 'id' => 200, + 'pool_key' => str_repeat('b', 32), + 'network_attachment_id' => 11, + 'address_family' => 6, + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + 'allocation_start' => '2404:c140:156:3a::10', + 'allocation_end' => '2404:c140:156:3a::ff', + 'max_allocations' => 2, + ]), +]); +Capsule::table('cloud_public_ips')->insert([ + 'id' => 1, + 'host_id' => 1, + 'public_ip_pool_id' => 100, + 'address_family' => 4, + 'address' => '8.8.8.10', + 'prefix_length' => 24, + 'state' => 'available', +]); +$candidate = collect([ + (object) ['id' => 1, 'resource_pool_line_id' => 7], +]); + +$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts( + $candidate + ) === [], + 'Pools split across two attachments were advertised as one dual-stack path.'); +Capsule::table('cloud_public_ip_pools')->where('id', 200)->update([ + 'network_attachment_id' => 10, +]); +$connection = Capsule::connection('default'); +$connection->flushQueryLog(); +$connection->enableQueryLog(); +$available = CloudPlacementNetworkService::advisoryDualStackAvailableHosts( + $candidate +); +$queryCount = count($connection->getQueryLog()); +$connection->disableQueryLog(); +$assert($available === [1 => true] && $queryCount <= 5, + 'A sparse IPv6 pool with capacity was not paired with available IPv4.'); +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => '{}', +]); +$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts( + $candidate + ) === [], + 'A host without current guarded-network capability remained sellable.'); +Capsule::table('cloud_host_agents')->where('host_id', 1)->update([ + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([ + 'observed_revision' => 2, +]); +$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts( + $candidate + ) === [], + 'A pool ahead of its desired revision remained visible as sellable.'); +Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([ + 'observed_revision' => 1, +]); +Capsule::table('cloud_public_ips')->insert([ + [ + 'id' => 2, + 'host_id' => 1, + 'public_ip_pool_id' => 200, + 'address_family' => 6, + 'address' => '2404:c140:156:3a::10', + 'prefix_length' => 64, + 'state' => 'assigned', + 'reservation_id' => null, + 'instance_id' => 90, + 'operation_id' => null, + ], + [ + 'id' => 3, + 'host_id' => 1, + 'public_ip_pool_id' => 200, + 'address_family' => 6, + 'address' => '2404:c140:156:3a::11', + 'prefix_length' => 64, + 'state' => 'changing', + 'reservation_id' => 91, + 'instance_id' => null, + 'operation_id' => str_repeat('c', 32), + ], +]); +$assert(CloudPlacementNetworkService::advisoryDualStackAvailableHosts( + $candidate + ) === [], + 'A changing sparse IPv6 address was omitted from provisioning capacity.'); + +echo "Dual-stack placement advisory tests passed.\n"; diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index c58f3f67..b483da66 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -85,6 +85,29 @@ namespace App\Services\Cloud { ): array { return $setting->testedNetworkSelectors(); } + + public static function publicNetworkReady( + \App\Models\CloudHostAgent $setting, + string $selector, + int $verifiedRevision + ): bool { + if (!$setting->isReady() + || $verifiedRevision !== (int) $setting->revision + || $verifiedRevision !== (int) $setting->tested_revision + || !in_array($selector, + self::testedNetworkSelectors($setting), true)) { + return false; + } + $capabilities = json_decode( + (string) $setting->public_network_capabilities_json, + true + ); + return is_array($capabilities) + && ($capabilities['contract'] ?? null) === 1 + && ($capabilities['dual_stack_required'] ?? null) === true + && ($capabilities['project_owned_filter'] ?? null) === true + && ($capabilities['ndp_guard'] ?? null) === true; + } } } namespace { @@ -150,6 +173,17 @@ namespace { use GuzzleHttp\Psr7\Request; use GuzzleHttp\Exception\ConnectException; $assert = function ($condition, $message) { if (!$condition) { throw new RuntimeException($message); } }; + $bundleState = static function (CloudResourceReservation $reservation, + string $claimState, string $ipState): bool { + $claims = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', (int) $reservation->id) + ->where('state', $claimState)->get(); + return $claims->count() === 2 + && $claims->pluck('address_family')->sort()->values()->all() + === [4, 6] + && CloudPublicIp::whereIn('id', $claims->pluck('public_ip_id')) + ->where('state', $ipState)->count() === 2; + }; /** Strictly unwrap one local PHP-to-Gateway request into its Agent request. */ $agentRequest = static function (array $historyEntry) use ($assert): array { $outer = $historyEntry['request'] ?? null; @@ -248,13 +282,13 @@ namespace { $schema->create('cloud_network_lines', function (Blueprint $t) { $t->increments('id'); $t->integer('region_id'); $t->integer('traffic_pool_group_id')->nullable(); $t->string('code'); $t->string('name'); $t->integer('is_default')->default(0); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_resource_pools', function (Blueprint $t) { $t->increments('id'); $t->integer('line_id'); $t->string('code'); $t->string('name'); $t->string('status'); $t->string('scheduling_policy')->default('balanced'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_hosts', function (Blueprint $t) { $t->increments('id'); $t->string('name'); $t->string('region')->default(''); $t->string('country_code')->default(''); $t->integer('enabled'); $t->integer('resource_pool_id')->nullable(); $t->string('scheduler_state')->default('disabled'); $t->string('default_network'); $t->integer('created_at')->default(0); $t->integer('updated_at')->default(0); }); - $schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->text('network_selectors_json')->default('[]'); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_host_agents', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->text('sealed_api_secret'); $t->integer('enabled')->default(0); $t->integer('revision')->default(1); $t->integer('tested_revision')->default(0); $t->string('last_test_status')->default('never'); $t->string('last_error_code')->default(''); $t->string('last_agent_version')->default(''); $t->text('network_selectors_json')->default('[]'); $t->text('public_network_capabilities_json')->default('{}'); $t->integer('last_tested_at')->default(0); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_storage_configurations', function (Blueprint $t) { $t->integer('host_id')->primary(); $t->integer('revision')->default(0); $t->string('state')->default('applying'); }); $schema->create('cloud_host_resource_pool_memberships', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('resource_pool_id'); $t->string('scheduler_state')->default('disabled'); $t->integer('priority')->default(0); $t->integer('weight')->default(100); $t->integer('revision')->default(1); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['host_id', 'resource_pool_id']); }); $schema->create('cloud_host_network_attachments', function (Blueprint $t) { $t->increments('id'); $t->string('attachment_key'); $t->integer('host_id'); $t->integer('line_id'); $t->string('name'); $t->string('network_mode')->default('selector'); $t->string('network_selector'); $t->integer('vlan_id')->nullable(); $t->integer('routing_table')->nullable(); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('config_revision')->default(1); $t->integer('verified_agent_revision')->default(0); $t->string('verification_state')->default('never'); $t->integer('last_verified_at')->default(0); $t->string('verification_error_code')->default(''); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); - $schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->string('cidr'); $t->string('gateway'); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_public_ip_pools', function (Blueprint $t) { $t->increments('id'); $t->string('pool_key'); $t->integer('host_id'); $t->integer('network_attachment_id'); $t->string('name'); $t->integer('address_family'); $t->string('cidr'); $t->string('gateway'); $t->boolean('gateway_on_link')->default(false); $t->integer('guest_prefix_length'); $t->text('dns_servers_json'); $t->text('reserved_ips_json'); $t->string('allocation_start')->nullable(); $t->string('allocation_end')->nullable(); $t->string('allocation_cursor')->nullable(); $t->integer('max_allocations')->default(0); $t->string('state')->default('active'); $t->integer('priority')->default(0); $t->integer('desired_revision')->default(1); $t->integer('observed_revision')->default(0); $t->string('sync_state')->default('never'); $t->string('last_error_code')->default(''); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_host_capacity_policies', function (Blueprint $t) { $t->integer('host_id')->primary(); foreach (['configured_cpu_cores', 'configured_memory_mib', 'configured_disk_gib', 'safety_cpu_cores', 'safety_memory_mib', 'safety_disk_gib', 'max_instances', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } }); - $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id')->nullable(); $t->string('address')->unique(); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable()->unique(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable()->unique(); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_public_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('host_id'); $t->integer('public_ip_pool_id'); $t->integer('address_family'); $t->string('address'); $t->binary('address_binary'); $t->integer('prefix_length'); $t->string('state'); $t->integer('reservation_id')->nullable(); $t->integer('instance_id')->nullable(); $t->string('operation_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['address_family', 'address_binary']); }); $schema->create('cloud_offers', function (Blueprint $t) { $t->increments('id'); $t->integer('plan_id'); $t->integer('resource_pool_id'); $t->string('code')->unique(); $t->string('name'); $t->string('price'); $t->string('backup_price')->default('0.00'); $t->string('currency')->default('USD'); $t->integer('price_version')->default(1); $t->integer('revision')->default(1); $t->integer('status')->default(1); $t->integer('stock')->default(-1); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['plan_id', 'resource_pool_id']); }); $schema->create('cloud_templates', function (Blueprint $t) { $t->string('id')->primary(); $t->string('catalog_key')->default('test-catalog'); $t->string('version_label')->default('test-version'); $t->boolean('is_default')->default(true); $t->string('name'); $t->string('os_family'); $t->string('os_version'); $t->integer('image_bytes'); $t->string('sha256'); $t->text('startup_script'); $t->integer('revision'); $t->string('generation_token'); $t->string('state'); $t->integer('active_job_id')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_user_isos', function (Blueprint $t) { $t->string('id')->primary(); $t->integer('active_job_id')->nullable(); }); @@ -264,7 +298,9 @@ namespace { $schema->create('cloud_orders', function (Blueprint $t) { $t->increments('id'); foreach (['user_id', 'plan_id', 'offer_id', 'resource_pool_id'] as $v) { $t->integer($v); } $t->integer('host_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('deployment_snapshot_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->string('currency')->default('USD'); $t->string('status'); $t->text('spec_json'); $t->text('sealed_payload')->nullable(); $t->integer('instance_id')->nullable(); $t->integer('refunded_at')->nullable(); $t->integer('stock_reserved_at')->nullable(); $t->integer('stock_released_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_order_items', function (Blueprint $t) { $t->increments('id'); $t->integer('order_id'); $t->string('code'); $t->string('label'); $t->string('amount'); $t->string('currency')->default('USD'); $t->text('snapshot_json'); $t->integer('created_at'); $t->unique(['order_id', 'code']); }); $schema->create('cloud_resource_reservations', function (Blueprint $t) { $t->increments('id'); $t->string('reservation_key')->unique(); $t->string('operation_id')->unique(); $t->integer('order_id')->nullable(); $t->integer('backup_restore_id')->nullable(); $t->integer('offer_id')->nullable(); foreach (['resource_pool_id', 'host_id', 'user_id'] as $v) { $t->integer($v); } $t->integer('instance_id')->nullable(); $t->integer('network_attachment_id')->nullable(); $t->integer('public_ip_pool_id')->nullable(); $t->integer('public_ip_id')->nullable(); foreach (['cpu_cores', 'memory_mib', 'disk_gib'] as $v) { $t->integer($v); } $t->string('state'); $t->integer('expires_at')->nullable(); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique('backup_restore_id'); }); + $schema->create('cloud_resource_reservation_ips', function (Blueprint $t) { $t->increments('id'); $t->integer('reservation_id'); $t->integer('address_family'); $t->integer('network_attachment_id'); $t->integer('public_ip_pool_id'); $t->integer('public_ip_id'); $t->string('operation_id'); $t->string('state'); $t->integer('created_at'); $t->integer('updated_at'); $t->integer('released_at')->nullable(); $t->string('release_reason')->default(''); $t->unique(['reservation_id', 'address_family']); }); $schema->create('cloud_backup_restores', function (Blueprint $t) { $t->increments('id'); $t->string('restore_key')->unique(); $t->integer('backup_id'); $t->integer('target_host_id'); $t->integer('target_instance_id')->nullable(); $t->integer('reservation_id')->nullable()->unique(); $t->integer('job_id')->nullable(); $t->string('operation_id')->unique(); $t->string('new_uuid'); $t->string('new_name'); $t->string('state'); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); }); + $schema->create('cloud_instance_migrations', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('restore_id'); $t->integer('source_host_id'); $t->integer('source_reservation_id'); $t->integer('target_host_id'); $t->integer('target_reservation_id'); $t->string('state'); }); $schema->create('cloud_instance_backups', function (Blueprint $t) { $t->increments('id'); $t->string('backup_key')->unique(); $t->integer('source_instance_id'); $t->integer('source_host_id'); $t->integer('user_id'); $t->string('source_uuid'); $t->string('name'); $t->string('purpose')->default('portable'); $t->string('source')->default('manual'); $t->integer('subscription_id')->nullable(); $t->integer('scheduled_for')->nullable(); $t->string('state')->default('creating'); $t->string('consistency'); $t->string('object_key')->unique(); $t->integer('object_size_bytes')->default(0); $t->integer('virtual_size_bytes')->default(0); $t->string('sha256')->default(''); $t->text('spec_json'); $t->text('sealed_storage_runtime'); $t->text('sealed_credential')->nullable(); $t->integer('storage_revision'); $t->integer('active_job_id')->nullable(); $t->string('last_operation_id')->nullable(); $t->string('error_code')->default(''); $t->integer('ready_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['subscription_id', 'scheduled_for']); }); $schema->create('cloud_deployment_snapshots', function (Blueprint $t) { $t->increments('id'); $t->string('snapshot_key')->unique(); $t->integer('user_id'); $t->integer('backup_id')->unique(); $t->integer('source_instance_id'); $t->string('name'); $t->string('state')->default('ready'); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('error_code')->default(''); $t->integer('ready_at'); $t->integer('deleted_at')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_jobs', function (Blueprint $t) { @@ -370,6 +406,12 @@ namespace { 'last_error_code' => '', 'last_agent_version' => 'test', 'network_selectors_json' => '["bridge:br0","bridge:br1"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), 'last_tested_at' => $now, 'created_at' => $now, 'updated_at' => $now, @@ -383,12 +425,89 @@ namespace { $membership = new CloudHostResourcePoolMembership(); $membership->host_id = $host->id; $membership->resource_pool_id = $pool->id; $membership->scheduler_state = 'active'; $membership->priority = 0; $membership->weight = 100; $membership->created_at = $membership->updated_at = $now; $membership->save(); $attachment = new CloudHostNetworkAttachment(); $attachment->attachment_key = str_repeat('a', 32); $attachment->host_id = $host->id; $attachment->line_id = $line->id; $attachment->name = 'Primary selector'; $attachment->network_mode = 'selector'; $attachment->network_selector = 'bridge:br0'; $attachment->state = 'active'; $attachment->priority = 0; $attachment->config_revision = 1; $attachment->verified_agent_revision = 1; $attachment->verification_state = 'verified'; $attachment->last_verified_at = $now; $attachment->verification_error_code = ''; $attachment->desired_revision = 1; $attachment->observed_revision = 1; $attachment->sync_state = 'applied'; $attachment->last_error_code = ''; $attachment->created_at = $attachment->updated_at = $now; $attachment->save(); $targetAttachment = new CloudHostNetworkAttachment(); $targetAttachment->attachment_key = str_repeat('b', 32); $targetAttachment->host_id = $host->id; $targetAttachment->line_id = $line->id; $targetAttachment->name = 'Secondary selector'; $targetAttachment->network_mode = 'selector'; $targetAttachment->network_selector = 'bridge:br1'; $targetAttachment->state = 'active'; $targetAttachment->priority = 10; $targetAttachment->config_revision = 1; $targetAttachment->verified_agent_revision = 1; $targetAttachment->verification_state = 'verified'; $targetAttachment->last_verified_at = $now; $targetAttachment->verification_error_code = ''; $targetAttachment->desired_revision = 1; $targetAttachment->observed_revision = 0; $targetAttachment->sync_state = 'never'; $targetAttachment->last_error_code = ''; $targetAttachment->created_at = $targetAttachment->updated_at = $now; $targetAttachment->save(); - $sourcePoolKey = str_repeat('1', 32); $targetPoolKey = str_repeat('2', 32); - $sourcePublicPool = new CloudPublicIpPool(); $sourcePublicPool->pool_key = $sourcePoolKey; $sourcePublicPool->host_id = $host->id; $sourcePublicPool->network_attachment_id = $attachment->id; $sourcePublicPool->name = 'Primary public pool'; $sourcePublicPool->cidr = '203.0.113.16/29'; $sourcePublicPool->gateway = '203.0.113.17'; $sourcePublicPool->guest_prefix_length = 28; $sourcePublicPool->dns_servers_json = '["1.1.1.1"]'; $sourcePublicPool->reserved_ips_json = '[]'; $sourcePublicPool->state = 'active'; $sourcePublicPool->priority = 0; $sourcePublicPool->desired_revision = 1; $sourcePublicPool->observed_revision = 1; $sourcePublicPool->sync_state = 'applied'; $sourcePublicPool->last_error_code = ''; $sourcePublicPool->created_at = $sourcePublicPool->updated_at = $now; $sourcePublicPool->save(); - $targetPublicPool = new CloudPublicIpPool(); $targetPublicPool->pool_key = $targetPoolKey; $targetPublicPool->host_id = $host->id; $targetPublicPool->network_attachment_id = $targetAttachment->id; $targetPublicPool->name = 'Secondary public pool'; $targetPublicPool->cidr = '203.0.113.32/29'; $targetPublicPool->gateway = '203.0.113.33'; $targetPublicPool->guest_prefix_length = 28; $targetPublicPool->dns_servers_json = '["1.0.0.1"]'; $targetPublicPool->reserved_ips_json = '[]'; $targetPublicPool->state = 'active'; $targetPublicPool->priority = 10; $targetPublicPool->desired_revision = 1; $targetPublicPool->observed_revision = 1; $targetPublicPool->sync_state = 'applied'; $targetPublicPool->last_error_code = ''; $targetPublicPool->created_at = $targetPublicPool->updated_at = $now; $targetPublicPool->save(); + $makePool = static function (string $key, int $attachmentId, + string $name, int $family, string $cidr, string $gateway, + int $prefix, array $dns, int $priority = 0, + ?string $allocationStart = null, ?string $allocationEnd = null, + int $maxAllocations = 0, bool $gatewayOnLink = false + ) use ($host, $now): CloudPublicIpPool { + $publicPool = new CloudPublicIpPool(); + $publicPool->pool_key = $key; + $publicPool->host_id = $host->id; + $publicPool->network_attachment_id = $attachmentId; + $publicPool->name = $name; + $publicPool->address_family = $family; + $publicPool->cidr = $cidr; + $publicPool->gateway = $gateway; + $publicPool->gateway_on_link = $gatewayOnLink; + $publicPool->guest_prefix_length = $prefix; + $publicPool->dns_servers_json = json_encode($dns, + JSON_THROW_ON_ERROR); + $publicPool->reserved_ips_json = '[]'; + $publicPool->allocation_start = $allocationStart; + $publicPool->allocation_end = $allocationEnd; + $publicPool->allocation_cursor = null; + $publicPool->max_allocations = $maxAllocations; + $publicPool->state = 'active'; + $publicPool->priority = $priority; + $publicPool->desired_revision = 1; + $publicPool->observed_revision = 1; + $publicPool->sync_state = 'applied'; + $publicPool->last_error_code = ''; + $publicPool->created_at = $publicPool->updated_at = $now; + $publicPool->save(); + return $publicPool; + }; + $sourcePoolKey = str_repeat('1', 32); + $sourceIpv6PoolKey = str_repeat('3', 32); + $targetPoolKey = str_repeat('2', 32); + $targetIpv6PoolKey = str_repeat('4', 32); + $sourcePublicPool = $makePool( + $sourcePoolKey, (int) $attachment->id, 'Primary IPv4 pool', + 4, '8.8.8.0/24', '8.8.8.1', 24, ['1.1.1.1'] + ); + $sourceIpv6Pool = $makePool( + $sourceIpv6PoolKey, (int) $attachment->id, 'Primary IPv6 pool', + 6, '2404:c140:156:3a::/64', '2404:c140:156::1', 64, + ['2606:4700:4700::1111'], 0, '2404:c140:156:3a::10', + '2404:c140:156:3a::ff', 32, true + ); + $targetPublicPool = $makePool( + $targetPoolKey, (int) $targetAttachment->id, 'Secondary IPv4 pool', + 4, '9.9.9.0/24', '9.9.9.1', 24, ['1.0.0.1'], 10 + ); + $targetIpv6Pool = $makePool( + $targetIpv6PoolKey, (int) $targetAttachment->id, + 'Secondary IPv6 pool', 6, '2606:4700:4700:100::/64', + '2606:4700:4700:100::1', 64, ['2606:4700:4700::1001'], + 10, '2606:4700:4700:100::10', + '2606:4700:4700:100::ff', 32 + ); $policy = new CloudHostCapacityPolicy(); $policy->host_id = $host->id; $policy->configured_cpu_cores = 64; $policy->configured_memory_mib = 131072; $policy->configured_disk_gib = 4096; $policy->safety_cpu_cores = 2; $policy->safety_memory_mib = 2048; $policy->safety_disk_gib = 64; $policy->max_instances = 100; $policy->created_at = $policy->updated_at = $now; $policy->save(); - foreach (['203.0.113.18', '203.0.113.19'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $sourcePublicPool->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); } - foreach (['203.0.113.34', '203.0.113.35'] as $address) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $targetPublicPool->id; $ip->address = $address; $ip->prefix_length = 28; $ip->state = 'available'; $ip->created_at = $ip->updated_at = $now; $ip->save(); } + foreach (['8.8.8.10', '8.8.8.11'] as $address) { + $ip = new CloudPublicIp(); + $ip->host_id = $host->id; + $ip->public_ip_pool_id = $sourcePublicPool->id; + $ip->address_family = 4; + $ip->address = $address; + $ip->address_binary = inet_pton($address); + $ip->prefix_length = 24; + $ip->state = 'available'; + $ip->created_at = $ip->updated_at = $now; + $ip->save(); + } + foreach (['9.9.9.10', '9.9.9.11'] as $address) { + $ip = new CloudPublicIp(); + $ip->host_id = $host->id; + $ip->public_ip_pool_id = $targetPublicPool->id; + $ip->address_family = 4; + $ip->address = $address; + $ip->address_binary = inet_pton($address); + $ip->prefix_length = 24; + $ip->state = 'available'; + $ip->created_at = $ip->updated_at = $now; + $ip->save(); + } $plan = new Shop(); $plan->name = 'plan'; $plan->cpu_cores = 2; $plan->memory_mib = 2048; $plan->bandwidth_mbps = 100; $plan->disk_gib = 20; $plan->validity_days = 30; $plan->traffic_quota_bytes = 1024 * 1024 * 1024; $plan->status = 1; $plan->sort = 0; $plan->save(); $soldOutPlan = new Shop(); $soldOutPlan->name = 'sold-out-plan'; $soldOutPlan->cpu_cores = 2; $soldOutPlan->memory_mib = 2048; $soldOutPlan->bandwidth_mbps = 100; $soldOutPlan->disk_gib = 20; $soldOutPlan->validity_days = 30; $soldOutPlan->traffic_quota_bytes = 1024 * 1024 * 1024; $soldOutPlan->status = 1; $soldOutPlan->sort = 0; $soldOutPlan->save(); $offer = new CloudOffer(); $offer->plan_id = $plan->id; $offer->resource_pool_id = $pool->id; $offer->code = 'test-offer'; $offer->name = 'Test Offer'; $offer->price = '9.99'; $offer->backup_price = '2.50'; $offer->currency = 'USD'; $offer->price_version = 1; $offer->status = 1; $offer->stock = 10; $offer->sort = 0; $offer->created_at = $offer->updated_at = $now; $offer->save(); @@ -456,7 +575,7 @@ namespace { $assert(count($catalog['offers'] ?? []) === 2 && ($catalog['offers'][0]['sellable'] ?? null) === true && ($catalog['offers'][1]['sellable'] ?? null) === false - && $catalogQueryCount <= 6, + && $catalogQueryCount <= 10, 'Catalog availability hid a sold-out offer, misclassified capacity, or queried per offer.'); $host->default_network = 'public'; $host->save(); @@ -696,6 +815,9 @@ namespace { (string) CloudOrder::find($first->id)->spec_json, true, flags: JSON_THROW_ON_ERROR )['platform_network_policy_snapshot'] ?? null; + $openingClaims = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', (int) ($openingReservation->id ?? 0)) + ->orderBy('address_family')->get(); $assert((string) $paidOpeningAgain->status === 'paid' && User::find(1)->money === '90.01' && $openingOrder->status === 'queued' @@ -705,11 +827,17 @@ namespace { && (int) $openingReservation->cpu_cores === 2 && (int) $openingReservation->memory_mib === 2048 && (int) $openingReservation->disk_gib === 20 - && (int) $openingReservation->network_attachment_id === (int) $attachment->id - && (int) $openingReservation->public_ip_pool_id - === (int) $sourcePublicPool->id + && $openingReservation->network_attachment_id === null + && $openingReservation->public_ip_pool_id === null + && $openingReservation->public_ip_id === null + && $openingClaims->count() === 2 + && $openingClaims->pluck('address_family')->all() === [4, 6] + && $openingClaims->every( + static fn ($claim): bool => (string) $claim->state === 'reserved' + ) && (string) $openingJob->operation_id === (string) $openingReservation->operation_id - && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'reserved' + && CloudPublicIp::whereIn('id', $openingClaims->pluck('public_ip_id')) + ->where('state', 'reserved')->count() === 2 && CloudJob::where('order_id', $first->id)->count() === 1 && is_array($queuedPolicy) && $queuedPolicy === $orderPolicy @@ -723,6 +851,10 @@ namespace { && ($openingSpec['os_source'] ?? null) === 'cloud_template' && ($openingSpec['os_name'] ?? null) === 'AlmaLinux 10' && ($openingSpec['login_name'] ?? null) === 'root' + && ($openingSpec['public_network']['ipv4']['address_cidr'] ?? null) + === '8.8.8.10/24' + && ($openingSpec['public_network']['ipv6']['address_cidr'] ?? null) + === '2404:c140:156:3a::10/64' && !array_key_exists('managed', $openingSpec) && CloudPlatformTestNetworkPolicy::assertSnapshot($queuedPolicy) === $queuedPolicy @@ -748,13 +880,14 @@ namespace { 'format' => 'qcow2', ]], 'autostart' => true, - 'public_pool_key' => $sourcePoolKey, - 'public_ip_cidr' => '203.0.113.18/28', + 'public_network' => $openingSpec['public_network'], 'console_port' => 5908, 'generated_password' => 'must-not-persist', ]; + $mismatchedNetwork = $openingSpec['public_network']; + $mismatchedNetwork['ipv4']['address_cidr'] = '8.8.8.11/24'; $mismatchedVm = array_replace($createdVm, [ - 'public_ip_cidr' => '203.0.113.19/28', + 'public_network' => $mismatchedNetwork, ]); $mock = new MockHandler([ new Response(200, [], json_encode([ @@ -788,7 +921,9 @@ namespace { && (string) \App\Models\CloudServicePeriod::first()->traffic_quota_mode === 'finite' && CloudResourceReservation::where('order_id', $first->id)->first()->state === 'committed' - && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'assigned' + && CloudPublicIp::whereIn('id', $openingClaims->pluck('public_ip_id')) + ->where('state', 'assigned')->whereNotNull('instance_id') + ->count() === 2 && CloudInvoice::find($openingInvoice->id)->instance_id !== null && CloudMailOutbox::where('invoice_id', $openingInvoice->id) ->where('kind', 'provision_succeeded')->count() === 1 @@ -815,8 +950,9 @@ namespace { $openingAgentRequest['headers']['X-Virt-Actor'], '-_', '+/' )), true); $assert($posted['vcpu'] === 2 && $posted['bandwidth_mbps'] === 100 - && $posted['network'] === 'bridge:br0' - && $posted['public_pool_key'] === $sourcePoolKey + && !array_key_exists('network', $posted) + && ($posted['public_network'] ?? null) + === $openingSpec['public_network'] && ($posted['platform_network_policy_snapshot'] ?? null) === $queuedPolicy && $signedActor['can_manage'] === true @@ -835,7 +971,8 @@ namespace { $instanceSpec = json_decode((string) $instance->spec_json, true, flags: JSON_THROW_ON_ERROR); $assert($instance->name === 'vm-one' - && ($instanceSpec['public_ip_cidr'] ?? null) === '203.0.113.18/28' + && ($instanceSpec['public_network'] ?? null) + === $openingSpec['public_network'] && ($instanceSpec['os_source'] ?? null) === 'cloud_template' && ($instanceSpec['os_name'] ?? null) === 'AlmaLinux 10' && ($instanceSpec['login_name'] ?? null) === 'root' @@ -848,7 +985,8 @@ namespace { 'Successful provisioning did not persist the safe Agent metadata snapshot.'); \App\Services\Cloud\CloudPlacementService::markUncertain($openingOrder->fresh()); $assert(CloudResourceReservation::find($openingReservation->id)->state === 'committed' - && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'assigned', + && CloudPublicIp::whereIn('id', $openingClaims->pluck('public_ip_id')) + ->where('state', 'assigned')->count() === 2, 'A late uncertainty marker rolled a committed reservation or assigned IP backward.'); // An unpaid provisioning reservation expires without entering the worker @@ -1021,165 +1159,29 @@ namespace { $deploymentSnapshot->created_at = $deploymentSnapshot->updated_at = time(); $deploymentSnapshot->save(); - $failed = CloudOrderService::purchase([ - 'offer_id' => (int) $offer->id, - 'source' => 'deployment_snapshot', - 'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key, - 'name' => 'vm-two', - 'automatic_backup' => false, - 'idempotency_key' => 'test-request-key-0002', - ], $actor); - $failedSpec = json_decode( - (string) $failed->spec_json, - true, - 64, - JSON_THROW_ON_ERROR - ); - $assert((int) $failed->deployment_snapshot_id - === (int) $deploymentSnapshot->id - && ($failedSpec['source'] ?? null) === 'deployment_snapshot' - && (int) ($failedSpec['deployment_snapshot_id'] ?? 0) - === (int) $deploymentSnapshot->id - && ($failedSpec['cloud_snapshot_key'] ?? null) - === $deploymentSnapshot->snapshot_key - && (int) ($failedSpec['backing_backup_id'] ?? 0) - === (int) $sourceBackup->id - && ($failedSpec['backing_backup_key'] ?? null) - === $sourceBackup->backup_key, - 'Cloud snapshot purchase did not freeze its snapshot and backing object identity.'); - $assert(User::find(1)->money === '90.01' - && CloudJob::where('order_id', $failed->id)->count() === 0, - 'A second unpaid deployment charged or entered the worker queue.'); - $deploymentSnapshot->state = 'deleting'; - $deploymentSnapshot->updated_at = time(); - $deploymentSnapshot->save(); - try { - CloudInvoiceService::payBalance( - CloudInvoice::where('order_id', $failed->id)->first(), - $actor, - 'snapshot-not-ready-payment-0001' - ); - throw new RuntimeException( - 'A non-ready cloud snapshot entered the worker queue.' - ); - } catch (CloudError $error) { - $assert($error->httpStatus === 404, - 'A non-ready cloud snapshot returned the wrong payment error.'); - } - $assert(User::find(1)->money === '90.01' - && CloudJob::where('order_id', $failed->id)->count() === 0 - && (string) CloudOrder::find($failed->id)->status - === 'awaiting_payment', - 'Rejected cloud snapshot payment changed money or finance state.'); - $deploymentSnapshot->state = 'ready'; - $deploymentSnapshot->updated_at = time(); - $deploymentSnapshot->save(); - $originalBackingSha256 = (string) $sourceBackup->sha256; - $sourceBackup->sha256 = str_repeat('b', 64); - $sourceBackup->updated_at = time(); - $sourceBackup->save(); + $snapshotOrderCount = CloudOrder::count(); + $snapshotInvoiceCount = CloudInvoice::count(); try { - CloudInvoiceService::payBalance( - CloudInvoice::where('order_id', $failed->id)->first(), - $actor, - 'snapshot-identity-payment-0001' - ); + CloudOrderService::purchase([ + 'offer_id' => (int) $offer->id, + 'source' => 'deployment_snapshot', + 'cloud_snapshot_key' => $deploymentSnapshot->snapshot_key, + 'name' => 'vm-two', + 'automatic_backup' => false, + 'idempotency_key' => 'test-request-key-0002', + ], $actor); throw new RuntimeException( - 'A changed cloud snapshot backing object entered the worker queue.' + 'Cloud snapshot provisioning crossed the C7 compatibility gate.' ); } catch (CloudError $error) { - $assert($error->httpStatus === 409, - 'A changed cloud snapshot backing object returned the wrong payment error.'); + $assert($error->httpStatus === 503 + && str_contains($error->getMessage(), '升级双栈网络'), + 'Cloud snapshot provisioning returned the wrong C7 gate.'); } - $assert(User::find(1)->money === '90.01' - && CloudJob::where('order_id', $failed->id)->count() === 0 - && (string) CloudOrder::find($failed->id)->status - === 'awaiting_payment', - 'Backing identity rejection changed money or finance state.'); - $sourceBackup->sha256 = $originalBackingSha256; - $sourceBackup->updated_at = time(); - $sourceBackup->save(); - // Cloud-snapshot provisioning must select from the paid offer's exact - // resource-pool line and current Agent evidence. default_network and the - // attachment sync projection are not placement authorities. - $host->default_network = 'public'; - $host->save(); - $attachment->state = 'draining'; - $attachment->save(); - CloudInvoiceService::payBalance(CloudInvoice::where('order_id', $failed->id)->first(), - $actor, 'provision-balance-test-0002'); - $failedJob = CloudJob::where('order_id', $failed->id)->first(); - $snapshotReservation = CloudResourceReservation::where( - 'order_id', (int) $failed->id - )->first(); - $assert($snapshotReservation !== null - && (int) $snapshotReservation->resource_pool_id === (int) $pool->id - && (int) $snapshotReservation->network_attachment_id - === (int) $targetAttachment->id - && (int) $snapshotReservation->public_ip_pool_id - === (int) $targetPublicPool->id, - 'Cloud snapshot payment did not freeze the exact offer pool and verified attachment.'); - $beforeBackupDispatch = count($history); - $mock->append(new Response(422, [], json_encode(['error' => [ - 'code' => 'invalid_request', - 'message' => '虚拟机参数校验失败', - 'retryable' => false, - 'dispatch_state' => 'not_dispatched', - ]]))); - $worker->tick(); $worker->tick(); - $backupAgentRequest = $agentRequest($history[$beforeBackupDispatch]); - $backupAgentBody = json_decode( - $backupAgentRequest['body'], true, 64, JSON_THROW_ON_ERROR - ); - $assert($backupAgentRequest['method'] === 'POST' - && str_ends_with( - $backupAgentRequest['request_target'], - '/restore-backup' - ) - && ($backupAgentBody['backup_key'] ?? null) - === $sourceBackup->backup_key - && ($backupAgentBody['source_sha256'] ?? null) - === $sourceBackup->sha256 - && ($backupAgentBody['source_size_bytes'] ?? null) - === (int) $sourceBackup->object_size_bytes - && str_starts_with( - (string) ($backupAgentBody['source_url'] ?? ''), - 'https://' - ) - && ($backupAgentBody['source'] ?? null) === '' - && ($backupAgentBody['root_password'] ?? null) === '' - && ($backupAgentBody['network'] ?? null) === 'bridge:br1' - && (int) $failedJob->backup_id === (int) $sourceBackup->id, - 'Paid backup-origin create lost its signed object identity or used the cloud-template endpoint.'); - $host->default_network = 'bridge:br0'; - $host->save(); - $attachment->state = 'active'; - $attachment->save(); - $instance->spec_json = $originalSourceSpec; - $instance->save(); - $subscription->enabled = false; - $subscription->updated_at = time(); - $subscription->save(); - $failedDisplay = CloudOrderService::display(CloudOrder::find($failed->id)); - $failedInvoiceDisplay = CloudInvoiceService::display( - CloudInvoice::where('order_id', $failed->id)->first()); - $assert(User::find(1)->money === '90.01' && CloudOrder::find($failed->id)->refunded_at !== null && CloudOffer::find(1)->stock === 9, - 'A definitive pre-operation Agent rejection was not refunded exactly once.'); - $failedReservation = CloudResourceReservation::where('order_id', $failed->id)->first(); - $assert($failedReservation !== null && $failedReservation->state === 'released' - && CloudPublicIp::find($failedReservation->public_ip_id)->state === 'available', - 'A safely failed create retained host capacity or its public IP.'); - $assert($failedDisplay['job_status'] === 'failed' && $failedDisplay['attempts'] >= 1 - && !array_key_exists('host_id', $failedDisplay) - && !array_key_exists('resource_pool_id', $failedDisplay) - && !array_key_exists('plan_id', $failedDisplay) - && str_contains($failedDisplay['error'], '开通失败,订单已退款') - && ($failedInvoiceDisplay['status'] ?? null) === 'refunded' - && ($failedInvoiceDisplay['order_status'] ?? null) === 'failed' - && str_contains((string) ($failedInvoiceDisplay['error'] ?? ''), - '开通失败,订单已退款') - && CloudMailOutbox::where('kind', 'provision_succeeded')->count() === 1, - 'Safe local failure diagnostics are missing from the unified invoice display.'); + $assert(CloudOrder::count() === $snapshotOrderCount + && CloudInvoice::count() === $snapshotInvoiceCount, + 'The C7 cloud-snapshot gate created financial state.'); + // A failed local TCP connection is not an ambiguous Agent dispatch. // Exercise the full worker/financial path, not only client classification. foreach ([7 => 'refused', 28 => 'connect-timeout'] as $curlError => $failure) { @@ -1215,7 +1217,11 @@ namespace { && !(bool) $gatewayFailureJob->finalization_incident && CloudOrder::find($gatewayFailure->id)->refunded_at !== null && $gatewayFailureReservation->state === 'released' - && CloudPublicIp::find($gatewayFailureReservation->public_ip_id)->state === 'available' + && $bundleState( + $gatewayFailureReservation, + 'released', + 'available' + ) && User::find(1)->money === '90.01' && CloudOffer::find(1)->stock === 9, 'Proven pre-send Gateway failure retained unknown effects, funds or placement.'); @@ -1239,7 +1245,6 @@ namespace { $uncertainReservation = CloudResourceReservation::where( 'order_id', $uncertain->id )->first(); - $uncertainIp = CloudPublicIp::find($uncertainReservation->public_ip_id); $assert($uncertainJob->phase === 'terminal' && $uncertainJob->outcome === 'failed' && $uncertainJob->status === 'failed' @@ -1250,7 +1255,7 @@ namespace { && CloudOrder::find($uncertain->id)->status === 'failed' && CloudOrder::find($uncertain->id)->refunded_at === null && $uncertainReservation->state === 'uncertain' - && $uncertainIp->state === 'uncertain' + && $bundleState($uncertainReservation, 'uncertain', 'uncertain') && User::find(1)->money === '80.02' && ($uncertainInvoiceDisplay['order_status'] ?? null) === 'failed' && CloudMailOutbox::where('kind', 'provision_succeeded')->count() === 1, @@ -1311,8 +1316,11 @@ namespace { ->value('status') === 'refunded' && CloudResourceReservation::find($uncertainReservation->id) ->state === 'released' - && CloudPublicIp::find($uncertainReservation->public_ip_id) - ->state === 'available' + && $bundleState( + CloudResourceReservation::find($uncertainReservation->id), + 'released', + 'available' + ) && User::find(1)->money === '90.01' && CloudOffer::find(1)->stock === 9, 'A prior Agent fence commit was not recovered into one atomic local create settlement.'); @@ -1388,8 +1396,7 @@ namespace { $lateCreatedVm = array_replace($createdVm, [ 'uuid' => $lateCreateIdentity['resource_id'], 'name' => '1:vm-late-create', - 'public_ip_cidr' => $lateCreatePayload['body']['public_ip_cidr'], - 'public_pool_key' => $lateCreatePayload['body']['public_pool_key'], + 'public_network' => $lateCreatePayload['body']['public_network'], ]); unset($lateCreatedVm['generated_password']); $lateReceipt = [ @@ -1505,9 +1512,6 @@ namespace { 'order_id', $lateCreate->id )->firstOrFail(); - $finiteGuardPublicIp = CloudPublicIp::findOrFail( - (int) $finiteGuardReservation->public_ip_id - ); $makeLateCreateRetryable(); $assert((new CloudAutomaticOperationRecoveryService())->tick(), 'Markerless finite-stock create was not retried safely.'); @@ -1519,9 +1523,13 @@ namespace { && (string) CloudResourceReservation::findOrFail( $finiteGuardReservation->id )->state === (string) $finiteGuardReservation->state - && (string) CloudPublicIp::findOrFail( - $finiteGuardPublicIp->id - )->state === (string) $finiteGuardPublicIp->state + && $bundleState( + CloudResourceReservation::findOrFail( + $finiteGuardReservation->id + ), + 'uncertain', + 'uncertain' + ) && (string) User::findOrFail(1)->money === $finiteGuardWallet && (int) CloudOffer::findOrFail(1)->stock === -1, 'A markerless finite-stock order released or refunded fenced ledgers.'); @@ -2291,7 +2299,8 @@ namespace { && CloudJob::find($reinstall->id)->status === 'succeeded' && $reinstalled->sealed_credential !== $oldCredential && ($reinstalledSpec['template_id'] ?? null) === $reinstallTemplate->id - && ($reinstalledSpec['public_ip_cidr'] ?? null) === '203.0.113.18/28' + && ($reinstalledSpec['public_network'] ?? null) + === $openingSpec['public_network'] && ($reinstalledSpec['os_source'] ?? null) === 'cloud_template' && ($reinstalledSpec['os_name'] ?? null) === 'Debian 13' && ($reinstalledSpec['login_name'] ?? null) === 'root' @@ -2365,11 +2374,44 @@ namespace { 'test fixture confirms replacement guest committed'; $partialJob->save(); + // Network-change transition ledgers are migrated in a later IPv6 stage. + // Adapt this pre-existing scalar-only financial scenario to the committed + // IPv4 leg without changing production provisioning authority. + $legacySourceClaim = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', (int) $openingReservation->id) + ->where('address_family', 4)->first(); + $assert($legacySourceClaim !== null, + 'The dual-stack opening reservation has no IPv4 transition fixture.'); + $openingReservation->network_attachment_id = + (int) $legacySourceClaim->network_attachment_id; + $openingReservation->public_ip_pool_id = + (int) $legacySourceClaim->public_ip_pool_id; + $openingReservation->public_ip_id = + (int) $legacySourceClaim->public_ip_id; + $openingReservation->save(); + $legacyInstanceSpec = json_decode( + (string) $instance->fresh()->spec_json, + true, + 64, + JSON_THROW_ON_ERROR + ); + $legacyInstanceSpec['network'] = 'bridge:br0'; + $legacyInstanceSpec['public_pool_key'] = $sourcePoolKey; + $legacyInstanceSpec['public_pool_cidr'] = '8.8.8.0/24'; + $legacyInstanceSpec['public_ip_cidr'] = '8.8.8.10/24'; + $legacyInstanceSpec['gateway'] = '8.8.8.1'; + $legacyInstanceSpec['dns_servers'] = ['1.1.1.1']; + $instance->spec_json = json_encode( + $legacyInstanceSpec, + JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES + ); + $instance->save(); + // A network change reserves only a locally available target. The encrypted // job keeps both ledger IDs, while the Agent receives only its existing // request body. An ambiguous response keeps both addresses unavailable and // a reconciled success atomically moves the reservation to the target. - $networkInput = ['public_ip_cidr' => '203.0.113.34/28', + $networkInput = ['public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true]; try { CloudJobService::enqueue($instance->fresh(), $actor, @@ -2399,7 +2441,7 @@ namespace { try { CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'confirm_restart' => true, ]); throw new RuntimeException('Network change accepted an implicit public pool.'); @@ -2410,7 +2452,7 @@ namespace { try { CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $sourcePoolKey, 'confirm_restart' => true, ]); @@ -2424,7 +2466,7 @@ namespace { try { CloudJobService::enqueue($instance->fresh(), $actor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true, ]); @@ -2442,8 +2484,8 @@ namespace { $sourcePublicPool->observed_revision = 0; $sourcePublicPool->save(); $reservationUpdatedAtBeforeNetwork = (int) $openingReservation->fresh()->updated_at; - $networkTarget = CloudPublicIp::where('address', '203.0.113.34')->first(); - $samePoolSpare = CloudPublicIp::where('address', '203.0.113.19')->first(); + $networkTarget = CloudPublicIp::where('address', '9.9.9.10')->first(); + $samePoolSpare = CloudPublicIp::where('address', '8.8.8.11')->first(); $samePoolSpare->state = 'disabled'; $samePoolSpare->updated_at = time(); $samePoolSpare->save(); @@ -2498,7 +2540,7 @@ namespace { try { CloudJobService::enqueue($instance->fresh(), $targetedPaidActor, 'network_change', 'POST', '/network', [ - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'confirm_restart' => true, ], null, '2.50'); @@ -2610,11 +2652,11 @@ namespace { $networkTarget->refresh(); $assert($networkBody === [ 'confirm_restart' => true, - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'network' => 'bridge:br1', - 'public_pool_cidr' => '203.0.113.32/29', - 'gateway' => '203.0.113.33', + 'public_pool_cidr' => '9.9.9.0/24', + 'gateway' => '9.9.9.1', 'dns_servers' => ['1.0.0.1'], ] && $networkTarget->state === 'changing' @@ -2635,7 +2677,7 @@ namespace { 'safe_to_resubmit' => false, 'error_code' => '', 'result' => [ - 'public_ip_cidr' => '203.0.113.34/28', + 'public_ip_cidr' => '9.9.9.10/24', 'public_pool_key' => $targetPoolKey, 'network_changed' => true, ], @@ -2659,7 +2701,7 @@ namespace { && (int) $networkTarget->instance_id === (int) $instance->id && CloudPublicIp::find($openingReservation->public_ip_id)->state === 'available' && (json_decode((string) $instance->fresh()->spec_json, true)['public_ip_cidr'] ?? null) - === '203.0.113.34/28' + === '9.9.9.10/24' && (string) $paidNetworkInvoice->fresh()->status === 'paid' && (string) User::findOrFail(1)->money === '17.50', 'Completion receipt did not atomically swap the reservation and instance metadata.'); @@ -2670,7 +2712,7 @@ namespace { $releasedNetworkSource->state = 'disabled'; $releasedNetworkSource->updated_at = time(); $releasedNetworkSource->save(); - $failedNetworkTarget = CloudPublicIp::where('address', '203.0.113.35')->first(); + $failedNetworkTarget = CloudPublicIp::where('address', '9.9.9.11')->first(); $failedNetworkActor = $actor + [ 'request_idempotency_key' => 'paid-ip-failure-0001', ]; @@ -2892,7 +2934,7 @@ namespace { 'safe_to_resubmit' => false, 'error_code' => '', 'result' => [ - 'public_ip_cidr' => '203.0.113.35/28', + 'public_ip_cidr' => '9.9.9.11/24', 'public_pool_key' => $targetPoolKey, 'network_changed' => true, ], @@ -2926,7 +2968,7 @@ namespace { && (json_decode( (string) $instance->fresh()->spec_json, true - )['public_ip_cidr'] ?? null) === '203.0.113.35/28' + )['public_ip_cidr'] ?? null) === '9.9.9.11/24' && (string) User::findOrFail(1)->money === '15.00' && (string) $unknownAppliedInvoice->fresh()->status === 'paid' && CloudJobService::blockingQueryForInstance( @@ -2949,6 +2991,34 @@ namespace { && (string) $unknownAppliedInvoice->fresh()->status === 'paid', 'Applied recovery did not publish exactly once with the recovered network and payment ledgers.'); + // The scalar IPv4 transition scenarios above predate the dual-stack + // transition ledger. Restore the canonical committed bundle before the + // C7 delete/settlement scenarios; C11 replaces this fixture bridge with a + // real all-family transition. + $canonicalIpv4Claim = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', (int) $openingReservation->id) + ->where('address_family', 4)->first(); + $canonicalIpv4 = CloudPublicIp::findOrFail( + (int) $canonicalIpv4Claim->public_ip_id + ); + $transitionIpv4 = CloudPublicIp::findOrFail( + (int) $openingReservation->fresh()->public_ip_id + ); + if ((int) $transitionIpv4->id !== (int) $canonicalIpv4->id) { + $transitionIpv4->state = 'available'; + $transitionIpv4->reservation_id = null; + $transitionIpv4->instance_id = null; + $transitionIpv4->operation_id = null; + $transitionIpv4->updated_at = time(); + $transitionIpv4->save(); + } + $canonicalIpv4->state = 'assigned'; + $canonicalIpv4->reservation_id = (int) $openingReservation->id; + $canonicalIpv4->instance_id = (int) $instance->id; + $canonicalIpv4->operation_id = (string) $openingReservation->operation_id; + $canonicalIpv4->updated_at = time(); + $canonicalIpv4->save(); + $interruptedDelete = CloudJobService::enqueue($instance, $actor, 'delete', 'DELETE', '', ['remove_managed_disks' => true]); @@ -3088,8 +3158,10 @@ namespace { $restoredIp = new CloudPublicIp(); $restoredIp->host_id = (int) $host->id; $restoredIp->public_ip_pool_id = (int) $targetPublicPool->id; - $restoredIp->address = '203.0.113.36'; - $restoredIp->prefix_length = 28; + $restoredIp->address_family = 4; + $restoredIp->address = '9.9.9.12'; + $restoredIp->address_binary = inet_pton('9.9.9.12'); + $restoredIp->prefix_length = 24; $restoredIp->state = 'assigned'; $restoredIp->reservation_id = null; $restoredIp->instance_id = null; @@ -3139,7 +3211,7 @@ namespace { 'vcpu' => 2, 'memory_mib' => 2048, 'disk_gib' => 20, - 'public_ip_cidr' => '203.0.113.36/28', + 'public_ip_cidr' => '9.9.9.12/24', ], JSON_THROW_ON_ERROR); $restoredInstance->sealed_credential = 'sealed-restored-credential'; $restoredInstance->created_at = $restoredInstance->updated_at = time(); @@ -4001,13 +4073,15 @@ namespace { // the authenticated terminal failure reaches PHP. Exact Agent proof that // both the guest and every managed artifact are absent must finish the // original paid order locally; it must never dispatch a second create. - foreach (['203.0.113.20', '203.0.113.21', '203.0.113.22'] as $address) { + foreach (['8.8.8.20', '8.8.8.21', '8.8.8.22'] as $address) { if (!CloudPublicIp::where('address', $address)->exists()) { $ip = new CloudPublicIp(); $ip->host_id = $host->id; $ip->public_ip_pool_id = $sourcePublicPool->id; + $ip->address_family = 4; $ip->address = $address; - $ip->prefix_length = 28; + $ip->address_binary = inet_pton($address); + $ip->prefix_length = 24; $ip->state = 'available'; $ip->created_at = $ip->updated_at = time(); $ip->save(); @@ -4083,9 +4157,6 @@ namespace { 'order_id', $lateFailureOrder->id )->firstOrFail(); - $lateFailureIp = CloudPublicIp::findOrFail( - (int) $lateFailureReservation->public_ip_id - ); $walletWhileFenced = (string) User::findOrFail(1)->money; $stockWhileFenced = (int) CloudOffer::findOrFail(1)->stock; $assert((string) $lateFailureJob->phase === 'terminal' @@ -4095,7 +4166,11 @@ namespace { && $lateFailureOrder->refunded_at === null && (string) $lateFailureInvoice->status === 'paid' && (string) $lateFailureReservation->state === 'uncertain' - && (string) $lateFailureIp->state === 'uncertain', + && $bundleState( + $lateFailureReservation, + 'uncertain', + 'uncertain' + ), 'Timed-out dispatched create did not retain its financial fence.'); $lateFailureEventId = 'create-late-failure-event-0001'; @@ -4122,7 +4197,6 @@ namespace { $lateFailureOrder->refresh(); $lateFailureInvoice->refresh(); $lateFailureReservation->refresh(); - $lateFailureIp->refresh(); $lateFailureEvent = \App\Models\CloudAgentCompletionEvent::where( 'event_id', $lateFailureEventId @@ -4139,7 +4213,11 @@ namespace { && $lateFailureOrder->refunded_at !== null && (string) $lateFailureInvoice->status === 'refunded' && (string) $lateFailureReservation->state === 'released' - && (string) $lateFailureIp->state === 'available' + && $bundleState( + $lateFailureReservation, + 'released', + 'available' + ) && (string) User::findOrFail(1)->money === CloudMoney::decimal( CloudMoney::cents($walletWhileFenced) + 999 @@ -4194,7 +4272,8 @@ namespace { $mock, $worker, &$history, - $assert + $assert, + $bundleState ): array { $order = CloudOrderService::purchase(array_replace($input, [ 'name' => 'vm-create-recovery-' . $suffix, @@ -4250,7 +4329,6 @@ namespace { 'order_id', $order->id )->firstOrFail(); - $ip = CloudPublicIp::findOrFail((int) $reservation->public_ip_id); $assert((string) $job->phase === 'terminal' && (string) $job->outcome === 'failed' && (string) $job->effect_resolution === 'unknown' @@ -4258,11 +4336,11 @@ namespace { && $order->refunded_at === null && (string) $invoice->status === 'paid' && (string) $reservation->state === 'uncertain' - && (string) $ip->state === 'uncertain', + && $bundleState($reservation, 'uncertain', 'uncertain'), 'Create recovery fixture did not retain its safety fence: ' . $suffix); return compact( - 'order', 'invoice', 'job', 'identity', 'reservation', 'ip', + 'order', 'invoice', 'job', 'identity', 'reservation', 'historyBefore' ) + [ 'walletBefore' => (string) User::findOrFail(1)->money, @@ -4312,12 +4390,11 @@ namespace { $assertCreateSettled = static function ( array $case, string $message - ) use ($assert, &$history): void { + ) use ($assert, $bundleState, &$history): void { $case['job']->refresh(); $case['order']->refresh(); $case['invoice']->refresh(); $case['reservation']->refresh(); - $case['ip']->refresh(); $assert((string) $case['job']->effect_resolution === 'not_applied' && !(bool) $case['job']->finalization_incident && $case['job']->lease_token === null @@ -4325,7 +4402,11 @@ namespace { && $case['order']->refunded_at !== null && (string) $case['invoice']->status === 'refunded' && (string) $case['reservation']->state === 'released' - && (string) $case['ip']->state === 'available' + && $bundleState( + $case['reservation'], + 'released', + 'available' + ) && (string) User::findOrFail(1)->money === CloudMoney::decimal( CloudMoney::cents($case['walletBefore']) + 999 @@ -4373,7 +4454,6 @@ namespace { $invoiceGuardCase['job']->refresh(); $invoiceGuardCase['order']->refresh(); $invoiceGuardCase['reservation']->refresh(); - $invoiceGuardCase['ip']->refresh(); $invoiceGuardEvent = \App\Models\CloudAgentCompletionEvent::findOrFail( $invoiceGuardReceipt['id'] ); @@ -4386,7 +4466,11 @@ namespace { && (string) $invoiceGuardCase['job']->effect_resolution === 'unknown' && $invoiceGuardCase['order']->refunded_at === null && (string) $invoiceGuardCase['reservation']->state === 'uncertain' - && (string) $invoiceGuardCase['ip']->state === 'uncertain' + && $bundleState( + $invoiceGuardCase['reservation'], + 'uncertain', + 'uncertain' + ) && (string) User::findOrFail(1)->money === $invoiceGuardCase['walletBefore'] && (int) CloudOffer::findOrFail(1)->stock @@ -4400,7 +4484,11 @@ namespace { $invoiceGuardCase['job']->effect_resolution, 'refunded_at' => $invoiceGuardCase['order']->refunded_at, 'reservation' => $invoiceGuardCase['reservation']->state, - 'ip' => $invoiceGuardCase['ip']->state, + 'bundle_uncertain' => $bundleState( + $invoiceGuardCase['reservation'], + 'uncertain', + 'uncertain' + ), 'wallet_before' => $invoiceGuardCase['walletBefore'], 'wallet_after' => User::findOrFail(1)->money, 'stock_before' => $invoiceGuardCase['stockBefore'], @@ -4441,7 +4529,6 @@ namespace { $envelopeCase['order']->refresh(); $envelopeCase['invoice']->refresh(); $envelopeCase['reservation']->refresh(); - $envelopeCase['ip']->refresh(); $envelopeEvent = \App\Models\CloudAgentCompletionEvent::findOrFail( $eventId ); @@ -4455,7 +4542,11 @@ namespace { && $envelopeCase['order']->refunded_at === null && (string) $envelopeCase['invoice']->status === 'paid' && (string) $envelopeCase['reservation']->state === 'uncertain' - && (string) $envelopeCase['ip']->state === 'uncertain' + && $bundleState( + $envelopeCase['reservation'], + 'uncertain', + 'uncertain' + ) && (string) User::findOrFail(1)->money === $envelopeCase['walletBefore'] && (int) CloudOffer::findOrFail(1)->stock @@ -4884,5 +4975,324 @@ namespace { && $conflictCase['order']->fresh()->refunded_at === null, 'Expired create recovery lease contacted Agent or released finance.'); + // Real address exhaustion on the first scored host is a scheduler miss, + // not a corrupt-order failure. The failed host must leave neither its + // temporary reservation nor a partial address claim before placement + // continues with the next host. + $attachment->state = 'active'; + $attachment->verification_state = 'verified'; + $attachment->verified_agent_revision = 1; + $attachment->last_verified_at = time(); + $attachment->save(); + $sourcePublicPool->state = 'active'; + $sourcePublicPool->sync_state = 'applied'; + $sourcePublicPool->desired_revision = 1; + $sourcePublicPool->observed_revision = 1; + $sourcePublicPool->save(); + $sourceIpv6Pool->state = 'active'; + $sourceIpv6Pool->sync_state = 'applied'; + $sourceIpv6Pool->desired_revision = 1; + $sourceIpv6Pool->observed_revision = 1; + $sourceIpv6Pool->allocation_start = '2404:c140:156:3a::10'; + $sourceIpv6Pool->allocation_end = '2404:c140:156:3a::10'; + $sourceIpv6Pool->allocation_cursor = null; + $sourceIpv6Pool->max_allocations = 1; + $sourceIpv6Pool->save(); + Capsule::table('cloud_public_ip_pools') + ->where('id', (int) $sourceIpv6Pool->id) + ->update(['allocation_cursor' => null]); + CloudPublicIp::where('public_ip_pool_id', $sourceIpv6Pool->id)->update([ + 'state' => 'disabled', + 'reservation_id' => null, + 'instance_id' => null, + 'operation_id' => null, + 'updated_at' => time(), + ]); + // Earlier scalar network-change scenarios deliberately reuse and then + // disable concrete IPv4 rows. New provisioning now validates the whole + // pool ledger, so return those test-only rows to the real disabled shape + // before exercising host-capacity fallback. + CloudPublicIp::where('state', 'disabled')->update([ + 'reservation_id' => null, + 'instance_id' => null, + 'operation_id' => null, + 'updated_at' => time(), + ]); + if (!CloudPublicIp::where('address_family', 6) + ->where('address_binary', inet_pton('2404:c140:156:3a::10')) + ->exists()) { + $blockedIpv6 = new CloudPublicIp(); + $blockedIpv6->host_id = (int) $host->id; + $blockedIpv6->public_ip_pool_id = (int) $sourceIpv6Pool->id; + $blockedIpv6->address_family = 6; + $blockedIpv6->address = '2404:c140:156:3a::10'; + $blockedIpv6->address_binary = inet_pton( + '2404:c140:156:3a::10' + ); + $blockedIpv6->prefix_length = 64; + $blockedIpv6->state = 'disabled'; + $blockedIpv6->created_at = $blockedIpv6->updated_at = time(); + $blockedIpv6->save(); + } + if (!CloudPublicIp::where('address_family', 4) + ->where('address_binary', inet_pton('8.8.8.23'))->exists()) { + $fallbackProbeIpv4 = new CloudPublicIp(); + $fallbackProbeIpv4->host_id = (int) $host->id; + $fallbackProbeIpv4->public_ip_pool_id = + (int) $sourcePublicPool->id; + $fallbackProbeIpv4->address_family = 4; + $fallbackProbeIpv4->address = '8.8.8.23'; + $fallbackProbeIpv4->address_binary = inet_pton('8.8.8.23'); + $fallbackProbeIpv4->prefix_length = 24; + $fallbackProbeIpv4->state = 'available'; + $fallbackProbeIpv4->created_at = + $fallbackProbeIpv4->updated_at = time(); + $fallbackProbeIpv4->save(); + } + $targetAttachment->state = 'draining'; + $targetAttachment->save(); + $firstHostPolicy = CloudHostCapacityPolicy::findOrFail((int) $host->id); + $firstHostPolicy->configured_cpu_cores = 1000000; + $firstHostPolicy->configured_memory_mib = 1000000000; + $firstHostPolicy->configured_disk_gib = 1000000000; + $firstHostPolicy->safety_cpu_cores = 0; + $firstHostPolicy->safety_memory_mib = 0; + $firstHostPolicy->safety_disk_gib = 0; + $firstHostPolicy->max_instances = 1000000; + $firstHostPolicy->save(); + + $fallbackHost = new CloudHost(); + $fallbackHost->name = 'fallback-host'; + $fallbackHost->enabled = true; + $fallbackHost->resource_pool_id = $pool->id; + $fallbackHost->scheduler_state = 'active'; + $fallbackHost->default_network = 'bridge:br0'; + $fallbackHost->created_at = $fallbackHost->updated_at = time(); + $fallbackHost->save(); + Capsule::table('cloud_host_agents')->insert([ + 'host_id' => $fallbackHost->id, + 'sealed_api_secret' => 'fallback-test-only-agent-secret', + 'enabled' => 1, + 'revision' => 1, + 'tested_revision' => 1, + 'last_test_status' => 'healthy', + 'last_error_code' => '', + 'last_agent_version' => 'test', + 'network_selectors_json' => '["bridge:br0"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), + 'last_tested_at' => time(), + 'created_at' => time(), + 'updated_at' => time(), + ]); + Capsule::table('cloud_host_storage_configurations')->insert([ + 'host_id' => $fallbackHost->id, + 'revision' => 1, + 'state' => 'applied', + ]); + $fallbackMembership = new CloudHostResourcePoolMembership(); + $fallbackMembership->host_id = $fallbackHost->id; + $fallbackMembership->resource_pool_id = $pool->id; + $fallbackMembership->scheduler_state = 'active'; + $fallbackMembership->priority = 0; + $fallbackMembership->weight = 100; + $fallbackMembership->created_at = + $fallbackMembership->updated_at = time(); + $fallbackMembership->save(); + $fallbackAttachment = new CloudHostNetworkAttachment(); + $fallbackAttachment->attachment_key = str_repeat('9', 32); + $fallbackAttachment->host_id = $fallbackHost->id; + $fallbackAttachment->line_id = $line->id; + $fallbackAttachment->name = 'Fallback dual stack'; + $fallbackAttachment->network_mode = 'selector'; + $fallbackAttachment->network_selector = 'bridge:br0'; + $fallbackAttachment->state = 'active'; + $fallbackAttachment->priority = 0; + $fallbackAttachment->config_revision = 1; + $fallbackAttachment->verified_agent_revision = 1; + $fallbackAttachment->verification_state = 'verified'; + $fallbackAttachment->last_verified_at = time(); + $fallbackAttachment->verification_error_code = ''; + $fallbackAttachment->desired_revision = 1; + $fallbackAttachment->observed_revision = 1; + $fallbackAttachment->sync_state = 'applied'; + $fallbackAttachment->last_error_code = ''; + $fallbackAttachment->created_at = + $fallbackAttachment->updated_at = time(); + $fallbackAttachment->save(); + $fallbackIpv4Pool = new CloudPublicIpPool(); + $fallbackIpv4Pool->pool_key = str_repeat('8', 32); + $fallbackIpv4Pool->host_id = $fallbackHost->id; + $fallbackIpv4Pool->network_attachment_id = $fallbackAttachment->id; + $fallbackIpv4Pool->name = 'Fallback IPv4'; + $fallbackIpv4Pool->address_family = 4; + $fallbackIpv4Pool->cidr = '11.0.0.0/24'; + $fallbackIpv4Pool->gateway = '11.0.0.1'; + $fallbackIpv4Pool->gateway_on_link = false; + $fallbackIpv4Pool->guest_prefix_length = 24; + $fallbackIpv4Pool->dns_servers_json = '["1.1.1.1"]'; + $fallbackIpv4Pool->reserved_ips_json = '[]'; + $fallbackIpv4Pool->allocation_start = null; + $fallbackIpv4Pool->allocation_end = null; + $fallbackIpv4Pool->allocation_cursor = null; + $fallbackIpv4Pool->max_allocations = 0; + $fallbackIpv4Pool->state = 'active'; + $fallbackIpv4Pool->priority = 0; + $fallbackIpv4Pool->desired_revision = 1; + $fallbackIpv4Pool->observed_revision = 1; + $fallbackIpv4Pool->sync_state = 'applied'; + $fallbackIpv4Pool->last_error_code = ''; + $fallbackIpv4Pool->created_at = + $fallbackIpv4Pool->updated_at = time(); + $fallbackIpv4Pool->save(); + $fallbackIpv6Pool = new CloudPublicIpPool(); + $fallbackIpv6Pool->pool_key = str_repeat('7', 32); + $fallbackIpv6Pool->host_id = $fallbackHost->id; + $fallbackIpv6Pool->network_attachment_id = $fallbackAttachment->id; + $fallbackIpv6Pool->name = 'Fallback IPv6'; + $fallbackIpv6Pool->address_family = 6; + $fallbackIpv6Pool->cidr = '2606:4700:4700:200::/64'; + $fallbackIpv6Pool->gateway = '2606:4700:4700:200::1'; + $fallbackIpv6Pool->gateway_on_link = false; + $fallbackIpv6Pool->guest_prefix_length = 64; + $fallbackIpv6Pool->dns_servers_json = '["2606:4700:4700::1111"]'; + $fallbackIpv6Pool->reserved_ips_json = '[]'; + $fallbackIpv6Pool->allocation_start = '2606:4700:4700:200::10'; + $fallbackIpv6Pool->allocation_end = '2606:4700:4700:200::20'; + $fallbackIpv6Pool->allocation_cursor = null; + $fallbackIpv6Pool->max_allocations = 4; + $fallbackIpv6Pool->state = 'active'; + $fallbackIpv6Pool->priority = 0; + $fallbackIpv6Pool->desired_revision = 1; + $fallbackIpv6Pool->observed_revision = 1; + $fallbackIpv6Pool->sync_state = 'applied'; + $fallbackIpv6Pool->last_error_code = ''; + $fallbackIpv6Pool->created_at = + $fallbackIpv6Pool->updated_at = time(); + $fallbackIpv6Pool->save(); + $fallbackIpv4 = new CloudPublicIp(); + $fallbackIpv4->host_id = $fallbackHost->id; + $fallbackIpv4->public_ip_pool_id = $fallbackIpv4Pool->id; + $fallbackIpv4->address_family = 4; + $fallbackIpv4->address = '11.0.0.10'; + $fallbackIpv4->address_binary = inet_pton('11.0.0.10'); + $fallbackIpv4->prefix_length = 24; + $fallbackIpv4->state = 'available'; + $fallbackIpv4->created_at = $fallbackIpv4->updated_at = time(); + $fallbackIpv4->save(); + $fallbackPolicy = new CloudHostCapacityPolicy(); + $fallbackPolicy->host_id = $fallbackHost->id; + $fallbackPolicy->configured_cpu_cores = 4; + $fallbackPolicy->configured_memory_mib = 4096; + $fallbackPolicy->configured_disk_gib = 40; + $fallbackPolicy->safety_cpu_cores = 0; + $fallbackPolicy->safety_memory_mib = 0; + $fallbackPolicy->safety_disk_gib = 0; + $fallbackPolicy->max_instances = 2; + $fallbackPolicy->created_at = $fallbackPolicy->updated_at = time(); + $fallbackPolicy->save(); + $fallbackScoreOrder = new CloudOrder(); + $fallbackScoreOrder->user_id = 1; + $fallbackScoreOrder->plan_id = $plan->id; + $fallbackScoreOrder->offer_id = $offer->id; + $fallbackScoreOrder->resource_pool_id = $pool->id; + $fallbackScoreOrder->host_id = $fallbackHost->id; + $fallbackScoreOrder->reservation_id = null; + $fallbackScoreOrder->deployment_snapshot_id = null; + $fallbackScoreOrder->idempotency_key = 'fallback-score-fixture'; + $fallbackScoreOrder->request_hash = str_repeat('4', 64); + $fallbackScoreOrder->amount = '0.00'; + $fallbackScoreOrder->currency = 'USD'; + $fallbackScoreOrder->status = 'succeeded'; + $fallbackScoreOrder->spec_json = '{}'; + $fallbackScoreOrder->sealed_payload = null; + $fallbackScoreOrder->instance_id = 999999; + $fallbackScoreOrder->refunded_at = null; + $fallbackScoreOrder->stock_reserved_at = null; + $fallbackScoreOrder->stock_released_at = null; + $fallbackScoreOrder->created_at = + $fallbackScoreOrder->updated_at = time(); + $fallbackScoreOrder->save(); + $fallbackScoreReservation = new CloudResourceReservation(); + $fallbackScoreReservation->reservation_key = str_repeat('6', 32); + $fallbackScoreReservation->operation_id = str_repeat('5', 32); + $fallbackScoreReservation->order_id = $fallbackScoreOrder->id; + $fallbackScoreReservation->backup_restore_id = null; + $fallbackScoreReservation->offer_id = $offer->id; + $fallbackScoreReservation->resource_pool_id = $pool->id; + $fallbackScoreReservation->host_id = $fallbackHost->id; + $fallbackScoreReservation->user_id = 1; + $fallbackScoreReservation->instance_id = 999999; + $fallbackScoreReservation->network_attachment_id = null; + $fallbackScoreReservation->public_ip_pool_id = null; + $fallbackScoreReservation->public_ip_id = null; + $fallbackScoreReservation->cpu_cores = 1; + $fallbackScoreReservation->memory_mib = 512; + $fallbackScoreReservation->disk_gib = 1; + $fallbackScoreReservation->state = 'committed'; + $fallbackScoreReservation->expires_at = null; + $fallbackScoreReservation->released_at = null; + $fallbackScoreReservation->release_reason = ''; + $fallbackScoreReservation->created_at = + $fallbackScoreReservation->updated_at = time(); + $fallbackScoreReservation->save(); + $fallbackScoreOrder->reservation_id = $fallbackScoreReservation->id; + $fallbackScoreOrder->save(); + Capsule::table('cloud_template_replicas')->insert([ + 'host_id' => $fallbackHost->id, + 'template_id' => $template->id, + 'revision' => $template->revision, + 'generation_token' => $template->generation_token, + 'state' => 'active', + 'image_bytes' => $template->image_bytes, + 'sha256' => $template->sha256, + 'operation_id' => 'fixture-fallback-template-import', + 'error_code' => '', + 'created_at' => time(), + 'updated_at' => time(), + ]); + $offerForFallback = CloudOffer::findOrFail((int) $offer->id); + $offerForFallback->stock = -1; + $offerForFallback->save(); + $fallbackUser = User::findOrFail(1); + $fallbackUser->money = '100.00'; + $fallbackUser->save(); + $beforeFallbackReservationId = (int) ( + CloudResourceReservation::max('id') ?? 0 + ); + $fallbackOrder = CloudOrderService::purchase(array_replace($input, [ + 'name' => 'vm-host-capacity-fallback', + 'idempotency_key' => 'test-host-capacity-fallback', + ]), $actor); + CloudInvoiceService::payBalance( + CloudInvoice::where('order_id', $fallbackOrder->id)->firstOrFail(), + $actor, + 'provision-host-capacity-fallback' + ); + $fallbackReservation = CloudResourceReservation::where( + 'order_id', + $fallbackOrder->id + )->firstOrFail(); + $assert((int) $fallbackOrder->fresh()->host_id + === (int) $fallbackHost->id + && (int) $fallbackReservation->host_id === (int) $fallbackHost->id + && (int) $fallbackReservation->id + >= $beforeFallbackReservationId + 2 + && Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', (int) $fallbackReservation->id) + ->count() === 2 + && CloudResourceReservation::where('order_id', $fallbackOrder->id) + ->where('host_id', $host->id)->count() === 0 + && Capsule::table('cloud_resource_reservation_ips as claim') + ->leftJoin('cloud_resource_reservations as reservation', + 'reservation.id', '=', 'claim.reservation_id') + ->where('claim.reservation_id', '>', $beforeFallbackReservationId) + ->whereNull('reservation.id')->count() === 0, + 'Capacity fallback did not continue to host two or left host-one ledger residue.'); + echo "Cloud SQLite purchase, provisioning, refund, ambiguity, quota and tenant checks passed (crypto double only).\n"; } diff --git a/web/tests/CloudMailOutboxDispatchTest.php b/web/tests/CloudMailOutboxDispatchTest.php index 90675a72..119dfd39 100644 --- a/web/tests/CloudMailOutboxDispatchTest.php +++ b/web/tests/CloudMailOutboxDispatchTest.php @@ -136,7 +136,28 @@ namespace { $instance->expires_at = $now + 30 * 86400; $instance->spec_json = json_encode([ 'region' => 'HongKong', - 'public_ip_cidr' => $ip . '/24', + 'public_network' => [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('1', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => $ip . '/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('2', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::11/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => [ + '1.1.1.1', + '2606:4700:4700::1111', + ], + ], 'os_name' => 'AlmaLinux 10', 'login_name' => 'root', // Secrets in old snapshots must never be forwarded to a template. @@ -178,7 +199,7 @@ namespace { return $mail; }; - $renewalInstance = $newInstance(1, 'renewal-vm', '203.0.113.10'); + $renewalInstance = $newInstance(1, 'renewal-vm', '8.8.8.10'); $renewal = $newInvoice('VC-MAIL-RENEWAL', 'renewal', 1, $renewalInstance); $renewalMail = $newMail($renewal, 'renewal_due'); $assert(CloudInvoiceService::deliverReminders(1) === 1 @@ -191,7 +212,7 @@ namespace { '实例续费账单已生成'), 'An open automatic renewal bill was not delivered and marked sent.'); - $provisionedInstance = $newInstance(1, 'ready-vm', '203.0.113.11'); + $provisionedInstance = $newInstance(1, 'ready-vm', '8.8.8.11'); $order = new CloudOrder(); $order->user_id = 1; $order->instance_id = $provisionedInstance->id; @@ -217,13 +238,13 @@ namespace { && ($provisionMessage['emailType'] ?? null) === 'cloud_provision_success' && str_contains((string) ($provisionMessage['subject'] ?? ''), '实例开通成功') && ($provisionMessage['data']['instance_name'] ?? null) === 'ready-vm' - && ($provisionMessage['data']['public_ip'] ?? null) === '203.0.113.11' + && ($provisionMessage['data']['public_ip'] ?? null) === '8.8.8.11' && !array_key_exists('root_password', $provisionMessage['data'] ?? []) && !array_key_exists('private_key', $provisionMessage['data'] ?? []), 'The provision-success message is incomplete or contains credentials.'); Mail::$accepted = false; - $retryInstance = $newInstance(1, 'retry-vm', '203.0.113.12'); + $retryInstance = $newInstance(1, 'retry-vm', '8.8.8.12'); $retryInvoice = $newInvoice('VC-MAIL-RETRY', 'renewal', 1, $retryInstance); $retryMail = $newMail($retryInvoice, 'renewal_due'); $assert(CloudInvoiceService::deliverReminders(1) === 0 @@ -239,7 +260,7 @@ namespace { && count(Mail::$messages) === $sentBeforeRetryProbe, 'A terminal failed SMTP message was retried.'); - $otherInstance = $newInstance(2, 'other-tenant-vm', '203.0.113.13'); + $otherInstance = $newInstance(2, 'other-tenant-vm', '8.8.8.13'); $corruptInvoice = $newInvoice('VC-MAIL-CROSS-TENANT', 'renewal', 1, $otherInstance); $corruptMail = $newMail($corruptInvoice, 'renewal_due'); diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index f7991945..5ab5be1b 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -97,7 +97,6 @@ $assert(is_string($jobs) 'Network-change enqueue no longer locks and persists the attachment/pool/address ledger identity.'); $assert(is_string($worker) && str_contains($worker, 'CloudPlacementService::finishNetworkChange') - && str_contains($worker, '$confirmedPublicPoolKey') && str_contains($worker, '$confirmedPoolKey') && str_contains($worker, '$sourceAttachmentId') && str_contains($worker, '$targetAttachmentId') @@ -111,9 +110,10 @@ $assert(is_string($placement) && str_contains($placement, 'cloud_host_resource_pool_memberships as pool_membership') && !str_contains($placement, 'eligible_host.host') && !str_contains($placement, "->where('cloud_hosts.resource_pool_id', \$poolId)") - && str_contains($placement, '$reservation->network_attachment_id = $selectedAttachment->id') - && str_contains($placement, '$reservation->public_ip_pool_id = $selectedPool->id') - && str_contains($placement, '$payload[\'body\'][\'public_pool_key\']') + && str_contains($placement, + 'CloudPublicNetworkAllocationService::reserveBundle(') + && str_contains($placement, + "\$payload['body']['public_network'] = \$publicNetwork->toArray()") && str_contains($placement, '$reservation->public_ip_id = $targetIpId') && str_contains($placement, '$reservation->network_attachment_id = $targetAttachmentId') @@ -129,7 +129,11 @@ $assert(is_string($placement) && str_contains($placement, '$target->state = \'assigned\'') && str_contains($placement, '$target->state = \'uncertain\'') && str_contains($placement, '$source->state = \'available\'') - && str_contains($placement, 'lockedHostAndReservation') + && str_contains($finishMethod, + "CloudHost::where('id', (int) \$instance->host_id)") + && str_contains($finishMethod, + "CloudResourceReservation::where('id',") + && substr_count($finishMethod, 'lockForUpdate()') >= 4 && str_contains($placement, '(string) $reservation->state === \'committed\'') && str_contains($placement, '$ip->instance_id ?? 0'), 'Placement no longer uses membership/pool-scoped allocation or enforce atomic multi-pool ledger swaps.'); diff --git a/web/tests/CloudOperationRecoveryMatrixTest.php b/web/tests/CloudOperationRecoveryMatrixTest.php index 5419ceaf..268654af 100644 --- a/web/tests/CloudOperationRecoveryMatrixTest.php +++ b/web/tests/CloudOperationRecoveryMatrixTest.php @@ -379,14 +379,16 @@ namespace { $schema->create('cloud_resource_reservations', static function (Blueprint $table): void { $table->increments('id'); - $table->integer('backup_restore_id'); + $table->integer('order_id')->nullable(); + $table->integer('backup_restore_id')->nullable(); + $table->integer('offer_id')->nullable(); $table->integer('host_id'); $table->integer('user_id'); $table->integer('resource_pool_id')->nullable(); $table->integer('network_attachment_id')->nullable(); $table->integer('public_ip_pool_id')->nullable(); $table->string('operation_id'); - $table->integer('public_ip_id'); + $table->integer('public_ip_id')->nullable(); $table->integer('instance_id')->nullable(); $table->integer('cpu_cores'); $table->integer('memory_mib'); @@ -398,6 +400,16 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_orders', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('offer_id'); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('reservation_id'); + $table->text('spec_json'); + }); $schema->create('cloud_public_ips', static function (Blueprint $table): void { $table->increments('id'); @@ -2657,6 +2669,25 @@ namespace { 'expected_action' => 'restore-backup:' . $restoreBackupKey, 'expected_resource' => $restoreUuid, ]; + $createPublicNetwork = [ + 'contract' => 1, + 'network_selector' => 'bridge:br0', + 'ipv4' => [ + 'pool_key' => str_repeat('5', 32), + 'pool_cidr' => '8.8.8.0/24', + 'address_cidr' => '8.8.8.30/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => false, + ], + 'ipv6' => [ + 'pool_key' => str_repeat('6', 32), + 'pool_cidr' => '2404:c140:156:3a::/64', + 'address_cidr' => '2404:c140:156:3a::30/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => true, + ], + 'dns_servers' => ['1.1.1.1', '2606:4700:4700::1111'], + ]; $createRecord = $insertJob( 'create', static fn (int $jobId, string $operationId): array => [ @@ -2670,16 +2701,11 @@ namespace { 'memory_mib' => 2048, 'disk_gib' => 40, 'bandwidth_mbps' => 100, - 'network' => 'bridge:br0', 'template_id' => 'debian-13', 'template_revision' => 1, 'template_generation_token' => str_repeat('4', 32), 'root_password' => 'MatrixPassword!123', - 'public_pool_key' => str_repeat('5', 32), - 'public_pool_cidr' => '203.0.113.0/24', - 'public_ip_cidr' => '203.0.113.30/24', - 'gateway' => '203.0.113.1', - 'dns_servers' => ['1.1.1.1'], + 'public_network' => $createPublicNetwork, 'platform_network_policy_snapshot' => [ 'schema_version' => 1, ], @@ -2702,6 +2728,39 @@ namespace { null, 9001 ); + $createReservationId = 9101; + Capsule::table('cloud_orders')->insert([ + 'id' => 9001, + 'user_id' => $ownerId, + 'offer_id' => 1, + 'resource_pool_id' => 1, + 'host_id' => $hostId, + 'reservation_id' => $createReservationId, + 'spec_json' => json_encode([ + 'source' => 'cloud', + 'public_network' => $createPublicNetwork, + ], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES), + ]); + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => $createReservationId, + 'order_id' => 9001, + 'backup_restore_id' => null, + 'offer_id' => 1, + 'host_id' => $hostId, + 'user_id' => $ownerId, + 'resource_pool_id' => 1, + 'network_attachment_id' => null, + 'public_ip_pool_id' => null, + 'operation_id' => $createRecord['operation_id'], + 'public_ip_id' => null, + 'instance_id' => null, + 'cpu_cores' => 2, + 'memory_mib' => 2048, + 'disk_gib' => 40, + 'state' => 'uncertain', + 'created_at' => $now - 180, + 'updated_at' => $now - 20, + ]); $dedicatedFixtures['create'] = $createRecord + [ 'expected_action' => 'create-vm', ]; @@ -3156,6 +3215,21 @@ namespace { $identity['resource_id'] ) === 1, 'Create identity lost its deterministic UUID scope.'); + $tamperedCreate = $fixture['payload']; + $tamperedCreate['body']['public_network']['ipv6'][ + 'address_cidr' + ] = '2404:c140:156:3a::31/64'; + $tamperRejected = false; + try { + CloudOperationRecoveryIdentity::expectedFromPayload( + $fixture['job'], + $tamperedCreate + ); + } catch (CloudError $error) { + $tamperRejected = $error->httpStatus === 409; + } + $assert($tamperRejected, + 'Create recovery accepted a different dual-stack snapshot.'); $projection = $projectionMethod->invoke(null, [ 'creation_absent' => true, 'managed_artifacts_absent' => true, diff --git a/web/tests/CloudProvisioningPublicNetworkContractTest.php b/web/tests/CloudProvisioningPublicNetworkContractTest.php new file mode 100644 index 00000000..d085dafc --- /dev/null +++ b/web/tests/CloudProvisioningPublicNetworkContractTest.php @@ -0,0 +1,121 @@ + ''") + && !str_contains($order, "'public_pool_cidr' => ''") + && !str_contains($order, "'public_ip_cidr' => ''") + && !str_contains($order, "'gateway' => ''"), + 'Unpaid orders still define the retired scalar public-network contract.'); +$snapshotGate = strpos($order, + "if (\$source === 'deployment_snapshot') {"); +$purchaseTransaction = strpos($order, + "return (new User())->getConnection()->transaction("); +$assert($snapshotGate !== false && $purchaseTransaction !== false + && $snapshotGate < $purchaseTransaction + && str_contains(substr($order, $snapshotGate, + $purchaseTransaction - $snapshotGate), + '云快照创建实例正在升级双栈网络,暂不可用'), + 'Deferred cloud-snapshot provisioning is not blocked before billing state is created.'); +$paymentStart = strpos($order, + 'public static function queuePaidProvision('); +$paymentPlacement = strpos($order, + 'CloudPlacementService::reserve(', + $paymentStart === false ? 0 : $paymentStart); +$paymentGate = $paymentStart === false || $paymentPlacement === false + ? '' : substr($order, $paymentStart, + $paymentPlacement - $paymentStart); +$assert(str_contains($paymentGate, + "if (\$source === 'deployment_snapshot')") + && str_contains($paymentGate, + '云快照创建实例正在升级双栈网络,暂不可用'), + 'A pre-existing unpaid cloud-snapshot order can cross the payment boundary.'); +$compactOrder = preg_replace('/\s+/', ' ', $order) ?? $order; +$assert(str_contains($compactOrder, + "\$orderSpec['public_network'] = \$placement['public_network']->toArray();") + && str_contains($order, + "\$placement['payload']['body']['public_network']"), + 'Paid order and dispatched job do not freeze the same public-network snapshot.'); + +foreach (['reserveBundle(', 'commitBundle(', 'fenceBundle(', + 'releaseBundle(', 'releaseCommittedBundle('] as $call) { + $assert(preg_match( + '/CloudPublicNetworkAllocationService::\s*' + . preg_quote($call, '/') . '/', + $placement + ) === 1, + 'Provisioning placement does not use bundle operation: ' . $call); +} +$assert(str_contains($placement, + "\$payload['body']['public_network'] = \$publicNetwork->toArray();") + && str_contains($placement, + "'public_network' => \$publicNetwork"), + 'Placement does not return and dispatch one immutable dual-stack snapshot.'); +$assert(!str_contains($reservation, + "foreach (['network_attachment_id', 'public_ip_pool_id',") + && str_contains($reservation, 'cloud_resource_reservation_ips'), + 'Resource reservations still treat one public_ip_id as network authority.'); + +$compactWorker = preg_replace('/\s+/', ' ', $worker) ?? $worker; +$workerFinalizationStart = strpos($worker, + '$provisionInvoice = CloudInvoice::where('); +$workerCommit = strpos($worker, 'CloudPlacementService::commit(', + $workerFinalizationStart === false ? 0 : $workerFinalizationStart); +$workerPreCommit = $workerFinalizationStart === false || $workerCommit === false + ? '' : substr($worker, $workerFinalizationStart, + $workerCommit - $workerFinalizationStart); +$assert($workerPreCommit !== '' + && !str_contains($workerPreCommit, 'CloudResourceReservation::where('), + 'Create success locks the reservation before canonical placement commit.'); +$tryHostStart = strpos($placement, 'private static function tryHost('); +$allocatorCall = strpos( + $placement, + 'CloudPublicNetworkAllocationService::reserveBundle(', + $tryHostStart === false ? 0 : $tryHostStart +); +$preAllocator = $tryHostStart === false || $allocatorCall === false + ? '' : substr($placement, $tryHostStart, + $allocatorCall - $tryHostStart); +$assert($preAllocator !== '' + && !str_contains($preAllocator, 'lockedCandidates(') + && !str_contains($preAllocator, 'hasCompleteDualStackCandidate('), + 'tryHost can bypass the canonical allocator through a stale precheck.'); +$assert(substr_count($worker, + 'CloudPublicNetworkSnapshot::fromArray(') >= 2 + && str_contains($compactWorker, + "\$instanceSpec['public_network'] = \$confirmedPublicNetwork->toArray();") + && str_contains($worker, + "\$requestedPublicNetwork->fingerprint()") + && str_contains($worker, + "\$confirmedPublicNetwork->fingerprint()"), + 'Create finalization does not compare and persist the exact dual-stack identity.'); +$assert(str_contains($invoice, 'CloudPublicNetworkSnapshot::fromArray(') + && str_contains($invoice, "\$spec['public_network']") + && !str_contains($invoice, "\$spec['public_ip_cidr']"), + 'Provision-success mail still treats scalar public_ip_cidr as authoritative.'); +$assert(substr_count($recovery, + 'CloudPublicNetworkSnapshot::fromArray(') >= 2 + && str_contains($recovery, "\$orderSpec['public_network']") + && str_contains($recovery, "\$body['public_network']"), + 'Create recovery identity is not bound to the frozen dual-stack snapshot.'); + +echo "Dual-stack provisioning call-chain contract passed.\n"; diff --git a/web/tests/CloudProvisioningPublicNetworkLedgerTest.php b/web/tests/CloudProvisioningPublicNetworkLedgerTest.php new file mode 100644 index 00000000..8cbdb240 --- /dev/null +++ b/web/tests/CloudProvisioningPublicNetworkLedgerTest.php @@ -0,0 +1,379 @@ +addConnection([ + 'driver' => 'sqlite', + 'database' => ':memory:', +], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->schema('default'); + +$schema->create('cloud_hosts', static function (Blueprint $table): void { + $table->increments('id'); +}); +$schema->create('cloud_host_agents', static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + $table->boolean('enabled'); + $table->integer('revision'); + $table->integer('tested_revision'); + $table->string('last_test_status'); + $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); +}); +$schema->create('cloud_host_network_attachments', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('line_id'); + $table->string('network_selector'); + $table->string('state'); + $table->integer('priority')->default(0); + $table->string('verification_state'); + $table->integer('verified_agent_revision'); + $table->integer('last_verified_at'); +}); +$schema->create('cloud_public_ip_pools', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->string('pool_key'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->string('cidr'); + $table->string('gateway'); + $table->boolean('gateway_on_link'); + $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'); + $table->string('state'); + $table->integer('priority')->default(0); + $table->integer('desired_revision'); + $table->integer('observed_revision'); + $table->string('sync_state'); +}); +$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->binary('address_binary'); + $table->integer('prefix_length'); + $table->string('state'); + $table->integer('reservation_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->string('operation_id')->nullable(); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->unique(['address_family', 'address_binary']); +}); +$schema->create('cloud_orders', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->integer('offer_id'); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('reservation_id'); +}); +$schema->create('cloud_resource_reservations', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->string('reservation_key'); + $table->string('operation_id'); + $table->integer('order_id')->nullable(); + $table->integer('backup_restore_id')->nullable(); + $table->integer('offer_id')->nullable(); + $table->integer('resource_pool_id'); + $table->integer('host_id'); + $table->integer('user_id'); + $table->integer('instance_id')->nullable(); + $table->integer('network_attachment_id')->nullable(); + $table->integer('public_ip_pool_id')->nullable(); + $table->integer('public_ip_id')->nullable(); + $table->integer('cpu_cores'); + $table->integer('memory_mib'); + $table->integer('disk_gib'); + $table->string('state'); + $table->integer('expires_at')->nullable(); + $table->integer('released_at')->nullable(); + $table->string('release_reason')->default(''); + $table->integer('created_at'); + $table->integer('updated_at'); +}); +$schema->create('cloud_instance_migrations', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('restore_id'); + $table->integer('source_host_id'); + $table->integer('source_reservation_id'); + $table->integer('target_host_id'); + $table->integer('target_reservation_id'); + $table->string('state'); +}); +$schema->create('cloud_resource_reservation_ips', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('address_family'); + $table->integer('network_attachment_id'); + $table->integer('public_ip_pool_id'); + $table->integer('public_ip_id'); + $table->string('operation_id'); + $table->string('state'); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->integer('released_at')->nullable(); + $table->string('release_reason')->default(''); + $table->unique(['reservation_id', 'address_family']); +}); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('order_id')->nullable(); + $table->integer('resource_pool_id'); + $table->integer('reservation_id'); + $table->string('status'); +}); + +Capsule::table('cloud_hosts')->insert(['id' => 1]); +Capsule::table('cloud_host_agents')->insert([ + 'host_id' => 1, + 'enabled' => 1, + 'revision' => 1, + 'tested_revision' => 1, + 'last_test_status' => 'healthy', + 'network_selectors_json' => '["bridge:br0"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), +]); +Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => 10, + 'host_id' => 1, + 'line_id' => 7, + 'network_selector' => 'bridge:br0', + 'state' => 'active', + 'priority' => 0, + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, + 'last_verified_at' => time(), +]); +$poolCommon = [ + 'host_id' => 1, + 'network_attachment_id' => 10, + 'state' => 'active', + 'priority' => 0, + 'desired_revision' => 1, + 'observed_revision' => 1, + 'sync_state' => 'applied', + 'reserved_ips_json' => '[]', +]; +Capsule::table('cloud_public_ip_pools')->insert([ + array_merge($poolCommon, [ + 'id' => 100, + 'pool_key' => str_repeat('a', 32), + 'address_family' => 4, + 'cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'gateway_on_link' => 0, + 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + 'allocation_start' => null, + 'allocation_end' => null, + 'allocation_cursor' => null, + 'max_allocations' => 0, + ]), + array_merge($poolCommon, [ + 'id' => 200, + 'pool_key' => str_repeat('b', 32), + 'address_family' => 6, + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + 'allocation_start' => '2404:c140:156:3a::10', + 'allocation_end' => '2404:c140:156:3a::ff', + 'allocation_cursor' => null, + 'max_allocations' => 8, + ]), +]); +$now = time(); +foreach (range(10, 13) as $suffix) { + $address = '8.8.8.' . $suffix; + Capsule::table('cloud_public_ips')->insert([ + 'host_id' => 1, + 'public_ip_pool_id' => 100, + 'address_family' => 4, + 'address' => $address, + 'address_binary' => inet_pton($address), + 'prefix_length' => 24, + 'state' => 'available', + 'created_at' => $now, + 'updated_at' => $now, + ]); +} + +$reserve = static function (int $id, string $operationId): array { + Capsule::table('cloud_orders')->insert([ + 'id' => $id, + 'user_id' => 40, + 'offer_id' => 50, + 'resource_pool_id' => 60, + 'host_id' => 1, + 'reservation_id' => 1000 + $id, + ]); + Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 1000 + $id, + 'reservation_key' => str_repeat((string) ($id % 10), 32), + 'operation_id' => $operationId, + 'order_id' => $id, + 'backup_restore_id' => null, + 'offer_id' => 50, + 'resource_pool_id' => 60, + 'host_id' => 1, + 'user_id' => 40, + 'instance_id' => null, + 'network_attachment_id' => null, + 'public_ip_pool_id' => null, + 'public_ip_id' => null, + 'cpu_cores' => 2, + 'memory_mib' => 2048, + 'disk_gib' => 20, + 'state' => 'held', + 'expires_at' => null, + 'released_at' => null, + 'release_reason' => '', + 'created_at' => time(), + 'updated_at' => time(), + ]); + return [ + CloudOrder::findOrFail($id), + CloudPublicNetworkAllocationService::reserveBundle( + 1, + 7, + 1000 + $id, + $operationId + ), + ]; +}; + +[$committedOrder, $committedSnapshot] = $reserve(1, str_repeat('1', 32)); +CloudPlacementService::commit( + $committedOrder, + 900, + $committedSnapshot->toArray() +); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001) + ->value('state') === 'committed' + && Capsule::table('cloud_public_ips')->where('instance_id', 900) + ->where('state', 'assigned')->count() === 2, + 'Provisioning commit did not bind the complete public-network bundle.'); +CloudPlacementService::markUncertain($committedOrder->fresh()); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001) + ->value('state') === 'committed' + && Capsule::table('cloud_public_ips')->where('instance_id', 900) + ->where('state', 'assigned')->count() === 2, + 'A late uncertainty marker rolled back a committed network bundle.'); + +[$failedOrder] = $reserve(2, str_repeat('2', 32)); +CloudPlacementService::markUncertain($failedOrder); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1002) + ->value('state') === 'uncertain' + && Capsule::table('cloud_public_ips')->where('reservation_id', 1002) + ->where('state', 'uncertain')->count() === 2, + 'Unknown effect did not fence the complete provisioning bundle.'); +CloudPlacementService::release($failedOrder, 'confirmed-not-applied'); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1002) + ->value('state') === 'released' + && Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 1002)->where('state', 'released')->count() === 2 + && Capsule::table('cloud_public_ips')->where('reservation_id', 1002) + ->count() === 0, + 'Confirmed non-application did not release both address families.'); + +[$recoveredOrder, $recoveredSnapshot] = $reserve(3, str_repeat('3', 32)); +CloudPlacementService::markUncertain($recoveredOrder); +CloudPlacementService::commit( + $recoveredOrder, + 901, + $recoveredSnapshot->toArray() +); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1003) + ->value('state') === 'committed' + && Capsule::table('cloud_public_ips')->where('instance_id', 901) + ->where('state', 'assigned')->count() === 2, + 'A recovered success did not commit its previously fenced bundle.'); + +[$mismatchOrder, $mismatchSnapshot] = $reserve(4, str_repeat('4', 32)); +$wrongSnapshot = $mismatchSnapshot->toArray(); +$wrongSnapshot['ipv4']['address_cidr'] = '8.8.8.99/24'; +$rejects(static fn () => CloudPlacementService::commit( + $mismatchOrder, + 902, + $wrongSnapshot +), 'A create receipt committed a different dual-stack identity.'); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1004) + ->value('state') === 'held' + && Capsule::table('cloud_public_ips')->where('reservation_id', 1004) + ->where('state', 'reserved')->count() === 2, + 'Rejecting a mismatched receipt partially committed the bundle.'); + +Capsule::table('cloud_instances')->insert([ + 'id' => 900, + 'host_id' => 1, + 'order_id' => 1, + 'resource_pool_id' => 60, + 'reservation_id' => 1001, + 'status' => 'deleted', +]); +CloudPlacementService::releaseDeletedInstance( + CloudInstance::findOrFail(900), + 'instance_deleted' +); +$assert(Capsule::table('cloud_resource_reservations')->where('id', 1001) + ->value('state') === 'released' + && Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 1001)->where('state', 'released')->count() === 2 + && Capsule::table('cloud_public_ips')->where('instance_id', 900) + ->count() === 0, + 'Confirmed instance deletion did not release its committed network bundle.'); + +echo "Provisioning dual-stack public-network ledger tests passed.\n"; diff --git a/web/tests/CloudPublicNetworkAllocationServiceTest.php b/web/tests/CloudPublicNetworkAllocationServiceTest.php index 23580b4a..0073fa0e 100644 --- a/web/tests/CloudPublicNetworkAllocationServiceTest.php +++ b/web/tests/CloudPublicNetworkAllocationServiceTest.php @@ -3,6 +3,8 @@ require dirname(__DIR__) . '/vendor/autoload.php'; use App\Services\Cloud\CloudPublicNetworkAllocationService; +use App\Services\Cloud\CloudPublicNetworkCapacityUnavailable; +use App\Services\Cloud\CloudError; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -32,6 +34,15 @@ $schema = $capsule->schema('default'); $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->increments('id'); }); +$schema->create('cloud_host_agents', static function (Blueprint $table): void { + $table->integer('host_id')->primary(); + $table->boolean('enabled'); + $table->integer('revision'); + $table->integer('tested_revision'); + $table->string('last_test_status'); + $table->text('network_selectors_json'); + $table->text('public_network_capabilities_json'); +}); $schema->create('cloud_host_network_attachments', static function ( Blueprint $table ): void { @@ -41,6 +52,9 @@ $schema->create('cloud_host_network_attachments', static function ( $table->string('network_selector'); $table->string('state'); $table->integer('priority')->default(0); + $table->string('verification_state'); + $table->integer('verified_agent_revision'); + $table->integer('last_verified_at'); }); $schema->create('cloud_public_ip_pools', static function ( Blueprint $table @@ -89,6 +103,24 @@ $schema->create('cloud_resource_reservations', static function ( $table->integer('host_id'); $table->string('operation_id'); $table->string('state'); + $table->integer('order_id')->nullable(); + $table->integer('backup_restore_id')->nullable(); + $table->integer('instance_id')->nullable(); + $table->integer('network_attachment_id')->nullable(); + $table->integer('public_ip_pool_id')->nullable(); + $table->integer('public_ip_id')->nullable(); +}); +$schema->create('cloud_instance_migrations', static function ( + Blueprint $table +): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('restore_id'); + $table->integer('source_host_id'); + $table->integer('source_reservation_id'); + $table->integer('target_host_id'); + $table->integer('target_reservation_id'); + $table->string('state'); }); $schema->create('cloud_resource_reservation_ips', static function ( Blueprint $table @@ -115,8 +147,25 @@ Capsule::table('cloud_host_network_attachments')->insert([ 'network_selector' => 'bridge:br0', 'state' => 'active', 'priority' => 0, + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, + 'last_verified_at' => time(), ]); Capsule::table('cloud_hosts')->insert(['id' => 1]); +Capsule::table('cloud_host_agents')->insert([ + 'host_id' => 1, + 'enabled' => 1, + 'revision' => 1, + 'tested_revision' => 1, + 'last_test_status' => 'healthy', + 'network_selectors_json' => '["bridge:br0"]', + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), +]); $common = [ 'host_id' => 1, 'network_attachment_id' => 10, @@ -369,26 +418,57 @@ Capsule::table('cloud_public_ip_pools')->where('id', 100)->update([ 'cidr' => '198.51.100.0/24', 'gateway' => '198.51.100.1', ]); -$rejects(static fn () => CloudPublicNetworkAllocationService::reserveBundle( - 1, - 7, - 503, - $operations[503] -), 'A special-use range crossed the public-network allocator.'); +$invalidPoolError = null; +try { + CloudPublicNetworkAllocationService::reserveBundle( + 1, + 7, + 503, + $operations[503] + ); +} catch (CloudError $error) { + $invalidPoolError = $error; +} +$assert($invalidPoolError instanceof CloudError + && !$invalidPoolError instanceof CloudPublicNetworkCapacityUnavailable, + 'Invalid pool configuration was downgraded to scheduler exhaustion.'); $assert(Capsule::table('cloud_resource_reservation_ips') ->where('reservation_id', 503)->count() === 0, 'Rejecting a non-public pool retained a partial address claim.'); +$addAgent = static function (int $hostId, array $selectors, + array $overrides = []): void { + Capsule::table('cloud_host_agents')->insert(array_replace([ + 'host_id' => $hostId, + 'enabled' => 1, + 'revision' => 1, + 'tested_revision' => 1, + 'last_test_status' => 'healthy', + 'network_selectors_json' => json_encode( + $selectors, + JSON_THROW_ON_ERROR + ), + 'public_network_capabilities_json' => json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, + ], JSON_THROW_ON_ERROR), + ], $overrides)); +}; $addAttachment = static function (int $id, int $hostId, int $lineId, - int $priority): void { - Capsule::table('cloud_host_network_attachments')->insert([ + int $priority, array $overrides = []): void { + Capsule::table('cloud_host_network_attachments')->insert(array_replace([ 'id' => $id, 'host_id' => $hostId, 'line_id' => $lineId, 'network_selector' => 'bridge:br' . $id, 'state' => 'active', 'priority' => $priority, - ]); + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, + 'last_verified_at' => time(), + ], $overrides)); }; $addPool = static function (int $id, int $hostId, int $attachmentId, int $family, int $priority, string $cidr, string $gateway, @@ -444,16 +524,78 @@ $addReservation = static function (int $id, int $hostId, 'state' => 'held', ]); }; +$assertHardFailure = static function (callable $callback, + string $message) use ($assert): void { + $failure = null; + try { + $callback(); + } catch (CloudError $error) { + $failure = $error; + } + $assert($failure instanceof CloudError + && !$failure instanceof CloudPublicNetworkCapacityUnavailable, + $message); +}; +$addPairHost = static function (int $hostId, int $lineId, + int $attachmentId, int $ipv4PoolId, int $ipv6PoolId, + string $ipv4Cidr, string $ipv6Cidr, array $agentOverrides = [], + array $attachmentOverrides = []) use ( + $addAgent, + $addAttachment, + $addPool, + $addIp + ): void { + $ipv4Prefix = substr($ipv4Cidr, 0, strrpos($ipv4Cidr, '.')); + $ipv6Network = substr($ipv6Cidr, 0, -3); + $selector = 'bridge:br' . $attachmentId; + Capsule::table('cloud_hosts')->insert(['id' => $hostId]); + $addAgent($hostId, [$selector], $agentOverrides); + $addAttachment( + $attachmentId, + $hostId, + $lineId, + 0, + $attachmentOverrides + ); + $addPool( + $ipv4PoolId, + $hostId, + $attachmentId, + 4, + 0, + $ipv4Cidr, + $ipv4Prefix . '.1' + ); + $addIp( + $hostId, + $ipv4PoolId, + 4, + $ipv4Prefix . '.10', + 24 + ); + $addPool( + $ipv6PoolId, + $hostId, + $attachmentId, + 6, + 0, + $ipv6Cidr, + '2404:c140:156::1', + $ipv6Network . '10', + $ipv6Network . '20', + 4 + ); +}; // A complete attachment may have more than one pool per family. Exhaustion // of a higher-priority pool must not hide capacity in its next sibling. Capsule::table('cloud_hosts')->insert(['id' => 2]); +$addAgent(2, ['bridge:br20', 'bridge:br30', 'bridge:br31']); $addAttachment(20, 2, 8, 0); $addPool(110, 2, 20, 4, 0, '9.9.9.0/24', '9.9.9.1'); Capsule::table('cloud_public_ip_pools')->where('id', 110)->update([ 'reserved_ips_json' => '["9.9.9.10"]', ]); -$addIp(2, 110, 4, '9.9.9.10', 24); $addPool(111, 2, 20, 4, 1, '11.0.0.0/24', '11.0.0.1'); $addIp(2, 111, 4, '11.0.0.10', 24); $addPool(210, 2, 20, 6, 0, '2404:c140:156:3b::/64', @@ -504,6 +646,7 @@ $assert($attachmentFallback->address(4) === '13.0.0.10/24' // An unavailable IPv6 leg must reject the whole bundle before the available // IPv4 leg is claimed. Capsule::table('cloud_hosts')->insert(['id' => 3]); +$addAgent(3, ['bridge:br40']); $addAttachment(40, 3, 10, 0); $addPool(130, 3, 40, 4, 0, '14.0.0.0/24', '14.0.0.1'); $addIp(3, 130, 4, '14.0.0.10', 24); @@ -513,13 +656,583 @@ $addPool(230, 3, 40, 6, 0, '2404:c140:156:3f::/64', $addIp(3, 230, 6, '2404:c140:156:3f::10', 64, 'assigned'); $exhaustedOperation = str_repeat('4', 32); $addReservation(602, 3, $exhaustedOperation); -$rejects(static fn () => CloudPublicNetworkAllocationService::reserveBundle( - 3, 10, 602, $exhaustedOperation -), 'A host without a complete usable pool pair was accepted.'); +$capacityUnavailable = false; +try { + CloudPublicNetworkAllocationService::reserveBundle( + 3, 10, 602, $exhaustedOperation + ); +} catch (CloudPublicNetworkCapacityUnavailable) { + $capacityUnavailable = true; +} +$assert($capacityUnavailable, + 'Pair exhaustion did not produce the dedicated capacity result.'); $assert(Capsule::table('cloud_resource_reservation_ips') ->where('reservation_id', 602)->count() === 0 && Capsule::table('cloud_public_ips')->where('public_ip_pool_id', 130) ->where('state', 'available')->whereNull('reservation_id')->count() === 1, 'A failed pair selection left a partial IPv4 claim.'); +// Exact allocation must ignore an unverified high-priority attachment and +// continue with a lower-priority attachment backed by the same locked current +// Agent evidence. +Capsule::table('cloud_hosts')->insert(['id' => 4]); +$addAgent(4, ['bridge:br51']); +$addAttachment(50, 4, 11, 0, [ + 'verification_state' => 'pending', + 'verified_agent_revision' => 0, +]); +$addPool(140, 4, 50, 4, 0, '15.0.0.0/24', '15.0.0.1'); +$addIp(4, 140, 4, '15.0.0.10', 24); +$addPool(240, 4, 50, 6, 0, '2404:c140:156:40::/64', + '2404:c140:156::1', '2404:c140:156:40::10', + '2404:c140:156:40::20', 4); +$addAttachment(51, 4, 11, 1); +$addPool(141, 4, 51, 4, 0, '16.0.0.0/24', '16.0.0.1'); +$addIp(4, 141, 4, '16.0.0.10', 24); +$addPool(241, 4, 51, 6, 0, '2404:c140:156:41::/64', + '2404:c140:156::1', '2404:c140:156:41::10', + '2404:c140:156:41::20', 4); +$verifiedFallbackOperation = str_repeat('3', 32); +$addReservation(603, 4, $verifiedFallbackOperation); +$verifiedFallback = CloudPublicNetworkAllocationService::reserveBundle( + 4, 11, 603, $verifiedFallbackOperation +); +$verifiedFallbackClaims = Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 603)->get(); +$assert($verifiedFallback->address(4) === '16.0.0.10/24' + && $verifiedFallbackClaims->count() === 2 + && $verifiedFallbackClaims->every( + static fn ($claim): bool => + (int) $claim->network_attachment_id === 51 + ), 'Allocator selected an unverified higher-priority attachment.'); + +// Missing capabilities, an untested selector and stale revision evidence are +// configuration/evidence failures. They must never be downgraded to ordinary +// address exhaustion and silently sent to the next host. +$addPairHost( + 5, + 12, + 60, + 150, + 250, + '17.0.0.0/24', + '2404:c140:156:50::/64' +); +$evidenceCases = [ + 'capabilities' => static function (): void { + Capsule::table('cloud_host_agents')->where('host_id', 5)->update([ + 'public_network_capabilities_json' => '{}', + ]); + }, + 'selector' => static function (): void { + Capsule::table('cloud_host_agents')->where('host_id', 5)->update([ + 'network_selectors_json' => '[]', + ]); + }, + 'agent revision' => static function (): void { + Capsule::table('cloud_host_agents')->where('host_id', 5)->update([ + 'tested_revision' => 0, + ]); + }, + 'attachment revision' => static function (): void { + Capsule::table('cloud_host_network_attachments')->where('id', 60) + ->update(['verified_agent_revision' => 2]); + }, +]; +$validCapabilities = json_encode([ + 'contract' => 1, + 'dual_stack_required' => true, + 'project_owned_filter' => true, + 'ndp_guard' => true, +], JSON_THROW_ON_ERROR); +$evidenceReservationId = 604; +foreach ($evidenceCases as $label => $mutateEvidence) { + Capsule::table('cloud_host_agents')->where('host_id', 5)->update([ + 'enabled' => 1, + 'revision' => 1, + 'tested_revision' => 1, + 'last_test_status' => 'healthy', + 'network_selectors_json' => '["bridge:br60"]', + 'public_network_capabilities_json' => $validCapabilities, + ]); + Capsule::table('cloud_host_network_attachments')->where('id', 60) + ->update([ + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, + 'last_verified_at' => time(), + ]); + $mutateEvidence(); + $operation = str_pad(dechex($evidenceReservationId), 32, 'a'); + $addReservation($evidenceReservationId, 5, $operation); + $assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::reserveBundle( + 5, + 12, + $evidenceReservationId, + $operation + ), + 'Stale ' . $label . ' evidence was treated as address exhaustion.' + ); + $assert(Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', $evidenceReservationId)->count() === 0, + 'Stale ' . $label . ' evidence retained an address claim.'); + $evidenceReservationId++; +} + +// An active pool whose observed revision is ahead of the desired catalog is +// not a capacity miss; it is a non-converged configuration that must stop the +// paid placement transaction. +Capsule::table('cloud_host_agents')->where('host_id', 5)->update([ + 'tested_revision' => 1, + 'network_selectors_json' => '["bridge:br60"]', + 'public_network_capabilities_json' => $validCapabilities, +]); +Capsule::table('cloud_host_network_attachments')->where('id', 60)->update([ + 'verification_state' => 'verified', + 'verified_agent_revision' => 1, +]); +Capsule::table('cloud_public_ip_pools')->where('id', 150)->update([ + 'observed_revision' => 2, +]); +$revisionOperation = str_repeat('2', 32); +$addReservation(608, 5, $revisionOperation); +$assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::reserveBundle( + 5, + 12, + 608, + $revisionOperation + ), + 'A pool ahead of desired revision was treated as address exhaustion.' +); +$assert(Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 608)->count() === 0, + 'A non-converged pool retained an address claim.'); + +// Every materialized row is validated before capacity is evaluated. Shape, +// topology and concrete address corruption must therefore hard-fail rather +// than make a host look merely full. +$addPairHost( + 6, + 13, + 70, + 160, + 260, + '18.0.0.0/24', + '2404:c140:156:60::/64' +); +$ledgerIpv4 = Capsule::table('cloud_public_ips') + ->where('public_ip_pool_id', 160)->first(); +$assert($ledgerIpv4 !== null, 'Ledger corruption fixture is missing IPv4.'); +$ledgerBaseline = [ + 'host_id' => 6, + 'public_ip_pool_id' => 160, + 'address_family' => 4, + 'address' => '18.0.0.10', + 'address_binary' => inet_pton('18.0.0.10'), + 'prefix_length' => 24, + 'state' => 'available', + 'reservation_id' => null, + 'instance_id' => null, + 'operation_id' => null, +]; +$ledgerCases = [ + 'dirty available ownership' => [ + 'reservation_id' => 9999, + ], + 'active row without ownership' => [ + 'state' => 'reserved', + ], + 'wrong host' => [ + 'host_id' => 999, + ], + 'wrong family' => [ + 'address_family' => 6, + ], + 'wrong pool' => [ + 'public_ip_pool_id' => 260, + ], + 'invalid prefix' => [ + 'prefix_length' => 23, + ], + 'address outside pool' => [ + 'address' => '19.0.0.10', + 'address_binary' => inet_pton('19.0.0.10'), + ], + 'same text with different binary' => [ + 'address_binary' => inet_pton('18.0.0.11'), + ], +]; +$ledgerReservationId = 609; +foreach ($ledgerCases as $label => $mutation) { + Capsule::table('cloud_public_ips')->where('id', (int) $ledgerIpv4->id) + ->update(array_replace($ledgerBaseline, $mutation)); + $operation = str_pad(dechex($ledgerReservationId), 32, 'b'); + $addReservation($ledgerReservationId, 6, $operation); + $assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::reserveBundle( + 6, + 13, + $ledgerReservationId, + $operation + ), + 'Corrupt ' . $label . ' ledger was treated as address exhaustion.' + ); + $assert(Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', $ledgerReservationId)->count() === 0, + 'Corrupt ' . $label . ' ledger retained a partial claim.'); + $ledgerReservationId++; +} + +// Canonical text is part of the concrete identity just like the packed bytes. +Capsule::table('cloud_public_ips')->where('id', (int) $ledgerIpv4->id) + ->update($ledgerBaseline); +$nonCanonicalIpv6Id = Capsule::table('cloud_public_ips')->insertGetId([ + 'host_id' => 6, + 'public_ip_pool_id' => 260, + 'address_family' => 6, + 'address' => '2404:C140:156:60::10', + 'address_binary' => inet_pton('2404:c140:156:60::10'), + 'prefix_length' => 64, + 'state' => 'available', + 'reservation_id' => null, + 'instance_id' => null, + 'operation_id' => null, + 'created_at' => time(), + 'updated_at' => time(), +]); +$canonicalOperation = str_repeat('1', 32); +$addReservation(617, 6, $canonicalOperation); +$assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::reserveBundle( + 6, + 13, + 617, + $canonicalOperation + ), + 'Non-canonical concrete address text was treated as address exhaustion.' +); +$assert(Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 617)->count() === 0, + 'Rejecting non-canonical text retained a partial claim.'); +Capsule::table('cloud_public_ips')->where('id', $nonCanonicalIpv6Id)->delete(); + +// A retained maintenance-migration source is a deliberate capacity debt, not +// a corrupt assigned address. Accept only the exact migration + restore +// reservation evidence, and keep that address unavailable to new placement. +$addPairHost( + 8, + 15, + 90, + 180, + 280, + '21.0.0.0/24', + '2404:c140:156:80::/64' +); +foreach ([ + ['21.0.0.14', 'changing', null, 8000, str_repeat('6', 32)], + ['21.0.0.15', 'uncertain', null, 8001, str_repeat('7', 32)], + ['21.0.0.16', 'disabled', null, null, null], +] as [$address, $state, $reservationId, $instanceId, $operationId]) { + Capsule::table('cloud_public_ips')->insert([ + 'host_id' => 8, + 'public_ip_pool_id' => 180, + 'address_family' => 4, + 'address' => $address, + 'address_binary' => inet_pton($address), + 'prefix_length' => 24, + 'state' => $state, + 'reservation_id' => $reservationId, + 'instance_id' => $instanceId, + 'operation_id' => $operationId, + 'created_at' => time(), + 'updated_at' => time(), + ]); +} +$retainedOperation = str_repeat('8', 32); +$retainedIpId = Capsule::table('cloud_public_ips')->insertGetId([ + 'host_id' => 8, + 'public_ip_pool_id' => 180, + 'address_family' => 4, + 'address' => '21.0.0.11', + 'address_binary' => inet_pton('21.0.0.11'), + 'prefix_length' => 24, + 'state' => 'assigned', + 'reservation_id' => 700, + 'instance_id' => null, + 'operation_id' => $retainedOperation, + 'created_at' => time(), + 'updated_at' => time(), +]); +Capsule::table('cloud_resource_reservations')->insert([ + 'id' => 700, + 'host_id' => 8, + 'operation_id' => $retainedOperation, + 'state' => 'committed', + 'order_id' => null, + 'backup_restore_id' => 800, + 'instance_id' => null, + 'network_attachment_id' => 90, + 'public_ip_pool_id' => 180, + 'public_ip_id' => $retainedIpId, +]); +Capsule::table('cloud_instance_migrations')->insert([ + 'id' => 800, + 'instance_id' => 8000, + 'restore_id' => 800, + 'source_host_id' => 8, + 'source_reservation_id' => 700, + 'target_host_id' => 9, + 'target_reservation_id' => 701, + 'state' => 'source_retained', +]); +$sourceRetainedOperation = str_repeat('9', 32); +$addReservation(621, 8, $sourceRetainedOperation); +$sourceRetainedBundle = CloudPublicNetworkAllocationService::reserveBundle( + 8, + 15, + 621, + $sourceRetainedOperation +); +$assert($sourceRetainedBundle->address(4) === '21.0.0.10/24' + && Capsule::table('cloud_public_ips')->where('id', $retainedIpId) + ->where('state', 'assigned')->whereNull('instance_id') + ->where('reservation_id', 700)->count() === 1, + 'Exact source-retained debt blocked placement or was reallocated.'); + +// The same debt remains valid while its cleanup mutation is in flight. +Capsule::table('cloud_instance_migrations')->where('id', 800)->update([ + 'state' => 'cleanup_running', +]); +$addIp(8, 180, 4, '21.0.0.12', 24); +$cleanupRunningOperation = str_repeat('a', 32); +$addReservation(622, 8, $cleanupRunningOperation); +$cleanupRunningBundle = CloudPublicNetworkAllocationService::reserveBundle( + 8, + 15, + 622, + $cleanupRunningOperation +); +$assert($cleanupRunningBundle->address(4) === '21.0.0.12/24' + && Capsule::table('cloud_public_ips')->where('id', $retainedIpId) + ->where('state', 'assigned')->whereNull('instance_id') + ->where('reservation_id', 700)->count() === 1, + 'Cleanup-running retained debt blocked placement or was reallocated.'); + +// An orphan or any material identity mismatch must remain a hard ledger +// failure. It must not become ordinary capacity exhaustion or claim a spare. +$addIp(8, 180, 4, '21.0.0.13', 24); +$retainedMigrationBaseline = (array) Capsule::table( + 'cloud_instance_migrations' +)->where('id', 800)->first(); +$retainedReservationBaseline = (array) Capsule::table( + 'cloud_resource_reservations' +)->where('id', 700)->first(); +$evidenceFailureReservationId = 623; +$assertRetainedEvidenceFailure = static function ( + string $label +) use ( + &$evidenceFailureReservationId, + $addReservation, + $assertHardFailure, + $assert +): void { + $operation = str_pad( + dechex($evidenceFailureReservationId), + 32, + 'b' + ); + $addReservation($evidenceFailureReservationId, 8, $operation); + $assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::reserveBundle( + 8, + 15, + $evidenceFailureReservationId, + $operation + ), + $label . ' was downgraded to ordinary capacity exhaustion.' + ); + $assert(Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', $evidenceFailureReservationId) + ->count() === 0, + $label . ' retained a partial public-network claim.'); + $evidenceFailureReservationId++; +}; + +Capsule::table('cloud_instance_migrations')->where('id', 800)->delete(); +$assertRetainedEvidenceFailure('Orphan retained-source address'); +Capsule::table('cloud_instance_migrations')->insert( + $retainedMigrationBaseline +); + +$retainedEvidenceMutations = [ + 'Unsupported retained-source state' => static function (): void { + Capsule::table('cloud_instance_migrations')->where('id', 800) + ->update(['state' => 'completed']); + }, + 'Migration restore identity mismatch' => static function (): void { + Capsule::table('cloud_instance_migrations')->where('id', 800) + ->update(['restore_id' => 801]); + }, + 'Reservation host identity mismatch' => static function (): void { + Capsule::table('cloud_resource_reservations')->where('id', 700) + ->update(['host_id' => 999]); + }, + 'Reservation pool identity mismatch' => static function (): void { + Capsule::table('cloud_resource_reservations')->where('id', 700) + ->update(['public_ip_pool_id' => 280]); + }, + 'Reservation IP identity mismatch' => static function (): void { + Capsule::table('cloud_resource_reservations')->where('id', 700) + ->update(['public_ip_id' => 999999]); + }, + 'Reservation operation identity mismatch' => static function (): void { + Capsule::table('cloud_resource_reservations')->where('id', 700) + ->update(['operation_id' => str_repeat('f', 32)]); + }, +]; +foreach ($retainedEvidenceMutations as $label => $mutate) { + Capsule::table('cloud_instance_migrations')->where('id', 800)->update( + $retainedMigrationBaseline + ); + Capsule::table('cloud_resource_reservations')->where('id', 700)->update( + $retainedReservationBaseline + ); + $mutate(); + $assertRetainedEvidenceFailure($label); +} +Capsule::table('cloud_instance_migrations')->where('id', 800)->update( + $retainedMigrationBaseline +); +Capsule::table('cloud_resource_reservations')->where('id', 700)->update( + $retainedReservationBaseline +); + +// Every state transition repeats the same concrete identity checks. A valid +// text paired with different packed bytes, or an address moved to another +// host, cannot be committed, fenced or released. +$addPairHost( + 7, + 14, + 80, + 170, + 270, + '20.0.0.0/24', + '2404:c140:156:70::/64' +); +$commitIdentityOperation = str_repeat('c', 32); +$addReservation(618, 7, $commitIdentityOperation); +CloudPublicNetworkAllocationService::reserveBundle( + 7, + 14, + 618, + $commitIdentityOperation +); +$commitIpv4 = Capsule::table('cloud_public_ips') + ->where('reservation_id', 618)->where('address_family', 4)->first(); +$assert($commitIpv4 !== null, 'Commit identity fixture is missing IPv4.'); +Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id) + ->update(['address_binary' => inet_pton('20.0.0.11')]); +$assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::commitBundle( + 618, + 918, + $commitIdentityOperation + ), + 'Commit accepted same-text/different-binary concrete identity.' +); +Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id) + ->update(['address_binary' => inet_pton('20.0.0.10')]); +CloudPublicNetworkAllocationService::commitBundle( + 618, + 918, + $commitIdentityOperation +); +Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id) + ->update(['host_id' => 999]); +$assertHardFailure( + static fn () => + CloudPublicNetworkAllocationService::releaseCommittedBundle( + 618, + 918, + $commitIdentityOperation, + 'instance_deleted', + true + ), + 'Committed release accepted a concrete address from another host.' +); +Capsule::table('cloud_public_ips')->where('id', (int) $commitIpv4->id) + ->update(['host_id' => 7]); +CloudPublicNetworkAllocationService::releaseCommittedBundle( + 618, + 918, + $commitIdentityOperation, + 'instance_deleted', + true +); + +$fenceIdentityOperation = str_repeat('d', 32); +$addReservation(619, 7, $fenceIdentityOperation); +CloudPublicNetworkAllocationService::reserveBundle( + 7, + 14, + 619, + $fenceIdentityOperation +); +$fenceIpv4 = Capsule::table('cloud_public_ips') + ->where('reservation_id', 619)->where('address_family', 4)->first(); +$assert($fenceIpv4 !== null, 'Fence identity fixture is missing IPv4.'); +Capsule::table('cloud_public_ips')->where('id', (int) $fenceIpv4->id) + ->update(['host_id' => 999]); +$assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::fenceBundle( + 619, + $fenceIdentityOperation + ), + 'Fence accepted a concrete address from another host.' +); +Capsule::table('cloud_public_ips')->where('id', (int) $fenceIpv4->id) + ->update(['host_id' => 7]); +CloudPublicNetworkAllocationService::fenceBundle( + 619, + $fenceIdentityOperation +); +CloudPublicNetworkAllocationService::releaseBundle( + 619, + $fenceIdentityOperation, + 'confirmed_not_applied', + true +); + +$releaseIdentityOperation = str_repeat('e', 32); +$addReservation(620, 7, $releaseIdentityOperation); +CloudPublicNetworkAllocationService::reserveBundle( + 7, + 14, + 620, + $releaseIdentityOperation +); +$releaseIpv4 = Capsule::table('cloud_public_ips') + ->where('reservation_id', 620)->where('address_family', 4)->first(); +$assert($releaseIpv4 !== null, 'Release identity fixture is missing IPv4.'); +Capsule::table('cloud_public_ips')->where('id', (int) $releaseIpv4->id) + ->update(['address_binary' => inet_pton('20.0.0.11')]); +$assertHardFailure( + static fn () => CloudPublicNetworkAllocationService::releaseBundle( + 620, + $releaseIdentityOperation, + 'confirmed_not_applied', + true + ), + 'Release accepted same-text/different-binary concrete identity.' +); +Capsule::table('cloud_public_ips')->where('id', (int) $releaseIpv4->id) + ->update(['address_binary' => inet_pton('20.0.0.10')]); +CloudPublicNetworkAllocationService::releaseBundle( + 620, + $releaseIdentityOperation, + 'confirmed_not_applied', + true +); + echo "Atomic dual-stack public network allocation tests passed.\n"; diff --git a/web/tests/CloudUndispatchedFinalizerRecoveryTest.php b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php index 8330aca3..2b5160f9 100644 --- a/web/tests/CloudUndispatchedFinalizerRecoveryTest.php +++ b/web/tests/CloudUndispatchedFinalizerRecoveryTest.php @@ -218,6 +218,38 @@ namespace { $schema->create('cloud_hosts', static function (Blueprint $table): void { $table->increments('id'); }); + $schema->create('cloud_host_network_attachments', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('host_id'); + $table->integer('line_id'); + $table->string('network_selector'); + $table->string('state'); + $table->integer('priority')->default(0); + }); + $schema->create('cloud_public_ip_pools', + static function (Blueprint $table): void { + $table->increments('id'); + $table->string('pool_key'); + $table->integer('host_id'); + $table->integer('network_attachment_id'); + $table->integer('address_family'); + $table->string('cidr'); + $table->string('gateway'); + $table->boolean('gateway_on_link'); + $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'); + $table->string('state'); + $table->integer('priority')->default(0); + $table->integer('desired_revision'); + $table->integer('observed_revision'); + $table->string('sync_state'); + }); $schema->create('cloud_offers', static function (Blueprint $table): void { $table->increments('id'); $table->integer('stock')->default(-1); @@ -251,6 +283,7 @@ namespace { $table->string('reservation_key'); $table->string('operation_id'); $table->integer('order_id'); + $table->integer('backup_restore_id')->nullable(); $table->integer('offer_id'); $table->integer('resource_pool_id'); $table->integer('host_id'); @@ -274,7 +307,9 @@ namespace { $table->increments('id'); $table->integer('host_id'); $table->integer('public_ip_pool_id')->nullable(); + $table->integer('address_family'); $table->string('address'); + $table->binary('address_binary'); $table->integer('prefix_length'); $table->string('state'); $table->integer('reservation_id')->nullable(); @@ -283,6 +318,21 @@ namespace { $table->integer('created_at'); $table->integer('updated_at'); }); + $schema->create('cloud_resource_reservation_ips', + static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('reservation_id'); + $table->integer('address_family'); + $table->integer('network_attachment_id'); + $table->integer('public_ip_pool_id'); + $table->integer('public_ip_id'); + $table->string('operation_id'); + $table->string('state'); + $table->integer('created_at'); + $table->integer('updated_at'); + $table->integer('released_at')->nullable(); + $table->string('release_reason')->default(''); + }); $schema->create('cloud_invoices', static function (Blueprint $table): void { $table->increments('id'); @@ -522,6 +572,53 @@ namespace { ); Capsule::table('user')->where('id', 1)->update(['money' => '0.00']); Capsule::table('cloud_hosts')->insert(['id' => 7]); + Capsule::table('cloud_host_network_attachments')->insert([ + 'id' => 601, + 'host_id' => 7, + 'line_id' => 601, + 'network_selector' => 'bridge:br0', + 'state' => 'active', + 'priority' => 0, + ]); + $publicPool = [ + 'host_id' => 7, + 'network_attachment_id' => 601, + 'gateway_on_link' => 0, + 'reserved_ips_json' => '[]', + 'allocation_cursor' => null, + 'state' => 'active', + 'priority' => 0, + 'desired_revision' => 1, + 'observed_revision' => 1, + 'sync_state' => 'applied', + ]; + Capsule::table('cloud_public_ip_pools')->insert([ + array_merge($publicPool, [ + 'id' => 601, + 'pool_key' => str_repeat('1', 32), + 'address_family' => 4, + 'cidr' => '8.8.8.0/24', + 'gateway' => '8.8.8.1', + 'guest_prefix_length' => 24, + 'dns_servers_json' => '["1.1.1.1"]', + 'allocation_start' => null, + 'allocation_end' => null, + 'max_allocations' => 0, + ]), + array_merge($publicPool, [ + 'id' => 602, + 'pool_key' => str_repeat('2', 32), + 'address_family' => 6, + 'cidr' => '2404:c140:156:3a::/64', + 'gateway' => '2404:c140:156::1', + 'gateway_on_link' => 1, + 'guest_prefix_length' => 64, + 'dns_servers_json' => '["2606:4700:4700::1111"]', + 'allocation_start' => '2404:c140:156:3a::10', + 'allocation_end' => '2404:c140:156:3a::ff', + 'max_allocations' => 8, + ]), + ]); Capsule::table('cloud_offers')->insert([ 'id' => 601, 'stock' => 0, @@ -554,14 +651,15 @@ namespace { 'reservation_key' => 'undispatched-create-reservation', 'operation_id' => $createOperationId, 'order_id' => 601, + 'backup_restore_id' => null, 'offer_id' => 601, 'resource_pool_id' => 601, 'host_id' => 7, 'user_id' => 1, 'instance_id' => null, - 'network_attachment_id' => 601, - 'public_ip_pool_id' => 601, - 'public_ip_id' => 601, + 'network_attachment_id' => null, + 'public_ip_pool_id' => null, + 'public_ip_id' => null, 'cpu_cores' => 1, 'memory_mib' => 512, 'disk_gib' => 10, @@ -573,17 +671,66 @@ namespace { 'updated_at' => $now - 30, ]); Capsule::table('cloud_public_ips')->insert([ - 'id' => 601, - 'host_id' => 7, - 'public_ip_pool_id' => 601, - 'address' => '203.0.113.61', - 'prefix_length' => 24, - 'state' => 'reserved', - 'reservation_id' => 601, - 'instance_id' => null, - 'operation_id' => $createOperationId, - 'created_at' => $now - 120, - 'updated_at' => $now - 30, + [ + 'id' => 601, + 'host_id' => 7, + 'public_ip_pool_id' => 601, + 'address_family' => 4, + 'address' => '8.8.8.61', + 'address_binary' => inet_pton('8.8.8.61'), + 'prefix_length' => 24, + 'state' => 'reserved', + 'reservation_id' => 601, + 'instance_id' => null, + 'operation_id' => $createOperationId, + 'created_at' => $now - 120, + 'updated_at' => $now - 30, + ], + [ + 'id' => 602, + 'host_id' => 7, + 'public_ip_pool_id' => 602, + 'address_family' => 6, + 'address' => '2404:c140:156:3a::61', + 'address_binary' => inet_pton('2404:c140:156:3a::61'), + 'prefix_length' => 64, + 'state' => 'reserved', + 'reservation_id' => 601, + 'instance_id' => null, + 'operation_id' => $createOperationId, + 'created_at' => $now - 120, + 'updated_at' => $now - 30, + ], + ]); + Capsule::table('cloud_resource_reservation_ips')->insert([ + [ + 'id' => 601, + 'reservation_id' => 601, + 'address_family' => 4, + 'network_attachment_id' => 601, + 'public_ip_pool_id' => 601, + 'public_ip_id' => 601, + 'operation_id' => $createOperationId, + 'state' => 'reserved', + 'created_at' => $now - 120, + 'updated_at' => $now - 30, + 'released_at' => null, + 'release_reason' => '', + ], + [ + 'id' => 602, + 'reservation_id' => 601, + 'address_family' => 6, + 'network_attachment_id' => 601, + 'public_ip_pool_id' => 602, + 'public_ip_id' => 602, + 'operation_id' => $createOperationId, + 'state' => 'reserved', + 'created_at' => $now - 120, + 'updated_at' => $now - 30, + 'released_at' => null, + 'release_reason' => '', + ], ]); Capsule::table('cloud_jobs')->insert([ 'id' => 601, @@ -693,8 +840,9 @@ namespace { ->value('money') === '0.00' && (string) Capsule::table('cloud_resource_reservations') ->where('id', 601)->value('state') === 'held' - && (string) Capsule::table('cloud_public_ips') - ->where('id', 601)->value('state') === 'reserved' + && Capsule::table('cloud_public_ips') + ->where('reservation_id', 601) + ->where('state', 'reserved')->count() === 2 && CloudAgentSettingsService::$requests === 0, 'Missing create ledger data caused a partial refund/release or Agent call.'); @@ -763,10 +911,15 @@ namespace { ->value('stock') === 1 && (string) Capsule::table('cloud_resource_reservations') ->where('id', 601)->value('state') === 'released' - && (string) Capsule::table('cloud_public_ips') - ->where('id', 601)->value('state') === 'available' - && Capsule::table('cloud_public_ips')->where('id', 601) - ->value('reservation_id') === null + && Capsule::table('cloud_public_ips') + ->whereIn('id', [601, 602]) + ->where('state', 'available')->count() === 2 + && Capsule::table('cloud_public_ips') + ->whereIn('id', [601, 602]) + ->whereNotNull('reservation_id')->count() === 0 + && Capsule::table('cloud_resource_reservation_ips') + ->where('reservation_id', 601) + ->where('state', 'released')->count() === 2 && CloudAgentSettingsService::$requests === 0, 'Recovered create did not atomically refund, release, scrub, and close.');