You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Cloud/CloudPublicNetworkTransitio...

1476 lines
60 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudInstance;
use App\Models\CloudInvoice;
use App\Models\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudPublicNetworkTransition;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\User;
use Illuminate\Database\Capsule\Manager as DB;
/**
* Durable seam for public-network transitions.
*
* Controllers, dispatch, evidence, local finalization and recovery all use
* this seam. Legacy in-flight jobs remain isolated by their missing
* public_network_transition_id.
*/
final class CloudPublicNetworkTransitionWorkflow
{
private const FAMILIES = [4, 6];
public static function begin(
CloudPublicNetworkTransitionCommand $command
): CloudPublicNetworkTransitionDispatch {
if ($command->kind() === 'pool_replacement') {
throw new CloudError(
'地址池替换必须通过原子批次工作流提交',
409
);
}
return DB::connection()->transaction(static function () use (
$command
): CloudPublicNetworkTransitionDispatch {
// The actor row is the first lock for every kind. Besides owning
// the paid wallet, it serializes the per-user idempotency-key
// namespace before instance and transition locks are acquired.
$actorUser = User::where('id', $command->actorUserId())
->lockForUpdate()->first();
if (!$actorUser instanceof User) {
throw new CloudError('公网网络变更的操作账户不存在', 409);
}
if ($command->kind() === 'user_paid'
&& (int) ($actorUser->enable ?? 0) !== 1) {
throw new CloudError('账户不可用', 403);
}
return self::reserveTransitionLocked($command, $actorUser);
}, 3);
}
/**
* Freeze one child of a pool-replacement batch inside the caller's outer
* transaction. The batch coordinator already owns the canonical actor ->
* parent -> instances -> host/agent -> transitions -> resource pools ->
* attachments/pools -> reservations -> claims/IPs lock chain. This seam
* therefore performs no lock acquisition and never opens a transaction.
*/
public static function beginPoolReplacementBatch(
CloudPublicNetworkTransitionCommand $command,
CloudPublicNetworkTransitionBatchPlan $plan
): CloudPublicNetworkTransitionDispatch {
$actorUser = $plan->actor;
$parent = $plan->parent;
$item = $plan->item;
$batch = $plan->batch;
$instance = $plan->instance;
$host = $plan->host;
$agent = $plan->agent;
$resourcePool = $plan->resourcePool;
$reservation = $plan->reservation;
$sourceAttachment = $plan->attachment;
$allClaims = $plan->allClaimsSorted;
$activeClaims = $plan->activeClaimsByFamily;
$sourceIps = $plan->sourceIpsByFamily;
$pools = $plan->poolsById;
$ips = $plan->ipsById;
$targetIp = $plan->exactTargetIp;
$family = (int) $item->address_family;
$targets = $command->targets();
if ($command->kind() !== 'pool_replacement'
|| DB::connection()->transactionLevel() < 1
|| (int) $actorUser->id !== $command->actorUserId()
|| (int) $parent->id !== (int) $command->parentJobId()
|| (string) $parent->kind
!== 'public_ip_pool_replacement_batch'
|| (string) $parent->execution_mode !== 'local'
|| $parent->parent_job_id !== null
|| $parent->host_id !== null
|| $parent->public_network_transition_id !== null
|| (int) $parent->user_id !== $command->actorUserId()
|| (int) $item->id !== (int) $command->batchItemId()
|| (int) $item->batch_id !== (int) $batch->id
|| (int) $item->instance_id !== $command->instanceId()
|| (string) $item->state !== 'preparing'
|| $item->child_job_id !== null
|| (int) $batch->parent_job_id !== (int) $parent->id
|| (int) $batch->requested_by_user_id
!== $command->actorUserId()
|| (int) $batch->host_id !== (int) $host->id
|| (string) $batch->state !== 'running'
|| (int) ($batch->active_claim ?? 0) !== 1
|| (int) $instance->id !== $command->instanceId()
|| (int) $instance->host_id !== (int) $host->id
|| (int) $agent->host_id !== (int) $host->id
|| (int) $resourcePool->id !== (int) $instance->resource_pool_id
|| (int) $reservation->id !== (int) $instance->reservation_id
|| (int) $reservation->host_id !== (int) $host->id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) $resourcePool->id
|| (string) $reservation->state !== 'committed'
|| (int) $item->source_reservation_id !== (int) $reservation->id
|| !in_array($family, self::FAMILIES, true)
|| array_keys($targets) !== [$family]
|| count($activeClaims) !== 2
|| !isset($activeClaims[4], $activeClaims[6])
|| !$sourceIps[4] instanceof CloudPublicIp
|| !$sourceIps[6] instanceof CloudPublicIp
|| (int) $activeClaims[$family]->public_ip_id
!== (int) $item->source_public_ip_id
|| (int) $targetIp->id !== (int) $item->target_public_ip_id) {
throw new CloudError('公网地址池迁移子任务身份无效', 409);
}
if (!$host instanceof CloudHost || !(bool) $host->enabled
|| !$agent instanceof CloudHostAgent || !$agent->isReady()
|| !$resourcePool instanceof CloudResourcePool
|| !$reservation instanceof CloudResourceReservation
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->host_id !== (int) $instance->host_id
|| (int) $reservation->resource_pool_id
!== (int) $instance->resource_pool_id
|| (int) $item->source_reservation_id !== (int) $reservation->id) {
throw new CloudError('公网地址池迁移资源账本不一致', 409);
}
$sourcePool = $pools->get(
(int) $activeClaims[$family]->public_ip_pool_id
);
$targetPool = $pools->get((int) $targetIp->public_ip_pool_id);
$attachmentId = (int) $activeClaims[4]->network_attachment_id;
$target = $targets[$family];
if (!$sourcePool instanceof CloudPublicIpPool
|| !$targetPool instanceof CloudPublicIpPool
|| !$sourceAttachment instanceof CloudHostNetworkAttachment
|| (int) $activeClaims[6]->network_attachment_id !== $attachmentId
|| (int) $item->source_network_attachment_id !== $attachmentId
|| (int) $item->target_network_attachment_id !== $attachmentId
|| (int) $sourcePool->id
!== (int) $batch->source_public_ip_pool_id
|| (int) $targetPool->id
!== (int) $batch->target_public_ip_pool_id
|| (int) $sourcePool->address_family !== $family
|| (int) $targetPool->address_family !== $family
|| (int) $sourcePool->host_id !== (int) $instance->host_id
|| (int) $targetPool->host_id !== (int) $instance->host_id
|| (int) $sourcePool->network_attachment_id !== $attachmentId
|| (int) $targetPool->network_attachment_id !== $attachmentId
|| (int) $sourceAttachment->line_id
!== (int) $resourcePool->line_id
|| !hash_equals((string) $targetPool->pool_key,
(string) $target['pool_key'])
|| !hash_equals(
(string) $targetIp->address . '/'
. (int) $targetIp->prefix_length,
(string) $target['address_cidr']
)) {
throw new CloudError('公网地址池迁移冻结拓扑不一致', 409);
}
foreach (self::FAMILIES as $sourceFamily) {
self::assertCommittedSourceLeg(
$activeClaims[$sourceFamily],
$sourceIps[$sourceFamily],
(int) $reservation->id,
(int) $instance->id
);
}
$dispatch = self::freezeTransitionLocked(
$command,
$actorUser,
$instance,
$agent,
$resourcePool,
$reservation,
$allClaims,
$activeClaims,
$sourceIps,
$sourceAttachment,
collect([(int) $sourceAttachment->id => $sourceAttachment]),
$pools,
$ips,
$targetIp,
$host
);
$item->child_job_id = $dispatch->jobId();
$item->state = 'queued';
$item->updated_at = time();
$item->save();
return $dispatch;
}
/**
* Reserve a transition while the caller owns the actor row and the outer
* transaction. This internal seam must never create a nested transaction:
* billing, transition, claim, address and job writes commit or roll back
* together.
*/
private static function reserveTransitionLocked(
CloudPublicNetworkTransitionCommand $command,
User $actorUser
): CloudPublicNetworkTransitionDispatch {
// Non-locking discovery may only identify the immutable rows. Every
// identity is revalidated after the canonical actor -> parent/job ->
// instance -> host/agent -> transition lock chain is held.
$existingHint = CloudPublicNetworkTransition::where(
'transition_key', $command->transitionKey()
)->first(['id', 'instance_id', 'host_id']);
$existingJob = null;
$existingParent = null;
if ($existingHint instanceof CloudPublicNetworkTransition) {
$jobHint = CloudJob::where(
'public_network_transition_id', (int) $existingHint->id
)->orderBy('id')->first(['id', 'parent_job_id']);
if ($jobHint instanceof CloudJob
&& (int) ($jobHint->parent_job_id ?? 0) > 0) {
$existingParent = CloudJob::where(
'id', (int) $jobHint->parent_job_id
)->lockForUpdate()->first();
}
if ($jobHint instanceof CloudJob) {
$existingJob = CloudJob::where('id', (int) $jobHint->id)
->lockForUpdate()->first();
}
} else {
$priorJob = CloudJob::where(
'user_id', $command->actorUserId()
)->where('request_idempotency_key', $command->requestKey())
->lockForUpdate()->first(['id']);
if ($priorJob instanceof CloudJob) {
throw new CloudError(
'公网网络变更幂等键已被其他任务占用',
409
);
}
}
$lockedInstanceId = $existingHint instanceof CloudPublicNetworkTransition
? (int) $existingHint->instance_id
: $command->instanceId();
$instance = CloudInstance::where('id', $lockedInstanceId)
->lockForUpdate()->first();
if (!$instance instanceof CloudInstance
|| ($command->kind() === 'user_paid'
&& (int) $instance->user_id
!== $command->actorUserId())) {
throw new CloudError('虚拟机不满足公网网络变更条件', 409);
}
if ($existingHint instanceof CloudPublicNetworkTransition) {
[$replayHost] = CloudPublicNetworkTransitionContext::lockHostBoundary(
(int) $existingHint->host_id
);
$existing = CloudPublicNetworkTransition::where(
'id', (int) $existingHint->id
)->where('transition_key', $command->transitionKey())
->lockForUpdate()->first();
if (!$existing instanceof CloudPublicNetworkTransition) {
throw new CloudError('公网网络变更幂等身份冲突', 409);
}
return self::replayLocked(
$existing,
$command,
$existingParent,
$existingJob,
$instance,
$replayHost
);
}
CloudPublicNetworkMutationAdmission::assertCanBegin($instance);
try {
$spec = json_decode(
(string) $instance->spec_json,
true,
64,
JSON_THROW_ON_ERROR
);
} catch (\Throwable) {
$spec = null;
}
if ((int) ($instance->host_id ?? 0) < 1
|| (int) ($instance->reservation_id ?? 0) < 1
|| (int) ($instance->resource_pool_id ?? 0) < 1
|| !is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? false) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template') {
throw new CloudError('虚拟机不满足公网网络变更条件', 409);
}
[$host, $agent] = CloudPublicNetworkTransitionContext::lockHostBoundary(
(int) $instance->host_id
);
$active = CloudPublicNetworkTransition::where(
'instance_id', (int) $instance->id
)->where('active_transition', 1)->lockForUpdate()->first();
if ($active instanceof CloudPublicNetworkTransition) {
throw new CloudError('虚拟机已有公网网络变更正在处理', 409);
}
$resourcePool = CloudResourcePool::where(
'id', (int) $instance->resource_pool_id
)->lockForUpdate()->first();
if (!$host instanceof CloudHost
|| !(bool) $host->enabled
|| !$agent instanceof CloudHostAgent || !$agent->isReady()
|| !$resourcePool instanceof CloudResourcePool
|| (int) ($resourcePool->line_id ?? 0) < 1) {
throw new CloudError('宿主机公网网络变更能力不可用', 409);
}
// Hints identify the rows that must be locked in canonical order.
// Every identity is revalidated after all locks are acquired.
$reservationId = (int) $instance->reservation_id;
$claimHints = DB::table('cloud_resource_reservation_ips')
->where('reservation_id', $reservationId)
->orderBy('id')->get()->all();
$sourceAttachmentIds = [];
$sourcePoolIds = [];
foreach ($claimHints as $hint) {
if ((int) ($hint->active_claim ?? 0) !== 1) {
continue;
}
$sourceAttachmentIds[(int) $hint->network_attachment_id] = true;
$sourcePoolIds[(int) $hint->public_ip_pool_id] = true;
}
if (count($sourceAttachmentIds) !== 1
|| count($sourcePoolIds) !== 2) {
throw new CloudError('虚拟机活动双栈公网账本不完整', 409);
}
$sourceAttachmentId = (int) array_key_first($sourceAttachmentIds);
$targetPoolHints = [];
foreach ($command->targets() as $target) {
if ($target === null) {
continue;
}
$pool = CloudPublicIpPool::where(
'host_id', (int) $instance->host_id
)->where('pool_key', $target['pool_key'])->first();
if (!$pool instanceof CloudPublicIpPool) {
throw new CloudError('目标公网地址池不存在', 409);
}
$targetPoolHints[(int) $pool->id] = $pool;
}
if ($command->kind() === 'user_paid') {
foreach (CloudPublicIpPool::where(
'host_id', (int) $instance->host_id
)->where('network_attachment_id', $sourceAttachmentId)
->where('address_family', 4)->orderBy('id')->get() as $pool) {
$targetPoolHints[(int) $pool->id] = $pool;
}
}
$attachmentIds = array_keys($sourceAttachmentIds);
$poolIds = array_keys($sourcePoolIds);
foreach ($targetPoolHints as $pool) {
$attachmentIds[] = (int) $pool->network_attachment_id;
$poolIds[] = (int) $pool->id;
}
$attachmentIds = array_values(array_unique($attachmentIds));
$poolIds = array_values(array_unique($poolIds));
sort($attachmentIds, SORT_NUMERIC);
sort($poolIds, SORT_NUMERIC);
$attachments = CloudHostNetworkAttachment::whereIn(
'id', $attachmentIds
)->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$pools = CloudPublicIpPool::whereIn('id', $poolIds)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
if ($attachments->count() !== count($attachmentIds)
|| $pools->count() !== count($poolIds)) {
throw new CloudError('公网网络候选目录发生变化', 409);
}
if ($command->kind() === 'user_paid'
&& $command->priceCents() !==
CloudIpChangeBillingService::priceCents()) {
throw new CloudError(
'付费更换公网 IPv4 的价格已发生变化,请刷新后重试',
409
);
}
$reservation = CloudResourceReservation::where(
'id', $reservationId
)->lockForUpdate()->first();
$allClaims = DB::table('cloud_resource_reservation_ips')
->where('reservation_id', $reservationId)
->orderBy('address_family')->orderBy('id')
->lockForUpdate()->get()->all();
if (!$reservation instanceof CloudResourceReservation
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->host_id !== (int) $instance->host_id
|| (int) $reservation->instance_id !== (int) $instance->id
|| (int) $reservation->resource_pool_id
!== (int) $instance->resource_pool_id) {
throw new CloudError('虚拟机公网资源预留账本不一致', 409);
}
$activeClaims = [];
foreach ($allClaims as $claim) {
if ((int) ($claim->active_claim ?? 0) === 1) {
$activeClaims[(int) $claim->address_family] = $claim;
}
}
if (count($activeClaims) !== 2
|| !isset($activeClaims[4], $activeClaims[6])) {
throw new CloudError('虚拟机活动双栈公网声明不完整', 409);
}
// The host lock serializes every allocator. Lock all concrete rows
// for the exact candidate pools in primary-key order so automatic
// selection and explicit selection share one race-free ledger.
$ips = CloudPublicIp::where('host_id', (int) $instance->host_id)
->whereIn('public_ip_pool_id', $poolIds)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$sourceIps = [];
foreach (self::FAMILIES as $family) {
$sourceId = (int) $activeClaims[$family]->public_ip_id;
$sourceIp = $ips->get($sourceId);
if (!$sourceIp instanceof CloudPublicIp) {
// A corrupt cross-catalog source must not be hidden by an
// extra out-of-order lock.
throw new CloudError('活动公网地址不在锁定目录中', 409);
}
self::assertCommittedSourceLeg(
$activeClaims[$family],
$sourceIp,
$reservationId,
(int) $instance->id
);
$sourceIps[$family] = $sourceIp;
}
return self::freezeTransitionLocked(
$command,
$actorUser,
$instance,
$agent,
$resourcePool,
$reservation,
$allClaims,
$activeClaims,
$sourceIps,
$attachments->get($sourceAttachmentId),
$attachments,
$pools,
$ips
);
}
private static function freezeTransitionLocked(
CloudPublicNetworkTransitionCommand $command,
User $actorUser,
CloudInstance $instance,
CloudHostAgent $agent,
CloudResourcePool $resourcePool,
CloudResourceReservation $reservation,
array $allClaims,
array $activeClaims,
array $sourceIps,
CloudHostNetworkAttachment $sourceAttachment,
$attachments,
$pools,
$ips,
?CloudPublicIp $exactTargetIp = null,
?CloudHost $lockedHost = null
): CloudPublicNetworkTransitionDispatch {
$reservationId = (int) $reservation->id;
$sourceSnapshot = self::snapshot(
$instance,
$agent,
$sourceAttachment,
$activeClaims,
$sourceIps,
$pools,
true,
(int) $resourcePool->line_id
);
$sourceSet = CloudActivePublicNetworkClaimSet::fromLedger(
$reservationId,
(int) $sourceAttachment->host_id,
array_values($activeClaims),
[
(int) $sourceIps[4]->id => $sourceIps[4],
(int) $sourceIps[6]->id => $sourceIps[6],
],
$sourceSnapshot
);
self::assertInstanceSnapshot($instance, $sourceSnapshot);
if ($exactTargetIp instanceof CloudPublicIp) {
$targetFamilies = array_keys($command->targets());
$family = count($targetFamilies) === 1
? (int) $targetFamilies[0] : 0;
$targetPool = $pools->get(
(int) $exactTargetIp->public_ip_pool_id
);
if (!in_array($family, self::FAMILIES, true)
|| !$targetPool instanceof CloudPublicIpPool
|| (int) $targetPool->address_family !== $family
|| (int) $targetPool->network_attachment_id
!== (int) $sourceAttachment->id
|| !self::poolUsable(
$targetPool,
$instance,
$agent,
$attachments,
(int) $resourcePool->line_id
)
|| !self::ipAvailableForPool(
$exactTargetIp,
$targetPool,
$lockedHost
)
|| (int) $exactTargetIp->id === (int) $sourceIps[$family]->id) {
throw new CloudError('公网地址池迁移精确目标已不可用', 409);
}
$targetAttachment = $sourceAttachment;
$targetClaims = $activeClaims;
$targetIps = $sourceIps;
$targetClaims[$family] = (object) [
'network_attachment_id' => (int) $sourceAttachment->id,
'public_ip_pool_id' => (int) $targetPool->id,
];
$targetIps[$family] = $exactTargetIp;
$changed = [$family => true];
} else {
[$targetAttachment, $targetClaims, $targetIps, $changed] =
self::selectTargetLocked(
$command,
$instance,
$agent,
$sourceAttachment,
$activeClaims,
$sourceIps,
$attachments,
$pools,
$ips,
(int) $resourcePool->line_id
);
}
$targetSnapshot = self::snapshot(
$instance,
$agent,
$targetAttachment,
$targetClaims,
$targetIps,
$pools,
false,
(int) $resourcePool->line_id
);
if (hash_equals(
$sourceSnapshot->fingerprint(),
$targetSnapshot->fingerprint()
)) {
throw new CloudError('目标公网网络与当前配置相同', 409);
}
$operationId = bin2hex(random_bytes(16));
$now = time();
$invoice = null;
if ($command->kind() === 'user_paid') {
$invoice = CloudIpChangeBillingService::chargeTransitionLocked(
$instance,
$actorUser,
$command
);
}
$transition = new CloudPublicNetworkTransition();
$transition->transition_key = $command->transitionKey();
$transition->operation_id = $operationId;
$transition->kind = $command->kind();
$transition->instance_id = (int) $instance->id;
$transition->host_id = (int) $instance->host_id;
$transition->reservation_id = $reservationId;
$transition->invoice_id = $invoice?->id;
$transition->pool_replacement_batch_item_id =
$command->batchItemId();
$transition->requested_by_user_id = $command->actorUserId();
$transition->source_network_attachment_id =
(int) $sourceAttachment->id;
$transition->target_network_attachment_id =
(int) $targetAttachment->id;
$transition->source_claim_set_sha256 = $sourceSet->digest();
$transition->target_claim_set_sha256 = str_repeat('0', 64);
$transition->source_public_network_json = self::json($sourceSnapshot);
$transition->source_public_network_sha256 =
$sourceSnapshot->fingerprint();
$transition->target_public_network_json = self::json($targetSnapshot);
$transition->target_public_network_sha256 =
$targetSnapshot->fingerprint();
$transition->state = 'reserved';
$transition->effect_resolution = 'not_applicable';
$transition->active_transition = 1;
$transition->last_error_code = '';
$transition->effect_resolved_at = null;
$transition->terminal_at = null;
$transition->created_at = $transition->updated_at = $now;
$transition->save();
$effectiveClaims = $activeClaims;
$effectiveIps = $sourceIps;
foreach (self::FAMILIES as $family) {
$sourceClaim = $activeClaims[$family];
if (!isset($changed[$family])) {
self::insertTransitionLeg(
(int) $transition->id,
$family,
(int) $sourceClaim->id,
null,
false,
$now
);
continue;
}
$targetIp = $targetIps[$family];
$targetPool = $pools->get(
(int) $targetIp->public_ip_pool_id
);
$generation = self::nextGeneration($allClaims, $family);
$claimId = DB::table('cloud_resource_reservation_ips')
->insertGetId([
'reservation_id' => $reservationId,
'address_family' => $family,
'claim_generation' => $generation,
'active_claim' => null,
'network_attachment_id' =>
(int) $targetPool->network_attachment_id,
'public_ip_pool_id' => (int) $targetPool->id,
'public_ip_id' => (int) $targetIp->id,
'operation_id' => $operationId,
'state' => 'reserved',
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
]);
$updated = CloudPublicIp::where('id', (int) $targetIp->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);
}
$targetClaim = (object) [
'id' => $claimId,
'reservation_id' => $reservationId,
'address_family' => $family,
'claim_generation' => $generation,
'active_claim' => null,
'network_attachment_id' =>
(int) $targetPool->network_attachment_id,
'public_ip_pool_id' => (int) $targetPool->id,
'public_ip_id' => (int) $targetIp->id,
'operation_id' => $operationId,
'state' => 'reserved',
'released_at' => null,
'release_reason' => '',
'created_at' => $now,
'updated_at' => $now,
];
$targetIp->state = 'reserved';
$targetIp->reservation_id = $reservationId;
$targetIp->reservation_ip_claim_id = $claimId;
$targetIp->instance_id = null;
$targetIp->operation_id = $operationId;
$targetIp->updated_at = $now;
$boundIp = $targetIp;
$effectiveClaims[$family] = $targetClaim;
$effectiveIps[$family] = $boundIp;
self::insertTransitionLeg(
(int) $transition->id,
$family,
(int) $sourceClaim->id,
$claimId,
true,
$now
);
}
$targetIdentity = CloudPublicNetworkClaimSetIdentity::fromLedger(
$reservationId,
$effectiveClaims,
[
(int) $effectiveIps[4]->id => $effectiveIps[4],
(int) $effectiveIps[6]->id => $effectiveIps[6],
],
$targetSnapshot
);
$transition->target_claim_set_sha256 = $targetIdentity->digest();
$job = new CloudJob();
$job->operation_id = $operationId;
$job->request_idempotency_key = $command->requestKey();
$job->request_fingerprint = $command->fingerprint();
$job->parent_job_id = $command->parentJobId();
$job->invoice_id = $invoice?->id;
$job->instance_id = (int) $instance->id;
$job->public_network_transition_id = (int) $transition->id;
$job->user_id = $command->actorUserId();
$job->host_id = (int) $instance->host_id;
$job->kind = 'network_change';
$job->execution_mode = 'agent';
$job->status = 'queued';
$job->sealed_payload = CloudSecrets::encrypt([
'method' => 'POST',
'request_target' => '/v1/vms/'
. rawurlencode((string) $instance->uuid) . '/network',
'body' => [
'public_network' => $targetSnapshot->toArray(),
'confirm_restart' => true,
],
'owner_id' => (int) $instance->user_id,
'can_manage' => true,
'public_network_transition_id' => (int) $transition->id,
'source_claim_set_sha256' => $sourceSet->digest(),
'target_claim_set_sha256' => $targetIdentity->digest(),
'price_cents' => $command->priceCents(),
'charged_amount' => $invoice === null
? null : (string) $invoice->amount,
'currency' => $invoice === null
? null : (string) $invoice->currency,
], 'job-payload');
$job->available_at = $job->created_at = $job->updated_at = $now;
$job->save();
$transition->state = 'queued';
$transition->updated_at = $now;
$transition->save();
return new CloudPublicNetworkTransitionDispatch(
(int) $transition->id,
(int) $job->id,
$operationId,
$targetSnapshot,
false
);
}
/** Publish the dispatch boundary without consulting mutable catalogs. */
public static function markDispatched(CloudJob $claimed): void
{
CloudPublicNetworkTransitionEvidence::markDispatched($claimed);
}
/** Fail closed when Worker can no longer classify the Agent effect. */
public static function markJobUncertain(CloudJob $claimed): void
{
CloudPublicNetworkTransitionEvidence::markJobUncertain($claimed);
}
/**
* Persist authenticated Agent evidence before the Worker starts local
* ledger finalization. This transaction deliberately survives a later
* PHP finalizer crash and is the authority for a PHP-only retry.
*/
public static function recordEvidence(
CloudJob $claimed,
string $catalogStatus,
mixed $result,
array $payload,
array $operation,
bool $recoveryPrepare = false
): void {
CloudPublicNetworkTransitionEvidence::record(
$claimed,
$catalogStatus,
$result,
$payload,
$operation,
$recoveryPrepare
);
}
/**
* Consume persisted evidence while Worker already owns user then job.
* Recovery prepare applies the projection but keeps the transition active
* until publishPreparedLocked() runs after the Agent fence is released.
*/
public static function finishJobLocked(
CloudJob $job,
string $catalogStatus,
array $payload,
?User $actor,
bool $deferPublish,
?CloudJob $parent = null
): void {
CloudPublicNetworkTransitionSettlement::finishJobLocked(
$job,
$catalogStatus,
$payload,
$actor,
$deferPublish,
$parent
);
}
/** Publish a recovery-prepared projection after the Agent fence release. */
public static function publishPreparedLocked(
CloudJob $job,
string $resolution,
?User $actor,
?CloudJob $parent = null
): void {
CloudPublicNetworkTransitionSettlement::publishPreparedLocked(
$job,
$resolution,
$actor,
$parent
);
}
/** Retry only PHP-owned writes after evidence survived a Worker crash. */
public static function retryPendingFinalization(
int $jobId,
string $leaseToken
): CloudJob {
return CloudPublicNetworkTransitionSettlement::
retryPendingFinalization($jobId, $leaseToken);
}
private static function replayLocked(
CloudPublicNetworkTransition $transition,
CloudPublicNetworkTransitionCommand $command,
?CloudJob $parent,
?CloudJob $job,
CloudInstance $instance,
CloudHost $host
): CloudPublicNetworkTransitionDispatch {
$transitionInvoiceId = $transition->invoice_id === null
? null : (int) $transition->invoice_id;
$jobInvoiceId = $job?->invoice_id === null
? null : (int) $job->invoice_id;
$terminalResolution = (string) $transition->effect_resolution;
$terminalReplay = $job instanceof CloudJob
&& in_array($terminalResolution,
['applied', 'not_applied'], true)
&& CloudPublicNetworkTransitionSettlement::terminalMatches(
$transition,
$terminalResolution
)
&& (string) $job->phase === 'terminal'
&& in_array((string) $job->outcome,
['succeeded', 'failed'], true)
&& (string) $job->status === (string) $job->outcome
&& $job->terminal_at !== null
&& hash_equals(
(string) $job->effect_resolution,
$terminalResolution
);
if (!$job instanceof CloudJob
|| (int) $transition->instance_id !== $command->instanceId()
|| (int) $transition->instance_id !== (int) $instance->id
|| (int) $transition->host_id !== (int) $host->id
|| (!$terminalReplay
&& (int) $instance->host_id !== (int) $host->id)
|| (int) $transition->requested_by_user_id
!== $command->actorUserId()
|| (string) $transition->kind !== $command->kind()
|| (int) ($transition->pool_replacement_batch_item_id ?? 0)
!== (int) ($command->batchItemId() ?? 0)
|| !hash_equals(
(string) $job->request_idempotency_key,
$command->requestKey()
)
|| !hash_equals(
(string) $job->request_fingerprint,
$command->fingerprint()
)
|| (string) $job->kind !== 'network_change'
|| ($command->kind() !== 'pool_replacement'
&& $job->parent_job_id !== null)
|| ($command->kind() === 'pool_replacement'
&& (!$parent instanceof CloudJob
|| (int) $parent->id !== (int) $command->parentJobId()
|| (string) $parent->kind
!== 'public_ip_pool_replacement_batch'
|| (int) $parent->user_id !== $command->actorUserId()
|| (string) $parent->execution_mode !== 'local'
|| $parent->parent_job_id !== null
|| $parent->host_id !== null
|| $parent->public_network_transition_id !== null
|| (int) ($job->parent_job_id ?? 0)
!== (int) $command->parentJobId()))
|| (int) $job->instance_id !== (int) $transition->instance_id
|| (int) $job->user_id
!== (int) $transition->requested_by_user_id
|| (int) $job->host_id !== (int) $transition->host_id
|| !hash_equals(
(string) $job->operation_id,
(string) $transition->operation_id
)
|| $jobInvoiceId !== $transitionInvoiceId) {
throw new CloudError('公网网络变更幂等身份冲突', 409);
}
$invoice = null;
if ($command->kind() === 'user_paid') {
$invoice = $transitionInvoiceId === null ? null
: CloudInvoice::where('id', $transitionInvoiceId)
->lockForUpdate()->first();
$priceCents = $command->priceCents();
if (!$invoice instanceof CloudInvoice || !is_int($priceCents)
|| (string) $invoice->purpose
!== CloudIpChangeBillingService::PURPOSE
|| (int) $invoice->instance_id !== $command->instanceId()
|| (int) $invoice->user_id !== $command->actorUserId()
|| (string) $invoice->currency !== 'USD'
|| CloudMoney::cents((string) $invoice->amount) !== $priceCents
|| !in_array((string) $invoice->status,
['paid', 'refunded'], true)
|| (string) $invoice->paid_via !== 'balance'
|| $invoice->paid_at === null
|| !hash_equals(
'public-network-transition-'
. $command->transitionKey(),
(string) $invoice->payment_reference
)) {
throw new CloudError('公网网络变更付费账本不一致', 409);
}
$refunded = (string) $invoice->status === 'refunded';
if ($refunded !== (
(string) $transition->state === 'failed'
&& (string) $transition->effect_resolution === 'not_applied'
&& $transition->active_transition === null
&& $transition->terminal_at !== null
)) {
throw new CloudError('公网网络变更退款终态不一致', 409);
}
} elseif ($transitionInvoiceId !== null) {
throw new CloudError('非付费公网网络变更关联了账单', 409);
}
try {
$target = CloudPublicNetworkSnapshot::fromArray(json_decode(
(string) $transition->target_public_network_json,
true,
16,
JSON_THROW_ON_ERROR
));
} catch (\Throwable) {
throw new CloudError('公网网络变更目标快照损坏', 409);
}
if (!hash_equals(
(string) $transition->target_public_network_sha256,
$target->fingerprint()
)) {
throw new CloudError('公网网络变更目标快照摘要不一致', 409);
}
$terminalState = in_array((string) $transition->state,
['succeeded', 'failed'], true);
if ($terminalState && !$terminalReplay) {
throw new CloudError('公网网络变更终态形状不一致', 409);
}
if ($terminalReplay) {
try {
$identity = CloudOperationRecoveryIdentity::expected($job);
} catch (\Throwable) {
throw new CloudError('公网网络变更终态身份无法核验', 409);
}
if (($identity['action'] ?? null) !== 'change-network'
|| !hash_equals(
strtolower((string) $identity['resource_id']),
strtolower((string) CloudInstance::where(
'id',
(int) $transition->instance_id
)->value('uuid'))
)
|| !hash_equals(
(string) $job->effect_resolution,
(string) $transition->effect_resolution
)) {
throw new CloudError('公网网络变更终态身份不一致', 409);
}
} else {
try {
$payload = CloudSecrets::decrypt(
(string) $job->sealed_payload,
'job-payload'
);
} catch (\Throwable) {
throw new CloudError('公网网络变更任务载荷无法核验', 409);
}
$expectedAmount = $invoice instanceof CloudInvoice
? (string) $invoice->amount : null;
$expectedCurrency = $invoice instanceof CloudInvoice
? (string) $invoice->currency : null;
if (($payload['body']['public_network'] ?? null)
!== $target->toArray()
|| ($payload['body']['confirm_restart'] ?? null) !== true
|| ($payload['public_network_transition_id'] ?? null)
!== (int) $transition->id
|| ($payload['source_claim_set_sha256'] ?? null)
!== (string) $transition->source_claim_set_sha256
|| ($payload['target_claim_set_sha256'] ?? null)
!== (string) $transition->target_claim_set_sha256
|| ($payload['price_cents'] ?? null) !== $command->priceCents()
|| ($payload['charged_amount'] ?? null) !== $expectedAmount
|| ($payload['currency'] ?? null) !== $expectedCurrency) {
throw new CloudError('公网网络变更任务载荷身份不一致', 409);
}
}
return new CloudPublicNetworkTransitionDispatch(
(int) $transition->id,
(int) $job->id,
(string) $transition->operation_id,
$target,
true
);
}
/**
* Select exact available target rows. No target row is mutated here.
*
* @return array{0:CloudHostNetworkAttachment,1:array<int,object>,
* 2:array<int,CloudPublicIp>,3:array<int,bool>}
*/
private static function selectTargetLocked(
CloudPublicNetworkTransitionCommand $command,
CloudInstance $instance,
CloudHostAgent $agent,
CloudHostNetworkAttachment $sourceAttachment,
array $sourceClaims,
array $sourceIps,
$attachments,
$pools,
$ips,
int $lineId
): array {
$attachmentMap = [];
foreach ($attachments as $attachment) {
$attachmentMap[(int) $attachment->id] = $attachment;
}
$poolsByAttachment = [];
$contracts = [];
$rowsByPool = [];
foreach ($pools as $pool) {
if (!self::poolUsable(
$pool,
$instance,
$agent,
$attachments,
$lineId
)) {
continue;
}
$poolId = (int) $pool->id;
$poolsByAttachment[(int) $pool->network_attachment_id][] = $pool;
$contracts[$poolId] = CloudPublicNetworkAddressPolicy::contract(
$pool,
(int) $pool->address_family
);
$rowsByPool[$poolId] = [];
}
foreach ($ips as $ip) {
$poolId = (int) $ip->public_ip_pool_id;
if (isset($rowsByPool[$poolId])) {
$rowsByPool[$poolId][] = $ip;
}
}
$selector = CloudPublicNetworkCandidateCatalog::fromLocked(
$attachmentMap,
$poolsByAttachment,
$contracts,
$rowsByPool,
CloudPanelUsageService::managementAddress(
CloudHost::find((int) $instance->host_id)
)
);
$plan = $selector->planTransition(
$command->targets(),
(int) $sourceAttachment->id,
$sourceIps
);
$effectiveClaims = $sourceClaims;
$effectiveIps = $sourceIps;
$changed = $plan->changedFamilies();
$targetAttachment = $plan->attachment();
foreach ($plan->candidates() as $family => $candidate) {
$pool = $plan->pools()[$family] ?? null;
$ip = $candidate['row'] ?? null;
$address = $candidate['candidate'] ?? null;
if (!$ip instanceof CloudPublicIp
&& $address instanceof CloudIpAddress
&& $pool instanceof CloudPublicIpPool) {
// The pure catalog may propose exact sparse IPv6. Keep the
// unique-key insert in this already-locked workflow; never
// introduce a late global address lock or cursor update.
$ip = self::materializeSparseTargetLocked(
$pool,
$address->text() . '/'
. (int) $pool->guest_prefix_length,
$ips
);
}
if (!$pool instanceof CloudPublicIpPool
|| !$ip instanceof CloudPublicIp
|| !self::ipAvailableForPool($ip, $pool)
|| (int) $ip->id === (int) $sourceIps[$family]->id) {
throw new CloudError('目标公网地址已不可分配', 409);
}
$effectiveIps[$family] = $ip;
// A placeholder is enough for snapshot construction; the durable
// target claim is inserted only after the transition row exists.
$effectiveClaims[$family] = (object) [
'network_attachment_id' => (int) $targetAttachment->id,
'public_ip_pool_id' => (int) $pool->id,
];
}
if ((int) $targetAttachment->id === (int) $sourceAttachment->id) {
foreach (self::FAMILIES as $family) {
if (!isset($changed[$family])) {
$effectiveClaims[$family] = $sourceClaims[$family];
$effectiveIps[$family] = $sourceIps[$family];
}
}
}
return [
$targetAttachment,
$effectiveClaims,
$effectiveIps,
$changed,
];
}
private static function snapshot(CloudInstance $instance,
CloudHostAgent $agent, ?CloudHostNetworkAttachment $attachment,
array $claims, array $ips, $pools,
bool $requireAssigned, int $lineId): CloudPublicNetworkSnapshot
{
$attachmentReady = $attachment instanceof
CloudHostNetworkAttachment
&& ($requireAssigned
? self::sourceAttachmentReadable($attachment, $agent)
: CloudPlacementNetworkService::attachmentReadyForAgent(
$attachment,
$agent
));
if (!$attachment instanceof CloudHostNetworkAttachment
|| (int) $attachment->host_id !== (int) $instance->host_id
|| (int) $attachment->line_id !== $lineId
|| !$attachmentReady
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
throw new CloudError('公网网络接入未通过当前 Agent 验证', 409);
}
$legs = [];
$dns = [];
foreach (self::FAMILIES as $family) {
$claim = $claims[$family] ?? null;
$ip = $ips[$family] ?? null;
$pool = is_object($claim)
? $pools->get((int) ($claim->public_ip_pool_id ?? 0)) : null;
if (!$pool instanceof CloudPublicIpPool
|| !$ip instanceof CloudPublicIp
|| (int) $pool->address_family !== $family
|| (int) $pool->network_attachment_id !== (int) $attachment->id
|| (int) $pool->host_id !== (int) $instance->host_id
|| (int) $ip->public_ip_pool_id !== (int) $pool->id
|| (int) $ip->address_family !== $family
|| ($requireAssigned
&& ((string) $ip->state !== 'assigned'
|| (int) $ip->instance_id !== (int) $instance->id))) {
throw new CloudError('公网网络地址账本与接入不一致', 409);
}
self::assertAddressInPool($ip, $pool);
$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 (self::dns($pool) as $server) {
$dns[$server] = $server;
}
}
return CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => (string) $attachment->network_selector,
'ipv4' => $legs[4] ?? null,
'ipv6' => $legs[6] ?? null,
'dns_servers' => array_values($dns),
]);
}
/** A draining/disabled source remains readable but is never a target. */
private static function sourceAttachmentReadable(
CloudHostNetworkAttachment $attachment,
CloudHostAgent $agent
): bool {
return (int) $attachment->host_id === (int) $agent->host_id
&& in_array((string) $attachment->state,
['active', 'draining', 'disabled'], true)
&& (string) $attachment->verification_state === 'verified'
&& CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
);
}
private static function poolUsable(CloudPublicIpPool $pool,
CloudInstance $instance, CloudHostAgent $agent, $attachments,
int $lineId): bool
{
try {
$contract = CloudPublicNetworkAddressPolicy::contract(
$pool,
(int) $pool->address_family
);
} catch (\Throwable) {
return false;
}
$attachment = $attachments->get((int) $pool->network_attachment_id);
return $attachment instanceof CloudHostNetworkAttachment
&& (int) $pool->host_id === (int) $instance->host_id
&& (int) $attachment->host_id === (int) $instance->host_id
&& (int) $attachment->line_id === $lineId
&& (string) $pool->state === 'active'
&& (string) $pool->sync_state === 'applied'
&& (int) $pool->observed_revision
=== (int) $pool->desired_revision
&& $contract->family() === (int) $pool->address_family
&& CloudPlacementNetworkService::attachmentReadyForAgent(
$attachment,
$agent
)
&& CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
);
}
private static function assertCommittedSourceLeg(object $claim,
CloudPublicIp $ip, int $reservationId, int $instanceId): void
{
if ((int) ($claim->reservation_id ?? 0) !== $reservationId
|| (int) ($claim->active_claim ?? 0) !== 1
|| (string) ($claim->state ?? '') !== 'committed'
|| (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id
|| (string) $ip->state !== 'assigned'
|| (int) ($ip->reservation_id ?? 0) !== $reservationId
|| (int) ($ip->reservation_ip_claim_id ?? 0)
!== (int) $claim->id
|| (int) ($ip->instance_id ?? 0) !== $instanceId
|| !hash_equals(
(string) ($claim->operation_id ?? ''),
(string) ($ip->operation_id ?? '')
)) {
throw new CloudError('活动公网地址声明与实例归属不一致', 409);
}
}
private static function ipAvailableForPool(CloudPublicIp $ip,
CloudPublicIpPool $pool, ?CloudHost $lockedHost = null): bool
{
if ((string) $ip->state !== 'available'
|| $ip->reservation_id !== null
|| $ip->reservation_ip_claim_id !== null
|| $ip->instance_id !== null || $ip->operation_id !== null) {
return false;
}
try {
self::assertAddressInPool($ip, $pool, $lockedHost);
return true;
} catch (\Throwable) {
return false;
}
}
private static function materializeSparseTargetLocked(
CloudPublicIpPool $pool,
string $addressCidr,
$lockedIps
): ?CloudPublicIp {
try {
$prefix = CloudIpPrefix::address($addressCidr);
if ($prefix->family() !== 6
|| $prefix->prefixLength()
!== (int) $pool->guest_prefix_length
|| (int) $pool->max_allocations < 1) {
return null;
}
$address = $prefix->addressValue();
if (!self::sparseCapacityAvailableLocked($pool, $lockedIps)) {
return null;
}
$matching = null;
foreach ($lockedIps as $row) {
if ((int) $row->public_ip_pool_id !== (int) $pool->id) {
continue;
}
if (is_string($row->address_binary)
&& hash_equals($address->binary(), $row->address_binary)) {
$matching = $row;
}
}
if ($matching instanceof CloudPublicIp) {
return self::ipAvailableForPool($matching, $pool)
? $matching : null;
}
// All rows in the candidate pool are already locked. Do not take
// a late global address lock that can reverse primary-key order;
// the global (family,address_binary) unique key fences a corrupt
// cross-pool collision at insert time.
$probe = new CloudPublicIp();
$probe->host_id = (int) $pool->host_id;
$probe->public_ip_pool_id = (int) $pool->id;
$probe->address_family = 6;
$probe->address = $address->text();
$probe->address_binary = $address->binary();
$probe->prefix_length = (int) $pool->guest_prefix_length;
$probe->state = 'available';
$probe->reservation_id = null;
$probe->reservation_ip_claim_id = null;
$probe->instance_id = null;
$probe->operation_id = null;
$probe->created_at = $probe->updated_at = time();
self::assertAddressInPool($probe, $pool);
$probe->save();
return $probe;
} catch (CloudError $error) {
throw $error;
} catch (\Illuminate\Database\QueryException) {
throw new CloudError('目标公网地址已被其他地址池占用', 409);
} catch (\Throwable) {
return null;
}
}
private static function sparseCapacityAvailableLocked(
CloudPublicIpPool $pool,
$lockedIps
): bool {
$occupied = 0;
foreach ($lockedIps as $row) {
if ((int) $row->public_ip_pool_id === (int) $pool->id
&& in_array((string) $row->state,
['reserved', 'assigned', 'changing', 'uncertain'], true)) {
$occupied++;
}
}
return (int) $pool->max_allocations > 0
&& $occupied < (int) $pool->max_allocations;
}
private static function assertAddressInPool(CloudPublicIp $ip,
CloudPublicIpPool $pool, ?CloudHost $lockedHost = null): void
{
try {
$contract = CloudPublicNetworkAddressPolicy::contract(
$pool,
(int) $pool->address_family
);
CloudPublicNetworkAddressPolicy::assertSelectable(
$ip,
$pool,
$contract,
CloudPanelUsageService::managementAddress(
$lockedHost instanceof CloudHost
? $lockedHost
: CloudHost::find((int) $pool->host_id)
)
);
} catch (\Throwable) {
throw new CloudError('公网地址具体身份与地址池不一致', 409);
}
}
/** @return list<string> */
private static function dns(CloudPublicIpPool $pool): array
{
try {
return CloudPublicNetworkAddressPolicy::contract(
$pool,
(int) $pool->address_family
)->dnsServers();
} catch (\Throwable) {
throw new CloudError('公网地址池 DNS 配置损坏', 409);
}
}
private static function assertInstanceSnapshot(CloudInstance $instance,
CloudPublicNetworkSnapshot $source): void
{
try {
$spec = json_decode(
(string) $instance->spec_json,
true,
64,
JSON_THROW_ON_ERROR
);
$frozen = CloudPublicNetworkSnapshot::fromArray(
is_array($spec) ? ($spec['public_network'] ?? null) : null
);
} catch (\Throwable) {
throw new CloudError('虚拟机公网网络配置记录损坏', 409);
}
if (!hash_equals($source->fingerprint(), $frozen->fingerprint())) {
throw new CloudError('虚拟机公网网络配置与活动账本不一致', 409);
}
}
private static function insertTransitionLeg(int $transitionId,
int $family, int $sourceClaimId, ?int $targetClaimId,
bool $changed, int $now): void
{
DB::table('cloud_public_network_transition_ips')->insert([
'transition_id' => $transitionId,
'address_family' => $family,
'source_claim_id' => $sourceClaimId,
'target_claim_id' => $targetClaimId,
'changed' => $changed ? 1 : 0,
'created_at' => $now,
'updated_at' => $now,
]);
}
private static function nextGeneration(array $claims, int $family): int
{
$maximum = 0;
foreach ($claims as $claim) {
if ((int) $claim->address_family === $family) {
$maximum = max(
$maximum,
(int) ($claim->claim_generation ?? 0)
);
}
}
if ($maximum < 1 || $maximum === PHP_INT_MAX) {
throw new CloudError('公网地址声明代际无效', 409);
}
return $maximum + 1;
}
private static function json(CloudPublicNetworkSnapshot $network): string
{
return json_encode(
$network->toArray(),
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
}
}