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/CloudPublicNetworkAllocatio...

1433 lines
59 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use Illuminate\Database\Capsule\Manager as DB;
use Illuminate\Database\Connection;
/**
* Owns one public-network resource bundle as a single transaction.
*
* Callers never allocate or release one address family independently. The
* service is also the only writer that may create sparse IPv6 ledger rows.
*/
final class CloudPublicNetworkAllocationService
{
private const FAMILIES = [4, 6];
/** Read-only projection of the exact active dual-stack authority. */
public static function currentClaimSet(
int $reservationId,
string $expectedState = 'committed',
?int $expectedInstanceId = null
): CloudActivePublicNetworkClaimSet {
if ($reservationId < 1
|| !in_array($expectedState,
['held', 'committed', 'uncertain'], true)
|| ($expectedInstanceId !== null && $expectedInstanceId < 1)) {
throw new CloudError('公网网络资源预留无效', 409);
}
// This interface is projection-only. A repeatable-read transaction
// prevents its several exact-ledger reads from accepting a torn pair;
// mutation callers use the private locking path instead.
return self::connection()->transaction(static function () use (
$reservationId,
$expectedState,
$expectedInstanceId
): CloudActivePublicNetworkClaimSet {
$reservation = self::unlockedReservation($reservationId);
$hostId = (int) ($reservation->host_id ?? 0);
$resourcePoolId = (int) ($reservation->resource_pool_id ?? 0);
$reservationUserId = (int) ($reservation->user_id ?? 0);
$resourcePoolLineId = $resourcePoolId > 0
? DB::table('cloud_resource_pools')
->where('id', $resourcePoolId)->value('line_id')
: null;
$reservationInstanceId = $reservation?->instance_id === null
? null : (int) $reservation->instance_id;
$instance = $expectedState === 'committed'
&& $reservationInstanceId !== null
&& $reservationInstanceId > 0
? DB::table('cloud_instances')
->where('id', $reservationInstanceId)->first()
: null;
if ($reservation === null || $hostId < 1
|| $resourcePoolId < 1
|| $reservationUserId < 1
|| $resourcePoolLineId === null
|| (int) $resourcePoolLineId < 1
|| (string) $reservation->state !== $expectedState
|| ($expectedState === 'committed'
&& ($reservationInstanceId === null
|| $reservationInstanceId < 1
|| $instance === null
|| (int) ($instance->reservation_id ?? 0)
!== $reservationId
|| (int) ($instance->host_id ?? 0) !== $hostId
|| (int) ($instance->resource_pool_id ?? 0)
!== $resourcePoolId
|| (int) ($instance->user_id ?? 0)
!== $reservationUserId))
|| ($expectedState !== 'committed'
&& $reservationInstanceId !== null)
|| ($expectedInstanceId !== null
&& $reservationInstanceId !== $expectedInstanceId)
|| DB::table('cloud_hosts')->where('id', $hostId)
->value('id') === null) {
throw new CloudError('公网网络资源预留权威链不一致', 409);
}
$claims = self::unlockedClaims($reservationId);
$set = self::claimSet(
$claims,
$expectedState === 'held' ? 'reserved' : $expectedState,
$expectedState === 'committed'
? $reservationInstanceId : null,
$hostId,
(int) $resourcePoolLineId
);
if ($set->reservationId() !== $reservationId) {
throw new CloudError('公网网络活动声明归属不一致', 409);
}
if ($expectedState === 'committed') {
self::assertInstancePublicNetworkSnapshot($instance, $set);
}
return $set;
});
}
private static function assertInstancePublicNetworkSnapshot(
?object $instance,
CloudActivePublicNetworkClaimSet $claimSet
): void {
try {
$spec = json_decode(
(string) ($instance->spec_json ?? ''),
true,
64,
JSON_THROW_ON_ERROR
);
if (!is_array($spec) || array_is_list($spec)) {
throw new \InvalidArgumentException(
'Instance specification is invalid.'
);
}
$frozen = CloudPublicNetworkSnapshot::fromArray(
$spec['public_network'] ?? null
);
} catch (\Throwable) {
throw new CloudError('实例缺少有效的冻结公网网络快照', 409);
}
if (!hash_equals(
$frozen->fingerprint(),
$claimSet->publicNetwork()->fingerprint()
)) {
throw new CloudError('实例冻结公网网络快照与活动声明不一致', 409);
}
}
public static function reserveBundle(int $hostId, int $lineId,
int $reservationId, string $operationId): CloudPublicNetworkSnapshot
{
self::assertIdentity($reservationId, $operationId);
if ($hostId < 1 || $lineId < 1) {
throw new CloudError('公网网络预留范围无效', 409);
}
return self::connection()->transaction(static function () use (
$hostId,
$lineId,
$reservationId,
$operationId
): CloudPublicNetworkSnapshot {
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
$catalog = null;
$selection = null;
if ($claimHints === []) {
$catalog = self::lockPoolCatalog($hostId, $lineId);
} else {
$selection = self::lockClaimNetworkContext(
$claimHints,
$hostId,
$lineId
);
}
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
$existing = self::lockedClaims($reservationId);
if ($existing !== []) {
$claimState = self::claimStateForReservation($reservation);
self::assertClaimSet($existing, $operationId, [$claimState]);
if ($selection === null) {
throw new CloudError('公网网络资源预留状态不明确', 409);
}
self::assertClaimsUseSelection($existing, $selection);
$addresses = self::lockClaimAddresses($existing);
self::assertClaimAddresses($existing, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'committed' => ['assigned'],
'uncertain' => ['uncertain'],
], $claimState === 'committed'
? (int) ($reservation->instance_id ?? 0) : null);
return self::snapshot($existing);
}
if (self::lockedHistoricalClaims($reservationId) !== []) {
throw new CloudError(
'初始公网网络预留不能复用历史地址声明',
409
);
}
if ($claimHints !== [] || (string) $reservation->state !== 'held') {
throw new CloudError('公网网络资源预留状态不明确', 409);
}
if ($catalog === null) {
throw new CloudError('公网网络候选目录不完整', 409);
}
$selection = self::selectAvailablePoolPair($catalog);
$now = time();
$claims = [];
foreach (self::FAMILIES as $family) {
$pool = $selection['pools'][$family];
$ip = self::reserveAddress($pool, $now,
$selection['address_candidates'][$family] ?? null);
$claimId = DB::table('cloud_resource_reservation_ips')
->insertGetId([
'reservation_id' => $reservationId,
'address_family' => $family,
'claim_generation' => 1,
'active_claim' => 1,
'network_attachment_id' =>
(int) $selection['attachment']->id,
'public_ip_pool_id' => (int) $pool->id,
'public_ip_id' => (int) $ip->id,
'operation_id' => $operationId,
'state' => 'reserved',
'created_at' => $now,
'updated_at' => $now,
'released_at' => null,
'release_reason' => '',
]);
self::bindAddressToClaim(
$ip,
$reservationId,
$operationId,
$claimId,
$now
);
$claims[] = DB::table('cloud_resource_reservation_ips')
->where('id', $claimId)->first();
}
return self::snapshot($claims);
});
}
public static function commitBundle(int $reservationId, int $instanceId,
string $operationId): CloudPublicNetworkSnapshot
{
self::assertIdentity($reservationId, $operationId);
if ($instanceId < 1) {
throw new CloudError('实例网络归属无效', 409);
}
return self::connection()->transaction(static function () use (
$reservationId,
$instanceId,
$operationId
): CloudPublicNetworkSnapshot {
$reservationHint = self::unlockedReservation($reservationId);
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
$claims = self::lockedClaims($reservationId);
$claimState = self::claimStateForReservation($reservation);
self::assertClaimSet(
$claims,
$operationId,
[$claimState]
);
if ($claimState === 'committed'
&& (int) ($reservation->instance_id ?? 0) !== $instanceId) {
throw new CloudError('实例网络归属与资源预留不一致', 409);
}
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
'committed' => ['assigned'],
], $instanceId);
if ($claimState === 'committed') {
return self::snapshot($claims);
}
$now = time();
foreach ($claims as $claim) {
$ip = $addresses[(int) $claim->public_ip_id];
$ipUpdated = DB::table('cloud_public_ips')
->where('id', (int) $ip->id)
->where('reservation_ip_claim_id', (int) $claim->id)
->where('operation_id', $operationId)->update([
'state' => 'assigned',
'reservation_id' => $reservationId,
'reservation_ip_claim_id' => (int) $claim->id,
'instance_id' => $instanceId,
'operation_id' => $operationId,
'updated_at' => $now,
]);
$claimUpdated = DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)
->where('active_claim', 1)->update([
'state' => 'committed',
'updated_at' => $now,
]);
if ($ipUpdated !== 1 || $claimUpdated !== 1) {
throw new CloudError('双栈公网地址提交账本未精确更新', 409);
}
}
return self::snapshot(self::lockedClaims($reservationId));
});
}
public static function fenceBundle(int $reservationId,
string $operationId): void
{
self::assertIdentity($reservationId, $operationId);
self::connection()->transaction(static function () use (
$reservationId,
$operationId
): void {
$reservationHint = self::unlockedReservation($reservationId);
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'uncertain']);
$claims = self::lockedClaims($reservationId);
$claimState = self::claimStateForReservation($reservation);
self::assertClaimSet(
$claims,
$operationId,
[$claimState]
);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
if ($claimState === 'uncertain') {
return;
}
$now = time();
foreach ($claims as $claim) {
$ipUpdated = DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('reservation_ip_claim_id', (int) $claim->id)
->where('operation_id', $operationId)->update([
'state' => 'uncertain',
'updated_at' => $now,
]);
$claimUpdated = DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)
->where('active_claim', 1)->update([
'state' => 'uncertain',
'updated_at' => $now,
]);
if ($ipUpdated !== 1 || $claimUpdated !== 1) {
throw new CloudError('双栈公网地址隔离账本未精确更新', 409);
}
}
});
}
public static function releaseBundle(int $reservationId,
string $operationId, string $reason, bool $effectConfirmedAbsent): void
{
self::assertIdentity($reservationId, $operationId);
if (!$effectConfirmedAbsent) {
throw new CloudError('操作效果尚未确认,公网地址继续锁定', 409);
}
self::assertReleaseReason($reason);
self::connection()->transaction(static function () use (
$reservationId,
$operationId,
$reason
): void {
$reservationHint = self::unlockedReservation($reservationId);
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'uncertain']);
$claims = self::lockedClaims($reservationId);
self::assertClaimSet(
$claims,
$operationId,
[self::claimStateForReservation($reservation)]
);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $selection,
$operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
self::releaseLockedClaims($claims, $reason);
});
}
/**
* Releases an assigned bundle only after the owning VM effect is known to
* be absent. Address replacement must use a separate transition ledger;
* it must never overwrite these committed source claims.
*/
public static function releaseCommittedBundle(int $reservationId,
int $instanceId, string $operationId, string $reason,
bool $effectConfirmedAbsent): void
{
self::assertIdentity($reservationId, $operationId);
if ($instanceId < 1 || !$effectConfirmedAbsent) {
throw new CloudError('实例删除效果尚未确认,公网地址继续锁定', 409);
}
self::assertReleaseReason($reason);
self::connection()->transaction(static function () use (
$reservationId,
$instanceId,
$operationId,
$reason
): void {
$reservationHint = self::unlockedReservation($reservationId);
if ($reservationHint === null) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$claimHints = self::unlockedClaims($reservationId);
if ($claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['committed']);
if ((int) ($reservation->instance_id ?? 0) !== $instanceId) {
throw new CloudError('实例网络归属与资源预留不一致', 409);
}
$claims = self::lockedClaims($reservationId);
self::assertActiveClaimSet($claims, ['committed']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $selection,
null, [
'committed' => ['assigned'],
], $instanceId);
self::releaseLockedClaims($claims, $reason);
});
}
private static function unlockedReservation(int $reservationId): ?object
{
return DB::table('cloud_resource_reservations')
->where('id', $reservationId)->first();
}
private static function unlockedClaims(int $reservationId): array
{
return DB::table('cloud_resource_reservation_ips')
->where('reservation_id', $reservationId)
->where('active_claim', 1)
->orderBy('address_family')->orderBy('id')->get()->all();
}
private static function lockHost(int $hostId): void
{
$host = DB::table('cloud_hosts')->where('id', $hostId)
->lockForUpdate()->first();
if ($host === null) {
throw new CloudError('公网网络宿主机不存在', 409);
}
}
private static function lockReservation(int $reservationId): ?object
{
return DB::table('cloud_resource_reservations')
->where('id', $reservationId)->lockForUpdate()->first();
}
private static function assertReservation(?object $reservation, int $hostId,
string $operationId, array $allowedStates): void
{
if ($reservation === null || (int) $reservation->host_id !== $hostId
|| !hash_equals($operationId,
(string) $reservation->operation_id)
|| !in_array((string) $reservation->state,
$allowedStates, true)) {
throw new CloudError('公网网络资源预留不一致', 409);
}
}
private static function claimStateForReservation(object $reservation): string
{
$state = (string) ($reservation->state ?? '');
$instanceId = $reservation->instance_id === null
? null : (int) $reservation->instance_id;
if (($state === 'committed'
&& ($instanceId === null || $instanceId < 1))
|| (in_array($state, ['held', 'uncertain'], true)
&& $instanceId !== null)) {
throw new CloudError(
'公网网络资源预留生命周期不一致',
409
);
}
return match ($state) {
'held' => 'reserved',
'committed' => 'committed',
'uncertain' => 'uncertain',
default => throw new CloudError(
'公网网络资源预留生命周期不一致',
409
),
};
}
/** Locks the exact historical attachment and pools before the reservation. */
private static function lockClaimNetworkContext(array $claimHints,
int $hostId, ?int $lineId = null): array
{
$attachmentIds = array_values(array_unique(array_map(
static fn ($claim): int => (int) $claim->network_attachment_id,
$claimHints
)));
$poolIds = array_values(array_unique(array_map(
static fn ($claim): int => (int) $claim->public_ip_pool_id,
$claimHints
)));
sort($attachmentIds, SORT_NUMERIC);
sort($poolIds, SORT_NUMERIC);
if ($attachmentIds === [] || $poolIds === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$attachments = DB::table('cloud_host_network_attachments')
->whereIn('id', $attachmentIds)->orderBy('id')
->lockForUpdate()->get()->all();
$poolRows = DB::table('cloud_public_ip_pools')
->whereIn('id', $poolIds)->orderBy('id')
->lockForUpdate()->get()->all();
if (count($attachments) !== 1 || count($poolRows) !== 2) {
throw new CloudError('双栈公网地址网络边界损坏', 409);
}
$attachment = $attachments[0];
if ((int) $attachment->host_id !== $hostId
|| ($lineId !== null && (int) $attachment->line_id !== $lineId)) {
throw new CloudError('双栈公网地址不属于预期网络', 409);
}
$pools = [];
$contracts = [];
foreach ($poolRows as $pool) {
$family = (int) $pool->address_family;
if (!in_array($family, self::FAMILIES, true)
|| isset($pools[$family])
|| (int) $pool->host_id !== $hostId
|| (int) $pool->network_attachment_id !== (int) $attachment->id) {
throw new CloudError('双栈公网地址池边界损坏', 409);
}
$contracts[$family] = self::validatePool($pool, $family);
$pools[$family] = $pool;
}
if (!isset($pools[4], $pools[6])) {
throw new CloudError('双栈公网地址池不完整', 409);
}
return [
'attachment' => $attachment,
'pools' => $pools,
'contracts' => $contracts,
];
}
private static function assertClaimsUseSelection(array $claims,
array $selection): void
{
foreach ($claims as $claim) {
$family = (int) $claim->address_family;
if (!isset($selection['pools'][$family])
|| (int) $claim->network_attachment_id
!== (int) $selection['attachment']->id
|| (int) $claim->public_ip_pool_id
!== (int) $selection['pools'][$family]->id) {
throw new CloudError('双栈公网地址账本网络边界不一致', 409);
}
}
}
/** @return array<int, object> */
private static function lockClaimAddresses(array $claims): array
{
$ids = array_values(array_unique(array_map(
static fn ($claim): int => (int) $claim->public_ip_id,
$claims
)));
sort($ids, SORT_NUMERIC);
$rows = DB::table('cloud_public_ips')->whereIn('id', $ids)
->orderBy('id')->lockForUpdate()->get()->all();
$result = [];
foreach ($rows as $row) {
$result[(int) $row->id] = $row;
}
if (count($result) !== count($ids)) {
throw new CloudError('双栈公网地址引用损坏', 409);
}
return $result;
}
private static function assertPoolLedger(object $pool,
CloudPublicIpPoolContract $contract, array $rows,
array $retainedSourceEvidence): void
{
foreach ($rows as $row) {
self::assertConcreteAddress($row, $pool, $contract);
self::assertAddressOwnership(
$row,
$pool,
$retainedSourceEvidence
);
}
}
private static function assertConcreteAddress(object $row, object $pool,
CloudPublicIpPoolContract $contract): CloudIpAddress
{
try {
$address = self::assertConcreteAddressIdentity(
$row,
$pool,
$contract
);
if (((string) $row->state !== 'disabled'
&& !self::rawAddressAllowedByPool(
$address,
$pool,
$contract
))) {
throw new \InvalidArgumentException();
}
if ($address->family() === 6
&& (string) $row->state !== 'disabled') {
$start = CloudIpAddress::parse($pool->allocation_start ?? null);
$end = CloudIpAddress::parse($pool->allocation_end ?? null);
if ($address->compare($start) < 0
|| $address->compare($end) > 0) {
throw new \InvalidArgumentException();
}
}
return $address;
} catch (\Throwable) {
throw new CloudError('公网地址具体身份与地址池不一致', 409);
}
}
/** Validate immutable identity without reapplying mutable allowlists. */
private static function assertConcreteAddressIdentity(object $row,
object $pool, CloudPublicIpPoolContract $contract): CloudIpAddress
{
try {
$address = CloudIpAddress::parse((string) $row->address);
if ((int) $row->host_id !== (int) $pool->host_id
|| (int) $row->public_ip_pool_id !== (int) $pool->id
|| (int) $row->address_family
!== (int) $pool->address_family
|| (int) $row->prefix_length
!== (int) $pool->guest_prefix_length
|| !hash_equals($address->text(), (string) $row->address)
|| !is_string($row->address_binary)
|| !hash_equals($address->binary(), $row->address_binary)
|| !self::rawAddressBelongsToPool(
$address,
$pool,
$contract
)) {
throw new \InvalidArgumentException();
}
return $address;
} catch (\Throwable) {
throw new CloudError('公网地址具体身份与地址池不一致', 409);
}
}
private static function assertAddressOwnership(object $row,
?object $pool = null, array $retainedSourceEvidence = []): void
{
$reservationId = $row->reservation_id === null
? null : (int) $row->reservation_id;
$instanceId = $row->instance_id === null
? null : (int) $row->instance_id;
$claimId = $row->reservation_ip_claim_id === null
? null : (int) $row->reservation_ip_claim_id;
$operationId = $row->operation_id;
$validOperation = is_string($operationId)
&& preg_match('/^[a-f0-9]{32}$/D', $operationId) === 1;
$state = (string) $row->state;
$valid = match ($state) {
'available', 'disabled' => $reservationId === null
&& $claimId === null && $instanceId === null
&& $operationId === null,
'reserved' => $reservationId !== null && $reservationId > 0
&& $claimId !== null && $claimId > 0
&& $instanceId === null && $validOperation,
'assigned' => $reservationId !== null && $reservationId > 0
&& $claimId !== null && $claimId > 0 && $validOperation && (
($instanceId !== null && $instanceId > 0)
|| self::matchesRetainedSourceEvidence(
$row,
$pool,
$retainedSourceEvidence
)
),
'changing', 'uncertain' => $reservationId !== null
&& $reservationId > 0 && $claimId !== null && $claimId > 0
&& ($instanceId === null || $instanceId > 0)
&& $validOperation,
default => false,
};
if (!$valid) {
throw new CloudError('公网地址占用账本形态不一致', 409);
}
}
private static function matchesRetainedSourceEvidence(object $row,
?object $pool, array $evidenceByPublicIpId): bool
{
if ($pool === null || $row->instance_id !== null) {
return false;
}
$evidence = $evidenceByPublicIpId[(int) ($row->id ?? 0)] ?? null;
return is_array($evidence)
&& in_array(
$evidence['migration_state'] ?? null,
['source_retained', 'cleanup_running'],
true
)
&& (int) ($evidence['reservation_id'] ?? 0)
=== (int) ($row->reservation_id ?? 0)
&& (int) ($evidence['host_id'] ?? 0) === (int) $row->host_id
&& (int) ($evidence['host_id'] ?? 0) === (int) $pool->host_id
&& (int) ($evidence['network_attachment_id'] ?? 0)
=== (int) $pool->network_attachment_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $row->public_ip_pool_id
&& (int) ($evidence['public_ip_pool_id'] ?? 0)
=== (int) $pool->id
&& (int) ($evidence['public_ip_id'] ?? 0) === (int) $row->id
&& is_string($evidence['operation_id'] ?? null)
&& hash_equals(
(string) $evidence['operation_id'],
(string) ($row->operation_id ?? '')
);
}
private static function assertClaimAddresses(array $claims,
array $addresses, array $selection, ?string $operationId,
array $allowedPairs, ?int $instanceId = null): void
{
foreach ($claims as $claim) {
$ip = $addresses[(int) $claim->public_ip_id] ?? null;
$claimState = (string) $claim->state;
$claimOperationId = (string) ($claim->operation_id ?? '');
$expectedOperationId = $operationId ?? $claimOperationId;
$allowedIpStates = $allowedPairs[$claimState] ?? [];
$family = (int) $claim->address_family;
$pool = $selection['pools'][$family] ?? null;
$contract = $selection['contracts'][$family] ?? null;
if ($ip === null || $pool === null
|| !$contract instanceof CloudPublicIpPoolContract
|| $allowedIpStates === []
|| !in_array((string) $ip->state, $allowedIpStates, true)
|| (int) $ip->reservation_id !== (int) $claim->reservation_id
|| (int) ($ip->reservation_ip_claim_id ?? 0)
!== (int) $claim->id
|| (int) $ip->address_family !== (int) $claim->address_family
|| (int) $ip->public_ip_pool_id
!== (int) $claim->public_ip_pool_id
|| preg_match('/^[a-f0-9]{32}$/D', $claimOperationId) !== 1
|| !hash_equals($claimOperationId,
(string) ($ip->operation_id ?? ''))
|| !hash_equals($expectedOperationId,
(string) ($ip->operation_id ?? ''))) {
throw new CloudError('公网地址与预留账本不一致', 409);
}
self::assertConcreteAddress($ip, $pool, $contract);
self::assertAddressOwnership($ip);
if ((string) $ip->state === 'assigned') {
$actualInstanceId = (int) ($ip->instance_id ?? 0);
if ($actualInstanceId < 1
|| ($instanceId !== null
&& $actualInstanceId !== $instanceId)) {
throw new CloudError('公网地址实例归属不一致', 409);
}
} elseif ($ip->instance_id !== null) {
throw new CloudError('未提交公网地址存在实例归属', 409);
}
}
}
private static function releaseLockedClaims(array $claims,
string $reason): void
{
$now = time();
foreach ($claims as $claim) {
$ipUpdated = DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('reservation_ip_claim_id', (int) $claim->id)
->where('operation_id', (string) $claim->operation_id)
->update([
'state' => 'available',
'reservation_id' => null,
'reservation_ip_claim_id' => null,
'instance_id' => null,
'operation_id' => null,
'updated_at' => $now,
]);
$claimUpdated = DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)
->where('active_claim', 1)->update([
'state' => 'released',
'active_claim' => null,
'released_at' => $now,
'release_reason' => $reason,
'updated_at' => $now,
]);
if ($ipUpdated !== 1 || $claimUpdated !== 1) {
throw new CloudError('双栈公网地址释放账本未精确更新', 409);
}
}
}
private static function assertReleaseReason(string $reason): void
{
if (preg_match('/^[a-z][a-z0-9_]{2,63}$/D', $reason) !== 1) {
throw new CloudError('公网地址释放原因无效', 409);
}
}
/**
* Lock the exact current Agent proof and every configured pool candidate.
* Concrete address rows are deliberately not locked here: the reservation
* row must come before claims/IPs in the canonical hierarchy.
*/
private static function lockPoolCatalog(int $hostId, int $lineId): array
{
$agent = CloudHostAgent::where('host_id', $hostId)
->lockForUpdate()->first();
if (!$agent instanceof CloudHostAgent || !$agent->isReady()) {
throw new CloudError('宿主机 Agent 双栈网络验证证据无效', 409);
}
$attachments = DB::table('cloud_host_network_attachments')
->where('host_id', $hostId)->where('line_id', $lineId)
->where('state', 'active')->orderBy('id')
->lockForUpdate()->get()->all();
$eligible = [];
foreach ($attachments as $attachment) {
if ((string) $attachment->verification_state !== 'verified'
|| (int) $attachment->last_verified_at < 1
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
continue;
}
$eligible[(int) $attachment->id] = $attachment;
}
if ($eligible === []) {
throw new CloudError('宿主机缺少当前双栈公网网络验证证据', 409);
}
uasort($eligible, static fn (object $left, object $right): int => [
(int) $left->priority,
(int) $left->id,
] <=> [
(int) $right->priority,
(int) $right->id,
]);
$poolRows = DB::table('cloud_public_ip_pools')
->where('host_id', $hostId)
->whereIn('network_attachment_id', array_keys($eligible))
->where('state', 'active')
->whereIn('address_family', self::FAMILIES)
->orderBy('id')->lockForUpdate()->get()->all();
$pools = [];
$contracts = [];
foreach ($poolRows as $pool) {
$attachmentId = (int) $pool->network_attachment_id;
$family = (int) $pool->address_family;
if (!isset($eligible[$attachmentId])
|| (int) $pool->host_id !== $hostId
|| !in_array($family, self::FAMILIES, true)
|| preg_match('/^[a-f0-9]{32}$/D',
(string) $pool->pool_key) !== 1
|| (string) $pool->sync_state !== 'applied'
|| (int) $pool->observed_revision
!== (int) $pool->desired_revision) {
throw new CloudError('公网地址池目录尚未精确收敛', 409);
}
$contracts[(int) $pool->id] = self::validatePool($pool, $family);
$pools[$attachmentId][] = $pool;
}
foreach ($pools as &$attachmentPools) {
usort($attachmentPools,
static fn (object $left, object $right): int => [
(int) $left->priority,
(int) $left->id,
] <=> [
(int) $right->priority,
(int) $right->id,
]);
}
unset($attachmentPools);
$complete = false;
foreach (array_keys($eligible) as $attachmentId) {
$families = [];
foreach ($pools[$attachmentId] ?? [] as $pool) {
$families[(int) $pool->address_family] = true;
}
if (isset($families[4], $families[6])) {
$complete = true;
break;
}
}
if (!$complete) {
throw new CloudError('宿主机双栈公网地址池目录不完整', 409);
}
$poolIds = array_map(
static fn (object $pool): int => (int) $pool->id,
$poolRows
);
$retainedSourceEvidence = CloudInstanceMigrationSettlement::
lockRetainedSourcePublicIpEvidence($hostId, $poolIds);
return [
'attachments' => $eligible,
'pools' => $pools,
'contracts' => $contracts,
'retained_source_evidence' => $retainedSourceEvidence,
];
}
/** Called only after the reservation row is locked. */
private static function selectAvailablePoolPair(array $catalog): array
{
$allPools = [];
foreach ($catalog['pools'] as $attachmentPools) {
foreach ($attachmentPools as $pool) {
$allPools[(int) $pool->id] = $pool;
}
}
ksort($allPools, SORT_NUMERIC);
$rowsByPool = array_fill_keys(array_keys($allPools), []);
$lockedRows = DB::table('cloud_public_ips')
->whereIn('public_ip_pool_id', array_keys($allPools))
->orderBy('id')->lockForUpdate()->get()->all();
foreach ($lockedRows as $row) {
$poolId = (int) $row->public_ip_pool_id;
if (!isset($rowsByPool[$poolId])) {
throw new CloudError('公网地址引用了候选目录之外的地址池', 409);
}
$rowsByPool[$poolId][] = $row;
}
foreach ($allPools as $poolId => $pool) {
$contract = $catalog['contracts'][$poolId] ?? null;
if (!$contract instanceof CloudPublicIpPoolContract) {
throw new CloudError('公网地址池合同缺失', 409);
}
self::assertPoolLedger(
$pool,
$contract,
$rowsByPool[$poolId],
$catalog['retained_source_evidence'] ?? []
);
}
foreach ($catalog['attachments'] as $attachmentId => $attachment) {
$selectedPools = [];
$selectedContracts = [];
$addressCandidates = [];
foreach ($catalog['pools'][$attachmentId] ?? [] as $pool) {
$family = (int) $pool->address_family;
if (isset($selectedPools[$family])) {
continue;
}
$contract = $catalog['contracts'][(int) $pool->id] ?? null;
if (!$contract instanceof CloudPublicIpPoolContract) {
throw new CloudError('公网地址池合同缺失', 409);
}
$candidate = self::lockReservableAddressCandidate(
$pool,
$contract,
$rowsByPool[(int) $pool->id] ?? []
);
if ($candidate !== null) {
$selectedPools[$family] = $pool;
$selectedContracts[$family] = $contract;
$addressCandidates[$family] = $candidate;
}
}
if (isset($selectedPools[4], $selectedPools[6])) {
return [
'attachment' => $attachment,
'pools' => $selectedPools,
'contracts' => $selectedContracts,
'address_candidates' => $addressCandidates,
];
}
}
throw new CloudPublicNetworkCapacityUnavailable(
'宿主机没有完整可用的双栈公网地址池',
409
);
}
/**
* Returns either an existing available row or one free sparse IPv6 value.
* The caller already owns the candidate pool lock, so a later claim in the
* same transaction observes the same answer.
*
* @return null|array{row:?object,candidate:?CloudIpAddress,
* range_start:?CloudIpAddress,range_end:?CloudIpAddress}
*/
private static function lockReservableAddressCandidate(
object $pool,
CloudPublicIpPoolContract $contract,
array $rows
): ?array {
$family = (int) $pool->address_family;
if ($family === 6) {
$activeCount = count(array_filter(
$rows,
static fn (object $row): bool => in_array(
(string) $row->state,
['reserved', 'assigned', 'changing', 'uncertain'],
true
)
));
if ((int) $pool->max_allocations < 1
|| $activeCount >= (int) $pool->max_allocations) {
return null;
}
}
foreach ($rows as $row) {
if ((string) $row->state === 'available') {
return [
'row' => $row,
'candidate' => null,
'range_start' => null,
'range_end' => null,
];
}
}
if ($family !== 6) {
return null;
}
$rangeStart = $contract->allocationStart();
$rangeEnd = $contract->allocationEnd();
$candidate = $contract->allocationCursor() ?? $rangeStart;
if (!$rangeStart instanceof CloudIpAddress
|| !$rangeEnd instanceof CloudIpAddress
|| !$candidate instanceof CloudIpAddress) {
throw new CloudError('公网 IPv6 稀疏分配合同损坏', 409);
}
$materializedCount = count($rows);
$attempts = max(1, $materializedCount
+ $contract->maxAllocations()
+ count($contract->reservedAddresses())
+ count($contract->dnsServers()) + 2);
for ($attempt = 0; $attempt < $attempts; $attempt++) {
$existing = DB::table('cloud_public_ips')
->where('address_family', 6)
->where('address_binary', $candidate->binary())
->lockForUpdate()->first();
if ($existing === null
&& self::rawAddressAllowedByPool(
$candidate,
$pool,
$contract
)) {
return [
'row' => null,
'candidate' => $candidate,
'range_start' => $rangeStart,
'range_end' => $rangeEnd,
];
}
$candidate = $candidate->compare($rangeEnd) === 0
? $rangeStart : $candidate->next();
}
return null;
}
private static function reserveAddress(object $pool, int $now,
?array $selection): object
{
$family = (int) $pool->address_family;
if ($selection === null) {
throw new CloudError(
$family === 6
? '公网 IPv6 地址池没有可分配地址'
: '公网 IPv4 地址池已经耗尽',
409
);
}
if ($selection['row'] !== null) {
$row = $selection['row'];
if ((string) $row->state !== 'available'
|| $row->reservation_id !== null
|| $row->reservation_ip_claim_id !== null
|| $row->instance_id !== null
|| $row->operation_id !== null) {
throw new CloudError('公网地址候选已被占用', 409);
}
return $row;
}
$candidate = $selection['candidate'];
$rangeStart = $selection['range_start'];
$rangeEnd = $selection['range_end'];
if (!$candidate instanceof CloudIpAddress
|| !$rangeStart instanceof CloudIpAddress
|| !$rangeEnd instanceof CloudIpAddress) {
throw new CloudError('公网 IPv6 稀疏分配选择损坏', 409);
}
$id = DB::table('cloud_public_ips')->insertGetId([
'host_id' => (int) $pool->host_id,
'public_ip_pool_id' => (int) $pool->id,
'address_family' => 6,
'address' => $candidate->text(),
'address_binary' => $candidate->binary(),
'prefix_length' => (int) $pool->guest_prefix_length,
'state' => 'available',
'reservation_id' => null,
'reservation_ip_claim_id' => null,
'instance_id' => null,
'operation_id' => null,
'created_at' => $now,
'updated_at' => $now,
]);
$next = $candidate->compare($rangeEnd) === 0
? $rangeStart : $candidate->next();
DB::table('cloud_public_ip_pools')
->where('id', (int) $pool->id)->update([
'allocation_cursor' => $next->text(),
]);
return DB::table('cloud_public_ips')->where('id', $id)->first();
}
private static function bindAddressToClaim(object $row, int $reservationId,
string $operationId, int $claimId, int $now): void
{
$updated = DB::table('cloud_public_ips')
->where('id', (int) $row->id)
->where('state', 'available')
->whereNull('reservation_id')
->whereNull('reservation_ip_claim_id')
->whereNull('instance_id')
->whereNull('operation_id')->update([
'state' => 'reserved',
'reservation_id' => $reservationId,
'reservation_ip_claim_id' => $claimId,
'instance_id' => null,
'operation_id' => $operationId,
'updated_at' => $now,
]);
if ($updated !== 1) {
throw new CloudError('公网地址声明绑定失败', 409);
}
}
private static function validatePool(object $pool,
int $family): CloudPublicIpPoolContract
{
try {
$contract = CloudPublicIpPoolContract::fromRow($pool);
if ($contract->family() !== $family) {
throw new \InvalidArgumentException();
}
return $contract;
} catch (\Throwable) {
throw new CloudError('公网地址池配置损坏', 409);
}
}
private static function rawAddressAllowedByPool(CloudIpAddress $address,
object $pool, CloudPublicIpPoolContract $contract): bool
{
if (!$contract->addressAllowed($address)) {
return false;
}
$management = CloudPanelUsageService::managementAddress(
CloudHost::find((int) $pool->host_id)
);
if (is_string($management) && $management !== '') {
$managementAddress = CloudIpAddress::parse($management);
if ($managementAddress->family() === $address->family()
&& $managementAddress->equals($address)) {
return false;
}
}
return true;
}
private static function rawAddressBelongsToPool(CloudIpAddress $address,
object $pool, CloudPublicIpPoolContract $contract): bool
{
return $contract->addressBelongs($address);
}
private static function decodedAddresses(string $json,
bool $allowEmpty, int $maximum = 256): array
{
$values = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
if (!is_array($values) || !array_is_list($values)
|| (!$allowEmpty && $values === []) || count($values) > $maximum) {
throw new \InvalidArgumentException('Address list is invalid.');
}
$result = [];
foreach ($values as $raw) {
$address = CloudIpAddress::parse($raw);
if (!$address->isPublicUnicast()
|| isset($result[$address->text()])) {
throw new \InvalidArgumentException('Address list is invalid.');
}
$result[$address->text()] = true;
}
return $result;
}
private static function lockedClaims(int $reservationId): array
{
return DB::table('cloud_resource_reservation_ips')
->where('reservation_id', $reservationId)
->where('active_claim', 1)
->orderBy('address_family')->orderBy('id')->lockForUpdate()->get()
->all();
}
private static function lockedHistoricalClaims(int $reservationId): array
{
return DB::table('cloud_resource_reservation_ips')
->where('reservation_id', $reservationId)
->whereNull('active_claim')->orderBy('id')->lockForUpdate()->get()
->all();
}
private static function assertClaimSet(array $claims, string $operationId,
array $allowedStates): void
{
self::assertActiveClaimSet($claims, $allowedStates);
foreach ($claims as $claim) {
if (!hash_equals($operationId, (string) $claim->operation_id)) {
throw new CloudError('双栈公网地址操作身份不一致', 409);
}
}
}
private static function assertActiveClaimSet(array $claims,
array $allowedStates): void
{
if (count($claims) !== 2) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$families = [];
foreach ($claims as $claim) {
$family = (int) $claim->address_family;
if (!in_array($family, self::FAMILIES, true)
|| isset($families[$family])
|| (int) ($claim->claim_generation ?? 0) < 1
|| (int) ($claim->active_claim ?? 0) !== 1
|| preg_match('/^[a-f0-9]{32}$/D',
(string) ($claim->operation_id ?? '')) !== 1
|| !in_array((string) $claim->state, $allowedStates, true)) {
throw new CloudError('双栈公网地址账本不一致', 409);
}
$families[$family] = true;
}
if (!isset($families[4], $families[6])) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
}
private static function snapshot(array $claims): CloudPublicNetworkSnapshot
{
return self::claimSet($claims)->publicNetwork();
}
private static function claimSet(
array $claims,
?string $expectedState = null,
?int $expectedInstanceId = null,
?int $expectedHostId = null,
?int $expectedLineId = null
): CloudActivePublicNetworkClaimSet
{
if (count($claims) !== 2) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$attachmentIds = array_values(array_unique(array_map(
static fn ($claim): int => (int) $claim->network_attachment_id,
$claims
)));
if (count($attachmentIds) !== 1) {
throw new CloudError('双栈公网地址不属于同一网络接入', 409);
}
$attachment = DB::table('cloud_host_network_attachments')
->where('id', $attachmentIds[0])->first();
if ($attachment === null
|| ($expectedHostId !== null
&& (int) $attachment->host_id !== $expectedHostId)
|| ($expectedLineId !== null
&& (int) $attachment->line_id !== $expectedLineId)) {
throw new CloudError('公网网络接入不存在', 409);
}
$legs = [];
$dns = [];
$addresses = [];
$reservationIds = [];
foreach ($claims as $claim) {
$family = (int) $claim->address_family;
$pool = DB::table('cloud_public_ip_pools')
->where('id', (int) $claim->public_ip_pool_id)->first();
$ip = DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)->first();
if ($pool === null || $ip === null
|| (int) $pool->address_family !== $family
|| (int) $ip->address_family !== $family
|| ($expectedHostId !== null
&& ((int) $pool->host_id !== $expectedHostId
|| (int) $ip->host_id !== $expectedHostId))
|| (int) $pool->network_attachment_id !== $attachmentIds[0]
|| (int) $ip->public_ip_pool_id !== (int) $pool->id) {
throw new CloudError('双栈公网地址引用损坏', 409);
}
$contract = self::validatePool($pool, $family);
self::assertConcreteAddressIdentity($ip, $pool, $contract);
$addresses[(int) $ip->id] = $ip;
$reservationIds[(int) $claim->reservation_id] = true;
$legs[$family] = [
'pool_key' => (string) $pool->pool_key,
'pool_cidr' => (string) $pool->cidr,
'address_cidr' => (string) $ip->address . '/'
. (int) $ip->prefix_length,
'gateway' => (string) $pool->gateway,
'gateway_on_link' => (bool) $pool->gateway_on_link,
];
foreach ($contract->dnsServers() as $text) {
$dns[$text] = $text;
}
}
if (count($reservationIds) !== 1) {
throw new CloudError('双栈公网地址不属于同一资源预留', 409);
}
self::assertCurrentClaimSetStates(
$claims,
$addresses,
$expectedState,
$expectedInstanceId
);
$snapshot = CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => (string) $attachment->network_selector,
'ipv4' => $legs[4] ?? null,
'ipv6' => $legs[6] ?? null,
'dns_servers' => array_values($dns),
]);
return CloudActivePublicNetworkClaimSet::fromLedger(
(int) array_key_first($reservationIds),
$claims,
$addresses,
$snapshot
);
}
/**
* @param array<int, object> $claims
* @param array<int, object> $addresses
*/
private static function assertCurrentClaimSetStates(array $claims,
array $addresses, ?string $expectedState,
?int $expectedInstanceId): void
{
$claimStates = [];
$instanceIds = [];
foreach ($claims as $claim) {
$claimState = (string) ($claim->state ?? '');
$ip = $addresses[(int) ($claim->public_ip_id ?? 0)] ?? null;
$ipState = is_object($ip) ? (string) ($ip->state ?? '') : '';
$expectedIpState = match ($claimState) {
'reserved' => 'reserved',
'committed' => 'assigned',
'uncertain' => 'uncertain',
default => '',
};
$instanceId = is_object($ip) && $ip->instance_id !== null
? (int) $ip->instance_id : null;
if ($expectedIpState === '' || $ipState !== $expectedIpState
|| ($claimState !== 'committed' && $instanceId !== null)
|| ($claimState === 'committed'
&& ($instanceId === null || $instanceId < 1))) {
throw new CloudError('活动双栈公网地址状态不一致', 409);
}
$claimStates[$claimState] = true;
if ($instanceId !== null) {
$instanceIds[$instanceId] = true;
}
}
if (count($claimStates) !== 1
|| ($expectedState !== null && !isset($claimStates[$expectedState]))
|| (isset($claimStates['committed']) && count($instanceIds) !== 1)
|| (!isset($claimStates['committed']) && $instanceIds !== [])
|| ($expectedInstanceId !== null
&& !isset($instanceIds[$expectedInstanceId]))) {
throw new CloudError('活动双栈公网地址集合状态不一致', 409);
}
}
private static function assertIdentity(int $reservationId,
string $operationId): void
{
if ($reservationId < 1
|| preg_match('/^[a-f0-9]{32}$/D', $operationId) !== 1) {
throw new CloudError('公网网络操作标识无效', 409);
}
}
private static function connection(): Connection
{
return DB::connection('default');
}
}