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

1610 lines
72 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\CloudJob;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudPublicIpPoolReplacementBatch;
use App\Models\CloudPublicIpPoolReplacementBatchItem;
use App\Models\CloudPublicNetworkTransition;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
use App\Models\CloudResourceReservationIp;
use App\Models\User;
use Illuminate\Database\Capsule\Manager as DB;
/**
* Durable same-host replacement of every assigned address in one public pool.
*
* The browser selects only the target pool. PHP freezes every concrete
* source/target tuple and queues ordinary network_change children. Unknown
* effects retain the batch claim and are never replayed.
*/
final class CloudPublicIpPoolReplacementBatchService
{
private const PARENT_KIND = 'public_ip_pool_replacement_batch';
private const OCCUPIED_IP_STATES = [
'reserved', 'assigned', 'changing', 'uncertain',
];
/** @return array<string,mixed> */
public static function overview(int $hostId, string $sourcePoolKey,
array $actor): array
{
self::assertAdminRead($actor);
if ($hostId < 1
|| preg_match('/^[a-f0-9]{32}$/D', $sourcePoolKey) !== 1) {
throw new CloudError('源公网地址池标识无效', 404);
}
$host = CloudHost::find($hostId);
$source = CloudPublicIpPool::where('host_id', $hostId)
->where('pool_key', $sourcePoolKey)->first();
$sourceAttachment = $source === null ? null
: CloudHostNetworkAttachment::find(
(int) $source->network_attachment_id
);
$agent = CloudHostAgent::find($hostId);
if ($host === null || $source === null || $sourceAttachment === null
|| (int) $sourceAttachment->host_id !== $hostId) {
throw new CloudError('源公网地址池不存在', 404);
}
$sourceInstanceIds = CloudResourceReservationIp::query()
->join(
'cloud_resource_reservations as reservation',
'reservation.id',
'=',
'cloud_resource_reservation_ips.reservation_id'
)->where('reservation.host_id', $hostId)
->where(
'cloud_resource_reservation_ips.public_ip_pool_id',
(int) $source->id
)->where(
'cloud_resource_reservation_ips.address_family',
(int) $source->address_family
)->where('cloud_resource_reservation_ips.active_claim', 1)
->where('cloud_resource_reservation_ips.state', 'committed')
->where('reservation.state', 'committed')
->whereNotNull('reservation.instance_id')
->orderBy('reservation.instance_id')
->pluck('reservation.instance_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$assignedCount = count($sourceInstanceIds);
$admissionMessage = '';
if ($sourceInstanceIds !== []) {
$instances = CloudInstance::whereIn('id', $sourceInstanceIds)
->orderBy('id')->get()->keyBy('id');
if ($instances->count() !== $assignedCount) {
$admissionMessage =
'公网网络变更运行态目录不可用,请联系管理员。';
} else {
foreach (
CloudPublicNetworkMutationAdmission::inspectMany($instances)
as $decision
) {
if (!$decision->allowed()) {
$admissionMessage = $decision->message;
break;
}
}
}
}
$activeBatches = CloudPublicIpPoolReplacementBatch::where(
'host_id', $hostId
)->where('active_claim', 1)->where(function ($query) use (
$source
): void {
$query->where(
'source_public_ip_pool_id', (int) $source->id
)->orWhere(
'target_public_ip_pool_id', (int) $source->id
);
})->orderByDesc('id')->get();
$lockedPoolIds = CloudPublicIpPoolReplacementBatch::where(
'host_id', $hostId
)->where('active_claim', 1)->get([
'source_public_ip_pool_id', 'target_public_ip_pool_id',
])->flatMap(static fn ($batch): array => [
(int) $batch->source_public_ip_pool_id,
(int) $batch->target_public_ip_pool_id,
])->unique()->values()->all();
$sourceReady = $agent instanceof CloudHostAgent
&& in_array((string) $source->state,
['active', 'draining'], true)
&& (string) $source->sync_state === 'applied'
&& (int) $source->observed_revision
=== (int) $source->desired_revision
&& CloudPlacementNetworkService::attachmentReadyForAgent(
$sourceAttachment,
$agent
)
&& CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $sourceAttachment->network_selector,
(int) $sourceAttachment->verified_agent_revision
);
$targets = [];
$pools = CloudPublicIpPool::where('host_id', $hostId)
->where('id', '<>', (int) $source->id)
->where('address_family', (int) $source->address_family)
->where(
'network_attachment_id',
(int) $source->network_attachment_id
)
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('observed_revision', '=', 'desired_revision')
->orderBy('priority')->orderBy('id')->get();
foreach ($pools as $pool) {
$attachment = CloudHostNetworkAttachment::find(
(int) $pool->network_attachment_id
);
if ($attachment === null || $agent === null
|| (int) $attachment->host_id !== $hostId
|| (int) $attachment->line_id
!== (int) $sourceAttachment->line_id
|| (int) $attachment->id !== (int) $sourceAttachment->id
|| !CloudPlacementNetworkService::
attachmentReadyForAgent($attachment, $agent)
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
continue;
}
$available = self::availableCount($pool, $host);
$targets[] = [
'pool_key' => (string) $pool->pool_key,
'name' => (string) $pool->name,
'available_count' => $available,
'network_selector' => (string) $attachment->network_selector,
'expected_revision' => (int) $pool->desired_revision,
'replacement_locked' => in_array(
(int) $pool->id,
$lockedPoolIds,
true
),
'eligible' => $assignedCount > 0
&& $sourceReady
&& $admissionMessage === ''
&& $available >= $assignedCount
&& !in_array((int) $pool->id, $lockedPoolIds, true),
];
}
$batches = CloudPublicIpPoolReplacementBatch::where(
'source_public_ip_pool_id', (int) $source->id
)->orderByDesc('id')->limit(21)->get();
$active = $activeBatches->first();
$history = $batches->filter(static fn ($batch): bool =>
$batch->active_claim === null)->take(20)->map(
static fn ($batch): array => self::display($batch)
)->values()->all();
$historyCount = CloudPublicIpPoolReplacementBatch::where(
'source_public_ip_pool_id', (int) $source->id
)->whereNull('active_claim')->count();
$activeDisplay = $active === null ? null : self::display($active);
if ($activeDisplay !== null) {
$activeDisplay['selected_pool_role'] =
(int) $active->source_public_ip_pool_id === (int) $source->id
? 'source' : 'target';
}
$canStart = $active === null
&& $assignedCount > 0
&& $sourceReady
&& $admissionMessage === ''
&& count(array_filter($targets, static fn (array $target): bool =>
($target['eligible'] ?? false) === true)) > 0;
return [
'host' => [
'id' => (string) $host->id,
'name' => (string) $host->name,
],
'source_pool' => [
'pool_key' => (string) $source->pool_key,
'name' => (string) $source->name,
'state' => (string) $source->state,
'network_selector' =>
(string) $sourceAttachment->network_selector,
'expected_revision' => (int) $source->desired_revision,
'assigned_count' => $assignedCount,
'replacement_locked' => $active !== null,
'replacement_history_count' => $historyCount,
'has_replacement_history' => $historyCount > 0,
],
'target_options' => $targets,
'active_batch' => $activeDisplay,
'history' => $history,
'replacement_history_count' => $historyCount,
'has_replacement_history' => $historyCount > 0,
'can_start' => $canStart,
'start_block_reason' => $canStart ? '' : ($active !== null
? '该地址池已参与执行中的迁移批次'
: ($assignedCount < 1
? '源地址池没有需要迁移的实例'
: (!$sourceReady
? '源公网地址池或网络接入尚未完成严格同步验证'
: ($admissionMessage !== ''
? $admissionMessage
: '当前没有容量足够的同线路目标地址池')))),
];
}
/** @return array<string,mixed> */
public static function detail(int $hostId, string $sourcePoolKey,
string $batchKey, array $actor): array
{
self::assertAdminRead($actor);
if ($hostId < 1
|| preg_match('/^[a-f0-9]{32}$/D', $sourcePoolKey) !== 1
|| preg_match('/^[a-f0-9]{32}$/D', $batchKey) !== 1) {
throw new CloudError('公网地址池迁移批次标识无效', 404);
}
$source = CloudPublicIpPool::where('host_id', $hostId)
->where('pool_key', $sourcePoolKey)->first();
$batch = $source === null ? null
: CloudPublicIpPoolReplacementBatch::where(
'batch_key', $batchKey
)->where('host_id', $hostId)->where(
'source_public_ip_pool_id', (int) $source->id
)->first();
if ($source === null || $batch === null) {
throw new CloudError('公网地址池迁移批次不存在', 404);
}
return self::display($batch);
}
public static function start(int $hostId, string $sourcePoolKey,
array $actor, array $input): array
{
CloudAccess::manage($actor);
CloudInput::only($input, [
'target_pool_key', 'expected_source_revision',
'expected_target_revision', 'confirm_replacement', 'request_key',
]);
if ($hostId < 1
|| preg_match('/^[a-f0-9]{32}$/D', $sourcePoolKey) !== 1) {
throw new CloudError('源公网地址池标识无效', 404);
}
$targetPoolKey = CloudInput::publicPoolKey(
$input['target_pool_key'] ?? null
);
if (hash_equals($sourcePoolKey, $targetPoolKey)) {
throw new CloudError('目标公网地址池不能与源地址池相同', 409);
}
$expectedSourceRevision = filter_var(
$input['expected_source_revision'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
$expectedTargetRevision = filter_var(
$input['expected_target_revision'] ?? null,
FILTER_VALIDATE_INT,
['options' => ['min_range' => 1]]
);
if ($expectedSourceRevision === false
|| $expectedTargetRevision === false) {
throw new CloudError('公网地址池版本无效,请刷新后重试', 422);
}
if (($input['confirm_replacement'] ?? null) !== true) {
throw new CloudError('请确认批次内实例会分别受控重启', 409);
}
$requestKey = $input['request_key'] ?? null;
$actorUserId = (int) ($actor['user_id'] ?? 0);
if ($actorUserId < 1 || !is_string($requestKey)
|| preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1) {
throw new CloudError('批量更换公网 IP 的请求标识无效', 400);
}
$canonical = [
'kind' => self::PARENT_KIND,
'host_id' => $hostId,
'source_pool_key' => $sourcePoolKey,
'target_pool_key' => $targetPoolKey,
'expected_source_revision' => (int) $expectedSourceRevision,
'expected_target_revision' => (int) $expectedTargetRevision,
];
$fingerprint = hash('sha256', json_encode(
$canonical,
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
));
$batchKey = substr(hash('sha256', "public-pool-replacement\0"
. $actorUserId . "\0" . $hostId . "\0" . $sourcePoolKey
. "\0" . $requestKey), 0, 32);
return (new CloudPublicIpPoolReplacementBatch())->getConnection()
->transaction(static function () use (
$hostId, $sourcePoolKey, $targetPoolKey, $actorUserId,
$requestKey, $fingerprint, $batchKey, $expectedSourceRevision,
$expectedTargetRevision
): array {
$actorUser = User::where('id', $actorUserId)
->lockForUpdate()->first();
if (!$actorUser instanceof User) {
throw new CloudError('批量更换公网 IP 的操作账户不存在', 409);
}
$prior = CloudJob::where('user_id', $actorUserId)
->where('request_idempotency_key', $requestKey)
->lockForUpdate()->first();
if ($prior !== null) {
return self::existingResult(
$prior,
$fingerprint,
$batchKey
);
}
$sourceRef = CloudPublicIpPool::where('host_id', $hostId)
->where('pool_key', $sourcePoolKey)->first();
$targetRef = CloudPublicIpPool::where('host_id', $hostId)
->where('pool_key', $targetPoolKey)->first();
if ($sourceRef === null || $targetRef === null) {
throw new CloudError('源或目标公网地址池不存在', 404);
}
$instanceIds = CloudResourceReservationIp::query()
->join(
'cloud_resource_reservations as reservation',
'reservation.id',
'=',
'cloud_resource_reservation_ips.reservation_id'
)->where('reservation.host_id', $hostId)
->where(
'cloud_resource_reservation_ips.public_ip_pool_id',
(int) $sourceRef->id
)->where(
'cloud_resource_reservation_ips.address_family',
(int) $sourceRef->address_family
)->where(
'cloud_resource_reservation_ips.active_claim',
1
)->where(
'cloud_resource_reservation_ips.state',
'committed'
)->where('reservation.state', 'committed')
->whereNotNull('reservation.instance_id')
->orderBy('reservation.instance_id')
->pluck('reservation.instance_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
if ($instanceIds === []) {
throw new CloudError('源公网地址池没有可迁移实例', 409);
}
$instances = CloudInstance::whereIn('id', $instanceIds)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
if ($instances->count() !== count($instanceIds)) {
throw new CloudError(
'源地址池实例占用已变化,请刷新后重试',
409
);
}
$reservationIds = $instances->pluck('reservation_id')
->map(static fn ($id): int => (int) $id)
->filter()->unique()->sort()->values()->all();
if (count($reservationIds) !== count($instanceIds)) {
throw new CloudError('源地址池实例缺少资源预留', 409);
}
CloudPublicNetworkMutationAdmission::assertCanBeginMany(
$instances
);
$host = CloudHost::where('id', $hostId)
->lockForUpdate()->first();
$agent = CloudHostAgent::where('host_id', $hostId)
->lockForUpdate()->first();
if ($host === null || $agent === null || !$agent->isReady()) {
throw new CloudError('宿主机 Agent 暂不可用于批量更换 IP', 409);
}
$activeTransitions = CloudPublicNetworkTransition::whereIn(
'instance_id', $instanceIds
)->where('active_transition', 1)->orderBy('id')
->lockForUpdate()->get(['id']);
if ($activeTransitions->isNotEmpty()) {
throw new CloudError(
'源地址池中有实例正在执行公网网络变更',
409
);
}
$resourcePoolIds = $instances->pluck('resource_pool_id')
->map(static fn ($id): int => (int) $id)
->unique()->sort()->values()->all();
$resourcePools = CloudResourcePool::whereIn(
'id', $resourcePoolIds
)->orderBy('id')->lockForUpdate()->get()->keyBy('id');
if ($resourcePools->count() !== count($resourcePoolIds)) {
throw new CloudError('源地址池实例资源池缺失', 409);
}
$claimHints = DB::table('cloud_resource_reservation_ips')
->whereIn('reservation_id', $reservationIds)
->where('active_claim', 1)
->where('state', 'committed')
->orderBy('reservation_id')->orderBy('address_family')
->orderBy('id')->get()->all();
$claimHintCounts = [];
$poolIds = [(int) $sourceRef->id, (int) $targetRef->id];
$attachmentIds = [];
foreach ($claimHints as $hint) {
$reservationId = (int) $hint->reservation_id;
$family = (int) $hint->address_family;
if (!in_array($family, [4, 6], true)
|| isset($claimHintCounts[$reservationId][$family])) {
throw new CloudError(
'源地址池实例活动双栈声明不完整',
409
);
}
$claimHintCounts[$reservationId][$family] = true;
$poolIds[] = (int) $hint->public_ip_pool_id;
$attachmentIds[] = (int) $hint->network_attachment_id;
}
foreach ($reservationIds as $reservationId) {
if (array_keys($claimHintCounts[$reservationId] ?? [])
!== [4, 6]) {
throw new CloudError(
'源地址池实例活动双栈声明不完整',
409
);
}
}
$poolIds = array_values(array_unique($poolIds));
sort($poolIds, SORT_NUMERIC);
$poolRefs = CloudPublicIpPool::whereIn('id', $poolIds)
->orderBy('id')->get()->keyBy('id');
foreach ($poolRefs as $poolRef) {
$attachmentIds[] = (int) $poolRef->network_attachment_id;
}
$attachmentIds = array_values(array_unique($attachmentIds));
sort($attachmentIds, SORT_NUMERIC);
$attachments = CloudHostNetworkAttachment::whereIn(
'id', $attachmentIds
)->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$pools = CloudPublicIpPool::whereIn('id', $poolIds)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$sourcePool = $pools->get((int) $sourceRef->id);
$targetPool = $pools->get((int) $targetRef->id);
$sourceAttachment = $sourcePool === null ? null
: $attachments->get(
(int) $sourcePool->network_attachment_id
);
$targetAttachment = $targetPool === null ? null
: $attachments->get(
(int) $targetPool->network_attachment_id
);
if ($sourcePool === null || $targetPool === null
|| $sourceAttachment === null || $targetAttachment === null
|| (int) $sourcePool->host_id !== $hostId
|| (int) $targetPool->host_id !== $hostId
|| !hash_equals(
(string) $sourcePool->pool_key,
$sourcePoolKey
)
|| !hash_equals(
(string) $targetPool->pool_key,
$targetPoolKey
)
|| !in_array((string) $sourcePool->state,
['active', 'draining'], true)
|| (string) $sourcePool->sync_state !== 'applied'
|| (int) $sourcePool->observed_revision
!== (int) $sourcePool->desired_revision
|| (string) $targetPool->state !== 'active'
|| (string) $targetPool->sync_state !== 'applied'
|| (int) $targetPool->observed_revision
!== (int) $targetPool->desired_revision
|| (int) $sourcePool->desired_revision
!== (int) $expectedSourceRevision
|| (int) $targetPool->desired_revision
!== (int) $expectedTargetRevision
|| (int) $sourceAttachment->host_id !== $hostId
|| (int) $targetAttachment->host_id !== $hostId
|| (int) $sourcePool->address_family
!== (int) $targetPool->address_family
|| (int) $sourcePool->network_attachment_id
!== (int) $targetPool->network_attachment_id
|| (int) $sourceAttachment->id
!== (int) $targetAttachment->id
|| (int) $sourceAttachment->line_id
!== (int) $targetAttachment->line_id
|| !CloudPlacementNetworkService::
attachmentReadyForAgent($sourceAttachment, $agent)
|| !CloudPlacementNetworkService::
attachmentReadyForAgent($targetAttachment, $agent)
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $sourceAttachment->network_selector,
(int) $sourceAttachment->verified_agent_revision
)
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $targetAttachment->network_selector,
(int) $targetAttachment->verified_agent_revision
)) {
throw new CloudError(
'源或目标公网地址池不满足同地址族同网络接入的迁移条件',
409
);
}
self::assertTargetPoolConfiguration($host, $targetPool);
$reservations = CloudResourceReservation::whereIn(
'id', $reservationIds
)->orderBy('id')->lockForUpdate()->get()->keyBy('id');
if ($reservations->count() !== count($reservationIds)) {
throw new CloudError('源地址池实例资源预留缺失', 409);
}
$allClaims = DB::table('cloud_resource_reservation_ips')
->whereIn('reservation_id', $reservationIds)
->orderBy('id')->lockForUpdate()->get();
$claimsByReservation = $allClaims->groupBy('reservation_id');
$activeClaimsByInstance = [];
$claimIpIds = $allClaims->pluck('public_ip_id')->map(
static fn ($id): int => (int) $id
)->unique()->sort()->values()->all();
// One current locking read owns every claim address plus the
// complete source/target catalogs. A prior non-locking pluck
// would be a repeatable-read snapshot and could miss a sparse
// IPv6 row committed just before the pool lock was obtained.
$ips = CloudPublicIp::where(static function ($query) use (
$claimIpIds,
$sourcePool,
$targetPool
): void {
$query->whereIn('id', $claimIpIds)->orWhereIn(
'public_ip_pool_id',
[(int) $sourcePool->id, (int) $targetPool->id]
);
})->orderBy('id')->lockForUpdate()->get()->keyBy('id');
foreach ($claimIpIds as $claimIpId) {
if (!$ips->has($claimIpId)) {
throw new CloudError(
'源地址池实例公网地址账本缺失',
409
);
}
}
$sourceIpIds = [];
foreach ($instanceIds as $instanceId) {
$instance = $instances->get($instanceId);
$reservation = $instance === null ? null
: $reservations->get((int) $instance->reservation_id);
$resourcePool = $reservation === null ? null
: $resourcePools->get(
(int) $reservation->resource_pool_id
);
$claims = $reservation === null ? collect()
: ($claimsByReservation->get(
(int) $reservation->id
) ?? collect());
$activeClaims = [];
foreach ($claims as $claim) {
if ((int) ($claim->active_claim ?? 0) === 1
&& (string) $claim->state === 'committed') {
$claimFamily = (int) $claim->address_family;
if (isset($activeClaims[$claimFamily])) {
throw new CloudError(
'源地址池实例活动双栈声明重复',
409
);
}
$activeClaims[$claimFamily] = $claim;
}
}
ksort($activeClaims, SORT_NUMERIC);
$spec = $instance === null ? null : json_decode(
(string) $instance->spec_json,
true
);
if ($instance === null || $reservation === null
|| $resourcePool === null
|| (int) $instance->host_id !== $hostId
|| !is_array($spec) || array_is_list($spec)
|| ($spec['managed'] ?? false) !== true
|| ($spec['os_source'] ?? null) !== 'cloud_template'
|| (int) $reservation->instance_id !== $instanceId
|| (int) $reservation->host_id !== $hostId
|| (string) $reservation->state !== 'committed'
|| (int) $reservation->resource_pool_id
!== (int) $instance->resource_pool_id
|| (int) $resourcePool->line_id
!== (int) $sourceAttachment->line_id
|| array_keys($activeClaims) !== [4, 6]
|| (int) $activeClaims[4]->network_attachment_id
!== (int) $sourceAttachment->id
|| (int) $activeClaims[6]->network_attachment_id
!== (int) $sourceAttachment->id
|| (int) $activeClaims[
(int) $sourcePool->address_family
]->public_ip_pool_id !== (int) $sourcePool->id) {
throw new CloudError(
'源地址池实例或资源预留账本不一致',
409
);
}
$sourceIps = [];
foreach ([4, 6] as $family) {
$claim = $activeClaims[$family];
$sourceIp = $ips->get((int) $claim->public_ip_id);
if (!$sourceIp instanceof CloudPublicIp
|| (int) $claim->reservation_id
!== (int) $reservation->id
|| (int) $claim->address_family !== $family
|| (int) $sourceIp->host_id !== $hostId
|| (int) $sourceIp->address_family !== $family
|| (int) $sourceIp->public_ip_pool_id
!== (int) $claim->public_ip_pool_id
|| (string) $sourceIp->state !== 'assigned'
|| (int) $sourceIp->reservation_id
!== (int) $reservation->id
|| (int) $sourceIp->reservation_ip_claim_id
!== (int) $claim->id
|| (int) $sourceIp->instance_id !== $instanceId
|| !hash_equals(
(string) $claim->operation_id,
(string) ($sourceIp->operation_id ?? '')
)) {
throw new CloudError(
'源地址池实例活动公网声明不一致',
409
);
}
$sourceIps[$family] = $sourceIp;
}
$changedFamily = (int) $sourcePool->address_family;
$sourceIpIds[] = (int) $sourceIps[$changedFamily]->id;
$activeClaimsByInstance[$instanceId] = [
'all_claims' => $claims->values()->all(),
'active_claims' => $activeClaims,
'source_ips' => $sourceIps,
'resource_pool' => $resourcePool,
];
}
sort($sourceIpIds, SORT_NUMERIC);
$occupiedSorted = $ips->filter(static fn ($ip): bool =>
(int) $ip->public_ip_pool_id === (int) $sourcePool->id
&& self::ipOccupied($ip)
)->pluck('id')->map(static fn ($id): int => (int) $id)
->unique()->sort()->values()->all();
sort($occupiedSorted, SORT_NUMERIC);
if ($sourceIpIds !== $occupiedSorted) {
throw new CloudError(
'源地址池存在未决占用,不能开始批量迁移',
409
);
}
[$targetIps, $ips] = self::freezeExactTargetsLocked(
$targetPool,
$host,
$ips,
count($instanceIds)
);
$replacementPoolIds = [
(int) $sourcePool->id,
(int) $targetPool->id,
];
$activeBatches = CloudPublicIpPoolReplacementBatch::where(
'host_id', $hostId
)->where('active_claim', 1)->where(function (
$query
) use ($replacementPoolIds): void {
$query->whereIn(
'source_public_ip_pool_id', $replacementPoolIds
)->orWhereIn(
'target_public_ip_pool_id', $replacementPoolIds
);
})->orderBy('id')->lockForUpdate()->get(['id']);
if ($activeBatches->isNotEmpty()) {
throw new CloudError(
'源或目标地址池已参与其他迁移批次',
409
);
}
$parent = self::newParentJob(
$actorUserId,
$requestKey,
$fingerprint,
$hostId,
$sourcePool,
$targetPool,
$instanceIds
);
$now = time();
$batch = new CloudPublicIpPoolReplacementBatch();
$batch->batch_key = $batchKey;
$batch->host_id = $hostId;
$batch->source_public_ip_pool_id = (int) $sourcePool->id;
$batch->target_public_ip_pool_id = (int) $targetPool->id;
$batch->source_initial_state = (string) $sourcePool->state;
$batch->parent_job_id = (int) $parent->id;
$batch->requested_by_user_id = $actorUserId;
$batch->state = 'running';
$batch->active_claim = 1;
$batch->last_error_code = '';
$batch->terminal_at = null;
$batch->created_at = $batch->updated_at = $now;
$batch->save();
self::setPoolStateLocked($sourcePool, 'draining');
foreach ($instanceIds as $index => $instanceId) {
$instance = $instances->get($instanceId);
$reservation = $reservations->get(
(int) $instance->reservation_id
);
$ledger = $activeClaimsByInstance[$instanceId];
$family = (int) $sourcePool->address_family;
$sourceIp = $ledger['source_ips'][$family];
$targetIp = $targetIps[$index];
$item = new CloudPublicIpPoolReplacementBatchItem();
$item->batch_id = (int) $batch->id;
$item->instance_id = $instanceId;
$item->address_family = $family;
$item->source_reservation_id = (int) $reservation->id;
$item->source_public_ip_id = (int) $sourceIp->id;
$item->target_public_ip_id = (int) $targetIp->id;
$item->source_network_attachment_id =
(int) $sourceAttachment->id;
$item->target_network_attachment_id =
(int) $targetAttachment->id;
$item->child_job_id = null;
$item->state = 'preparing';
$item->last_error_code = '';
$item->created_at = $item->updated_at = $now;
$item->save();
$childRequestKey = substr(
'pool-replacement-' . $batchKey . '-'
. $instanceId . '-' . $family,
0,
128
);
$command = CloudPublicNetworkTransitionCommand::
poolReplacement(
$instanceId,
$actorUserId,
$childRequestKey,
(int) $parent->id,
(int) $item->id,
[$family => [
'pool_key' => (string) $targetPool->pool_key,
'address_cidr' => (string) $targetIp->address
. '/' . (int) $targetIp->prefix_length,
]]
);
CloudPublicNetworkTransitionWorkflow::
beginPoolReplacementBatch(
$command,
new CloudPublicNetworkTransitionBatchPlan(
$actorUser,
$parent,
$batch,
$item,
$instance,
$host,
$agent,
$ledger['resource_pool'],
$sourceAttachment,
$reservation,
$pools,
$ips,
$ledger['all_claims'],
$ledger['active_claims'],
$ledger['source_ips'],
$targetIp
)
);
}
return [
'job' => $parent,
'batch' => self::display($batch),
'unchanged' => false,
];
}, 3);
}
/**
* Project one pool-replacement child from its durable transition ledger.
*
* The caller already owns actor -> parent -> child -> instance -> host ->
* transition and the transition resource ledger. Mutable job catalog
* fields are deliberately not accepted here: only the frozen transition
* shape may advance an item or its aggregate parent.
*/
public static function projectTransitionEvidenceLocked(
?CloudJob $parent,
CloudJob $job,
CloudPublicNetworkTransition $transition
): void
{
if (DB::connection()->transactionLevel() < 1) {
throw new \LogicException(
'Pool-replacement projection requires an outer transaction'
);
}
if ((string) $transition->kind !== 'pool_replacement') {
if (($parent instanceof CloudJob
&& (string) $parent->kind === self::PARENT_KIND)
|| $transition->pool_replacement_batch_item_id !== null) {
throw new CloudError(
'公网地址池迁移网络变更种类不一致',
409
);
}
return;
}
if (!$parent instanceof CloudJob
|| (string) $parent->kind !== self::PARENT_KIND
|| (int) ($job->parent_job_id ?? 0) !== (int) $parent->id
|| (int) ($job->public_network_transition_id ?? 0)
!== (int) $transition->id) {
throw new CloudError('公网地址池迁移父子任务关联不一致', 409);
}
$itemHint = CloudPublicIpPoolReplacementBatchItem::where(
'id', (int) ($transition->pool_replacement_batch_item_id ?? 0)
)->first(['id', 'batch_id']);
if ($itemHint === null) {
throw new CloudError('公网地址池迁移子任务缺少批次明细', 409);
}
$batchHint = CloudPublicIpPoolReplacementBatch::find(
(int) $itemHint->batch_id
);
if ($batchHint === null) {
throw new CloudError('公网地址池迁移批次账本不一致', 409);
}
$source = CloudPublicIpPool::where(
'id', (int) $batchHint->source_public_ip_pool_id
)->lockForUpdate()->first();
if ($source === null
|| (int) $source->host_id !== (int) $batchHint->host_id) {
throw new CloudError('公网地址池迁移源池账本缺失', 409);
}
$batch = CloudPublicIpPoolReplacementBatch::where(
'id', (int) $batchHint->id
)->lockForUpdate()->first();
if ($batch === null) {
throw new CloudError('公网地址池迁移批次账本不一致', 409);
}
$items = CloudPublicIpPoolReplacementBatchItem::where(
'batch_id', (int) $batch->id
)->orderBy('id')->lockForUpdate()->get();
$item = $items->first(static fn ($candidate): bool =>
(int) $candidate->id === (int) $itemHint->id
&& (int) ($candidate->child_job_id ?? 0) === (int) $job->id
);
if ($item === null
|| (int) $batch->parent_job_id !== (int) $parent->id
|| (int) $batch->host_id !== (int) $job->host_id
|| (int) $batch->source_public_ip_pool_id !== (int) $source->id
|| (int) $item->batch_id !== (int) $batch->id
|| (int) $item->instance_id !== (int) $job->instance_id) {
throw new CloudError('公网地址池迁移批次账本不一致', 409);
}
self::assertItemTransitionTopology(
$item,
$batch,
$parent,
$job,
$transition
);
[$nextState, $errorCode] = self::transitionProjection($transition);
if (in_array((string) $item->state,
['succeeded', 'failed'], true)) {
if (!in_array($nextState, ['succeeded', 'failed'], true)
|| (string) $item->state !== $nextState) {
throw new CloudError(
'公网地址池迁移明细终态与持久证据冲突',
409
);
}
return;
}
if (in_array((string) $batch->state,
['succeeded', 'failed'], true)) {
if (!in_array($nextState, ['succeeded', 'failed'], true)
|| (string) $item->state !== $nextState) {
throw new CloudError(
'公网地址池迁移终态与子任务证据冲突',
409
);
}
return;
}
if ((string) $item->state !== $nextState
|| !hash_equals((string) $item->last_error_code, $errorCode)) {
$item->state = $nextState;
$item->last_error_code = $errorCode;
$item->updated_at = time();
$item->save();
}
self::convergeLocked($batch, $parent, $source, $items);
}
/** @return array<string,mixed> */
public static function display(CloudPublicIpPoolReplacementBatch $batch): array
{
$items = CloudPublicIpPoolReplacementBatchItem::where(
'batch_id', (int) $batch->id
)->orderBy('id')->get();
$jobs = CloudJob::whereIn(
'id',
$items->pluck('child_job_id')->map(
static fn ($id): int => (int) $id
)->all()
)->get()->keyBy('id');
$projectedItems = $items->map(static function ($item) use (
$jobs
): array {
$state = (string) $item->state;
$child = $jobs->get((int) $item->child_job_id);
if ($state === 'queued' && $child !== null
&& (string) $child->phase !== 'terminal'
&& ((string) $child->status === 'running'
|| in_array((string) $child->phase,
['dispatching', 'awaiting_receipt'], true))) {
$state = 'running';
}
return [
'instance_id' => (string) $item->instance_id,
'child_job_id' => (string) $item->child_job_id,
'state' => $state,
'last_error_code' => (string) $item->last_error_code,
];
})->values();
$poolIds = [
(int) $batch->source_public_ip_pool_id,
(int) $batch->target_public_ip_pool_id,
];
$pools = CloudPublicIpPool::whereIn('id', $poolIds)
->get(['id', 'pool_key'])->keyBy('id');
$sourcePool = $pools->get((int) $batch->source_public_ip_pool_id);
$targetPool = $pools->get((int) $batch->target_public_ip_pool_id);
return [
'batch_key' => (string) $batch->batch_key,
'host_id' => (string) $batch->host_id,
'source_public_ip_pool_id' =>
(string) $batch->source_public_ip_pool_id,
'source_initial_state' => (string) $batch->source_initial_state,
'source_pool_key' => $sourcePool === null
? null : (string) $sourcePool->pool_key,
'target_public_ip_pool_id' =>
(string) $batch->target_public_ip_pool_id,
'target_pool_key' => $targetPool === null
? null : (string) $targetPool->pool_key,
'parent_job_id' => (string) $batch->parent_job_id,
'state' => (string) $batch->state,
'last_error_code' => (string) $batch->last_error_code,
'terminal_at' => $batch->terminal_at === null
? null : (int) $batch->terminal_at,
'counts' => [
'total' => $items->count(),
'queued' => $projectedItems->where('state', 'queued')->count(),
'running' => $projectedItems->where('state', 'running')->count(),
'succeeded' =>
$projectedItems->where('state', 'succeeded')->count(),
'failed' => $projectedItems->where('state', 'failed')->count(),
'unknown' => $projectedItems->where('state', 'unknown')->count(),
],
'items' => $projectedItems->all(),
];
}
/** @return array{0:string,1:string} */
private static function transitionProjection(
CloudPublicNetworkTransition $transition
): array {
$state = (string) $transition->state;
$resolution = (string) $transition->effect_resolution;
$active = $transition->active_transition;
$resolvedAt = $transition->effect_resolved_at;
$terminalAt = $transition->terminal_at;
if (in_array($state,
['reserved', 'queued', 'awaiting_receipt'], true)
&& $resolution === 'not_applicable'
&& (int) $active === 1
&& $resolvedAt === null
&& $terminalAt === null) {
return ['queued', ''];
}
if ($state === 'effect_unknown'
&& $resolution === 'unknown'
&& (int) $active === 1
&& $resolvedAt === null
&& $terminalAt === null) {
$code = trim((string) $transition->last_error_code);
return [
'unknown',
substr($code !== '' ? $code
: 'network_change_effect_unknown', 0, 64),
];
}
if ($state === 'finalization_pending'
&& in_array($resolution, ['applied', 'not_applied'], true)
&& (int) $active === 1
&& $resolvedAt !== null
&& $terminalAt === null) {
return ['queued', ''];
}
if ($state === 'succeeded'
&& $resolution === 'applied'
&& $active === null
&& $resolvedAt !== null
&& $terminalAt !== null) {
return ['succeeded', ''];
}
if ($state === 'failed'
&& $resolution === 'not_applied'
&& $active === null
&& $resolvedAt !== null
&& $terminalAt !== null) {
$code = trim((string) $transition->last_error_code);
return [
'failed',
substr($code !== '' ? $code
: 'network_change_not_applied', 0, 64),
];
}
throw new CloudError('公网地址池迁移网络变更状态形状损坏', 409);
}
private static function convergeLocked(
CloudPublicIpPoolReplacementBatch $batch,
CloudJob $parent,
CloudPublicIpPool $source,
\Illuminate\Support\Collection $items
): void {
if ($items->contains(static fn ($item): bool =>
(string) $item->state === 'unknown')) {
$batch->state = 'blocked';
$batch->last_error_code = 'network_change_effect_unknown';
$batch->updated_at = time();
$batch->save();
return;
}
if ($items->contains(static fn ($item): bool =>
(string) $item->state === 'queued')) {
$batch->state = 'running';
$batch->last_error_code = '';
$batch->updated_at = time();
$batch->save();
return;
}
$succeeded = $items->where('state', 'succeeded')->count();
$failed = $items->where('state', 'failed')->count();
if ((int) $source->id !== (int) $batch->source_public_ip_pool_id
|| (int) $source->host_id !== (int) $batch->host_id) {
throw new CloudError('公网地址池迁移源池账本缺失', 409);
}
$occupied = CloudPublicIp::where(
'public_ip_pool_id', (int) $source->id
)->where(function ($query): void {
$query->whereIn('state', self::OCCUPIED_IP_STATES)
->orWhereNotNull('reservation_id')
->orWhereNotNull('reservation_ip_claim_id')
->orWhereNotNull('instance_id')
->orWhereNotNull('operation_id');
})->count();
$success = $failed === 0 && $occupied === 0;
$sourceInitialState = (string) $batch->source_initial_state;
if (!in_array($sourceInitialState, ['active', 'draining'], true)) {
throw new CloudError(
'公网地址池迁移批次的源池初始状态损坏',
409
);
}
if ($success) {
self::setPoolStateLocked($source, 'disabled');
$code = '';
$effect = false;
$safe = false;
} elseif ($succeeded === 0) {
self::setPoolStateLocked($source, $sourceInitialState);
$code = 'public_pool_replacement_failed';
$effect = false;
$safe = true;
} else {
self::setPoolStateLocked($source, 'draining');
$code = $failed === 0
? 'source_public_pool_not_empty'
: 'public_pool_replacement_partial';
$effect = true;
$safe = false;
}
$now = time();
$batch->state = $success ? 'succeeded' : 'failed';
$batch->active_claim = null;
$batch->last_error_code = $code;
$batch->terminal_at = $now;
$batch->updated_at = $now;
$batch->save();
CloudJobService::completeAggregateLocked(
$parent,
$success ? 'succeeded' : 'failed',
$effect,
$safe,
$code,
[
'batch_key' => (string) $batch->batch_key,
'total' => $items->count(),
'succeeded' => $succeeded,
'failed' => $failed,
'source_occupied' => $occupied,
]
);
if (!$success && $effect) {
$parent->effect_resolution = 'applied';
$parent->effect_resolved_at = $now;
$parent->effect_resolution_reason =
'Known partial public-pool replacement result';
$parent->save();
}
}
private static function existingResult(CloudJob $job,
string $fingerprint, string $batchKey): array
{
if ((string) $job->kind !== self::PARENT_KIND
|| !hash_equals((string) $job->request_fingerprint, $fingerprint)) {
throw new CloudError(
'同一请求标识不能用于不同的地址池迁移批次',
409
);
}
$batch = CloudPublicIpPoolReplacementBatch::where(
'parent_job_id', (int) $job->id
)->where('batch_key', $batchKey)->first();
if ($batch === null) {
throw new CloudError('公网地址池迁移幂等账本不完整', 409);
}
$items = CloudPublicIpPoolReplacementBatchItem::where(
'batch_id', (int) $batch->id
)->orderBy('id')->get();
$childIds = $items->pluck('child_job_id')->map(
static fn ($id): int => (int) $id
)->filter()->unique()->sort()->values()->all();
$itemIds = $items->pluck('id')->map(
static fn ($id): int => (int) $id
)->all();
$ipIds = $items->flatMap(static fn ($item): array => [
(int) $item->source_public_ip_id,
(int) $item->target_public_ip_id,
])->unique()->sort()->values()->all();
$children = CloudJob::whereIn('id', $childIds)
->orderBy('id')->get()->keyBy('id');
$transitions = CloudPublicNetworkTransition::whereIn(
'pool_replacement_batch_item_id', $itemIds
)->orderBy('id')->get()->keyBy('pool_replacement_batch_item_id');
$ips = CloudPublicIp::whereIn('id', $ipIds)
->orderBy('id')->get()->keyBy('id');
if ($items->isEmpty() || count($childIds) !== $items->count()
|| $children->count() !== $items->count()
|| $transitions->count() !== $items->count()
|| $ips->count() !== count($ipIds)) {
throw new CloudError('公网地址池迁移幂等拓扑不完整', 409);
}
foreach ($items as $item) {
$child = $children->get((int) $item->child_job_id);
$transition = $transitions->get((int) $item->id);
$sourceIp = $ips->get((int) $item->source_public_ip_id);
$targetIp = $ips->get((int) $item->target_public_ip_id);
if (!$child instanceof CloudJob
|| !$transition instanceof CloudPublicNetworkTransition
|| !$sourceIp instanceof CloudPublicIp
|| !$targetIp instanceof CloudPublicIp
|| !in_array((int) $item->address_family, [4, 6], true)
|| (string) $item->state === 'preparing'
|| (int) $item->source_network_attachment_id
!== (int) $item->target_network_attachment_id
|| (int) $sourceIp->address_family
!== (int) $item->address_family
|| (int) $targetIp->address_family
!== (int) $item->address_family
|| (int) $sourceIp->public_ip_pool_id
!== (int) $batch->source_public_ip_pool_id
|| (int) $targetIp->public_ip_pool_id
!== (int) $batch->target_public_ip_pool_id
|| (int) $transition->pool_replacement_batch_item_id
!== (int) $item->id
|| (string) $transition->kind !== 'pool_replacement'
|| (int) $transition->instance_id !== (int) $item->instance_id
|| (int) $transition->host_id !== (int) $batch->host_id
|| (int) $transition->requested_by_user_id
!== (int) $job->user_id
|| (int) $child->id !== (int) $item->child_job_id
|| (int) ($child->parent_job_id ?? 0) !== (int) $job->id
|| (int) ($child->public_network_transition_id ?? 0)
!== (int) $transition->id
|| (int) $child->instance_id !== (int) $item->instance_id
|| (int) $child->user_id !== (int) $job->user_id
|| (int) $child->host_id !== (int) $batch->host_id
|| (string) $child->kind !== 'network_change') {
throw new CloudError('公网地址池迁移幂等拓扑不一致', 409);
}
self::assertItemTransitionTopology(
$item,
$batch,
$job,
$child,
$transition
);
}
return [
'job' => $job,
'batch' => self::display($batch),
'unchanged' => true,
];
}
private static function assertItemTransitionTopology(
CloudPublicIpPoolReplacementBatchItem $item,
CloudPublicIpPoolReplacementBatch $batch,
CloudJob $parent,
CloudJob $child,
CloudPublicNetworkTransition $transition
): CloudPublicNetworkTransition {
if ((string) $parent->kind !== self::PARENT_KIND
|| (string) $parent->execution_mode !== 'local'
|| $parent->parent_job_id !== null
|| $parent->host_id !== null
|| $parent->public_network_transition_id !== null
|| (int) $batch->parent_job_id !== (int) $parent->id
|| (int) $batch->requested_by_user_id !== (int) $parent->user_id
|| (int) $item->batch_id !== (int) $batch->id
|| (string) $transition->kind !== 'pool_replacement'
|| (int) $transition->pool_replacement_batch_item_id
!== (int) $item->id
|| (int) $transition->instance_id !== (int) $item->instance_id
|| (int) $transition->host_id !== (int) $batch->host_id
|| (int) $transition->reservation_id
!== (int) $item->source_reservation_id
|| (int) $transition->requested_by_user_id !== (int) $parent->user_id
|| (int) $transition->source_network_attachment_id
!== (int) $item->source_network_attachment_id
|| (int) $transition->target_network_attachment_id
!== (int) $item->target_network_attachment_id
|| (int) $item->source_network_attachment_id
!== (int) $item->target_network_attachment_id
|| (int) $child->id !== (int) $item->child_job_id
|| (int) ($child->parent_job_id ?? 0) !== (int) $parent->id
|| (int) ($child->public_network_transition_id ?? 0)
!== (int) $transition->id
|| (int) $child->instance_id !== (int) $item->instance_id
|| (int) $child->host_id !== (int) $batch->host_id
|| (int) $child->user_id !== (int) $parent->user_id
|| (string) $child->kind !== 'network_change'
|| (string) $child->execution_mode !== 'agent'
|| !hash_equals(
(string) $transition->operation_id,
(string) $child->operation_id
)) {
throw new CloudError('公网地址池迁移子任务拓扑不一致', 409);
}
$legs = DB::table('cloud_public_network_transition_ips')
->where('transition_id', (int) $transition->id)
->orderBy('address_family')->orderBy('id')->get()->all();
if (count($legs) !== 2) {
throw new CloudError('公网地址池迁移双栈明细不完整', 409);
}
$changed = null;
$unchanged = null;
foreach ($legs as $leg) {
if ((bool) $leg->changed) {
if ($changed !== null || $leg->target_claim_id === null) {
throw new CloudError('公网地址池迁移变更明细损坏', 409);
}
$changed = $leg;
} else {
if ($unchanged !== null || $leg->target_claim_id !== null) {
throw new CloudError('公网地址池迁移保留明细损坏', 409);
}
$unchanged = $leg;
}
}
if ($changed === null || $unchanged === null
|| (int) $changed->address_family !== (int) $item->address_family
|| !in_array((int) $unchanged->address_family, [4, 6], true)
|| (int) $unchanged->address_family === (int) $item->address_family) {
throw new CloudError('公网地址池迁移地址族明细不一致', 409);
}
$claimIds = [
(int) $changed->source_claim_id,
(int) $changed->target_claim_id,
(int) $unchanged->source_claim_id,
];
$claimIds = array_values(array_unique($claimIds));
sort($claimIds, SORT_NUMERIC);
$claims = DB::table('cloud_resource_reservation_ips')
->whereIn('id', $claimIds)->orderBy('id')->get()->keyBy('id');
$source = $claims->get((int) $changed->source_claim_id);
$target = $claims->get((int) $changed->target_claim_id);
$companion = $claims->get((int) $unchanged->source_claim_id);
// A terminal transition no longer owns the instance mutation fence
// even while siblings keep the aggregate batch running. Historical
// replay therefore validates only its frozen companion identity;
// every active transition still requires the live companion claim
// that was frozen for the Agent operation.
$requireActiveCompanion = (int) (
$transition->active_transition ?? 0
) === 1;
if ($claims->count() !== 3
|| !is_object($source) || !is_object($target)
|| !is_object($companion)
|| (int) $source->public_ip_id !== (int) $item->source_public_ip_id
|| (int) $target->public_ip_id !== (int) $item->target_public_ip_id
|| (int) $source->reservation_id
!== (int) $item->source_reservation_id
|| (int) $target->reservation_id
!== (int) $item->source_reservation_id
|| (int) $companion->reservation_id
!== (int) $item->source_reservation_id
|| (int) $source->address_family !== (int) $item->address_family
|| (int) $target->address_family !== (int) $item->address_family
|| (int) $companion->address_family
!== (int) $unchanged->address_family
|| (int) $source->public_ip_pool_id
!== (int) $batch->source_public_ip_pool_id
|| (int) $target->public_ip_pool_id
!== (int) $batch->target_public_ip_pool_id
|| (int) $source->network_attachment_id
!== (int) $item->source_network_attachment_id
|| (int) $target->network_attachment_id
!== (int) $item->target_network_attachment_id
|| (int) $companion->network_attachment_id
!== (int) $item->source_network_attachment_id
|| ($requireActiveCompanion
&& ((int) ($companion->active_claim ?? 0) !== 1
|| (string) ($companion->state ?? '') !== 'committed'))) {
throw new CloudError('公网地址池迁移声明明细不一致', 409);
}
return $transition;
}
private static function newParentJob(int $actorUserId,
string $requestKey, string $fingerprint, int $hostId,
CloudPublicIpPool $source, CloudPublicIpPool $target,
array $instanceIds): CloudJob
{
$now = time();
$job = new CloudJob();
$job->operation_id = bin2hex(random_bytes(16));
$job->request_idempotency_key = $requestKey;
$job->request_fingerprint = $fingerprint;
$job->user_id = $actorUserId;
$job->host_id = null;
$job->kind = self::PARENT_KIND;
$job->execution_mode = 'local';
$job->sealed_payload = CloudSecrets::encrypt([
'local_public_ip_pool_replacement_batch' => true,
'host_id' => $hostId,
'source_public_ip_pool_id' => (int) $source->id,
'target_public_ip_pool_id' => (int) $target->id,
'instance_ids' => $instanceIds,
], 'job-payload');
$job->dispatch_deadline_at = $now + 315360000;
$job->available_at = 0;
$job->created_at = $job->updated_at = $now;
$job->save();
return $job;
}
private static function setPoolStateLocked(CloudPublicIpPool $pool,
string $state): void
{
if (!in_array($state, ['active', 'draining', 'disabled'], true)) {
throw new \LogicException('Invalid public pool state');
}
if ((string) $pool->state === $state) {
return;
}
$revision = max(
(int) $pool->desired_revision,
(int) $pool->observed_revision
) + 1;
$pool->state = $state;
$pool->desired_revision = $revision;
$pool->observed_revision = $revision;
$pool->sync_state = 'applied';
$pool->last_error_code = '';
$pool->updated_at = time();
$pool->save();
}
private static function assertTargetPoolConfiguration(CloudHost $host,
CloudPublicIpPool $pool): void
{
try {
CloudPublicIpPoolContract::fromRow($pool);
} catch (\Throwable) {
throw new CloudError('目标公网地址池配置损坏', 409);
}
$management = CloudPanelUsageService::managementAddress($host);
if ($management !== null && !is_string($management)) {
throw new CloudError('宿主机管理地址配置损坏', 409);
}
}
private static function targetIpIsSafe(CloudPublicIp $ip,
CloudPublicIpPool $pool, CloudHost $host): bool
{
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
|| (string) $ip->state !== 'available'
|| $ip->reservation_id !== null
|| $ip->reservation_ip_claim_id !== null
|| $ip->instance_id !== null
|| $ip->operation_id !== null
|| (int) $ip->prefix_length
!== (int) $pool->guest_prefix_length) {
return false;
}
try {
$contract = CloudPublicIpPoolContract::fromRow($pool);
$address = CloudIpAddress::parse((string) $ip->address);
if (!is_string($ip->address_binary)
|| !hash_equals($address->binary(), $ip->address_binary)
|| !$contract->addressAllowed($address)) {
return false;
}
$management = CloudPanelUsageService::managementAddress($host);
return !is_string($management) || $management === ''
|| !$address->equals(CloudIpAddress::parse($management));
} catch (\Throwable) {
return false;
}
}
private static function availableCount(CloudPublicIpPool $pool,
CloudHost $host): int
{
try {
$contract = CloudPublicIpPoolContract::fromRow($pool);
} catch (\Throwable) {
return 0;
}
$rows = CloudPublicIp::where(
'public_ip_pool_id', (int) $pool->id
)->orderBy('id')->get();
if ($contract->family() === 4) {
return $rows->filter(static fn ($ip): bool =>
self::targetIpIsSafe($ip, $pool, $host)
)->count();
}
$occupied = $rows->filter(static fn ($ip): bool =>
self::ipOccupied($ip)
)->count();
return max(0, $contract->maxAllocations() - $occupied);
}
private static function ipOccupied(CloudPublicIp $ip): bool
{
return in_array((string) $ip->state,
self::OCCUPIED_IP_STATES, true)
|| $ip->reservation_id !== null
|| $ip->reservation_ip_claim_id !== null
|| $ip->instance_id !== null
|| $ip->operation_id !== null;
}
/**
* @return array{0:list<CloudPublicIp>,1:\Illuminate\Support\Collection}
*/
private static function freezeExactTargetsLocked(
CloudPublicIpPool $pool,
CloudHost $host,
$lockedIps,
int $needed
): array {
if ($needed < 1) {
throw new CloudError('目标公网地址池迁移数量无效', 409);
}
try {
$contract = CloudPublicIpPoolContract::fromRow($pool);
} catch (\Throwable) {
throw new CloudError('目标公网地址池配置损坏', 409);
}
$poolRows = $lockedIps->filter(static fn ($ip): bool =>
(int) $ip->public_ip_pool_id === (int) $pool->id
)->sortBy('id')->values();
$selected = $poolRows->filter(static fn ($ip): bool =>
self::targetIpIsSafe($ip, $pool, $host)
)->take($needed)->values()->all();
if ($contract->family() === 4) {
if (count($selected) !== $needed) {
throw new CloudError('目标公网 IPv4 地址池可用地址不足', 409);
}
return [$selected, $lockedIps];
}
$occupied = $poolRows->filter(static fn ($ip): bool =>
self::ipOccupied($ip)
)->count();
if ($contract->maxAllocations() - $occupied < $needed) {
throw new CloudError('目标公网 IPv6 稀疏容量不足', 409);
}
if (count($selected) === $needed) {
return [$selected, $lockedIps];
}
$start = $contract->allocationStart();
$end = $contract->allocationEnd();
$candidate = $contract->allocationCursor() ?? $start;
if (!$start instanceof CloudIpAddress
|| !$end instanceof CloudIpAddress
|| !$candidate instanceof CloudIpAddress) {
throw new CloudError('目标公网 IPv6 稀疏分配合同损坏', 409);
}
$seen = [];
foreach ($lockedIps as $row) {
if (is_string($row->address_binary)) {
$seen[bin2hex($row->address_binary)] = true;
}
}
$management = null;
try {
$rawManagement = CloudPanelUsageService::managementAddress($host);
$management = is_string($rawManagement) && $rawManagement !== ''
? CloudIpAddress::parse($rawManagement) : null;
} catch (\Throwable) {
throw new CloudError('宿主机管理地址配置损坏', 409);
}
$attempts = max(1, $poolRows->count()
+ $contract->maxAllocations()
+ count($contract->reservedAddresses())
+ count($contract->dnsServers()) + 2);
$now = time();
for ($attempt = 0; $attempt < $attempts
&& count($selected) < $needed; $attempt++) {
$current = $candidate;
$candidate = $candidate->compare($end) === 0
? $start : $candidate->next();
$binaryKey = bin2hex($current->binary());
if (isset($seen[$binaryKey])
|| !$contract->addressAllowed($current)
|| ($management instanceof CloudIpAddress
&& $current->equals($management))) {
continue;
}
$ip = new CloudPublicIp();
$ip->host_id = (int) $pool->host_id;
$ip->public_ip_pool_id = (int) $pool->id;
$ip->address_family = 6;
$ip->address = $current->text();
$ip->address_binary = $current->binary();
$ip->prefix_length = $contract->guestPrefixLength();
$ip->state = 'available';
$ip->reservation_id = null;
$ip->reservation_ip_claim_id = null;
$ip->instance_id = null;
$ip->operation_id = null;
$ip->created_at = $ip->updated_at = $now;
try {
$ip->save();
} catch (\Illuminate\Database\QueryException) {
throw new CloudError(
'目标公网 IPv6 地址已被其他地址池占用',
409
);
}
$seen[$binaryKey] = true;
$lockedIps->put((int) $ip->id, $ip);
$selected[] = $ip;
}
if (count($selected) !== $needed) {
throw new CloudError('目标公网 IPv6 稀疏范围可用地址不足', 409);
}
$pool->allocation_cursor = $candidate->text();
$pool->updated_at = $now;
$pool->save();
return [$selected, $lockedIps];
}
private static function assertAdminRead(array $actor): void
{
if (!($actor['is_admin'] ?? false)) {
throw new CloudError(
'只有管理员可以查看公网地址池迁移批次',
403
);
}
}
}