transaction(static function () use ( $reservationId, $expectedState, $expectedInstanceId ): CloudActivePublicNetworkClaimSet { $reservation = self::unlockedReservation($reservationId); $hostId = (int) ($reservation->host_id ?? 0); $resourcePoolId = (int) ($reservation->resource_pool_id ?? 0); $reservationUserId = (int) ($reservation->user_id ?? 0); $resourcePoolLineId = $resourcePoolId > 0 ? DB::table('cloud_resource_pools') ->where('id', $resourcePoolId)->value('line_id') : null; $reservationInstanceId = $reservation?->instance_id === null ? null : (int) $reservation->instance_id; $instance = $expectedState === 'committed' && $reservationInstanceId !== null && $reservationInstanceId > 0 ? DB::table('cloud_instances') ->where('id', $reservationInstanceId)->first() : null; if ($reservation === null || $hostId < 1 || $resourcePoolId < 1 || $reservationUserId < 1 || $resourcePoolLineId === null || (int) $resourcePoolLineId < 1 || (string) $reservation->state !== $expectedState || ($expectedState === 'committed' && ($reservationInstanceId === null || $reservationInstanceId < 1 || $instance === null || (int) ($instance->reservation_id ?? 0) !== $reservationId || (int) ($instance->host_id ?? 0) !== $hostId || (int) ($instance->resource_pool_id ?? 0) !== $resourcePoolId || (int) ($instance->user_id ?? 0) !== $reservationUserId)) || ($expectedState !== 'committed' && $reservationInstanceId !== null) || ($expectedInstanceId !== null && $reservationInstanceId !== $expectedInstanceId) || DB::table('cloud_hosts')->where('id', $hostId) ->value('id') === null) { throw new CloudError('公网网络资源预留权威链不一致', 409); } $claims = self::unlockedClaims($reservationId); $set = self::claimSet( $claims, $expectedState === 'held' ? 'reserved' : $expectedState, $expectedState === 'committed' ? $reservationInstanceId : null, $hostId, (int) $resourcePoolLineId ); if ($set->reservationId() !== $reservationId) { throw new CloudError('公网网络活动声明归属不一致', 409); } if ($expectedState === 'committed') { self::assertInstancePublicNetworkSnapshot($instance, $set); } return $set; }); } private static function assertInstancePublicNetworkSnapshot( ?object $instance, CloudActivePublicNetworkClaimSet $claimSet ): void { try { $spec = json_decode( (string) ($instance->spec_json ?? ''), true, 64, JSON_THROW_ON_ERROR ); if (!is_array($spec) || array_is_list($spec)) { throw new \InvalidArgumentException( 'Instance specification is invalid.' ); } $frozen = CloudPublicNetworkSnapshot::fromArray( $spec['public_network'] ?? null ); } catch (\Throwable) { throw new CloudError('实例缺少有效的冻结公网网络快照', 409); } if (!hash_equals( $frozen->fingerprint(), $claimSet->publicNetwork()->fingerprint() )) { throw new CloudError('实例冻结公网网络快照与活动声明不一致', 409); } } public static function reserveBundle(int $hostId, int $lineId, int $reservationId, string $operationId): CloudPublicNetworkSnapshot { return self::reserveBundleUsingConstraint( $hostId, $lineId, $reservationId, $operationId, null, false ); } /** * Lock and verify one already-reserved bundle without ever allocating. * * Restore replay must fail closed when its durable claims disappeared; * silently selecting replacement addresses would change guest identity. */ public static function verifyExistingBundle(int $hostId, int $lineId, int $reservationId, string $operationId): CloudPublicNetworkSnapshot { return self::reserveBundleUsingConstraint( $hostId, $lineId, $reservationId, $operationId, null, true ); } /** * Reserve only the scheduler-frozen attachment and pool pair. * * The placement coordinator owns the outer host sentinel. This module * deliberately locks it again before entering its catalog hierarchy so a * future direct caller cannot invert the allocator's lock order. */ public static function reservePlannedBundle(int $hostId, int $lineId, int $reservationId, string $operationId, CloudPublicNetworkBundleConstraint $constraint ): CloudPublicNetworkSnapshot { $constraint->assertScope($hostId, $lineId); return self::reserveBundleUsingConstraint( $hostId, $lineId, $reservationId, $operationId, $constraint, false ); } private static function reserveBundleUsingConstraint(int $hostId, int $lineId, int $reservationId, string $operationId, ?CloudPublicNetworkBundleConstraint $constraint, bool $requireExisting ): CloudPublicNetworkSnapshot { self::assertIdentity($reservationId, $operationId); if ($hostId < 1 || $lineId < 1) { throw new CloudError('公网网络预留范围无效', 409); } return self::connection()->transaction(static function () use ( $hostId, $lineId, $reservationId, $operationId, $constraint, $requireExisting ): CloudPublicNetworkSnapshot { self::lockHost($hostId); $claimHints = self::unlockedClaims($reservationId); $catalog = null; $selection = null; if ($claimHints === []) { if ($requireExisting) { throw new CloudError( '公网网络资源预留缺少既有双栈声明', 409 ); } $catalog = self::lockPoolCatalog( $hostId, $lineId, $constraint ); } else { $selection = self::lockClaimNetworkContext( $claimHints, $hostId, $lineId ); } $reservation = self::lockReservation($reservationId); self::assertReservation($reservation, $hostId, $operationId, ['held', 'committed', 'uncertain']); $existing = self::lockedClaims($reservationId); if ($existing !== []) { $claimState = self::claimStateForReservation($reservation); self::assertClaimSet($existing, $operationId, [$claimState]); if ($selection === null) { throw new CloudError('公网网络资源预留状态不明确', 409); } if ($constraint !== null) { $constraint->assertMatches( $selection['attachment'], $selection['pools'] ); } self::assertClaimsUseSelection($existing, $selection); $addresses = self::lockClaimAddresses($existing); self::assertClaimAddresses($existing, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'committed' => ['assigned'], 'uncertain' => ['uncertain'], ], $claimState === 'committed' ? (int) ($reservation->instance_id ?? 0) : null); return self::snapshot($existing); } if (self::lockedHistoricalClaims($reservationId) !== []) { throw new CloudError( '初始公网网络预留不能复用历史地址声明', 409 ); } if ($claimHints !== [] || (string) $reservation->state !== 'held') { throw new CloudError('公网网络资源预留状态不明确', 409); } if ($catalog === null) { throw new CloudError('公网网络候选目录不完整', 409); } $selection = self::selectAvailablePoolPair( $catalog, $constraint ); $now = time(); $claims = []; foreach (self::FAMILIES as $family) { $pool = $selection['pools'][$family]; $ip = self::reserveAddress($pool, $now, $selection['address_candidates'][$family] ?? null); $claimId = DB::table('cloud_resource_reservation_ips') ->insertGetId([ 'reservation_id' => $reservationId, 'address_family' => $family, 'claim_generation' => 1, 'active_claim' => 1, 'network_attachment_id' => (int) $selection['attachment']->id, 'public_ip_pool_id' => (int) $pool->id, 'public_ip_id' => (int) $ip->id, 'operation_id' => $operationId, 'state' => 'reserved', 'created_at' => $now, 'updated_at' => $now, 'released_at' => null, 'release_reason' => '', ]); self::bindAddressToClaim( $ip, $reservationId, $operationId, $claimId, $now ); $claims[] = DB::table('cloud_resource_reservation_ips') ->where('id', $claimId)->first(); } return self::snapshot($claims); }); } public static function commitBundle(int $reservationId, int $instanceId, string $operationId): CloudPublicNetworkSnapshot { self::assertIdentity($reservationId, $operationId); if ($instanceId < 1) { throw new CloudError('实例网络归属无效', 409); } return self::connection()->transaction(static function () use ( $reservationId, $instanceId, $operationId ): CloudPublicNetworkSnapshot { $reservationHint = self::unlockedReservation($reservationId); 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, ['held', 'committed', 'uncertain']); $claims = self::lockedClaims($reservationId); $claimState = self::claimStateForReservation($reservation); self::assertClaimSet( $claims, $operationId, [$claimState] ); if ($claimState === 'committed' && (int) ($reservation->instance_id ?? 0) !== $instanceId) { throw new CloudError('实例网络归属与资源预留不一致', 409); } self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], 'committed' => ['assigned'], ], $instanceId); if ($claimState === 'committed') { return self::snapshot($claims); } $now = time(); foreach ($claims as $claim) { $ip = $addresses[(int) $claim->public_ip_id]; $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $ip->id) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $operationId)->update([ 'state' => 'assigned', 'reservation_id' => $reservationId, 'reservation_ip_claim_id' => (int) $claim->id, 'instance_id' => $instanceId, 'operation_id' => $operationId, 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1)->update([ 'state' => 'committed', 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('双栈公网地址提交账本未精确更新', 409); } } return self::snapshot(self::lockedClaims($reservationId)); }); } /** * Atomically hand one migration instance from its source bundle to target. * * Both hosts and every network row are locked in a single deterministic * order. Claim and address identities never move between reservations. * * @return array{source:CloudActivePublicNetworkClaimSet, * target:CloudActivePublicNetworkClaimSet} */ public static function handoffMigrationBundles( int $sourceReservationId, int $targetReservationId, int $instanceId, string $sourceOperationId, string $targetOperationId ): array { self::assertIdentity($sourceReservationId, $sourceOperationId); self::assertIdentity($targetReservationId, $targetOperationId); if ($instanceId < 1) { throw new CloudError('实例网络归属无效', 409); } if ($sourceReservationId === $targetReservationId) { throw new CloudError('迁移源和目标资源预留必须不同', 409); } return self::connection()->transaction(static function () use ( $sourceReservationId, $targetReservationId, $instanceId, $sourceOperationId, $targetOperationId ): array { $reservationIds = [$sourceReservationId, $targetReservationId]; sort($reservationIds, SORT_NUMERIC); $reservationHints = DB::table('cloud_resource_reservations') ->whereIn('id', $reservationIds)->orderBy('id')->get()->all(); if (count($reservationHints) !== 2) { throw new CloudError('双栈公网地址账本不完整', 409); } $reservationHintsById = []; $hostIds = []; foreach ($reservationHints as $hint) { $reservationHintsById[(int) $hint->id] = $hint; $hostIds[(int) $hint->host_id] = true; } if (!isset($reservationHintsById[$sourceReservationId], $reservationHintsById[$targetReservationId]) || count($hostIds) !== 2) { throw new CloudError('迁移双栈网络宿主机边界无效', 409); } $hostIds = array_keys($hostIds); sort($hostIds, SORT_NUMERIC); $hosts = DB::table('cloud_hosts')->whereIn('id', $hostIds) ->orderBy('id')->lockForUpdate()->get()->all(); if (count($hosts) !== 2) { throw new CloudError('公网网络宿主机不存在', 409); } $claimHints = DB::table('cloud_resource_reservation_ips') ->whereIn('reservation_id', $reservationIds) ->where('active_claim', 1)->orderBy('reservation_id') ->orderBy('address_family')->orderBy('id')->get()->all(); if (count($claimHints) !== 4) { throw new CloudError('双栈公网地址账本不完整', 409); } $attachmentIds = []; $poolIds = []; foreach ($claimHints as $claim) { $attachmentIds[(int) $claim->network_attachment_id] = true; $poolIds[(int) $claim->public_ip_pool_id] = true; } $attachmentIds = array_keys($attachmentIds); $poolIds = array_keys($poolIds); sort($attachmentIds, SORT_NUMERIC); sort($poolIds, SORT_NUMERIC); DB::table('cloud_host_network_attachments') ->whereIn('id', $attachmentIds)->orderBy('id') ->lockForUpdate()->get(); DB::table('cloud_public_ip_pools')->whereIn('id', $poolIds) ->orderBy('id')->lockForUpdate()->get(); $lockedReservations = DB::table('cloud_resource_reservations') ->whereIn('id', $reservationIds)->orderBy('id') ->lockForUpdate()->get()->all(); $reservations = []; foreach ($lockedReservations as $reservation) { $reservations[(int) $reservation->id] = $reservation; } $source = $reservations[$sourceReservationId] ?? null; $target = $reservations[$targetReservationId] ?? null; self::assertReservation( $source, (int) $reservationHintsById[$sourceReservationId]->host_id, $sourceOperationId, ['committed'] ); self::assertReservation( $target, (int) $reservationHintsById[$targetReservationId]->host_id, $targetOperationId, ['held', 'uncertain'] ); if ((int) ($source->instance_id ?? 0) !== $instanceId || $target->instance_id !== null) { throw new CloudError('迁移双栈网络归属不一致', 409); } $lockedClaims = DB::table('cloud_resource_reservation_ips') ->whereIn('reservation_id', $reservationIds) ->where('active_claim', 1)->orderBy('reservation_id') ->orderBy('address_family')->orderBy('id')->lockForUpdate() ->get()->all(); $claimIdentity = static function (object $claim): array { return [ (int) $claim->id, (int) $claim->reservation_id, (string) $claim->address_family, (int) $claim->network_attachment_id, (int) $claim->public_ip_pool_id, (int) $claim->public_ip_id, (string) $claim->operation_id, (int) $claim->claim_generation, (string) $claim->state, ]; }; if (array_map($claimIdentity, $claimHints) !== array_map($claimIdentity, $lockedClaims)) { // The network context was selected from the unlocked hints. // A changed claim could otherwise introduce a late attachment // or pool lock and break the canonical global lock order. throw new CloudError('迁移双栈网络账本已变化,请重新核对', 409); } $claimsByReservation = [ $sourceReservationId => [], $targetReservationId => [], ]; foreach ($lockedClaims as $claim) { $claimsByReservation[(int) $claim->reservation_id][] = $claim; } $sourceClaims = $claimsByReservation[$sourceReservationId]; $targetClaims = $claimsByReservation[$targetReservationId]; $targetClaimState = self::claimStateForReservation($target); self::assertClaimSet( $sourceClaims, $sourceOperationId, ['committed'] ); self::assertClaimSet( $targetClaims, $targetOperationId, [$targetClaimState] ); $sourceSelection = self::lockClaimNetworkContext( $sourceClaims, (int) $source->host_id ); $targetSelection = self::lockClaimNetworkContext( $targetClaims, (int) $target->host_id ); self::assertClaimsUseSelection($sourceClaims, $sourceSelection); self::assertClaimsUseSelection($targetClaims, $targetSelection); $addresses = self::lockClaimAddresses($lockedClaims); self::assertClaimAddresses( $sourceClaims, $addresses, $sourceSelection, $sourceOperationId, ['committed' => ['assigned']], $instanceId ); self::assertClaimAddresses( $targetClaims, $addresses, $targetSelection, $targetOperationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ] ); $sourceClaimSet = self::claimSet( $sourceClaims, 'committed', $instanceId, (int) $source->host_id ); $now = time(); foreach ($sourceClaims as $claim) { $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_id', $sourceReservationId) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $sourceOperationId) ->where('instance_id', $instanceId) ->where('state', 'assigned')->update([ 'state' => 'reserved', 'instance_id' => null, 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1) ->where('operation_id', $sourceOperationId) ->where('state', 'committed')->update([ 'state' => 'reserved', 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('迁移源双栈地址未精确转为清理债务', 409); } } foreach ($targetClaims as $claim) { $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_id', $targetReservationId) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $targetOperationId) ->whereNull('instance_id') ->where('state', $targetClaimState)->update([ 'state' => 'assigned', 'instance_id' => $instanceId, 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1) ->where('operation_id', $targetOperationId) ->where('state', $targetClaimState)->update([ 'state' => 'committed', 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('迁移目标双栈地址未精确提交', 409); } } $sourceUpdated = DB::table('cloud_resource_reservations') ->where('id', $sourceReservationId) ->where('operation_id', $sourceOperationId) ->where('instance_id', $instanceId) ->where('state', 'committed')->update([ 'state' => 'held', 'instance_id' => null, 'expires_at' => null, 'updated_at' => $now, ]); $targetUpdated = DB::table('cloud_resource_reservations') ->where('id', $targetReservationId) ->where('operation_id', $targetOperationId) ->whereNull('instance_id') ->where('state', (string) $target->state)->update([ 'state' => 'committed', 'instance_id' => $instanceId, 'expires_at' => null, 'released_at' => null, 'release_reason' => '', 'updated_at' => $now, ]); if ($sourceUpdated !== 1 || $targetUpdated !== 1) { throw new CloudError('迁移源资源预留未精确转为清理债务', 409); } $targetClaimSet = self::claimSet( self::lockedClaims($targetReservationId), 'committed', $instanceId, (int) $target->host_id ); return [ 'source' => $sourceClaimSet, 'target' => $targetClaimSet, ]; }); } public static function fenceBundle(int $reservationId, string $operationId): void { self::assertIdentity($reservationId, $operationId); self::connection()->transaction(static function () use ( $reservationId, $operationId ): void { $reservationHint = self::unlockedReservation($reservationId); 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, ['held', 'uncertain']); $claims = self::lockedClaims($reservationId); $claimState = self::claimStateForReservation($reservation); self::assertClaimSet( $claims, $operationId, [$claimState] ); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); if ($claimState === 'uncertain') { return; } $now = time(); foreach ($claims as $claim) { $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $operationId)->update([ 'state' => 'uncertain', 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1)->update([ 'state' => 'uncertain', 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('双栈公网地址隔离账本未精确更新', 409); } } }); } /** * Re-open one fenced bundle only after the Agent effect is proven absent. * * The same two addresses remain reserved. This transition never allocates * replacements and never accepts an ambiguous effect. */ public static function reopenBundleForRetry(int $reservationId, string $operationId, bool $effectConfirmedAbsent): CloudPublicNetworkSnapshot { self::assertIdentity($reservationId, $operationId); if (!$effectConfirmedAbsent) { throw new CloudError('操作效果尚未确认,公网地址继续锁定', 409); } return self::connection()->transaction(static function () use ( $reservationId, $operationId ): CloudPublicNetworkSnapshot { $reservationHint = self::unlockedReservation($reservationId); 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, ['held', 'uncertain']); $claims = self::lockedClaims($reservationId); $claimState = self::claimStateForReservation($reservation); self::assertClaimSet($claims, $operationId, [$claimState]); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); if ($claimState === 'reserved') { return self::snapshot($claims); } $now = time(); foreach ($claims as $claim) { $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $operationId) ->where('state', 'uncertain')->update([ 'state' => 'reserved', 'instance_id' => null, 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1) ->where('state', 'uncertain')->update([ 'state' => 'reserved', 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('双栈公网地址重试账本未精确恢复', 409); } } $reservationUpdated = DB::table('cloud_resource_reservations') ->where('id', $reservationId) ->where('operation_id', $operationId) ->where('state', 'uncertain') ->whereNull('instance_id')->update([ 'state' => 'held', 'updated_at' => $now, ]); if ($reservationUpdated !== 1) { throw new CloudError('双栈公网地址重试预留未精确恢复', 409); } return self::snapshot(self::lockedClaims($reservationId)); }); } /** * Give a confirmed-not-applied retry a fresh Agent operation identity. * * Historical claims remain immutable evidence for the old operation. A * new active generation owns the same two addresses under the new ID. */ public static function rotateHeldBundleOperation(int $reservationId, string $oldOperationId, string $newOperationId): CloudPublicNetworkSnapshot { self::assertIdentity($reservationId, $oldOperationId); self::assertIdentity($reservationId, $newOperationId); if (hash_equals($oldOperationId, $newOperationId)) { throw new CloudError('公网网络重试必须使用新的操作标识', 409); } return self::connection()->transaction(static function () use ( $reservationId, $oldOperationId, $newOperationId ): CloudPublicNetworkSnapshot { $reservationHint = self::unlockedReservation($reservationId); 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); if ($reservation === null || (int) $reservation->host_id !== $hostId || (string) $reservation->state !== 'held' || $reservation->instance_id !== null) { throw new CloudError('公网网络资源预留不一致', 409); } $currentOperationId = (string) $reservation->operation_id; if (!hash_equals($currentOperationId, $oldOperationId) && !hash_equals($currentOperationId, $newOperationId)) { throw new CloudError('公网网络操作身份已经变化', 409); } $claims = self::lockedClaims($reservationId); self::assertClaimSet($claims, $currentOperationId, ['reserved']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, $currentOperationId, ['reserved' => ['reserved']]); if (hash_equals($currentOperationId, $newOperationId)) { return self::snapshot($claims); } $historical = self::lockedHistoricalClaims($reservationId); $generation = 0; foreach (array_merge($historical, $claims) as $claim) { $generation = max( $generation, (int) ($claim->claim_generation ?? 0) ); } if ($generation < 1 || $generation === PHP_INT_MAX) { throw new CloudError('双栈公网地址声明代次无效', 409); } $nextGeneration = $generation + 1; $now = time(); $newClaims = []; foreach ($claims as $claim) { $retired = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1) ->where('operation_id', $oldOperationId) ->where('state', 'reserved')->update([ 'state' => 'released', 'active_claim' => null, 'released_at' => $now, 'release_reason' => 'migration_transfer_not_applied', 'updated_at' => $now, ]); if ($retired !== 1) { throw new CloudError('旧双栈公网地址声明未精确归档', 409); } $claimId = DB::table('cloud_resource_reservation_ips') ->insertGetId([ 'reservation_id' => $reservationId, 'address_family' => (int) $claim->address_family, 'claim_generation' => $nextGeneration, 'active_claim' => 1, 'network_attachment_id' => (int) $claim->network_attachment_id, 'public_ip_pool_id' => (int) $claim->public_ip_pool_id, 'public_ip_id' => (int) $claim->public_ip_id, 'operation_id' => $newOperationId, 'state' => 'reserved', 'created_at' => $now, 'updated_at' => $now, 'released_at' => null, 'release_reason' => '', ]); $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_id', $reservationId) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', $oldOperationId) ->where('state', 'reserved')->update([ 'reservation_ip_claim_id' => $claimId, 'operation_id' => $newOperationId, 'instance_id' => null, 'updated_at' => $now, ]); if ($ipUpdated !== 1) { throw new CloudError('新双栈公网地址声明未精确绑定', 409); } $newClaims[] = DB::table('cloud_resource_reservation_ips') ->where('id', $claimId)->first(); } $reservationUpdated = DB::table('cloud_resource_reservations') ->where('id', $reservationId) ->where('operation_id', $oldOperationId) ->where('state', 'held') ->whereNull('instance_id')->update([ 'operation_id' => $newOperationId, 'updated_at' => $now, ]); if ($reservationUpdated !== 1) { throw new CloudError('双栈公网地址重试操作未精确轮换', 409); } return self::snapshot($newClaims); }); } public static function releaseBundle(int $reservationId, string $operationId, string $reason, bool $effectConfirmedAbsent): void { self::assertIdentity($reservationId, $operationId); if (!$effectConfirmedAbsent) { throw new CloudError('操作效果尚未确认,公网地址继续锁定', 409); } self::assertReleaseReason($reason); self::connection()->transaction(static function () use ( $reservationId, $operationId, $reason ): void { $reservationHint = self::unlockedReservation($reservationId); 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, ['held', 'uncertain']); $claims = self::lockedClaims($reservationId); self::assertClaimSet( $claims, $operationId, [self::claimStateForReservation($reservation)] ); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, $operationId, [ 'reserved' => ['reserved'], 'uncertain' => ['uncertain'], ]); self::releaseLockedClaims($claims, $reason); }); } /** * Releases an assigned bundle only after the owning VM effect is known to * be absent. Address replacement must use a separate transition ledger; * it must never overwrite these committed source claims. */ public static function releaseCommittedBundle(int $reservationId, int $instanceId, string $operationId, string $reason, bool $effectConfirmedAbsent): void { self::assertIdentity($reservationId, $operationId); if ($instanceId < 1 || !$effectConfirmedAbsent) { throw new CloudError('实例删除效果尚未确认,公网地址继续锁定', 409); } self::assertReleaseReason($reason); self::connection()->transaction(static function () use ( $reservationId, $instanceId, $operationId, $reason ): void { $reservationHint = self::unlockedReservation($reservationId); 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, ['committed']); if ((int) ($reservation->instance_id ?? 0) !== $instanceId) { throw new CloudError('实例网络归属与资源预留不一致', 409); } $claims = self::lockedClaims($reservationId); self::assertActiveClaimSet($claims, ['committed']); self::assertClaimsUseSelection($claims, $selection); $addresses = self::lockClaimAddresses($claims); self::assertClaimAddresses($claims, $addresses, $selection, null, [ 'committed' => ['assigned'], ], $instanceId); self::releaseLockedClaims($claims, $reason); }); } private static function unlockedReservation(int $reservationId): ?object { return DB::table('cloud_resource_reservations') ->where('id', $reservationId)->first(); } private static function unlockedClaims(int $reservationId): array { return DB::table('cloud_resource_reservation_ips') ->where('reservation_id', $reservationId) ->where('active_claim', 1) ->orderBy('address_family')->orderBy('id')->get()->all(); } private static function lockHost(int $hostId): void { $host = DB::table('cloud_hosts')->where('id', $hostId) ->lockForUpdate()->first(); if ($host === null) { throw new CloudError('公网网络宿主机不存在', 409); } } private static function lockReservation(int $reservationId): ?object { return DB::table('cloud_resource_reservations') ->where('id', $reservationId)->lockForUpdate()->first(); } private static function assertReservation(?object $reservation, int $hostId, string $operationId, array $allowedStates): void { if ($reservation === null || (int) $reservation->host_id !== $hostId || !hash_equals($operationId, (string) $reservation->operation_id) || !in_array((string) $reservation->state, $allowedStates, true)) { throw new CloudError('公网网络资源预留不一致', 409); } } private static function claimStateForReservation(object $reservation): string { $state = (string) ($reservation->state ?? ''); $instanceId = $reservation->instance_id === null ? null : (int) $reservation->instance_id; if (($state === 'committed' && ($instanceId === null || $instanceId < 1)) || (in_array($state, ['held', 'uncertain'], true) && $instanceId !== null)) { throw new CloudError( '公网网络资源预留生命周期不一致', 409 ); } return match ($state) { 'held' => 'reserved', 'committed' => 'committed', 'uncertain' => 'uncertain', default => throw new CloudError( '公网网络资源预留生命周期不一致', 409 ), }; } /** Locks the exact historical attachment and pools before the reservation. */ private static function lockClaimNetworkContext(array $claimHints, int $hostId, ?int $lineId = null): array { $attachmentIds = array_values(array_unique(array_map( static fn ($claim): int => (int) $claim->network_attachment_id, $claimHints ))); $poolIds = array_values(array_unique(array_map( static fn ($claim): int => (int) $claim->public_ip_pool_id, $claimHints ))); sort($attachmentIds, SORT_NUMERIC); sort($poolIds, SORT_NUMERIC); if ($attachmentIds === [] || $poolIds === []) { throw new CloudError('双栈公网地址账本不完整', 409); } $attachments = DB::table('cloud_host_network_attachments') ->whereIn('id', $attachmentIds)->orderBy('id') ->lockForUpdate()->get()->all(); $poolRows = DB::table('cloud_public_ip_pools') ->whereIn('id', $poolIds)->orderBy('id') ->lockForUpdate()->get()->all(); if (count($attachments) !== 1 || count($poolRows) !== 2) { throw new CloudError('双栈公网地址网络边界损坏', 409); } $attachment = $attachments[0]; if ((int) $attachment->host_id !== $hostId || ($lineId !== null && (int) $attachment->line_id !== $lineId)) { throw new CloudError('双栈公网地址不属于预期网络', 409); } $pools = []; $contracts = []; foreach ($poolRows as $pool) { $family = (int) $pool->address_family; if (!in_array($family, self::FAMILIES, true) || isset($pools[$family]) || (int) $pool->host_id !== $hostId || (int) $pool->network_attachment_id !== (int) $attachment->id) { throw new CloudError('双栈公网地址池边界损坏', 409); } $contracts[$family] = self::requirePoolContract($pool, $family); $pools[$family] = $pool; } if (!isset($pools[4], $pools[6])) { throw new CloudError('双栈公网地址池不完整', 409); } return [ 'attachment' => $attachment, 'pools' => $pools, 'contracts' => $contracts, ]; } private static function assertClaimsUseSelection(array $claims, array $selection): void { foreach ($claims as $claim) { $family = (int) $claim->address_family; if (!isset($selection['pools'][$family]) || (int) $claim->network_attachment_id !== (int) $selection['attachment']->id || (int) $claim->public_ip_pool_id !== (int) $selection['pools'][$family]->id) { throw new CloudError('双栈公网地址账本网络边界不一致', 409); } } } /** @return array */ private static function lockClaimAddresses(array $claims): array { $ids = array_values(array_unique(array_map( static fn ($claim): int => (int) $claim->public_ip_id, $claims ))); sort($ids, SORT_NUMERIC); $rows = DB::table('cloud_public_ips')->whereIn('id', $ids) ->orderBy('id')->lockForUpdate()->get()->all(); $result = []; foreach ($rows as $row) { $result[(int) $row->id] = $row; } if (count($result) !== count($ids)) { throw new CloudError('双栈公网地址引用损坏', 409); } return $result; } private static function assertPoolLedger(object $pool, CloudPublicIpPoolContract $contract, array $rows): void { foreach ($rows as $row) { self::assertConcreteAddress($row, $pool, $contract); self::assertAddressOwnership($row); } } private static function assertConcreteAddress(object $row, object $pool, CloudPublicIpPoolContract $contract): CloudIpAddress { try { if ((string) $row->state === 'disabled') { return CloudPublicNetworkAddressPolicy::assertIdentity( $row, $pool, $contract ); } return CloudPublicNetworkAddressPolicy::assertSelectable( $row, $pool, $contract, CloudPanelUsageService::managementAddress( CloudHost::find((int) $pool->host_id) ) ); } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } } /** Validate immutable identity without reapplying mutable allowlists. */ private static function assertConcreteAddressIdentity(object $row, object $pool, CloudPublicIpPoolContract $contract): CloudIpAddress { try { return CloudPublicNetworkAddressPolicy::assertIdentity( $row, $pool, $contract ); } catch (\Throwable) { throw new CloudError('公网地址具体身份与地址池不一致', 409); } } private static function assertAddressOwnership(object $row): void { $reservationId = $row->reservation_id === null ? null : (int) $row->reservation_id; $instanceId = $row->instance_id === null ? null : (int) $row->instance_id; $claimId = $row->reservation_ip_claim_id === null ? null : (int) $row->reservation_ip_claim_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 && $claimId === null && $instanceId === null && $operationId === null, 'reserved' => $reservationId !== null && $reservationId > 0 && $claimId !== null && $claimId > 0 && $instanceId === null && $validOperation, 'assigned' => $reservationId !== null && $reservationId > 0 && $claimId !== null && $claimId > 0 && $instanceId !== null && $instanceId > 0 && $validOperation, 'changing', 'uncertain' => $reservationId !== null && $reservationId > 0 && $claimId !== null && $claimId > 0 && ($instanceId === null || $instanceId > 0) && $validOperation, default => false, }; if (!$valid) { throw new CloudError('公网地址占用账本形态不一致', 409); } } private static function assertClaimAddresses(array $claims, 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; $claimOperationId = (string) ($claim->operation_id ?? ''); $expectedOperationId = $operationId ?? $claimOperationId; $allowedIpStates = $allowedPairs[$claimState] ?? []; $family = (int) $claim->address_family; $pool = $selection['pools'][$family] ?? null; $contract = $selection['contracts'][$family] ?? null; if ($ip === null || $pool === null || !$contract instanceof CloudPublicIpPoolContract || $allowedIpStates === [] || !in_array((string) $ip->state, $allowedIpStates, true) || (int) $ip->reservation_id !== (int) $claim->reservation_id || (int) ($ip->reservation_ip_claim_id ?? 0) !== (int) $claim->id || (int) $ip->address_family !== (int) $claim->address_family || (int) $ip->public_ip_pool_id !== (int) $claim->public_ip_pool_id || preg_match('/^[a-f0-9]{32}$/D', $claimOperationId) !== 1 || !hash_equals($claimOperationId, (string) ($ip->operation_id ?? '')) || !hash_equals($expectedOperationId, (string) ($ip->operation_id ?? ''))) { throw new CloudError('公网地址与预留账本不一致', 409); } self::assertConcreteAddress($ip, $pool, $contract); self::assertAddressOwnership($ip); if ((string) $ip->state === 'assigned') { $actualInstanceId = (int) ($ip->instance_id ?? 0); if ($actualInstanceId < 1 || ($instanceId !== null && $actualInstanceId !== $instanceId)) { throw new CloudError('公网地址实例归属不一致', 409); } } elseif ($ip->instance_id !== null) { throw new CloudError('未提交公网地址存在实例归属', 409); } } } private static function releaseLockedClaims(array $claims, string $reason): void { $now = time(); foreach ($claims as $claim) { $ipUpdated = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id) ->where('reservation_ip_claim_id', (int) $claim->id) ->where('operation_id', (string) $claim->operation_id) ->update([ 'state' => 'available', 'reservation_id' => null, 'reservation_ip_claim_id' => null, 'instance_id' => null, 'operation_id' => null, 'updated_at' => $now, ]); $claimUpdated = DB::table('cloud_resource_reservation_ips') ->where('id', (int) $claim->id) ->where('active_claim', 1)->update([ 'state' => 'released', 'active_claim' => null, 'released_at' => $now, 'release_reason' => $reason, 'updated_at' => $now, ]); if ($ipUpdated !== 1 || $claimUpdated !== 1) { throw new CloudError('双栈公网地址释放账本未精确更新', 409); } } } private static function assertReleaseReason(string $reason): void { if (preg_match('/^[a-z][a-z0-9_]{2,63}$/D', $reason) !== 1) { throw new CloudError('公网地址释放原因无效', 409); } } /** * 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, ?CloudPublicNetworkBundleConstraint $constraint = null): array { $agent = CloudHostAgent::where('host_id', $hostId) ->lockForUpdate()->first(); if (!$agent instanceof CloudHostAgent || !$agent->isReady()) { throw new CloudError('宿主机 Agent 双栈网络验证证据无效', 409); } $attachmentQuery = DB::table('cloud_host_network_attachments') ->where('host_id', $hostId)->where('line_id', $lineId) ->where('state', 'active'); if ($constraint !== null) { $attachmentQuery->where('id', $constraint->attachmentId()); } $attachments = $attachmentQuery->orderBy('id')->lockForUpdate() ->get()->all(); $eligible = []; foreach ($attachments as $attachment) { 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, ]); $poolQuery = 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); if ($constraint !== null) { $poolQuery->whereIn('id', [ $constraint->poolId(4), $constraint->poolId(6), ]); } $poolRows = $poolQuery->orderBy('id')->lockForUpdate()->get()->all(); $pools = []; $contracts = []; 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); } $contracts[(int) $pool->id] = self::requirePoolContract( $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); } return [ 'attachments' => $eligible, 'pools' => $pools, 'contracts' => $contracts, ]; } /** Called only after the reservation row is locked. */ private static function selectAvailablePoolPair(array $catalog, ?CloudPublicNetworkBundleConstraint $constraint = null): 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) { $contract = $catalog['contracts'][$poolId] ?? null; if (!$contract instanceof CloudPublicIpPoolContract) { throw new CloudError('公网地址池合同缺失', 409); } self::assertPoolLedger($pool, $contract, $rowsByPool[$poolId]); } $firstPool = reset($allPools); $selector = CloudPublicNetworkCandidateCatalog::fromLocked( $catalog['attachments'], $catalog['pools'], $catalog['contracts'], $rowsByPool, is_object($firstPool) ? CloudPanelUsageService::managementAddress( CloudHost::find((int) $firstPool->host_id) ) : null ); $excluded = []; while (true) { $plan = $selector->planAllocation($constraint, $excluded); if (!$plan instanceof CloudPublicNetworkCandidatePlan) { throw new CloudPublicNetworkCapacityUnavailable( $constraint === null ? '宿主机没有完整可用的双栈公网地址池' : '计划公网网络双栈地址池没有完整可用容量', 409 ); } $selection = $plan->allocationSelection(); $retry = false; foreach ($selection['address_candidates'] as $candidate) { $address = $candidate['candidate'] ?? null; if (!$address instanceof CloudIpAddress) { continue; } // Keep the global collision lock outside the pure catalog. $existing = DB::table('cloud_public_ips') ->where('address_family', $address->family()) ->where('address_binary', $address->binary()) ->lockForUpdate()->first(); if ($existing !== null) { $excluded[bin2hex($address->binary())] = true; $retry = true; break; } } if (!$retry) { return $selection; } } } private static function reserveAddress(object $pool, int $now, ?array $selection): object { $family = (int) $pool->address_family; if ($selection === null) { throw new CloudError( $family === 6 ? '公网 IPv6 地址池没有可分配地址' : '公网 IPv4 地址池已经耗尽', 409 ); } if ($selection['row'] !== null) { $row = $selection['row']; if ((string) $row->state !== 'available' || $row->reservation_id !== null || $row->reservation_ip_claim_id !== null || $row->instance_id !== null || $row->operation_id !== null) { throw new CloudError('公网地址候选已被占用', 409); } return $row; } $candidate = $selection['candidate']; $rangeStart = $selection['range_start']; $rangeEnd = $selection['range_end']; if (!$candidate instanceof CloudIpAddress || !$rangeStart instanceof CloudIpAddress || !$rangeEnd instanceof CloudIpAddress) { throw new CloudError('公网 IPv6 稀疏分配选择损坏', 409); } $id = DB::table('cloud_public_ips')->insertGetId([ 'host_id' => (int) $pool->host_id, 'public_ip_pool_id' => (int) $pool->id, 'address_family' => 6, 'address' => $candidate->text(), 'address_binary' => $candidate->binary(), 'prefix_length' => (int) $pool->guest_prefix_length, 'state' => 'available', 'reservation_id' => null, 'reservation_ip_claim_id' => null, 'instance_id' => null, 'operation_id' => null, 'created_at' => $now, 'updated_at' => $now, ]); $next = $candidate->compare($rangeEnd) === 0 ? $rangeStart : $candidate->next(); DB::table('cloud_public_ip_pools') ->where('id', (int) $pool->id)->update([ 'allocation_cursor' => $next->text(), ]); return DB::table('cloud_public_ips')->where('id', $id)->first(); } private static function bindAddressToClaim(object $row, int $reservationId, string $operationId, int $claimId, int $now): void { $updated = DB::table('cloud_public_ips') ->where('id', (int) $row->id) ->where('state', 'available') ->whereNull('reservation_id') ->whereNull('reservation_ip_claim_id') ->whereNull('instance_id') ->whereNull('operation_id')->update([ 'state' => 'reserved', 'reservation_id' => $reservationId, 'reservation_ip_claim_id' => $claimId, 'instance_id' => null, 'operation_id' => $operationId, 'updated_at' => $now, ]); if ($updated !== 1) { throw new CloudError('公网地址声明绑定失败', 409); } } private static function requirePoolContract(object $pool, int $family): CloudPublicIpPoolContract { try { return CloudPublicNetworkAddressPolicy::contract($pool, $family); } catch (\Throwable) { throw new CloudError('公网地址池配置损坏', 409); } } private static function decodedAddresses(string $json, bool $allowEmpty, int $maximum = 256): array { $values = json_decode($json, true, 16, JSON_THROW_ON_ERROR); if (!is_array($values) || !array_is_list($values) || (!$allowEmpty && $values === []) || count($values) > $maximum) { throw new \InvalidArgumentException('Address list is invalid.'); } $result = []; foreach ($values as $raw) { $address = CloudIpAddress::parse($raw); if (!$address->isPublicUnicast() || isset($result[$address->text()])) { throw new \InvalidArgumentException('Address list is invalid.'); } $result[$address->text()] = true; } return $result; } private static function lockedClaims(int $reservationId): array { return DB::table('cloud_resource_reservation_ips') ->where('reservation_id', $reservationId) ->where('active_claim', 1) ->orderBy('address_family')->orderBy('id')->lockForUpdate()->get() ->all(); } private static function lockedHistoricalClaims(int $reservationId): array { return DB::table('cloud_resource_reservation_ips') ->where('reservation_id', $reservationId) ->whereNull('active_claim')->orderBy('id')->lockForUpdate()->get() ->all(); } private static function assertClaimSet(array $claims, string $operationId, array $allowedStates): void { self::assertActiveClaimSet($claims, $allowedStates); foreach ($claims as $claim) { if (!hash_equals($operationId, (string) $claim->operation_id)) { throw new CloudError('双栈公网地址操作身份不一致', 409); } } } private static function assertActiveClaimSet(array $claims, array $allowedStates): void { if (count($claims) !== 2) { throw new CloudError('双栈公网地址账本不完整', 409); } $families = []; foreach ($claims as $claim) { $family = (int) $claim->address_family; if (!in_array($family, self::FAMILIES, true) || isset($families[$family]) || (int) ($claim->claim_generation ?? 0) < 1 || (int) ($claim->active_claim ?? 0) !== 1 || preg_match('/^[a-f0-9]{32}$/D', (string) ($claim->operation_id ?? '')) !== 1 || !in_array((string) $claim->state, $allowedStates, true)) { throw new CloudError('双栈公网地址账本不一致', 409); } $families[$family] = true; } if (!isset($families[4], $families[6])) { throw new CloudError('双栈公网地址账本不完整', 409); } } private static function snapshot(array $claims): CloudPublicNetworkSnapshot { return self::claimSet($claims)->publicNetwork(); } private static function claimSet( array $claims, ?string $expectedState = null, ?int $expectedInstanceId = null, ?int $expectedHostId = null, ?int $expectedLineId = null ): CloudActivePublicNetworkClaimSet { if (count($claims) !== 2) { throw new CloudError('双栈公网地址账本不完整', 409); } $attachmentIds = array_values(array_unique(array_map( static fn ($claim): int => (int) $claim->network_attachment_id, $claims ))); if (count($attachmentIds) !== 1) { throw new CloudError('双栈公网地址不属于同一网络接入', 409); } $attachment = DB::table('cloud_host_network_attachments') ->where('id', $attachmentIds[0])->first(); if ($attachment === null) { throw new CloudError('公网网络接入不存在', 409); } $attachmentHostId = (int) $attachment->host_id; if ($attachmentHostId < 1 || ($expectedHostId !== null && $attachmentHostId !== $expectedHostId) || ($expectedLineId !== null && (int) $attachment->line_id !== $expectedLineId)) { throw new CloudError('公网网络接入不存在', 409); } $legs = []; $dns = []; $addresses = []; $reservationIds = []; foreach ($claims as $claim) { $family = (int) $claim->address_family; $pool = DB::table('cloud_public_ip_pools') ->where('id', (int) $claim->public_ip_pool_id)->first(); $ip = DB::table('cloud_public_ips') ->where('id', (int) $claim->public_ip_id)->first(); if ($pool === null || $ip === null || (int) $pool->address_family !== $family || (int) $ip->address_family !== $family || (int) $pool->host_id !== $attachmentHostId || (int) $ip->host_id !== $attachmentHostId || (int) $pool->network_attachment_id !== $attachmentIds[0] || (int) $ip->public_ip_pool_id !== (int) $pool->id) { throw new CloudError('双栈公网地址引用损坏', 409); } $contract = self::requirePoolContract($pool, $family); self::assertConcreteAddressIdentity($ip, $pool, $contract); $addresses[(int) $ip->id] = $ip; $reservationIds[(int) $claim->reservation_id] = true; $legs[$family] = [ 'pool_key' => (string) $pool->pool_key, 'pool_cidr' => (string) $pool->cidr, 'address_cidr' => (string) $ip->address . '/' . (int) $ip->prefix_length, 'gateway' => (string) $pool->gateway, 'gateway_on_link' => (bool) $pool->gateway_on_link, ]; foreach ($contract->dnsServers() as $text) { $dns[$text] = $text; } } if (count($reservationIds) !== 1) { throw new CloudError('双栈公网地址不属于同一资源预留', 409); } self::assertCurrentClaimSetStates( $claims, $addresses, $expectedState, $expectedInstanceId ); $snapshot = CloudPublicNetworkSnapshot::fromArray([ 'contract' => 1, 'network_selector' => (string) $attachment->network_selector, 'ipv4' => $legs[4] ?? null, 'ipv6' => $legs[6] ?? null, 'dns_servers' => array_values($dns), ]); return CloudActivePublicNetworkClaimSet::fromLedger( (int) array_key_first($reservationIds), $attachmentHostId, $claims, $addresses, $snapshot ); } /** * @param array $claims * @param array $addresses */ private static function assertCurrentClaimSetStates(array $claims, array $addresses, ?string $expectedState, ?int $expectedInstanceId): void { $claimStates = []; $instanceIds = []; foreach ($claims as $claim) { $claimState = (string) ($claim->state ?? ''); $ip = $addresses[(int) ($claim->public_ip_id ?? 0)] ?? null; $ipState = is_object($ip) ? (string) ($ip->state ?? '') : ''; $expectedIpState = match ($claimState) { 'reserved' => 'reserved', 'committed' => 'assigned', 'uncertain' => 'uncertain', default => '', }; $instanceId = is_object($ip) && $ip->instance_id !== null ? (int) $ip->instance_id : null; if ($expectedIpState === '' || $ipState !== $expectedIpState || ($claimState !== 'committed' && $instanceId !== null) || ($claimState === 'committed' && ($instanceId === null || $instanceId < 1))) { throw new CloudError('活动双栈公网地址状态不一致', 409); } $claimStates[$claimState] = true; if ($instanceId !== null) { $instanceIds[$instanceId] = true; } } if (count($claimStates) !== 1 || ($expectedState !== null && !isset($claimStates[$expectedState])) || (isset($claimStates['committed']) && count($instanceIds) !== 1) || (!isset($claimStates['committed']) && $instanceIds !== []) || ($expectedInstanceId !== null && !isset($instanceIds[$expectedInstanceId]))) { throw new CloudError('活动双栈公网地址集合状态不一致', 409); } } private static function assertIdentity(int $reservationId, string $operationId): void { if ($reservationId < 1 || preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) { throw new CloudError('公网网络操作标识无效', 409); } } private static function connection(): Connection { return DB::connection('default'); } }