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

863 lines
36 KiB
PHP

<?php
namespace App\Services\Cloud;
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];
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 {
$claimHints = self::unlockedClaims($reservationId);
self::lockHost($hostId);
$selection = $claimHints === []
? self::lockPoolPair($hostId, $lineId)
: self::lockClaimNetworkContext($claimHints, $hostId, $lineId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
$existing = self::lockedClaims($reservationId);
if ($existing !== []) {
self::assertClaimSet($existing, $operationId, [
'reserved', 'committed', 'uncertain',
]);
self::assertClaimsUseSelection($existing, $selection);
$addresses = self::lockClaimAddresses($existing);
self::assertClaimAddresses($existing, $addresses,
$operationId, [
'reserved' => ['reserved'],
'committed' => ['assigned'],
'uncertain' => ['uncertain'],
]);
return self::snapshot($existing);
}
if ($claimHints !== [] || (string) $reservation->state !== 'held') {
throw new CloudError('公网网络资源预留状态不明确', 409);
}
$now = time();
$claims = [];
foreach (self::FAMILIES as $family) {
$pool = $selection['pools'][$family];
$ip = self::reserveAddress($pool, $reservationId,
$operationId, $now,
$selection['address_candidates'][$family] ?? null);
$claimId = DB::table('cloud_resource_reservation_ips')
->insertGetId([
'reservation_id' => $reservationId,
'address_family' => $family,
'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' => '',
]);
$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);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
$claims = self::lockedClaims($reservationId);
self::assertClaimSet($claims, $operationId,
['reserved', 'uncertain', 'committed']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
'committed' => ['assigned'],
], $instanceId);
$now = time();
foreach ($claims as $claim) {
$ip = $addresses[(int) $claim->public_ip_id];
DB::table('cloud_public_ips')->where('id', (int) $ip->id)
->update([
'state' => 'assigned',
'reservation_id' => $reservationId,
'instance_id' => $instanceId,
'operation_id' => $operationId,
'updated_at' => $now,
]);
DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)->update([
'state' => 'committed',
'updated_at' => $now,
]);
}
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);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'uncertain']);
$claims = self::lockedClaims($reservationId);
self::assertClaimSet($claims, $operationId,
['reserved', 'uncertain']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
$now = time();
foreach ($claims as $claim) {
DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('operation_id', $operationId)->update([
'state' => 'uncertain',
'updated_at' => $now,
]);
DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)->update([
'state' => 'uncertain',
'updated_at' => $now,
]);
}
});
}
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);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'uncertain']);
$claims = self::lockedClaims($reservationId);
self::assertClaimSet($claims, $operationId,
['reserved', 'uncertain']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
'reserved' => ['reserved'],
'uncertain' => ['uncertain'],
]);
self::releaseLockedClaims($claims, $operationId, $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);
$claimHints = self::unlockedClaims($reservationId);
if ($reservationHint === null || $claimHints === []) {
throw new CloudError('双栈公网地址账本不完整', 409);
}
$hostId = (int) $reservationHint->host_id;
self::lockHost($hostId);
$selection = self::lockClaimNetworkContext($claimHints, $hostId);
$reservation = self::lockReservation($reservationId);
self::assertReservation($reservation, $hostId, $operationId,
['held', 'committed', 'uncertain']);
$claims = self::lockedClaims($reservationId);
self::assertClaimSet($claims, $operationId, ['committed']);
self::assertClaimsUseSelection($claims, $selection);
$addresses = self::lockClaimAddresses($claims);
self::assertClaimAddresses($claims, $addresses, $operationId, [
'committed' => ['assigned'],
], $instanceId);
self::releaseLockedClaims($claims, $operationId, $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)
->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);
}
}
/** 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 = [];
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);
}
self::validatePool($pool, $family);
$pools[$family] = $pool;
}
if (!isset($pools[4], $pools[6])) {
throw new CloudError('双栈公网地址池不完整', 409);
}
return ['attachment' => $attachment, 'pools' => $pools];
}
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 assertClaimAddresses(array $claims,
array $addresses, string $operationId, array $allowedPairs,
?int $instanceId = null): void
{
foreach ($claims as $claim) {
$ip = $addresses[(int) $claim->public_ip_id] ?? null;
$claimState = (string) $claim->state;
$allowedIpStates = $allowedPairs[$claimState] ?? [];
if ($ip === null || $allowedIpStates === []
|| !in_array((string) $ip->state, $allowedIpStates, true)
|| (int) $ip->reservation_id !== (int) $claim->reservation_id
|| (int) $ip->address_family !== (int) $claim->address_family
|| (int) $ip->public_ip_pool_id
!== (int) $claim->public_ip_pool_id
|| !hash_equals($operationId,
(string) ($ip->operation_id ?? ''))) {
throw new CloudError('公网地址与预留账本不一致', 409);
}
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 $operationId, string $reason): void
{
$now = time();
foreach ($claims as $claim) {
DB::table('cloud_public_ips')
->where('id', (int) $claim->public_ip_id)
->where('operation_id', $operationId)->update([
'state' => 'available',
'reservation_id' => null,
'instance_id' => null,
'operation_id' => null,
'updated_at' => $now,
]);
DB::table('cloud_resource_reservation_ips')
->where('id', (int) $claim->id)->update([
'state' => 'released',
'released_at' => $now,
'release_reason' => $reason,
'updated_at' => $now,
]);
}
}
private static function assertReleaseReason(string $reason): void
{
if (preg_match('/^[a-z][a-z0-9_]{2,63}$/D', $reason) !== 1) {
throw new CloudError('公网地址释放原因无效', 409);
}
}
private static function lockPoolPair(int $hostId, int $lineId): array
{
$attachments = DB::table('cloud_host_network_attachments')
->where('host_id', $hostId)->where('line_id', $lineId)
->where('state', 'active')->orderBy('priority')->orderBy('id')
->lockForUpdate()->get();
foreach ($attachments as $attachment) {
$rows = DB::table('cloud_public_ip_pools')
->where('host_id', $hostId)
->where('network_attachment_id', (int) $attachment->id)
->where('state', 'active')->where('sync_state', 'applied')
->whereColumn('desired_revision', 'observed_revision')
->whereIn('address_family', self::FAMILIES)
->orderBy('address_family')->orderBy('priority')->orderBy('id')
->lockForUpdate()->get();
$pools = [];
$addressCandidates = [];
foreach ($rows as $row) {
$family = (int) $row->address_family;
self::validatePool($row, $family);
if (isset($pools[$family])) {
continue;
}
$candidate = self::lockReservableAddressCandidate($row);
if ($candidate !== null) {
$pools[$family] = $row;
$addressCandidates[$family] = $candidate;
}
}
if (isset($pools[4], $pools[6])) {
return [
'attachment' => $attachment,
'pools' => $pools,
'address_candidates' => $addressCandidates,
];
}
}
throw new CloudError('宿主机没有完整可用的双栈公网地址池', 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
): ?array {
$family = (int) $pool->address_family;
if ($family === 6) {
$activeCount = DB::table('cloud_public_ips')
->where('public_ip_pool_id', (int) $pool->id)
->whereIn('state', [
'reserved', 'assigned', 'changing', 'uncertain',
])->count();
if ((int) $pool->max_allocations < 1
|| $activeCount >= (int) $pool->max_allocations) {
return null;
}
}
$available = DB::table('cloud_public_ips')
->where('host_id', (int) $pool->host_id)
->where('public_ip_pool_id', (int) $pool->id)
->where('address_family', $family)->where('state', 'available')
->whereNull('reservation_id')->whereNull('instance_id')
->whereNull('operation_id')->orderBy('id')->lockForUpdate()->get();
foreach ($available as $row) {
if (self::addressAllowedByPool($row, $pool)) {
return [
'row' => $row,
'candidate' => null,
'range_start' => null,
'range_end' => null,
];
}
}
if ($family !== 6) {
return null;
}
$rangeStart = CloudIpAddress::parse($pool->allocation_start ?? null);
$rangeEnd = CloudIpAddress::parse($pool->allocation_end ?? null);
$candidate = $pool->allocation_cursor === null
? $rangeStart : CloudIpAddress::parse($pool->allocation_cursor);
if ($candidate->compare($rangeStart) < 0
|| $candidate->compare($rangeEnd) > 0) {
$candidate = $rangeStart;
}
$materializedCount = DB::table('cloud_public_ips')
->where('public_ip_pool_id', (int) $pool->id)->count();
$attempts = max(1, $materializedCount
+ (int) $pool->max_allocations
+ count(self::decodedAddresses(
(string) $pool->reserved_ips_json,
true
))
+ count(self::decodedAddresses(
(string) $pool->dns_servers_json,
false,
4
)) + 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)) {
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 $reservationId,
string $operationId, 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) {
return self::claimAddress(
$selection['row'],
$reservationId,
$operationId,
$now
);
}
$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' => 'reserved',
'reservation_id' => $reservationId,
'instance_id' => null,
'operation_id' => $operationId,
'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 claimAddress(object $row, int $reservationId,
string $operationId, int $now): object
{
DB::table('cloud_public_ips')->where('id', (int) $row->id)->update([
'state' => 'reserved',
'reservation_id' => $reservationId,
'instance_id' => null,
'operation_id' => $operationId,
'updated_at' => $now,
]);
return DB::table('cloud_public_ips')->where('id', (int) $row->id)
->first();
}
private static function validatePool(object $pool, int $family): void
{
try {
$prefix = CloudIpPrefix::network((string) $pool->cidr);
$gateway = CloudIpAddress::parse((string) $pool->gateway);
if ($prefix->family() !== $family || $gateway->family() !== $family
|| (int) $pool->guest_prefix_length !== $prefix->prefixLength()
|| !$prefix->networkAddress()->isPublicUnicast()
|| !$gateway->isPublicUnicast()
|| (!$prefix->contains($gateway)
&& !(bool) $pool->gateway_on_link)) {
throw new \InvalidArgumentException();
}
self::decodedAddresses(
(string) $pool->dns_servers_json,
false,
4
);
$reserved = self::decodedAddresses(
(string) $pool->reserved_ips_json,
true
);
foreach (array_keys($reserved) as $text) {
$address = CloudIpAddress::parse($text);
if ($address->family() !== $family
|| !$prefix->contains($address)) {
throw new \InvalidArgumentException();
}
}
if ($family === 4) {
if ($pool->allocation_start !== null
|| $pool->allocation_end !== null
|| $pool->allocation_cursor !== null
|| (int) $pool->max_allocations !== 0) {
throw new \InvalidArgumentException();
}
} else {
$start = CloudIpAddress::parse($pool->allocation_start ?? null);
$end = CloudIpAddress::parse($pool->allocation_end ?? null);
if ($start->family() !== 6 || $end->family() !== 6
|| !$start->isPublicUnicast() || !$end->isPublicUnicast()
|| !$prefix->contains($start) || !$prefix->contains($end)
|| $start->compare($end) > 0
|| (int) $pool->max_allocations < 1) {
throw new \InvalidArgumentException();
}
if ($pool->allocation_cursor !== null) {
$cursor = CloudIpAddress::parse($pool->allocation_cursor);
if ($cursor->family() !== 6
|| $cursor->compare($start) < 0
|| $cursor->compare($end) > 0) {
throw new \InvalidArgumentException();
}
}
}
} catch (\Throwable) {
throw new CloudError('公网地址池配置损坏', 409);
}
}
private static function addressAllowedByPool(object $row,
object $pool): bool
{
try {
if ((int) $row->address_family !== (int) $pool->address_family
|| (int) $row->prefix_length
!== (int) $pool->guest_prefix_length) {
return false;
}
return self::rawAddressAllowedByPool(
CloudIpAddress::parse((string) $row->address),
$pool
);
} catch (\Throwable) {
return false;
}
}
private static function rawAddressAllowedByPool(CloudIpAddress $address,
object $pool): bool
{
$prefix = CloudIpPrefix::network((string) $pool->cidr);
if ($address->family() !== (int) $pool->address_family
|| !$address->isPublicUnicast() || !$prefix->contains($address)
|| $address->equals($prefix->networkAddress())
|| ($address->family() === 4
&& $address->equals($prefix->lastAddress()))) {
return false;
}
$blocked = self::decodedAddresses(
(string) $pool->reserved_ips_json,
true
);
$gateway = CloudIpAddress::parse((string) $pool->gateway);
$blocked[$gateway->text()] = true;
foreach (self::decodedAddresses(
(string) $pool->dns_servers_json,
false,
4
) as $text => $_) {
$blocked[$text] = true;
}
return !isset($blocked[$address->text()]);
}
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)
->orderBy('address_family')->orderBy('id')->lockForUpdate()->get()
->all();
}
private static function assertClaimSet(array $claims, string $operationId,
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])
|| !hash_equals($operationId, (string) $claim->operation_id)
|| !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
{
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) {
throw new CloudError('公网网络接入不存在', 409);
}
$legs = [];
$dns = [];
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
|| (int) $pool->network_attachment_id !== $attachmentIds[0]
|| (int) $ip->public_ip_pool_id !== (int) $pool->id) {
throw new CloudError('双栈公网地址引用损坏', 409);
}
$legs[$family] = [
'pool_key' => (string) $pool->pool_key,
'pool_cidr' => (string) $pool->cidr,
'address_cidr' => (string) $ip->address . '/'
. (int) $ip->prefix_length,
'gateway' => (string) $pool->gateway,
'gateway_on_link' => (bool) $pool->gateway_on_link,
];
foreach (self::decodedAddresses(
(string) $pool->dns_servers_json,
false
) as $text => $_) {
$dns[$text] = $text;
}
}
return CloudPublicNetworkSnapshot::fromArray([
'contract' => 1,
'network_selector' => (string) $attachment->network_selector,
'ipv4' => $legs[4] ?? null,
'ipv6' => $legs[6] ?? null,
'dns_servers' => array_values($dns),
]);
}
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');
}
}