From a0861247e0c678b2dcc9de253c9e1ec53d22752c Mon Sep 17 00:00:00 2001 From: codex Date: Wed, 28 Oct 2026 20:53:02 +0800 Subject: [PATCH] feat(vpc): clean up ports after instance deletion --- .../Services/Cloud/CloudLifecycleService.php | 10 + .../Services/Cloud/CloudVpcPortService.php | 207 +++++++++++++++++- web/app/Services/Cloud/CloudWorkerService.php | 3 + web/tests/CloudFinancialWorkflowTest.php | 1 + web/tests/CloudRuntimeHeartbeatTest.php | 8 + web/tests/CloudVpcPortWorkflowTest.php | 112 ++++++++++ 6 files changed, 340 insertions(+), 1 deletion(-) diff --git a/web/app/Services/Cloud/CloudLifecycleService.php b/web/app/Services/Cloud/CloudLifecycleService.php index a1c3cf91..3db25fe7 100644 --- a/web/app/Services/Cloud/CloudLifecycleService.php +++ b/web/app/Services/Cloud/CloudLifecycleService.php @@ -72,6 +72,16 @@ final class CloudLifecycleService error_log('cloud automatic backup retention unavailable: ' . get_class($error)); } + $this->heartbeat?->busy('vpc_deleted_instance_cleanup'); + try { + $queued += CloudVpcPortService::retryDeletedCleanupDue( + $automaticLimit + ); + } catch (\Throwable $error) { + $this->observeFailure('vpc_deleted_instance_cleanup_failed'); + error_log('cloud VPC deleted-instance cleanup unavailable: ' + . get_class($error)); + } $this->heartbeat?->busy('traffic_sync'); try { $collection = CloudTrafficService::collect($batchSize); diff --git a/web/app/Services/Cloud/CloudVpcPortService.php b/web/app/Services/Cloud/CloudVpcPortService.php index 1f1881cf..46374060 100644 --- a/web/app/Services/Cloud/CloudVpcPortService.php +++ b/web/app/Services/Cloud/CloudVpcPortService.php @@ -21,6 +21,8 @@ use App\Models\CloudVpcPort; */ final class CloudVpcPortService { + private const DELETED_CLEANUP_RETRY_DELAY = 300; + private const JOB_KINDS = [ 'vpc_host_apply', 'vpc_host_remove', 'vpc_port_attach', 'vpc_port_detach', @@ -255,6 +257,186 @@ final class CloudVpcPortService }, 3); } + /** + * Start route/IP cleanup only after the Agent has proved the VM and every + * managed artifact are absent. The caller already holds the instance row + * lock inside the delete finalizer transaction. No private address is + * released until every resulting host projection has converged. + * + * @return list + */ + public static function releaseAfterInstanceDeletedLocked( + CloudInstance $instance + ): array { + $reference = CloudVpcPort::query() + ->where('instance_id', (int) $instance->id) + ->where('active_claim', 1)->first(); + if ($reference === null) { + return []; + } + $vpc = CloudVpc::query()->where('id', (int) $reference->vpc_id) + ->lockForUpdate()->first(); + $port = CloudVpcPort::query()->where('id', (int) $reference->id) + ->where('active_claim', 1)->lockForUpdate()->first(); + if ($vpc === null || $port === null + || (int) $port->instance_id !== (int) $instance->id + || (int) $port->user_id !== (int) $instance->user_id + || (int) $port->vpc_id !== (int) $vpc->id + || (int) $vpc->user_id !== (int) $instance->user_id) { + throw new CloudError('删除实例的 VPC 端口账本不一致', 409); + } + if (self::activePortJobLocked($instance, $port) !== null) { + throw new CloudError('删除实例仍有 VPC 任务未收敛', 409); + } + if ((string) $port->state === 'release_pending') { + $job = self::retryReleaseLocked($instance, $vpc, $port); + return $job === null ? [] : [$job]; + } + if (!in_array((string) $port->state, + ['attached', 'preparing'], true)) { + throw new CloudError('删除实例的 VPC 端口状态不允许释放', 409); + } + + $now = time(); + $port->state = 'release_pending'; + $port->last_operation_id = null; + $port->last_error_code = ''; + $port->updated_at = $now; + $port->save(); + $revision = (int) $vpc->desired_revision + 1; + $vpc->desired_revision = $revision; + $vpc->state = 'provisioning'; + $vpc->updated_at = $now; + $vpc->save(); + $jobs = self::queueProjectionLocked($vpc, $port, $revision); + if ($jobs === []) { + self::releasePortLocked($vpc, $port); + } + return $jobs; + } + + /** Queue new, audited cleanup generations for deleted instances only. */ + public static function retryDeletedCleanupDue(int $limit = 10): int + { + $limit = max(1, min(100, $limit)); + $candidates = CloudVpcPort::query() + ->join('cloud_instances as deleted_instance', + 'deleted_instance.id', '=', 'cloud_vpc_ports.instance_id') + ->where('cloud_vpc_ports.active_claim', 1) + ->where('cloud_vpc_ports.state', 'release_pending') + ->where('deleted_instance.status', 'deleted') + ->orderBy('cloud_vpc_ports.id') + ->limit($limit) + ->get([ + 'cloud_vpc_ports.id as port_id', + 'cloud_vpc_ports.instance_id as instance_id', + ]); + $queued = 0; + foreach ($candidates as $candidate) { + try { + $queued += (new CloudInstance())->getConnection() + ->transaction(static function () use ($candidate): int { + $instance = CloudInstance::query() + ->where('id', (int) $candidate->instance_id) + ->lockForUpdate()->first(); + if ($instance === null + || (string) $instance->status !== 'deleted') { + return 0; + } + $reference = CloudVpcPort::query() + ->where('id', (int) $candidate->port_id) + ->where('instance_id', (int) $instance->id) + ->where('active_claim', 1)->first(); + if ($reference === null + || (string) $reference->state + !== 'release_pending') { + return 0; + } + if (!self::deletedCleanupRetryReadyLocked( + $reference, time() + )) { + return 0; + } + $jobs = self::releaseAfterInstanceDeletedLocked( + $instance + ); + return count($jobs); + }, 3); + } catch (\Throwable $error) { + error_log('cloud VPC deleted-instance cleanup unavailable: ' + . get_class($error)); + } + } + return $queued; + } + + private static function deletedCleanupRetryReadyLocked( + CloudVpcPort $port, + int $now + ): bool { + if (self::activePortJob( + (int) $port->instance_id, + (int) $port->id + ) !== null) { + return false; + } + $states = CloudVpcHostState::query() + ->where('vpc_id', (int) $port->vpc_id) + ->orderBy('host_id')->lockForUpdate()->get(); + if ($states->every(static fn ($state): bool => + self::hostReady($state))) { + return true; + } + foreach ($states as $state) { + if (self::hostReady($state)) { + continue; + } + if (self::knownNotAppliedHostFailureLocked( + $state, $now - self::DELETED_CLEANUP_RETRY_DELAY + ) === null) { + return false; + } + } + return true; + } + + /** + * Return the exact terminal generation only when it proves that no host + * mutation was applied. A failed UI state alone is never replay evidence. + */ + private static function knownNotAppliedHostFailureLocked( + CloudVpcHostState $state, + ?int $completedNoLaterThan = null + ): ?CloudJob { + if ((string) $state->sync_state !== 'failed' + || !is_string($state->last_operation_id) + || $state->last_operation_id === '') { + return null; + } + $job = CloudJob::query() + ->where('operation_id', (string) $state->last_operation_id) + ->where('vpc_id', (int) $state->vpc_id) + ->where('host_id', (int) $state->host_id) + ->whereIn('kind', ['vpc_host_apply', 'vpc_host_remove']) + ->lockForUpdate()->first(); + if ($job === null + || (string) $job->phase !== 'terminal' + || (string) $job->outcome !== 'failed' + || (string) $job->status !== 'failed' + || (string) $job->effect_resolution !== 'not_applied' + || (bool) $job->effect_may_have_applied + || !(bool) $job->safe_to_resubmit + || (bool) $job->finalization_incident) { + return null; + } + if ($completedNoLaterThan !== null + && max((int) ($job->terminal_at ?? 0), + (int) ($job->updated_at ?? 0)) > $completedNoLaterThan) { + return null; + } + return $job; + } + /** Trusted worker marker for VPC jobs that must finish after acceptance. */ public static function isSystemJob(CloudJob $job, array $payload): bool { @@ -612,7 +794,20 @@ final class CloudVpcPortService } foreach ($states as $state) { if (!self::hostReady($state)) { - throw new CloudError('旧 VPC 宿主机投影尚未收敛,不能清理', 409); + if (self::knownNotAppliedHostFailureLocked($state) === null) { + throw new CloudError( + '旧 VPC 宿主机投影尚未收敛,不能清理', 409 + ); + } + $hasAppliedProjection = (int) $state->applied_revision > 0 + && preg_match('/^[a-f0-9]{64}$/D', + (string) $state->applied_digest) === 1; + if (!$hasAppliedProjection) { + // A known-not-applied first projection has no host state + // to remove. Dropping only this failed intent is safe. + $state->delete(); + continue; + } } $state->sync_state = 'pending'; $state->last_error_code = ''; @@ -671,6 +866,11 @@ final class CloudVpcPortService if ((string) $state->sync_state !== 'failed') { continue; } + if (self::knownNotAppliedHostFailureLocked($state) === null) { + throw new CloudError( + 'VPC 路由失败结果尚未证明未生效,不能重试', 409 + ); + } $projection = $projections[(int) $state->host_id] ?? null; if ($projection !== null && hash_equals((string) $state->desired_digest, @@ -707,6 +907,11 @@ final class CloudVpcPortService if ((string) $state->sync_state !== 'failed') { continue; } + if (self::knownNotAppliedHostFailureLocked($state) === null) { + throw new CloudError( + 'VPC 清理失败结果尚未证明未生效,不能重试', 409 + ); + } // Rebuild the desired topology. A state absent from the new // projection is a remove retry; otherwise queue the exact apply. $ports = CloudVpcPort::query()->where('vpc_id', (int) $vpc->id) diff --git a/web/app/Services/Cloud/CloudWorkerService.php b/web/app/Services/Cloud/CloudWorkerService.php index c5bafdeb..90958e74 100644 --- a/web/app/Services/Cloud/CloudWorkerService.php +++ b/web/app/Services/Cloud/CloudWorkerService.php @@ -2968,6 +2968,9 @@ final class CloudWorkerService } if (in_array((string) $job->kind, ['delete', 'expiry_delete', 'delete_force'], true)) { + CloudVpcPortService::releaseAfterInstanceDeletedLocked( + $instance + ); $instance->status = 'deleted'; $instance->sealed_credential = null; CloudBackupSubscription::where( diff --git a/web/tests/CloudFinancialWorkflowTest.php b/web/tests/CloudFinancialWorkflowTest.php index fbd8eebf..395f5286 100644 --- a/web/tests/CloudFinancialWorkflowTest.php +++ b/web/tests/CloudFinancialWorkflowTest.php @@ -320,6 +320,7 @@ namespace { $t->unique(['host_id', 'operation_id']); }); $schema->create('cloud_instances', function (Blueprint $t) { $t->increments('id'); foreach (['host_id', 'user_id'] as $v) { $t->integer($v); } foreach (['order_id', 'plan_id', 'offer_id', 'resource_pool_id', 'reservation_id', 'current_period_id', 'expires_at', 'suspended_at', 'network_suspended_at'] as $v) { $t->integer($v)->nullable(); } foreach (['renewal_days', 'renewal_traffic_bytes', 'traffic_quota_bytes', 'traffic_download_bytes', 'traffic_upload_bytes', 'lifetime_download_bytes', 'lifetime_upload_bytes', 'traffic_synced_at'] as $v) { $t->integer($v)->default(0); } $t->string('renewal_price')->nullable(); $t->string('uuid'); $t->string('name'); $t->string('status'); $t->string('service_status')->default('exempt'); $t->string('network_status')->default('active'); $t->text('spec_json'); $t->text('sealed_credential')->nullable(); $t->integer('created_at'); $t->integer('updated_at'); $t->unique('order_id'); $t->unique(['host_id', 'uuid']); }); + $schema->create('cloud_vpc_ports', function (Blueprint $t) { $t->increments('id'); $t->integer('vpc_id'); $t->integer('instance_id'); $t->integer('user_id'); $t->integer('active_claim')->nullable(); $t->string('state'); }); $schema->create('cloud_instance_snapshots', function (Blueprint $t) { $t->increments('id'); $t->string('snapshot_key')->unique(); foreach (['instance_id', 'user_id', 'host_id'] as $v) { $t->integer($v); } $t->string('name'); $t->string('state'); $t->string('consistency'); $t->integer('size_bytes')->nullable(); $t->string('last_operation_id')->nullable(); foreach (['ready_at', 'last_restored_at', 'deleted_at'] as $v) { $t->integer($v)->nullable(); } $t->integer('created_at'); $t->integer('updated_at'); }); $schema->create('cloud_renewals', function (Blueprint $t) { $t->increments('id'); $t->integer('instance_id'); $t->integer('user_id'); $t->integer('plan_id')->nullable(); $t->integer('period_id')->nullable(); $t->string('idempotency_key'); $t->string('request_hash'); $t->string('amount'); $t->integer('validity_days'); $t->integer('traffic_bytes_added'); $t->integer('previous_expires_at'); $t->integer('new_expires_at'); $t->integer('created_at'); $t->unique(['user_id', 'idempotency_key']); }); $schema->create('cloud_service_periods', function (Blueprint $t) { $t->increments('id'); foreach (['instance_id', 'user_id'] as $v) { $t->integer($v); } foreach (['plan_id', 'order_id', 'renewal_id', 'download_base_bytes', 'upload_base_bytes', 'activated_at'] as $v) { $t->integer($v)->nullable(); } foreach (['starts_at', 'ends_at', 'traffic_quota_bytes', 'download_used_bytes', 'upload_used_bytes', 'created_at', 'updated_at'] as $v) { $t->integer($v)->default(0); } $t->string('status'); $t->unique('order_id'); $t->unique('renewal_id'); }); diff --git a/web/tests/CloudRuntimeHeartbeatTest.php b/web/tests/CloudRuntimeHeartbeatTest.php index 13f2aa30..b52080c0 100644 --- a/web/tests/CloudRuntimeHeartbeatTest.php +++ b/web/tests/CloudRuntimeHeartbeatTest.php @@ -372,6 +372,14 @@ try { $table->integer($column)->nullable(); } }); + $schema->create('cloud_vpc_ports', static function ( + Blueprint $table + ): void { + $table->increments('id'); + $table->integer('instance_id'); + $table->integer('active_claim')->nullable(); + $table->string('state'); + }); $schema->create('cloud_invoices', static function (Blueprint $table): void { $table->increments('id'); $table->string('purpose'); diff --git a/web/tests/CloudVpcPortWorkflowTest.php b/web/tests/CloudVpcPortWorkflowTest.php index 5eaff5f3..01b46ded 100644 --- a/web/tests/CloudVpcPortWorkflowTest.php +++ b/web/tests/CloudVpcPortWorkflowTest.php @@ -51,6 +51,22 @@ namespace { $job->updated_at = $now; $job->save(); }; + $terminalizeFailed = static function (CloudJob $job): void { + $finishedAt = time() - 600; + $job->phase = 'terminal'; + $job->outcome = $job->status = 'failed'; + $job->attempts = $job->dispatch_attempts = 1; + $job->dispatch_started_at = $job->dispatched_at = $finishedAt - 1; + $job->agent_accepted_at = $finishedAt - 1; + $job->receipt_deadline_at = $finishedAt + 900; + $job->terminal_at = $finishedAt; + $job->effect_may_have_applied = 0; + $job->safe_to_resubmit = 1; + $job->effect_resolution = 'not_applied'; + $job->error_code = 'vpc_host_remove_failed'; + $job->updated_at = $finishedAt; + $job->save(); + }; $capsule = new Capsule(); $capsule->addConnection([ @@ -396,5 +412,101 @@ namespace { && (int) CloudVpcHostState::where('vpc_id', 1)->value('host_id') === 2, 'Detach did not release the IP after every host cleanup converged.'); + $knownFailedState = CloudVpcHostState::where('vpc_id', 1) + ->where('host_id', 2)->first(); + $knownFailedState->desired_revision = (int) $knownFailedState->desired_revision + 1; + $knownFailedState->desired_digest = str_repeat('f', 64); + $knownFailedState->sync_state = 'failed'; + $knownFailedState->last_error_code = 'vpc_host_apply_failed'; + $knownFailedState->save(); + $knownFailedJob = CloudJob::where( + 'operation_id', (string) $knownFailedState->last_operation_id + )->first(); + $assert($knownFailedJob !== null, + 'Failed host-state fixture lost its exact operation generation.'); + $terminalizeFailed($knownFailedJob); + $vpc->desired_revision = (int) $knownFailedState->desired_revision; + $vpc->state = 'degraded'; + $vpc->save(); + $deleteCleanupJobs = $peer->getConnection()->transaction( + static function (): array { + $locked = CloudInstance::where('id', 2) + ->lockForUpdate()->first(); + return CloudVpcPortService::releaseAfterInstanceDeletedLocked( + $locked + ); + } + ); + $peerPort = $peerPort->fresh(); + $assert(count($deleteCleanupJobs) === 1 + && (string) $deleteCleanupJobs[0]->kind === 'vpc_host_remove' + && (string) $peerPort->state === 'release_pending' + && $peerPort->active_claim !== null, + 'Confirmed instance deletion released its private IP before route cleanup.'); + $deleteCleanupJob = $deleteCleanupJobs[0]; + $deleteCleanupPayload = CloudSecrets::decrypt( + (string) $deleteCleanupJob->sealed_payload, 'job-payload' + ); + $deleteHostState = CloudVpcHostState::where('vpc_id', 1) + ->where('host_id', 2)->first(); + CloudVpcPortService::finishJobLocked($deleteCleanupJob, 'failed', null, + $deleteCleanupPayload, [ + 'operation_id' => (string) $deleteCleanupJob->operation_id, + 'error_code' => 'vpc_host_remove_failed', + ]); + $terminalizeFailed($deleteCleanupJob); + $peer->status = 'deleted'; + $peer->save(); + $deleteCleanupJob->effect_resolution = 'unknown'; + $deleteCleanupJob->effect_may_have_applied = 1; + $deleteCleanupJob->safe_to_resubmit = 0; + $deleteCleanupJob->save(); + $jobCountBeforeUnknownRetry = CloudJob::count(); + $assert(CloudVpcPortService::retryDeletedCleanupDue(10) === 0 + && CloudJob::count() === $jobCountBeforeUnknownRetry, + 'Unknown-effect deleted-instance cleanup was replayed.'); + $terminalizeFailed($deleteCleanupJob); + $assert(CloudVpcPortService::retryDeletedCleanupDue(10) === 1, + 'Known-not-applied deleted-instance cleanup was not retried.'); + $peerPort = $peerPort->fresh(); + $assert((string) $peerPort->state === 'release_pending' + && $peerPort->active_claim !== null, + 'A failed deleted-instance cleanup released the address early.'); + $deleteCleanupJob = CloudJob::where('kind', 'vpc_host_remove') + ->where('phase', 'accepted')->orderByDesc('id')->first(); + $deleteCleanupPayload = CloudSecrets::decrypt( + (string) $deleteCleanupJob->sealed_payload, 'job-payload' + ); + $deleteHostState = CloudVpcHostState::where('vpc_id', 1) + ->where('host_id', 2)->first(); + CloudVpcPortService::finishJobLocked($deleteCleanupJob, 'succeeded', [ + 'vpc_key' => (string) $vpc->vpc_key, + 'desired_revision' => (int) $deleteHostState->applied_revision, + 'desired_digest' => (string) $deleteHostState->applied_digest, + 'removed' => true, + ], $deleteCleanupPayload, [ + 'operation_id' => (string) $deleteCleanupJob->operation_id, + ]); + $terminalize($deleteCleanupJob); + $peerPort = $peerPort->fresh(); + $assert((string) $peerPort->state === 'released' + && $peerPort->active_claim === null + && CloudVpcHostState::where('vpc_id', 1)->count() === 0, + 'Deleted instance VPC cleanup did not release the address after convergence.'); + + $worker = file_get_contents( + dirname(__DIR__) . '/app/Services/Cloud/CloudWorkerService.php' + ); + $cleanupPosition = strpos($worker, + 'CloudVpcPortService::releaseAfterInstanceDeletedLocked'); + $deletedPosition = strpos($worker, "\$instance->status = 'deleted';"); + $placementPosition = strpos($worker, + 'CloudPlacementService::releaseDeletedInstance'); + $assert($cleanupPosition !== false && $deletedPosition !== false + && $placementPosition !== false + && $cleanupPosition < $deletedPosition + && $deletedPosition < $placementPosition, + 'Delete finalization does not fence VPC cleanup before resource release.'); + echo "VPC host projection and VM port workflow passed.\n"; }