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.
3067 lines
124 KiB
PHP
3067 lines
124 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];
|
|
private const RECOVERY_PREPARE_PENDING = 'recovery_prepare_pending';
|
|
|
|
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] = self::lockHostBoundaryLocked(
|
|
(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
|
|
);
|
|
}
|
|
|
|
try {
|
|
$spec = json_decode(
|
|
(string) $instance->spec_json,
|
|
true,
|
|
64,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
} catch (\Throwable) {
|
|
$spec = null;
|
|
}
|
|
if ((string) $instance->status !== 'active'
|
|
|| !$instance->serviceAvailable()
|
|
|| (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);
|
|
}
|
|
CloudInstanceMigrationService::assertInstanceMutationAvailable(
|
|
$instance
|
|
);
|
|
if (DB::table('cloud_backup_recoveries')
|
|
->where('instance_id', (int) $instance->id)
|
|
->whereIn('state', ['recovering', 'uncertain'])->exists()) {
|
|
throw new CloudError('虚拟机正在恢复备份,请等待完成', 409);
|
|
}
|
|
// The instance row serializes all supported mutation writers.
|
|
// This is intentionally an unlocked predicate: Worker finalizers
|
|
// lock job before instance, so taking job locks here would reverse
|
|
// that global order and create a job/instance deadlock.
|
|
if (CloudJobService::blockingQueryForInstance(
|
|
(int) $instance->id
|
|
)->exists()) {
|
|
throw new CloudError('虚拟机已有任务,请等待完成', 409);
|
|
}
|
|
|
|
[$host, $agent] = self::lockHostBoundaryLocked(
|
|
(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(
|
|
'付费更换 IP 的价格已发生变化,请刷新后重试',
|
|
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,
|
|
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
|
|
{
|
|
if ($claimed->public_network_transition_id === null) {
|
|
return;
|
|
}
|
|
CloudDispatchLedger::assertValid($claimed);
|
|
if ((string) $claimed->phase !== 'dispatching'
|
|
|| (int) $claimed->attempts !== 1
|
|
|| (int) $claimed->dispatch_attempts !== 1
|
|
|| $claimed->dispatched_at === null
|
|
|| $claimed->receipt_deadline_at === null) {
|
|
throw new CloudError('公网网络变更尚未跨越派发边界', 409);
|
|
}
|
|
$updated = CloudPublicNetworkTransition::where(
|
|
'id',
|
|
(int) $claimed->public_network_transition_id
|
|
)->where('operation_id', (string) $claimed->operation_id)
|
|
->where('instance_id', (int) $claimed->instance_id)
|
|
->where('host_id', (int) $claimed->host_id)
|
|
->where('state', 'queued')
|
|
->where('effect_resolution', 'not_applicable')
|
|
->where('active_transition', 1)
|
|
->update([
|
|
'state' => 'awaiting_receipt',
|
|
'updated_at' => time(),
|
|
]);
|
|
if ($updated === 1) {
|
|
return;
|
|
}
|
|
$transition = CloudPublicNetworkTransition::find(
|
|
(int) $claimed->public_network_transition_id
|
|
);
|
|
if ($transition instanceof CloudPublicNetworkTransition
|
|
&& (string) $transition->state === 'awaiting_receipt'
|
|
&& (string) $transition->effect_resolution === 'not_applicable'
|
|
&& (int) $transition->active_transition === 1
|
|
&& hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $claimed->operation_id
|
|
)) {
|
|
return;
|
|
}
|
|
throw new CloudError('公网网络变更派发账本不一致', 409);
|
|
}
|
|
|
|
/** Fail closed when Worker can no longer classify the Agent effect. */
|
|
public static function markJobUncertain(CloudJob $claimed): void
|
|
{
|
|
if ($claimed->public_network_transition_id === null) {
|
|
return;
|
|
}
|
|
$payload = self::recoveryPayload($claimed);
|
|
$parentId = (int) ($claimed->parent_job_id ?? 0);
|
|
DB::connection()->transaction(static function () use (
|
|
$claimed,
|
|
$payload,
|
|
$parentId
|
|
): void {
|
|
$actor = User::where('id', (int) $claimed->user_id)
|
|
->lockForUpdate()->first();
|
|
$parent = $parentId > 0
|
|
? CloudJob::where('id', $parentId)
|
|
->lockForUpdate()->first()
|
|
: null;
|
|
$job = CloudJob::where('id', (int) $claimed->id)
|
|
->lockForUpdate()->first();
|
|
if (!$actor instanceof User || !$job instanceof CloudJob) {
|
|
throw new CloudError('公网网络变更未知效果账户缺失', 409);
|
|
}
|
|
if ((int) $job->user_id !== (int) $claimed->user_id
|
|
|| ($parentId > 0 && !$parent instanceof CloudJob)
|
|
|| (int) ($job->parent_job_id ?? 0) !== $parentId) {
|
|
throw new CloudError('公网网络变更父任务关联不一致', 409);
|
|
}
|
|
$instance = CloudInstance::where('id', (int) $job->instance_id)
|
|
->lockForUpdate()->first();
|
|
self::lockHostBoundaryLocked((int) ($job->host_id ?? 0));
|
|
$transition = CloudPublicNetworkTransition::where(
|
|
'id',
|
|
(int) $job->public_network_transition_id
|
|
)->lockForUpdate()->first();
|
|
if (!$instance instanceof CloudInstance
|
|
|| !$transition instanceof CloudPublicNetworkTransition) {
|
|
throw new CloudError('公网网络变更未知效果账本缺失', 409);
|
|
}
|
|
[$source, $target] = self::assertAssociationLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$payload,
|
|
true
|
|
);
|
|
if ((string) $transition->state === 'finalization_pending'
|
|
|| in_array((string) $transition->state,
|
|
['succeeded', 'failed'], true)) {
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
$resolution = (string) $transition->effect_resolution;
|
|
$allowed = (string) $transition->state
|
|
=== 'finalization_pending'
|
|
? ['prepared', $resolution]
|
|
: [$resolution];
|
|
if (!in_array($ledger['projection'], $allowed, true)) {
|
|
throw new CloudError(
|
|
'公网网络变更持久证据与资源投影不一致',
|
|
409
|
|
);
|
|
}
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked(
|
|
$parent,
|
|
$job,
|
|
$transition
|
|
);
|
|
return;
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== 'prepared') {
|
|
throw new CloudError('公网网络变更未知效果投影不一致', 409);
|
|
}
|
|
$now = time();
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if (!(bool) $leg->changed) {
|
|
continue;
|
|
}
|
|
$claim = $ledger['target_claims'][$family];
|
|
$ip = $ledger['target_ips'][$family];
|
|
DB::table('cloud_resource_reservation_ips')
|
|
->where('id', (int) $claim->id)->update([
|
|
'state' => 'uncertain',
|
|
'updated_at' => $now,
|
|
]);
|
|
$ip->state = 'uncertain';
|
|
$ip->updated_at = $now;
|
|
$ip->save();
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
false
|
|
);
|
|
$transition->state = 'effect_unknown';
|
|
$transition->effect_resolution = 'unknown';
|
|
$transition->effect_resolved_at = null;
|
|
$transition->last_error_code = 'local_finalization_failed';
|
|
$transition->updated_at = $now;
|
|
$transition->save();
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
}, 3);
|
|
}
|
|
|
|
/**
|
|
* 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 {
|
|
if ($claimed->public_network_transition_id === null) {
|
|
return;
|
|
}
|
|
$resolution = match ($catalogStatus) {
|
|
'succeeded' => 'applied',
|
|
'failed' => 'not_applied',
|
|
'uncertain' => 'unknown',
|
|
default => throw new CloudError(
|
|
'公网网络变更回执状态无效',
|
|
409
|
|
),
|
|
};
|
|
$parentId = (int) ($claimed->parent_job_id ?? 0);
|
|
DB::connection()->transaction(static function () use (
|
|
$claimed,
|
|
$resolution,
|
|
$result,
|
|
$payload,
|
|
$operation,
|
|
$recoveryPrepare,
|
|
$parentId
|
|
): void {
|
|
$actor = User::where('id', (int) $claimed->user_id)
|
|
->lockForUpdate()->first();
|
|
$parent = $parentId > 0
|
|
? CloudJob::where('id', $parentId)
|
|
->lockForUpdate()->first()
|
|
: null;
|
|
$job = CloudJob::where('id', (int) $claimed->id)
|
|
->lockForUpdate()->first();
|
|
if (!$actor instanceof User || !$job instanceof CloudJob) {
|
|
throw new CloudError('公网网络变更任务账户不存在', 409);
|
|
}
|
|
if ((int) $job->user_id !== (int) $claimed->user_id
|
|
|| ($parentId > 0 && !$parent instanceof CloudJob)
|
|
|| (int) ($job->parent_job_id ?? 0) !== $parentId) {
|
|
throw new CloudError('公网网络变更父任务关联不一致', 409);
|
|
}
|
|
$sameLease = is_string($claimed->lease_token)
|
|
&& is_string($job->lease_token)
|
|
&& hash_equals(
|
|
(string) $claimed->lease_token,
|
|
(string) $job->lease_token
|
|
);
|
|
$recoveryTerminal = $recoveryPrepare
|
|
&& (string) $job->phase === 'terminal'
|
|
&& (string) $job->effect_resolution === 'unknown';
|
|
if (!hash_equals(
|
|
(string) $claimed->operation_id,
|
|
(string) $job->operation_id
|
|
)
|
|
|| (!$sameLease && !$recoveryTerminal)
|
|
|| (!$recoveryTerminal && (string) $job->phase === 'terminal')) {
|
|
throw new CloudError('公网网络变更回执租约已失效', 409);
|
|
}
|
|
$instance = CloudInstance::where('id', (int) $job->instance_id)
|
|
->lockForUpdate()->first();
|
|
self::lockHostBoundaryLocked((int) ($job->host_id ?? 0));
|
|
$transition = CloudPublicNetworkTransition::where(
|
|
'id',
|
|
(int) $job->public_network_transition_id
|
|
)->lockForUpdate()->first();
|
|
if (!$instance instanceof CloudInstance
|
|
|| !$transition instanceof CloudPublicNetworkTransition) {
|
|
throw new CloudError('公网网络变更冻结账本缺失', 409);
|
|
}
|
|
[$source, $target] = self::assertAssociationLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$payload,
|
|
true
|
|
);
|
|
if (in_array((string) $transition->state,
|
|
['succeeded', 'failed'], true)) {
|
|
if (!hash_equals(
|
|
(string) $transition->effect_resolution,
|
|
$resolution
|
|
)) {
|
|
throw new CloudError(
|
|
'公网网络变更已有冲突的终态证据',
|
|
409
|
|
);
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== $resolution) {
|
|
throw new CloudError(
|
|
'公网网络变更终态资源投影不一致',
|
|
409
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
$resolution === 'not_applied'
|
|
);
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked(
|
|
$parent,
|
|
$job,
|
|
$transition
|
|
);
|
|
return;
|
|
}
|
|
if ((string) $transition->state === 'finalization_pending') {
|
|
if ($resolution === 'unknown'
|
|
|| !hash_equals(
|
|
(string) $transition->effect_resolution,
|
|
$resolution
|
|
)) {
|
|
throw new CloudError(
|
|
'公网网络变更已有冲突的最终化证据',
|
|
409
|
|
);
|
|
}
|
|
if ($resolution === 'applied') {
|
|
self::assertAppliedResult($instance, $target, $result);
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if (!in_array($ledger['projection'],
|
|
['prepared', $resolution], true)) {
|
|
throw new CloudError(
|
|
'公网网络变更待最终化投影不一致',
|
|
409
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
false
|
|
);
|
|
if ($recoveryPrepare
|
|
&& !hash_equals(
|
|
(string) $transition->last_error_code,
|
|
self::RECOVERY_PREPARE_PENDING
|
|
)) {
|
|
$transition->last_error_code =
|
|
self::RECOVERY_PREPARE_PENDING;
|
|
$transition->updated_at = time();
|
|
$transition->save();
|
|
}
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked(
|
|
$parent,
|
|
$job,
|
|
$transition
|
|
);
|
|
return;
|
|
}
|
|
if (!in_array((string) $transition->state, [
|
|
'reserved', 'queued', 'awaiting_receipt', 'effect_unknown',
|
|
], true)) {
|
|
throw new CloudError('公网网络变更状态不允许记录回执', 409);
|
|
}
|
|
if ((string) $transition->state === 'effect_unknown'
|
|
&& $resolution === 'unknown') {
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== 'prepared') {
|
|
throw new CloudError(
|
|
'公网网络变更未知效果资源投影不一致',
|
|
409
|
|
);
|
|
}
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if ((bool) $leg->changed
|
|
&& ((string) $ledger['target_claims'][$family]->state
|
|
!== 'uncertain'
|
|
|| (string) $ledger['target_ips'][$family]->state
|
|
!== 'uncertain')) {
|
|
throw new CloudError(
|
|
'公网网络变更未知效果目标未锁定',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
false
|
|
);
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked(
|
|
$parent,
|
|
$job,
|
|
$transition
|
|
);
|
|
return;
|
|
}
|
|
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== 'prepared') {
|
|
throw new CloudError(
|
|
'公网网络变更回执前资源账本已发生变化',
|
|
409
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
false
|
|
);
|
|
$now = time();
|
|
if ($resolution === 'unknown') {
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if (!(bool) $leg->changed) {
|
|
continue;
|
|
}
|
|
$claim = $ledger['target_claims'][$family];
|
|
$ip = $ledger['target_ips'][$family];
|
|
DB::table('cloud_resource_reservation_ips')
|
|
->where('id', (int) $claim->id)->update([
|
|
'state' => 'uncertain',
|
|
'updated_at' => $now,
|
|
]);
|
|
$ip->state = 'uncertain';
|
|
$ip->updated_at = $now;
|
|
$ip->save();
|
|
}
|
|
$transition->state = 'effect_unknown';
|
|
$transition->effect_resolution = 'unknown';
|
|
$transition->effect_resolved_at = null;
|
|
} else {
|
|
if ($resolution === 'applied') {
|
|
self::assertAppliedResult($instance, $target, $result);
|
|
}
|
|
$transition->state = 'finalization_pending';
|
|
$transition->effect_resolution = $resolution;
|
|
$transition->effect_resolved_at = $now;
|
|
}
|
|
$transition->last_error_code = $recoveryPrepare
|
|
? self::RECOVERY_PREPARE_PENDING
|
|
: self::errorCode($operation);
|
|
$transition->updated_at = $now;
|
|
$transition->save();
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
}, 3);
|
|
}
|
|
|
|
/**
|
|
* 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 {
|
|
if ($job->public_network_transition_id === null) {
|
|
return;
|
|
}
|
|
$resolution = match ($catalogStatus) {
|
|
'succeeded' => 'applied',
|
|
'failed' => 'not_applied',
|
|
'uncertain' => 'unknown',
|
|
default => throw new CloudError(
|
|
'公网网络变更本地最终化状态无效',
|
|
409
|
|
),
|
|
};
|
|
$instance = CloudInstance::where('id', (int) $job->instance_id)
|
|
->lockForUpdate()->first();
|
|
self::lockHostBoundaryLocked((int) ($job->host_id ?? 0));
|
|
$transition = CloudPublicNetworkTransition::where(
|
|
'id',
|
|
(int) $job->public_network_transition_id
|
|
)->lockForUpdate()->first();
|
|
if (!$instance instanceof CloudInstance
|
|
|| !$transition instanceof CloudPublicNetworkTransition) {
|
|
throw new CloudError('公网网络变更本地冻结账本缺失', 409);
|
|
}
|
|
[$source, $target] = self::assertAssociationLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$payload,
|
|
true
|
|
);
|
|
if ($resolution === 'unknown') {
|
|
if ((string) $transition->state !== 'effect_unknown'
|
|
|| (string) $transition->effect_resolution !== 'unknown'
|
|
|| (int) $transition->active_transition !== 1) {
|
|
throw new CloudError('公网网络变更未知效果账本不一致', 409);
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== 'prepared') {
|
|
throw new CloudError('公网网络变更未知效果投影不一致', 409);
|
|
}
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if ((bool) $leg->changed
|
|
&& ((string) $ledger['target_claims'][$family]->state
|
|
!== 'uncertain'
|
|
|| (string) $ledger['target_ips'][$family]->state
|
|
!== 'uncertain')) {
|
|
throw new CloudError(
|
|
'公网网络变更未知效果目标未锁定',
|
|
409
|
|
);
|
|
}
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
false
|
|
);
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
return;
|
|
}
|
|
if ((string) $transition->state !== 'finalization_pending'
|
|
|| !hash_equals(
|
|
(string) $transition->effect_resolution,
|
|
$resolution
|
|
)
|
|
|| (int) $transition->active_transition !== 1
|
|
|| $transition->effect_resolved_at === null) {
|
|
if (self::terminalMatches($transition, $resolution)) {
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== $resolution) {
|
|
throw new CloudError(
|
|
'公网网络变更终态资源投影不一致',
|
|
409
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
$resolution === 'not_applied'
|
|
);
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked(
|
|
$parent,
|
|
$job,
|
|
$transition
|
|
);
|
|
return;
|
|
}
|
|
throw new CloudError('公网网络变更最终化证据不一致', 409);
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
$now = time();
|
|
if ($resolution === 'applied') {
|
|
if ($ledger['projection'] === 'prepared') {
|
|
self::applyTargetLocked($ledger, $instance, $target, $now);
|
|
} elseif ($ledger['projection'] !== 'applied') {
|
|
throw new CloudError(
|
|
'公网网络变更生效投影与证据不一致',
|
|
409
|
|
);
|
|
}
|
|
} else {
|
|
if ($ledger['projection'] === 'prepared') {
|
|
self::releaseTargetLocked($ledger, $now);
|
|
} elseif ($ledger['projection'] !== 'not_applied') {
|
|
throw new CloudError(
|
|
'公网网络变更未生效投影与证据不一致',
|
|
409
|
|
);
|
|
}
|
|
if (!$deferPublish) {
|
|
CloudIpChangeBillingService::refundTransitionNotAppliedLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload
|
|
);
|
|
}
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
$resolution === 'not_applied' && !$deferPublish
|
|
);
|
|
if (!$deferPublish) {
|
|
self::publishLocked($transition, $resolution, $now);
|
|
}
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
}
|
|
|
|
/** Publish a recovery-prepared projection after the Agent fence release. */
|
|
public static function publishPreparedLocked(
|
|
CloudJob $job,
|
|
string $resolution,
|
|
?User $actor,
|
|
?CloudJob $parent = null
|
|
): void {
|
|
if ($job->public_network_transition_id === null) {
|
|
return;
|
|
}
|
|
if (!in_array($resolution, ['applied', 'not_applied'], true)) {
|
|
throw new CloudError('公网网络变更恢复结论无效', 409);
|
|
}
|
|
$instance = CloudInstance::where('id', (int) $job->instance_id)
|
|
->lockForUpdate()->first();
|
|
self::lockHostBoundaryLocked((int) ($job->host_id ?? 0));
|
|
$transition = CloudPublicNetworkTransition::where(
|
|
'id',
|
|
(int) $job->public_network_transition_id
|
|
)->lockForUpdate()->first();
|
|
if (!$instance instanceof CloudInstance
|
|
|| !$transition instanceof CloudPublicNetworkTransition) {
|
|
throw new CloudError('公网网络变更恢复账本缺失', 409);
|
|
}
|
|
[$source, $target] = self::assertAssociationLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
null,
|
|
false
|
|
);
|
|
if (self::terminalMatches($transition, $resolution)) {
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== $resolution) {
|
|
throw new CloudError(
|
|
'公网网络变更恢复终态投影不一致',
|
|
409
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
null,
|
|
$resolution === 'not_applied'
|
|
);
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
return;
|
|
}
|
|
if ((string) $transition->state !== 'finalization_pending'
|
|
|| (string) $transition->effect_resolution !== $resolution
|
|
|| (int) $transition->active_transition !== 1
|
|
|| !hash_equals(
|
|
(string) $transition->last_error_code,
|
|
self::RECOVERY_PREPARE_PENDING
|
|
)) {
|
|
throw new CloudError('公网网络变更恢复预提交不一致', 409);
|
|
}
|
|
$ledger = self::lockLedgerLocked(
|
|
$job,
|
|
$instance,
|
|
$transition,
|
|
$source,
|
|
$target
|
|
);
|
|
if ($ledger['projection'] !== $resolution) {
|
|
throw new CloudError('公网网络变更恢复资源投影不一致', 409);
|
|
}
|
|
$payload = self::recoveryPayload($job);
|
|
if ($resolution === 'not_applied') {
|
|
CloudIpChangeBillingService::refundTransitionNotAppliedLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload
|
|
);
|
|
}
|
|
self::assertInvoiceAssociationLocked(
|
|
$transition,
|
|
$job,
|
|
$actor,
|
|
$payload,
|
|
$resolution === 'not_applied'
|
|
);
|
|
self::publishLocked($transition, $resolution, time());
|
|
CloudPublicIpPoolReplacementBatchService::
|
|
projectTransitionEvidenceLocked($parent, $job, $transition);
|
|
}
|
|
|
|
/** Retry only PHP-owned writes after evidence survived a Worker crash. */
|
|
public static function retryPendingFinalization(
|
|
int $jobId,
|
|
string $leaseToken
|
|
): CloudJob {
|
|
$snapshot = CloudJob::find($jobId);
|
|
if (!$snapshot instanceof CloudJob) {
|
|
throw new CloudError('任务不存在', 404);
|
|
}
|
|
try {
|
|
$payload = CloudSecrets::decrypt(
|
|
(string) $snapshot->sealed_payload,
|
|
'job-payload'
|
|
);
|
|
} catch (\Throwable) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'公网网络变更本地恢复数据无法解密',
|
|
409
|
|
);
|
|
}
|
|
if (!is_array($payload) || array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'公网网络变更本地恢复数据无效',
|
|
409
|
|
);
|
|
}
|
|
$identity = CloudOperationRecoveryIdentity::expectedFromPayload(
|
|
$snapshot,
|
|
$payload,
|
|
false
|
|
);
|
|
$userId = (int) $snapshot->user_id;
|
|
$parentId = (int) ($snapshot->parent_job_id ?? 0);
|
|
DB::connection()->transaction(static function () use (
|
|
$jobId,
|
|
$leaseToken,
|
|
$payload,
|
|
$identity,
|
|
$userId,
|
|
$parentId
|
|
): void {
|
|
$actor = User::where('id', $userId)
|
|
->lockForUpdate()->first();
|
|
if (!$actor instanceof User) {
|
|
throw new CloudError('公网网络变更本地恢复账户缺失', 409);
|
|
}
|
|
$parent = $parentId > 0
|
|
? CloudJob::where('id', $parentId)
|
|
->lockForUpdate()->first()
|
|
: null;
|
|
$job = CloudJob::where('id', $jobId)->lockForUpdate()->first();
|
|
if (!$job instanceof CloudJob
|
|
|| (int) $job->user_id !== $userId
|
|
|| (string) $job->kind !== 'network_change'
|
|
|| $job->public_network_transition_id === null
|
|
|| (string) $job->phase !== 'terminal'
|
|
|| (string) $job->outcome !== 'failed'
|
|
|| (string) $job->status !== 'failed'
|
|
|| !(bool) $job->effect_may_have_applied
|
|
|| (bool) $job->safe_to_resubmit
|
|
|| (string) $job->effect_resolution !== 'unknown'
|
|
|| !(bool) $job->finalization_incident
|
|
|| !is_string($job->lease_token)
|
|
|| !hash_equals((string) $job->lease_token, $leaseToken)) {
|
|
throw new CloudError(
|
|
'公网网络变更不处于可重跑的本地收尾状态',
|
|
409
|
|
);
|
|
}
|
|
if (($parentId > 0 && !$parent instanceof CloudJob)
|
|
|| (int) ($job->parent_job_id ?? 0) !== $parentId) {
|
|
throw new CloudError('公网网络变更父任务关联不一致', 409);
|
|
}
|
|
$transition = CloudPublicNetworkTransition::find(
|
|
(int) $job->public_network_transition_id
|
|
);
|
|
if (!$transition instanceof CloudPublicNetworkTransition
|
|
|| (string) $transition->state !== 'finalization_pending'
|
|
|| !in_array((string) $transition->effect_resolution,
|
|
['applied', 'not_applied'], true)
|
|
|| hash_equals(
|
|
(string) $transition->last_error_code,
|
|
self::RECOVERY_PREPARE_PENDING
|
|
)) {
|
|
throw new CloudError(
|
|
'公网网络变更没有可安全重跑的持久化回执',
|
|
409
|
|
);
|
|
}
|
|
$resolution = (string) $transition->effect_resolution;
|
|
self::finishJobLocked(
|
|
$job,
|
|
$resolution === 'applied' ? 'succeeded' : 'failed',
|
|
$payload,
|
|
$actor,
|
|
false,
|
|
$parent
|
|
);
|
|
$now = time();
|
|
$job->effect_resolution = $resolution;
|
|
$job->effect_resolved_at = $now;
|
|
$job->effect_resolved_by = null;
|
|
$job->effect_resolution_reason =
|
|
'automatic_public_network_finalization';
|
|
$safePayload = CloudInput::safeResult($payload);
|
|
$safePayload[
|
|
CloudOperationRecoveryIdentity::payloadKey()
|
|
] = CloudOperationRecoveryIdentity::persisted($identity);
|
|
$job->sealed_payload = CloudSecrets::encrypt(
|
|
$safePayload,
|
|
'job-payload'
|
|
);
|
|
$job->finalization_incident = 0;
|
|
$job->finalization_error_code = null;
|
|
$job->read_at = null;
|
|
$job->lease_token = null;
|
|
$job->lease_until = 0;
|
|
$job->available_at = 0;
|
|
$job->updated_at = $now;
|
|
$job->save();
|
|
CloudJobService::reconcileAggregateParentEffectLocked(
|
|
$job,
|
|
null
|
|
);
|
|
}, 3);
|
|
return CloudJob::find($jobId) ?? $snapshot;
|
|
}
|
|
|
|
/** @return array{0:CloudHost,1:CloudHostAgent} */
|
|
private static function lockHostBoundaryLocked(int $hostId): array
|
|
{
|
|
if ($hostId < 1) {
|
|
throw new CloudError('公网网络变更宿主机身份缺失', 409);
|
|
}
|
|
$host = CloudHost::where('id', $hostId)
|
|
->lockForUpdate()->first();
|
|
$agent = CloudHostAgent::where('host_id', $hostId)
|
|
->lockForUpdate()->first();
|
|
if (!$host instanceof CloudHost
|
|
|| !$agent instanceof CloudHostAgent) {
|
|
throw new CloudError('公网网络变更宿主机账本缺失', 409);
|
|
}
|
|
return [$host, $agent];
|
|
}
|
|
|
|
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)
|
|
&& self::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
|
|
);
|
|
}
|
|
|
|
/**
|
|
* @return array{0:CloudPublicNetworkSnapshot,1:CloudPublicNetworkSnapshot}
|
|
*/
|
|
private static function assertAssociationLocked(
|
|
CloudJob $job,
|
|
CloudInstance $instance,
|
|
CloudPublicNetworkTransition $transition,
|
|
?array $payload,
|
|
bool $requirePayload
|
|
): array {
|
|
$jobInvoiceId = $job->invoice_id === null
|
|
? null : (int) $job->invoice_id;
|
|
$transitionInvoiceId = $transition->invoice_id === null
|
|
? null : (int) $transition->invoice_id;
|
|
if ((string) $job->kind !== 'network_change'
|
|
|| (string) $job->execution_mode !== 'agent'
|
|
|| (int) $job->public_network_transition_id
|
|
!== (int) $transition->id
|
|
|| (int) $job->instance_id !== (int) $instance->id
|
|
|| (int) $transition->instance_id !== (int) $instance->id
|
|
|| (int) $job->host_id !== (int) $instance->host_id
|
|
|| (int) $transition->host_id !== (int) $instance->host_id
|
|
|| (int) $transition->reservation_id
|
|
!== (int) $instance->reservation_id
|
|
|| (int) $job->user_id
|
|
!== (int) $transition->requested_by_user_id
|
|
|| !hash_equals(
|
|
(string) $job->operation_id,
|
|
(string) $transition->operation_id
|
|
)
|
|
|| $jobInvoiceId !== $transitionInvoiceId
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
(string) $transition->operation_id) !== 1
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
(string) $transition->source_claim_set_sha256) !== 1
|
|
|| preg_match('/^[a-f0-9]{64}$/D',
|
|
(string) $transition->target_claim_set_sha256) !== 1) {
|
|
throw new CloudError('公网网络变更任务与冻结账本不一致', 409);
|
|
}
|
|
try {
|
|
$source = CloudPublicNetworkSnapshot::fromArray(json_decode(
|
|
(string) $transition->source_public_network_json,
|
|
true,
|
|
16,
|
|
JSON_THROW_ON_ERROR
|
|
));
|
|
$target = CloudPublicNetworkSnapshot::fromArray(json_decode(
|
|
(string) $transition->target_public_network_json,
|
|
true,
|
|
16,
|
|
JSON_THROW_ON_ERROR
|
|
));
|
|
$spec = json_decode(
|
|
(string) $instance->spec_json,
|
|
true,
|
|
64,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
$projected = CloudPublicNetworkSnapshot::fromArray(
|
|
is_array($spec) ? ($spec['public_network'] ?? null) : null
|
|
);
|
|
} catch (\Throwable) {
|
|
throw new CloudError('公网网络变更冻结快照损坏', 409);
|
|
}
|
|
if (!hash_equals(
|
|
(string) $transition->source_public_network_sha256,
|
|
$source->fingerprint()
|
|
)
|
|
|| !hash_equals(
|
|
(string) $transition->target_public_network_sha256,
|
|
$target->fingerprint()
|
|
)
|
|
|| hash_equals($source->fingerprint(), $target->fingerprint())
|
|
|| (!hash_equals(
|
|
$projected->fingerprint(),
|
|
$source->fingerprint()
|
|
) && !hash_equals(
|
|
$projected->fingerprint(),
|
|
$target->fingerprint()
|
|
))) {
|
|
throw new CloudError('公网网络变更冻结快照摘要不一致', 409);
|
|
}
|
|
if ($requirePayload) {
|
|
$body = is_array($payload['body'] ?? null)
|
|
&& !array_is_list($payload['body'])
|
|
? $payload['body'] : null;
|
|
$bodyKeys = is_array($body) ? array_keys($body) : [];
|
|
$unexpected = array_diff(
|
|
$bodyKeys,
|
|
['operation_id', 'public_network', 'confirm_restart']
|
|
);
|
|
if ($body === null || $unexpected !== []
|
|
|| ($body['confirm_restart'] ?? null) !== true
|
|
|| ($payload['public_network_transition_id'] ?? null)
|
|
!== (int) $transition->id
|
|
|| !hash_equals(
|
|
(string) ($payload['source_claim_set_sha256'] ?? ''),
|
|
(string) $transition->source_claim_set_sha256
|
|
)
|
|
|| !hash_equals(
|
|
(string) ($payload['target_claim_set_sha256'] ?? ''),
|
|
(string) $transition->target_claim_set_sha256
|
|
)) {
|
|
throw new CloudError('公网网络变更任务载荷关联无效', 409);
|
|
}
|
|
try {
|
|
$requested = CloudPublicNetworkSnapshot::fromArray(
|
|
$body['public_network'] ?? null
|
|
);
|
|
} catch (\Throwable) {
|
|
throw new CloudError('公网网络变更任务目标无效', 409);
|
|
}
|
|
if (!hash_equals(
|
|
$requested->fingerprint(),
|
|
$target->fingerprint()
|
|
)) {
|
|
throw new CloudError('公网网络变更任务目标已漂移', 409);
|
|
}
|
|
}
|
|
return [$source, $target];
|
|
}
|
|
|
|
private static function assertInvoiceAssociationLocked(
|
|
CloudPublicNetworkTransition $transition,
|
|
CloudJob $job,
|
|
?User $actor,
|
|
?array $payload,
|
|
bool $expectRefunded
|
|
): void {
|
|
if ((string) $transition->kind !== 'user_paid') {
|
|
if ($transition->invoice_id !== null || $job->invoice_id !== null
|
|
|| ($payload !== null && (
|
|
($payload['price_cents'] ?? null) !== null
|
|
|| ($payload['charged_amount'] ?? null) !== null
|
|
|| ($payload['currency'] ?? null) !== null
|
|
))) {
|
|
throw new CloudError('非付费公网网络变更账单关联无效', 409);
|
|
}
|
|
return;
|
|
}
|
|
if (!$actor instanceof User
|
|
|| (int) $actor->id !== (int) $transition->requested_by_user_id
|
|
|| $transition->invoice_id === null
|
|
|| (int) $job->invoice_id !== (int) $transition->invoice_id) {
|
|
throw new CloudError('付费公网网络变更账户关联无效', 409);
|
|
}
|
|
$invoice = CloudInvoice::where(
|
|
'id',
|
|
(int) $transition->invoice_id
|
|
)->lockForUpdate()->first();
|
|
if (!$invoice instanceof CloudInvoice
|
|
|| (string) $invoice->purpose
|
|
!== CloudIpChangeBillingService::PURPOSE
|
|
|| (int) $invoice->instance_id !== (int) $transition->instance_id
|
|
|| (int) $invoice->user_id !== (int) $actor->id
|
|
|| (string) $invoice->currency !== 'USD'
|
|
|| (string) $invoice->paid_via !== 'balance'
|
|
|| $invoice->paid_at === null
|
|
|| !hash_equals(
|
|
'public-network-transition-'
|
|
. (string) $transition->transition_key,
|
|
(string) $invoice->payment_reference
|
|
)
|
|
|| (string) $invoice->status
|
|
!== ($expectRefunded ? 'refunded' : 'paid')) {
|
|
throw new CloudError('付费公网网络变更账单关联不一致', 409);
|
|
}
|
|
if ($payload === null) {
|
|
return;
|
|
}
|
|
$priceCents = $payload['price_cents'] ?? null;
|
|
$amount = $payload['charged_amount'] ?? null;
|
|
if (!is_int($priceCents) || $priceCents < 1
|
|
|| !is_string($amount)
|
|
|| ($payload['currency'] ?? null) !== 'USD'
|
|
|| CloudMoney::cents($amount) !== $priceCents
|
|
|| CloudMoney::cents((string) $invoice->amount) !== $priceCents) {
|
|
throw new CloudError('付费公网网络变更冻结金额不一致', 409);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Lock and validate the exact dual-stack ledger frozen by a transition.
|
|
*
|
|
* @return array{reservation:CloudResourceReservation,legs:array<int,object>,
|
|
* source_claims:array<int,object>,target_claims:array<int,object>,
|
|
* source_ips:array<int,CloudPublicIp>,target_ips:array<int,CloudPublicIp>,
|
|
* projection:string}
|
|
*/
|
|
private static function lockLedgerLocked(
|
|
CloudJob $job,
|
|
CloudInstance $instance,
|
|
CloudPublicNetworkTransition $transition,
|
|
CloudPublicNetworkSnapshot $source,
|
|
CloudPublicNetworkSnapshot $target
|
|
): array {
|
|
self::lockFrozenTopologyLocked($transition, $source, $target);
|
|
$reservation = CloudResourceReservation::where(
|
|
'id',
|
|
(int) $transition->reservation_id
|
|
)->lockForUpdate()->first();
|
|
if (!$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) {
|
|
throw new CloudError('公网网络变更资源预留关联不一致', 409);
|
|
}
|
|
$legRows = DB::table('cloud_public_network_transition_ips')
|
|
->where('transition_id', (int) $transition->id)
|
|
->orderBy('address_family')->orderBy('id')
|
|
->lockForUpdate()->get()->all();
|
|
$legs = [];
|
|
$claimIds = [];
|
|
foreach ($legRows as $leg) {
|
|
$family = (int) ($leg->address_family ?? 0);
|
|
if (!in_array($family, self::FAMILIES, true)
|
|
|| isset($legs[$family])
|
|
|| (int) ($leg->source_claim_id ?? 0) < 1
|
|
|| ((bool) ($leg->changed ?? false))
|
|
!== ($leg->target_claim_id !== null)) {
|
|
throw new CloudError('公网网络变更双栈明细损坏', 409);
|
|
}
|
|
$legs[$family] = $leg;
|
|
$claimIds[] = (int) $leg->source_claim_id;
|
|
if ($leg->target_claim_id !== null) {
|
|
$claimIds[] = (int) $leg->target_claim_id;
|
|
}
|
|
}
|
|
if (array_keys($legs) !== self::FAMILIES) {
|
|
throw new CloudError('公网网络变更双栈明细不完整', 409);
|
|
}
|
|
$claimIds = array_values(array_unique($claimIds));
|
|
sort($claimIds, SORT_NUMERIC);
|
|
$claims = DB::table('cloud_resource_reservation_ips')
|
|
->whereIn('id', $claimIds)->orderBy('id')
|
|
->lockForUpdate()->get()->keyBy('id');
|
|
if ($claims->count() !== count($claimIds)) {
|
|
throw new CloudError('公网网络变更地址声明缺失', 409);
|
|
}
|
|
$ipIds = [];
|
|
foreach ($claims as $claim) {
|
|
$ipIds[] = (int) $claim->public_ip_id;
|
|
}
|
|
$ipIds = array_values(array_unique($ipIds));
|
|
sort($ipIds, SORT_NUMERIC);
|
|
$ips = CloudPublicIp::whereIn('id', $ipIds)->orderBy('id')
|
|
->lockForUpdate()->get()->keyBy('id');
|
|
if ($ips->count() !== count($ipIds)) {
|
|
throw new CloudError('公网网络变更地址记录缺失', 409);
|
|
}
|
|
|
|
$sourceClaims = [];
|
|
$targetClaims = [];
|
|
$sourceIps = [];
|
|
$targetIps = [];
|
|
$projection = null;
|
|
foreach (self::FAMILIES as $family) {
|
|
$leg = $legs[$family];
|
|
$sourceClaim = $claims->get((int) $leg->source_claim_id);
|
|
$sourceIp = is_object($sourceClaim)
|
|
? $ips->get((int) $sourceClaim->public_ip_id) : null;
|
|
if (!is_object($sourceClaim)
|
|
|| !$sourceIp instanceof CloudPublicIp) {
|
|
throw new CloudError('公网网络变更源声明缺失', 409);
|
|
}
|
|
self::assertFrozenRowIdentity(
|
|
$sourceClaim,
|
|
$sourceIp,
|
|
$family,
|
|
(int) $reservation->id,
|
|
$source,
|
|
(int) $transition->source_network_attachment_id,
|
|
(int) $transition->host_id
|
|
);
|
|
$sourceClaims[$family] = $sourceClaim;
|
|
$sourceIps[$family] = $sourceIp;
|
|
if (!(bool) $leg->changed) {
|
|
if ($leg->target_claim_id !== null
|
|
|| !self::sourceActive(
|
|
$sourceClaim,
|
|
$sourceIp,
|
|
(int) $instance->id
|
|
)
|
|
|| !hash_equals(
|
|
$source->address($family),
|
|
$target->address($family)
|
|
)) {
|
|
throw new CloudError('公网网络变更未变更明细不一致', 409);
|
|
}
|
|
$targetClaims[$family] = $sourceClaim;
|
|
$targetIps[$family] = $sourceIp;
|
|
continue;
|
|
}
|
|
$targetClaim = $claims->get((int) $leg->target_claim_id);
|
|
$targetIp = is_object($targetClaim)
|
|
? $ips->get((int) $targetClaim->public_ip_id) : null;
|
|
if (!is_object($targetClaim)
|
|
|| !$targetIp instanceof CloudPublicIp
|
|
|| (int) $targetClaim->id === (int) $sourceClaim->id) {
|
|
throw new CloudError('公网网络变更目标声明缺失', 409);
|
|
}
|
|
self::assertFrozenRowIdentity(
|
|
$targetClaim,
|
|
$targetIp,
|
|
$family,
|
|
(int) $reservation->id,
|
|
$target,
|
|
(int) $transition->target_network_attachment_id,
|
|
(int) $transition->host_id
|
|
);
|
|
$targetClaims[$family] = $targetClaim;
|
|
$targetIps[$family] = $targetIp;
|
|
$legProjection = self::legProjection(
|
|
$sourceClaim,
|
|
$sourceIp,
|
|
$targetClaim,
|
|
$targetIp,
|
|
$instance,
|
|
$transition
|
|
);
|
|
if ($projection === null) {
|
|
$projection = $legProjection;
|
|
} elseif ($projection !== $legProjection) {
|
|
throw new CloudError('公网网络变更双栈投影部分提交', 409);
|
|
}
|
|
}
|
|
$projection ??= 'prepared';
|
|
if (!hash_equals(
|
|
self::frozenClaimSetDigest(
|
|
(int) $reservation->id,
|
|
$sourceClaims,
|
|
$sourceIps,
|
|
$source
|
|
),
|
|
(string) $transition->source_claim_set_sha256
|
|
)
|
|
|| !hash_equals(
|
|
self::frozenClaimSetDigest(
|
|
(int) $reservation->id,
|
|
$targetClaims,
|
|
$targetIps,
|
|
$target
|
|
),
|
|
(string) $transition->target_claim_set_sha256
|
|
)) {
|
|
throw new CloudError('公网网络变更声明集合摘要不一致', 409);
|
|
}
|
|
$spec = json_decode((string) $instance->spec_json, true);
|
|
$projected = CloudPublicNetworkSnapshot::fromArray(
|
|
is_array($spec) ? ($spec['public_network'] ?? null) : null
|
|
);
|
|
$expectedSpec = $projection === 'applied' ? $target : $source;
|
|
if (!hash_equals(
|
|
$projected->fingerprint(),
|
|
$expectedSpec->fingerprint()
|
|
)) {
|
|
throw new CloudError('公网网络变更实例投影与账本不一致', 409);
|
|
}
|
|
return [
|
|
'reservation' => $reservation,
|
|
'legs' => $legs,
|
|
'source_claims' => $sourceClaims,
|
|
'target_claims' => $targetClaims,
|
|
'source_ips' => $sourceIps,
|
|
'target_ips' => $targetIps,
|
|
'projection' => $projection,
|
|
];
|
|
}
|
|
|
|
private static function lockFrozenTopologyLocked(
|
|
CloudPublicNetworkTransition $transition,
|
|
CloudPublicNetworkSnapshot $source,
|
|
CloudPublicNetworkSnapshot $target
|
|
): void {
|
|
$attachmentIds = array_values(array_unique([
|
|
(int) $transition->source_network_attachment_id,
|
|
(int) $transition->target_network_attachment_id,
|
|
]));
|
|
sort($attachmentIds, SORT_NUMERIC);
|
|
$attachments = CloudHostNetworkAttachment::whereIn(
|
|
'id', $attachmentIds
|
|
)->orderBy('id')->lockForUpdate()->get();
|
|
if ($attachments->count() !== count($attachmentIds)) {
|
|
throw new CloudError('公网网络变更冻结附件缺失', 409);
|
|
}
|
|
|
|
$poolKeys = [];
|
|
foreach ([$source->toArray(), $target->toArray()] as $snapshot) {
|
|
foreach (['ipv4', 'ipv6'] as $leg) {
|
|
$poolKeys[(string) $snapshot[$leg]['pool_key']] = true;
|
|
}
|
|
}
|
|
$poolKeys = array_keys($poolKeys);
|
|
sort($poolKeys, SORT_STRING);
|
|
$pools = CloudPublicIpPool::where(
|
|
'host_id', (int) $transition->host_id
|
|
)->whereIn('pool_key', $poolKeys)->orderBy('id')
|
|
->lockForUpdate()->get();
|
|
if ($pools->count() !== count($poolKeys)) {
|
|
throw new CloudError('公网网络变更冻结地址池缺失', 409);
|
|
}
|
|
}
|
|
|
|
private static function assertFrozenRowIdentity(
|
|
object $claim,
|
|
CloudPublicIp $ip,
|
|
int $family,
|
|
int $reservationId,
|
|
CloudPublicNetworkSnapshot $network,
|
|
int $attachmentId,
|
|
int $hostId
|
|
): void {
|
|
if ((int) ($claim->reservation_id ?? 0) !== $reservationId
|
|
|| (int) ($claim->address_family ?? 0) !== $family
|
|
|| (int) ($claim->claim_generation ?? 0) < 1
|
|
|| (int) ($claim->network_attachment_id ?? 0) !== $attachmentId
|
|
|| (int) ($claim->public_ip_pool_id ?? 0) < 1
|
|
|| (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id
|
|
|| (int) $ip->host_id !== $hostId
|
|
|| (int) $ip->address_family !== $family
|
|
|| (int) $ip->public_ip_pool_id
|
|
!== (int) $claim->public_ip_pool_id
|
|
|| !hash_equals(
|
|
(string) $ip->address . '/' . (int) $ip->prefix_length,
|
|
$network->address($family)
|
|
)
|
|
|| preg_match('/^[a-f0-9]{32}$/D',
|
|
(string) ($claim->operation_id ?? '')) !== 1) {
|
|
throw new CloudError('公网网络变更声明具体身份不一致', 409);
|
|
}
|
|
}
|
|
|
|
private static function sourceActive(
|
|
object $claim,
|
|
CloudPublicIp $ip,
|
|
int $instanceId
|
|
): bool {
|
|
return (int) ($claim->active_claim ?? 0) === 1
|
|
&& (string) ($claim->state ?? '') === 'committed'
|
|
&& $claim->released_at === null
|
|
&& (string) $ip->state === 'assigned'
|
|
&& (int) ($ip->reservation_id ?? 0)
|
|
=== (int) $claim->reservation_id
|
|
&& (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 ?? '')
|
|
);
|
|
}
|
|
|
|
private static function legProjection(
|
|
object $sourceClaim,
|
|
CloudPublicIp $sourceIp,
|
|
object $targetClaim,
|
|
CloudPublicIp $targetIp,
|
|
CloudInstance $instance,
|
|
CloudPublicNetworkTransition $transition
|
|
): string {
|
|
$sourceActive = self::sourceActive(
|
|
$sourceClaim,
|
|
$sourceIp,
|
|
(int) $instance->id
|
|
);
|
|
$sourceReleased = $sourceClaim->active_claim === null
|
|
&& (string) $sourceClaim->state === 'released'
|
|
&& $sourceClaim->released_at !== null
|
|
&& (string) $sourceClaim->release_reason
|
|
=== 'public_network_transition_succeeded'
|
|
&& (string) $sourceIp->state === 'available'
|
|
&& $sourceIp->reservation_id === null
|
|
&& $sourceIp->reservation_ip_claim_id === null
|
|
&& $sourceIp->instance_id === null
|
|
&& $sourceIp->operation_id === null;
|
|
$targetPrepared = $targetClaim->active_claim === null
|
|
&& in_array((string) $targetClaim->state,
|
|
['reserved', 'uncertain'], true)
|
|
&& $targetClaim->released_at === null
|
|
&& (string) $targetIp->state === (string) $targetClaim->state
|
|
&& (int) ($targetIp->reservation_id ?? 0)
|
|
=== (int) $transition->reservation_id
|
|
&& (int) ($targetIp->reservation_ip_claim_id ?? 0)
|
|
=== (int) $targetClaim->id
|
|
&& $targetIp->instance_id === null
|
|
&& hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $targetClaim->operation_id
|
|
)
|
|
&& hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $targetIp->operation_id
|
|
);
|
|
$targetActive = (int) ($targetClaim->active_claim ?? 0) === 1
|
|
&& (string) $targetClaim->state === 'committed'
|
|
&& $targetClaim->released_at === null
|
|
&& (string) $targetIp->state === 'assigned'
|
|
&& (int) ($targetIp->reservation_id ?? 0)
|
|
=== (int) $transition->reservation_id
|
|
&& (int) ($targetIp->reservation_ip_claim_id ?? 0)
|
|
=== (int) $targetClaim->id
|
|
&& (int) ($targetIp->instance_id ?? 0) === (int) $instance->id
|
|
&& hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $targetClaim->operation_id
|
|
)
|
|
&& hash_equals(
|
|
(string) $transition->operation_id,
|
|
(string) $targetIp->operation_id
|
|
);
|
|
$targetReleased = $targetClaim->active_claim === null
|
|
&& (string) $targetClaim->state === 'released'
|
|
&& $targetClaim->released_at !== null
|
|
&& (string) $targetClaim->release_reason
|
|
=== 'public_network_transition_not_applied'
|
|
&& (string) $targetIp->state === 'available'
|
|
&& $targetIp->reservation_id === null
|
|
&& $targetIp->reservation_ip_claim_id === null
|
|
&& $targetIp->instance_id === null
|
|
&& $targetIp->operation_id === null;
|
|
if ($sourceActive && $targetPrepared) {
|
|
return 'prepared';
|
|
}
|
|
if ($sourceReleased && $targetActive) {
|
|
return 'applied';
|
|
}
|
|
if ($sourceActive && $targetReleased) {
|
|
return 'not_applied';
|
|
}
|
|
throw new CloudError('公网网络变更地址账本部分提交', 409);
|
|
}
|
|
|
|
private static function frozenClaimSetDigest(
|
|
int $reservationId,
|
|
array $claims,
|
|
array $ips,
|
|
CloudPublicNetworkSnapshot $network
|
|
): string {
|
|
$canonical = [];
|
|
$attachmentId = null;
|
|
foreach (self::FAMILIES as $family) {
|
|
$claim = $claims[$family] ?? null;
|
|
$ip = $ips[$family] ?? null;
|
|
if (!is_object($claim) || !$ip instanceof CloudPublicIp
|
|
|| (int) ($claim->reservation_id ?? 0) !== $reservationId
|
|
|| (int) ($claim->address_family ?? 0) !== $family
|
|
|| (int) ($claim->public_ip_id ?? 0) !== (int) $ip->id
|
|
|| !hash_equals(
|
|
(string) $ip->address . '/' . (int) $ip->prefix_length,
|
|
$network->address($family)
|
|
)) {
|
|
throw new CloudError('公网网络变更摘要输入不一致', 409);
|
|
}
|
|
$currentAttachment = (int) $claim->network_attachment_id;
|
|
if ($attachmentId === null) {
|
|
$attachmentId = $currentAttachment;
|
|
} elseif ($attachmentId !== $currentAttachment) {
|
|
throw new CloudError('公网网络变更摘要跨越网络接入', 409);
|
|
}
|
|
$canonical[] = [
|
|
'family' => $family,
|
|
'claim_id' => (int) $claim->id,
|
|
'claim_generation' => (int) $claim->claim_generation,
|
|
'claim_operation_id' => (string) $claim->operation_id,
|
|
'public_ip_id' => (int) $claim->public_ip_id,
|
|
'network_attachment_id' => $currentAttachment,
|
|
'public_ip_pool_id' => (int) $claim->public_ip_pool_id,
|
|
];
|
|
}
|
|
return hash('sha256', json_encode([
|
|
'reservation_id' => $reservationId,
|
|
'claims' => $canonical,
|
|
'public_network_sha256' => $network->fingerprint(),
|
|
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES));
|
|
}
|
|
|
|
private static function applyTargetLocked(
|
|
array $ledger,
|
|
CloudInstance $instance,
|
|
CloudPublicNetworkSnapshot $target,
|
|
int $now
|
|
): void {
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if (!(bool) $leg->changed) {
|
|
continue;
|
|
}
|
|
$sourceClaim = $ledger['source_claims'][$family];
|
|
$sourceIp = $ledger['source_ips'][$family];
|
|
$targetClaim = $ledger['target_claims'][$family];
|
|
$targetIp = $ledger['target_ips'][$family];
|
|
DB::table('cloud_resource_reservation_ips')
|
|
->where('id', (int) $sourceClaim->id)->update([
|
|
'active_claim' => null,
|
|
'state' => 'released',
|
|
'released_at' => $now,
|
|
'release_reason' =>
|
|
'public_network_transition_succeeded',
|
|
'updated_at' => $now,
|
|
]);
|
|
$sourceIp->state = 'available';
|
|
$sourceIp->reservation_id = null;
|
|
$sourceIp->reservation_ip_claim_id = null;
|
|
$sourceIp->instance_id = null;
|
|
$sourceIp->operation_id = null;
|
|
$sourceIp->updated_at = $now;
|
|
$sourceIp->save();
|
|
DB::table('cloud_resource_reservation_ips')
|
|
->where('id', (int) $targetClaim->id)->update([
|
|
'active_claim' => 1,
|
|
'state' => 'committed',
|
|
'released_at' => null,
|
|
'release_reason' => '',
|
|
'updated_at' => $now,
|
|
]);
|
|
$targetIp->state = 'assigned';
|
|
$targetIp->instance_id = (int) $instance->id;
|
|
$targetIp->updated_at = $now;
|
|
$targetIp->save();
|
|
}
|
|
$spec = json_decode(
|
|
(string) $instance->spec_json,
|
|
true,
|
|
64,
|
|
JSON_THROW_ON_ERROR
|
|
);
|
|
if (!is_array($spec) || array_is_list($spec)) {
|
|
throw new CloudError('虚拟机配置记录损坏', 409);
|
|
}
|
|
foreach (['network', 'public_pool_key', 'public_pool_cidr',
|
|
'public_ip', 'public_ip_cidr', 'gateway', 'dns_servers']
|
|
as $retired) {
|
|
unset($spec[$retired]);
|
|
}
|
|
$spec['public_network'] = $target->toArray();
|
|
$instance->spec_json = json_encode(
|
|
$spec,
|
|
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
|
|
| JSON_UNESCAPED_UNICODE
|
|
);
|
|
$instance->updated_at = $now;
|
|
$instance->save();
|
|
}
|
|
|
|
private static function releaseTargetLocked(array $ledger, int $now): void
|
|
{
|
|
foreach ($ledger['legs'] as $family => $leg) {
|
|
if (!(bool) $leg->changed) {
|
|
continue;
|
|
}
|
|
$claim = $ledger['target_claims'][$family];
|
|
$ip = $ledger['target_ips'][$family];
|
|
DB::table('cloud_resource_reservation_ips')
|
|
->where('id', (int) $claim->id)->update([
|
|
'active_claim' => null,
|
|
'state' => 'released',
|
|
'released_at' => $now,
|
|
'release_reason' =>
|
|
'public_network_transition_not_applied',
|
|
'updated_at' => $now,
|
|
]);
|
|
$ip->state = 'available';
|
|
$ip->reservation_id = null;
|
|
$ip->reservation_ip_claim_id = null;
|
|
$ip->instance_id = null;
|
|
$ip->operation_id = null;
|
|
$ip->updated_at = $now;
|
|
$ip->save();
|
|
}
|
|
}
|
|
|
|
private static function publishLocked(
|
|
CloudPublicNetworkTransition $transition,
|
|
string $resolution,
|
|
int $now
|
|
): void {
|
|
$transition->state = $resolution === 'applied'
|
|
? 'succeeded' : 'failed';
|
|
$transition->effect_resolution = $resolution;
|
|
$transition->active_transition = null;
|
|
$transition->terminal_at = $now;
|
|
$transition->last_error_code = '';
|
|
$transition->updated_at = $now;
|
|
$transition->save();
|
|
}
|
|
|
|
private static function terminalMatches(
|
|
CloudPublicNetworkTransition $transition,
|
|
string $resolution
|
|
): bool {
|
|
return (string) $transition->state === (
|
|
$resolution === 'applied' ? 'succeeded' : 'failed'
|
|
)
|
|
&& (string) $transition->effect_resolution === $resolution
|
|
&& $transition->active_transition === null
|
|
&& $transition->effect_resolved_at !== null
|
|
&& $transition->terminal_at !== null;
|
|
}
|
|
|
|
private static function assertAppliedResult(
|
|
CloudInstance $instance,
|
|
CloudPublicNetworkSnapshot $target,
|
|
mixed $result
|
|
): void {
|
|
$vm = is_array($result) && is_array($result['vm'] ?? null)
|
|
? $result['vm'] : $result;
|
|
try {
|
|
$confirmed = is_array($vm)
|
|
? CloudPublicNetworkSnapshot::fromArray(
|
|
$vm['public_network'] ?? null
|
|
) : null;
|
|
} catch (\Throwable) {
|
|
$confirmed = null;
|
|
}
|
|
if (!is_array($vm) || ($vm['network_changed'] ?? null) !== true
|
|
|| !is_string($vm['uuid'] ?? null)
|
|
|| !hash_equals(
|
|
strtolower((string) $instance->uuid),
|
|
strtolower((string) $vm['uuid'])
|
|
)
|
|
|| !$confirmed instanceof CloudPublicNetworkSnapshot
|
|
|| !hash_equals(
|
|
$target->fingerprint(),
|
|
$confirmed->fingerprint()
|
|
)) {
|
|
throw new CloudError(
|
|
'Agent 成功结果未确认精确的双栈公网目标',
|
|
502
|
|
);
|
|
}
|
|
}
|
|
|
|
private static function errorCode(array $operation): string
|
|
{
|
|
$code = is_string($operation['error_code'] ?? null)
|
|
? strtolower(trim($operation['error_code'])) : '';
|
|
return preg_match('/^[a-z][a-z0-9_]{0,63}$/D', $code) === 1
|
|
? $code : '';
|
|
}
|
|
|
|
private static function recoveryPayload(CloudJob $job): array
|
|
{
|
|
try {
|
|
$payload = CloudSecrets::decrypt(
|
|
(string) $job->sealed_payload,
|
|
'job-payload'
|
|
);
|
|
} catch (\Throwable) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'公网网络变更恢复载荷无法解密',
|
|
409
|
|
);
|
|
}
|
|
if (!is_array($payload) || array_is_list($payload)) {
|
|
throw new CloudRecoveryPayloadUnavailable(
|
|
'公网网络变更恢复载荷无效',
|
|
409
|
|
);
|
|
}
|
|
return $payload;
|
|
}
|
|
|
|
/**
|
|
* 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 {
|
|
$effectiveClaims = $sourceClaims;
|
|
$effectiveIps = $sourceIps;
|
|
$changed = [];
|
|
$targetAttachment = null;
|
|
foreach ($command->targets() as $family => $target) {
|
|
$pool = null;
|
|
$ip = null;
|
|
if ($target === null) {
|
|
foreach ($pools->sortBy(static fn ($candidate) => [
|
|
(int) $candidate->priority,
|
|
(int) $candidate->id,
|
|
]) as $candidate) {
|
|
if ((int) $candidate->address_family !== $family
|
|
|| (int) $candidate->network_attachment_id
|
|
!== (int) $sourceAttachment->id
|
|
|| !self::poolUsable($candidate, $instance, $agent,
|
|
$attachments, $lineId)) {
|
|
continue;
|
|
}
|
|
foreach ($ips as $candidateIp) {
|
|
if ((int) $candidateIp->public_ip_pool_id
|
|
=== (int) $candidate->id
|
|
&& (int) $candidateIp->id
|
|
!== (int) $sourceIps[$family]->id
|
|
&& self::ipAvailableForPool(
|
|
$candidateIp, $candidate
|
|
)) {
|
|
$pool = $candidate;
|
|
$ip = $candidateIp;
|
|
break 2;
|
|
}
|
|
}
|
|
}
|
|
} else {
|
|
foreach ($pools as $candidate) {
|
|
if ((int) $candidate->address_family === $family
|
|
&& hash_equals(
|
|
(string) $candidate->pool_key,
|
|
(string) $target['pool_key']
|
|
)) {
|
|
$pool = $candidate;
|
|
break;
|
|
}
|
|
}
|
|
if ($pool instanceof CloudPublicIpPool) {
|
|
foreach ($ips as $candidateIp) {
|
|
if ((int) $candidateIp->public_ip_pool_id
|
|
=== (int) $pool->id
|
|
&& hash_equals(
|
|
(string) $candidateIp->address . '/'
|
|
. (int) $candidateIp->prefix_length,
|
|
(string) $target['address_cidr']
|
|
)) {
|
|
$ip = $candidateIp;
|
|
break;
|
|
}
|
|
}
|
|
if ($ip instanceof CloudPublicIp
|
|
&& (int) $pool->address_family === 6
|
|
&& !self::sparseCapacityAvailableLocked(
|
|
$pool,
|
|
$ips
|
|
)) {
|
|
$ip = null;
|
|
}
|
|
if (!$ip instanceof CloudPublicIp
|
|
&& (int) $pool->address_family === 6) {
|
|
$ip = self::materializeSparseTargetLocked(
|
|
$pool,
|
|
(string) $target['address_cidr'],
|
|
$ips
|
|
);
|
|
}
|
|
}
|
|
}
|
|
if (!$pool instanceof CloudPublicIpPool
|
|
|| !$ip instanceof CloudPublicIp
|
|
|| !self::poolUsable(
|
|
$pool, $instance, $agent, $attachments, $lineId
|
|
)
|
|
|| !self::ipAvailableForPool($ip, $pool)
|
|
|| (int) $ip->id === (int) $sourceIps[$family]->id) {
|
|
throw new CloudError('目标公网地址已不可分配', 409);
|
|
}
|
|
$attachment = $attachments->get(
|
|
(int) $pool->network_attachment_id
|
|
);
|
|
if (!$attachment instanceof CloudHostNetworkAttachment) {
|
|
throw new CloudError('目标公网网络接入不存在', 409);
|
|
}
|
|
if ($targetAttachment === null) {
|
|
$targetAttachment = $attachment;
|
|
} elseif ((int) $targetAttachment->id !== (int) $attachment->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) $attachment->id,
|
|
'public_ip_pool_id' => (int) $pool->id,
|
|
];
|
|
$changed[$family] = true;
|
|
}
|
|
if ($changed === [] || !$targetAttachment instanceof
|
|
CloudHostNetworkAttachment) {
|
|
throw new CloudError('公网网络变更至少需要一个目标地址', 409);
|
|
}
|
|
if ((int) $targetAttachment->id !== (int) $sourceAttachment->id
|
|
&& (!isset($changed[4]) || !isset($changed[6]))) {
|
|
throw new CloudError('跨网络接入必须同时更换 IPv4 和 IPv6', 409);
|
|
}
|
|
if ((int) $targetAttachment->id === (int) $sourceAttachment->id) {
|
|
foreach (self::FAMILIES as $family) {
|
|
if (!isset($changed[$family])) {
|
|
$effectiveClaims[$family] = $sourceClaims[$family];
|
|
$effectiveIps[$family] = $sourceIps[$family];
|
|
}
|
|
}
|
|
} elseif (count($changed) !== 2) {
|
|
throw new CloudError('跨网络接入目标双栈不完整', 409);
|
|
}
|
|
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 = CloudPublicIpPoolContract::fromRow($pool);
|
|
} 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 = CloudPublicIpPoolContract::fromRow($pool);
|
|
$address = CloudIpAddress::parse((string) $ip->address);
|
|
if ((int) $ip->host_id !== (int) $pool->host_id
|
|
|| (int) $ip->public_ip_pool_id !== (int) $pool->id
|
|
|| (int) $ip->address_family !== (int) $pool->address_family
|
|
|| (int) $ip->prefix_length
|
|
!== $contract->guestPrefixLength()
|
|
|| !hash_equals($address->text(), (string) $ip->address)
|
|
|| !$contract->addressAllowed($address)
|
|
|| !is_string($ip->address_binary)
|
|
|| !hash_equals($address->binary(), $ip->address_binary)) {
|
|
throw new \InvalidArgumentException();
|
|
}
|
|
$management = CloudPanelUsageService::managementAddress(
|
|
$lockedHost instanceof CloudHost
|
|
? $lockedHost
|
|
: CloudHost::find((int) $pool->host_id)
|
|
);
|
|
if (is_string($management) && $management !== ''
|
|
&& $address->equals(CloudIpAddress::parse($management))) {
|
|
throw new \InvalidArgumentException();
|
|
}
|
|
} catch (\Throwable) {
|
|
throw new CloudError('公网地址具体身份与地址池不一致', 409);
|
|
}
|
|
}
|
|
|
|
/** @return list<string> */
|
|
private static function dns(CloudPublicIpPool $pool): array
|
|
{
|
|
try {
|
|
return CloudPublicIpPoolContract::fromRow($pool)->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
|
|
);
|
|
}
|
|
}
|