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

1403 lines
56 KiB
PHP

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Services\Cloud;
use App\Models\CloudHost;
use App\Models\CloudHostAgent;
use App\Models\CloudHostNetworkAttachment;
use App\Models\CloudHostResourcePoolMembership;
use App\Models\CloudNetworkLine;
use App\Models\CloudPublicIp;
use App\Models\CloudPublicIpPool;
use App\Models\CloudPublicIpPoolCatalogMutex;
use App\Models\CloudPublicIpPoolReplacementBatch;
use App\Models\CloudResourcePool;
use App\Models\CloudResourceReservation;
/**
* Administrator-owned desired state for one host's public IPv4/IPv6 pools.
*
* PHP is the sole authority for public-pool configuration and IP allocation.
* VM create/change-network jobs carry a signed immutable pool snapshot to the
* host Agent; the Agent validates it but never stores a second pool catalog.
*/
final class CloudAdminHostNetworkService
{
private const MAX_POOLS = 32;
private const MAX_IPV6_ALLOCATIONS = 65535;
private const STATES = ['active', 'draining', 'disabled'];
private const OCCUPIED_IP_STATES = [
'reserved', 'assigned', 'changing', 'uncertain',
];
public function read(int $hostId, array $actor): array
{
$host = $this->host($hostId);
$catalog = $this->databaseCatalog($hostId);
return $this->response($host, $catalog);
}
public function create(int $hostId, array $actor, array $body): array
{
$requestKey = $body['request_key'] ?? null;
if (!is_string($requestKey)
|| preg_match('/^[0-9a-f]{32}$/D', $requestKey) !== 1) {
throw new CloudError('请提供有效的地址池创建请求标识', 422);
}
return $this->save(
$hostId,
$actor,
self::poolKeyForRequest($hostId, $requestKey),
$body,
true,
null
);
}
public function update(int $hostId, string $poolKey, array $actor,
array $body): array
{
if (preg_match('/^[0-9a-f]{32}$/D', $poolKey) !== 1) {
throw new CloudError('公网地址池标识无效', 404);
}
$expectedRevision = $body['expected_revision'] ?? null;
if (is_bool($expectedRevision) || !is_int($expectedRevision)
|| $expectedRevision < 1) {
throw new CloudError('公网地址池版本无效,请刷新后重试', 422);
}
return $this->save(
$hostId,
$actor,
$poolKey,
$body,
false,
$expectedRevision
);
}
private function save(int $hostId, array $actor, string $poolKey,
array $body, bool $creating, ?int $expectedRevision): array
{
$host = $this->host($hostId);
$catalog = $this->databaseCatalog($hostId);
$desired = self::normalizeInput($body);
$prepared = $this->prepareDesired(
$host,
$poolKey,
$desired,
$catalog['items'],
$creating,
$expectedRevision
);
if ($prepared['replay']) {
return $this->response($host, $catalog, $poolKey);
}
$applied = [
'pool_key' => $poolKey,
...$prepared['payload'],
];
$replaced = false;
foreach ($catalog['items'] as $index => $item) {
if (hash_equals((string) $item['pool_key'], $poolKey)) {
$catalog['items'][$index] = $applied;
$replaced = true;
break;
}
}
if (!$replaced) {
$catalog['items'][] = $applied;
}
return $this->response(
$this->host($hostId),
$catalog,
$poolKey
);
}
/** Record one desired revision under the host-scoped lock order. */
private function prepareDesired(CloudHost $host, string $poolKey,
array $desired, array $catalogItems, bool $creating,
?int $expectedRevision): array
{
return $host->getConnection()->transaction(function () use (
$host, $poolKey, $desired, $catalogItems, $creating,
$expectedRevision
): array {
$catalogMutex = CloudPublicIpPoolCatalogMutex::where('id', 1)
->lockForUpdate()->first();
if ($catalogMutex === null) {
throw new CloudError(
'公网地址池全局目录锁未初始化,请先完成数据库结构更新',
503
);
}
$lockedHost = CloudHost::where('id', (int) $host->id)
->lockForUpdate()->first();
if ($lockedHost === null) {
throw new CloudError('宿主机不存在', 404);
}
$memberships = CloudHostPoolMembershipService::lockedRows($lockedHost);
$agent = CloudHostAgent::where(
'host_id', (int) $lockedHost->id
)->lockForUpdate()->first();
$attachments = CloudHostNetworkAttachment::where(
'host_id', (int) $lockedHost->id
)->orderBy('id')->lockForUpdate()->get();
$attachment = $attachments->first(static fn ($row): bool =>
(int) $row->id === $desired['network_attachment_id']
);
$poolRows = CloudPublicIpPool::where(
'host_id', (int) $lockedHost->id
)->orderBy('id')->lockForUpdate()->get();
$pool = $poolRows->first(static fn ($row): bool =>
hash_equals((string) $row->pool_key, $poolKey)
);
$originalAttachment = $pool === null ? null
: $attachments->first(static fn ($row): bool =>
(int) $row->id === (int) $pool->network_attachment_id
);
$live = null;
$liveKeys = [];
foreach ($catalogItems as $item) {
$liveKeys[(string) $item['pool_key']] = true;
if (hash_equals((string) $item['pool_key'], $poolKey)) {
$live = $item;
}
}
$liveRevision = $live === null ? 0 : (int) $live['revision'];
$revisionBase = max(
$liveRevision,
(int) ($pool?->desired_revision ?? 0),
(int) ($pool?->observed_revision ?? 0)
);
if ($creating) {
if ($pool !== null || $live !== null) {
if ($pool !== null && self::sameCreateRequest(
$pool, $desired
)) {
if ((string) $pool->sync_state === 'applied') {
return [
'replay' => true,
'revision' => $revisionBase,
'payload' => [],
];
}
}
throw new CloudError(
'同一创建请求标识不能用于不同的公网地址池配置',
409
);
}
foreach ($poolRows as $row) {
if (!isset($liveKeys[(string) $row->pool_key])) {
throw new CloudError(
'存在尚未核对的地址池创建记录,请刷新后编辑该记录,不能继续创建新地址池',
409
);
}
}
} else {
if ($pool === null && $live === null) {
throw new CloudError('公网地址池不存在', 404);
}
if ($expectedRevision !== $revisionBase) {
throw new CloudError(
'公网地址池版本已变化,请刷新后重试',
409
);
}
}
if ($pool !== null && CloudPublicIpPoolReplacementBatch::query()
->where('active_claim', 1)
->where(static function ($query) use ($pool): void {
$query->where(
'source_public_ip_pool_id',
(int) $pool->id
)->orWhere(
'target_public_ip_pool_id',
(int) $pool->id
);
})->exists()) {
// The host row already serializes batch creation with pool
// editing. Do not wait on a batch row while holding pool rows:
// child finalization locks batch -> source pool.
throw new CloudError(
'该地址池正在执行受控换池,批次收敛前不能修改配置',
409
);
}
if ($attachment === null) {
throw new CloudError('所选网络接入不存在或不属于该宿主机', 409);
}
$line = self::assertMembershipLine(
$memberships, (int) $attachment->line_id
);
if ($creating || $desired['state'] === 'active') {
self::assertAttachmentReady($attachment, $agent);
if ((string) $line->status !== 'active') {
throw new CloudError('网络接入所属线路未启用', 409);
}
}
if ($pool === null && self::catalogCount($poolRows) >= self::MAX_POOLS) {
throw new CloudError(
'一台宿主机最多配置 32 个公网地址池',
409
);
}
if ($pool !== null
&& (int) $pool->address_family
!== $desired['address_family']) {
throw new CloudError(
'公网地址池地址族创建后不能修改,请新建目标地址族的地址池',
409
);
}
self::assertActiveAttachmentDnsContract(
$pool,
$desired,
$poolRows
);
self::assertNoOverlap(
$poolKey,
$desired['address_family'],
$desired['cidr'],
$poolRows
);
self::assertNoGlobalOverlap(
(int) $lockedHost->id,
$desired['address_family'],
$desired['cidr']
);
$occupiedByPool = [];
$occupiedAddressesByPool = [];
if (!$poolRows->isEmpty()) {
$occupiedRows = CloudPublicIp::where(
'host_id', (int) $lockedHost->id
)->whereIn('public_ip_pool_id', $poolRows->pluck('id')->all())
->where(function ($query): void {
$query->whereIn('state', self::OCCUPIED_IP_STATES)
->orWhereNotNull('reservation_id')
->orWhereNotNull('instance_id')
->orWhereNotNull('operation_id');
})->orderBy('id')->lockForUpdate()
->get(['id', 'public_ip_pool_id', 'address']);
foreach ($occupiedRows as $occupiedRow) {
$id = (int) $occupiedRow->public_ip_pool_id;
$occupiedByPool[$id] = ($occupiedByPool[$id] ?? 0) + 1;
$occupiedAddressesByPool[$id][
(string) $occupiedRow->address
] = true;
}
}
$occupied = $pool === null ? 0
: ($occupiedByPool[(int) $pool->id] ?? 0);
$current = $live ?? ($pool === null
? null : self::poolConfig($pool));
$attachmentChanged = $pool !== null && (
$originalAttachment === null
|| (int) $originalAttachment->id !== (int) $attachment->id
);
$occupiedAddresses = $pool === null ? []
: ($occupiedAddressesByPool[(int) $pool->id] ?? []);
$requestedOccupiedAddresses = array_values(array_filter(
$desired['reserved_ips'],
static fn (string $address): bool =>
isset($occupiedAddresses[$address])
));
if ($requestedOccupiedAddresses !== []) {
sort($requestedOccupiedAddresses, SORT_STRING);
throw new CloudError(
'已分配或任务占用的公网 IP 不能加入保留 / 禁用列表:'
. implode(', ', $requestedOccupiedAddresses),
409
);
}
if ($occupied > 0 && ($attachmentChanged
|| ($current !== null
&& self::occupiedUnsafeRuntimeChanged(
$current, $desired
)))) {
throw new CloudError(
'该地址池仍有实例或任务占用,只能修改名称、运行状态和未占用的保留 / 禁用 IP',
409
);
}
if ($revisionBase >= PHP_INT_MAX) {
throw new CloudError('公网地址池版本已达到上限', 409);
}
$revision = $revisionBase + 1;
$now = time();
if ($pool === null) {
$pool = new CloudPublicIpPool();
$pool->pool_key = $poolKey;
$pool->host_id = (int) $lockedHost->id;
$pool->network_attachment_id = 0;
$pool->priority = 0;
$pool->observed_revision = 0;
$pool->created_at = $now;
}
$pool->name = $desired['name'];
$pool->address_family = $desired['address_family'];
$pool->cidr = $desired['cidr'];
$pool->gateway = $desired['gateway'];
$pool->gateway_on_link = $desired['gateway_on_link'];
$pool->guest_prefix_length = $desired['guest_prefix_length'];
$pool->dns_servers_json = json_encode(
$desired['dns_servers'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$pool->reserved_ips_json = json_encode(
$desired['reserved_ips'],
JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES
);
$pool->allocation_start = $desired['allocation_start'];
$pool->allocation_end = $desired['allocation_end'];
$pool->allocation_cursor = $pool->address_family === 6
? ($pool->allocation_cursor ?? $desired['allocation_start'])
: null;
$pool->max_allocations = $desired['max_allocations'];
$pool->state = $desired['state'];
$pool->desired_revision = $revision;
// Public-pool configuration is PHP-owned. Desired state, the
// concrete IP ledger and its observed revision commit atomically;
// there is no Agent task or follow-up repair phase.
$pool->observed_revision = $revision;
$pool->sync_state = 'applied';
$pool->last_error_code = '';
$pool->updated_at = $now;
$pool->network_attachment_id = (int) $attachment->id;
$pool->save();
self::materializeIpLedger($pool);
return [
'replay' => false,
'revision' => $revision,
'payload' => [
'revision' => $revision,
'state' => $desired['state'],
'network_attachment_id' => (int) $attachment->id,
'network_selector' => (string) $attachment->network_selector,
'address_family' => $desired['address_family'],
'cidr' => $desired['cidr'],
'gateway' => $desired['gateway'],
'gateway_on_link' => $desired['gateway_on_link'],
'dns_servers' => $desired['dns_servers'],
'reserved_ips' => $desired['reserved_ips'],
'allocation_start' => $desired['allocation_start'],
'allocation_end' => $desired['allocation_end'],
'max_allocations' => $desired['max_allocations'],
'guest_prefix_length' => $desired['guest_prefix_length'],
],
];
}, 3);
}
private function response(CloudHost $host, array $catalog,
?string $savedPoolKey = null): array
{
$dbRows = CloudPublicIpPool::where('host_id', (int) $host->id)
->orderBy('priority')->orderBy('id')->get();
$attachmentRows = CloudHostNetworkAttachment::where(
'host_id', (int) $host->id
)->orderBy('priority')->orderBy('id')->get();
$lineIds = $attachmentRows->pluck('line_id')->map(
static fn ($id): int => (int) $id
)->filter()->unique()->values()->all();
$lines = $lineIds === [] ? collect()
: CloudNetworkLine::whereIn('id', $lineIds)->get()->keyBy('id');
$agent = CloudHostAgent::find((int) $host->id);
$activePoolIds = CloudHostResourcePoolMembership::where(
'host_id', (int) $host->id
)->where('scheduler_state', 'active')
->pluck('resource_pool_id')->map(
static fn ($id): int => (int) $id
)->unique()->values()->all();
$activeLineIds = $activePoolIds === [] ? []
: CloudResourcePool::whereIn('id', $activePoolIds)
->where('status', 'active')->pluck('line_id')->mapWithKeys(
static fn ($id): array => [(int) $id => true]
)->all();
$attachments = [];
$attachmentsById = [];
foreach ($attachmentRows as $attachmentRow) {
$dto = self::attachmentDto(
$attachmentRow,
$lines->get((int) $attachmentRow->line_id),
$agent,
$activeLineIds
);
$attachments[] = $dto;
$attachmentsById[(int) $attachmentRow->id] = $dto;
}
$byKey = [];
foreach ($dbRows as $row) {
$byKey[(string) $row->pool_key] = $row;
}
$occupied = [];
$assigned = [];
$available = [];
if (!$dbRows->isEmpty()) {
foreach (CloudPublicIp::whereIn(
'public_ip_pool_id', $dbRows->pluck('id')->all()
)->selectRaw('public_ip_pool_id, COUNT(*) AS aggregate')
->where(function ($query): void {
$query->whereIn('state', self::OCCUPIED_IP_STATES)
->orWhereNotNull('reservation_id')
->orWhereNotNull('instance_id')
->orWhereNotNull('operation_id');
})->groupBy('public_ip_pool_id')->get() as $count) {
$occupied[(int) $count->public_ip_pool_id] = (int) $count->aggregate;
}
foreach (CloudPublicIp::whereIn(
'public_ip_pool_id', $dbRows->pluck('id')->all()
)->where('state', 'assigned')
->selectRaw('public_ip_pool_id, COUNT(*) AS aggregate')
->groupBy('public_ip_pool_id')->get() as $count) {
$assigned[(int) $count->public_ip_pool_id] = (int) $count->aggregate;
}
foreach (CloudPublicIp::whereIn(
'public_ip_pool_id', $dbRows->pluck('id')->all()
)->where('state', 'available')
->whereNull('reservation_id')->whereNull('instance_id')
->whereNull('operation_id')
->selectRaw('public_ip_pool_id, COUNT(*) AS aggregate')
->groupBy('public_ip_pool_id')->get() as $count) {
$available[(int) $count->public_ip_pool_id] = (int) $count->aggregate;
}
}
$replacementByPool = [];
foreach (CloudPublicIpPoolReplacementBatch::where(
'host_id', (int) $host->id
)->where('active_claim', 1)->orderBy('id')->get() as $batch) {
$display = CloudPublicIpPoolReplacementBatchService::display(
$batch
);
$sourcePoolId = (int) $batch->source_public_ip_pool_id;
$targetPoolId = (int) $batch->target_public_ip_pool_id;
$replacementByPool[$sourcePoolId] = [
...$display,
'role' => 'source',
'job_url' => '/admin/operations?q='
. (int) $batch->parent_job_id,
];
$replacementByPool[$targetPoolId] = [
...$display,
'role' => 'target',
'job_url' => '/admin/operations?q='
. (int) $batch->parent_job_id,
];
}
$replacementHistoryByPool = [];
foreach (CloudPublicIpPoolReplacementBatch::where(
'host_id', (int) $host->id
)->whereNull('active_claim')
->selectRaw(
'source_public_ip_pool_id, COUNT(*) AS aggregate'
)->groupBy('source_public_ip_pool_id')->get() as $count) {
$replacementHistoryByPool[
(int) $count->source_public_ip_pool_id
] = (int) $count->aggregate;
}
$items = [];
$seen = [];
foreach ($catalog['items'] as $live) {
$key = (string) $live['pool_key'];
$row = $byKey[$key] ?? null;
$attachmentId = (int) (
$row?->network_attachment_id
?? ($live['network_attachment_id'] ?? 0)
);
$items[] = self::poolDto(
$row,
$live,
$row === null ? 0 : ($occupied[(int) $row->id] ?? 0),
$attachmentsById[$attachmentId]
?? self::missingAttachmentDto($attachmentId),
$row === null ? 0 : ($assigned[(int) $row->id] ?? 0),
$row === null ? 0 : self::availableCount(
$row,
$occupied[(int) $row->id] ?? 0,
$available[(int) $row->id] ?? 0
),
$row === null ? null
: ($replacementByPool[(int) $row->id] ?? null),
$row === null ? 0
: ($replacementHistoryByPool[(int) $row->id] ?? 0)
);
$seen[$key] = true;
}
foreach ($dbRows as $row) {
$key = (string) $row->pool_key;
if (isset($seen[$key])) {
continue;
}
$items[] = self::poolDto(
$row,
null,
$occupied[(int) $row->id] ?? 0,
$attachmentsById[(int) $row->network_attachment_id]
?? self::missingAttachmentDto(
(int) $row->network_attachment_id
),
$assigned[(int) $row->id] ?? 0,
self::availableCount(
$row,
$occupied[(int) $row->id] ?? 0,
$available[(int) $row->id] ?? 0
),
$replacementByPool[(int) $row->id] ?? null,
$replacementHistoryByPool[(int) $row->id] ?? 0
);
}
$publicCapacity =
CloudAdminPublicNetworkCapacityProjection::forHosts([
(int) $host->id,
])[(int) $host->id]['attachments'] ?? [];
foreach ($attachments as &$attachment) {
$attachment['public_network_capacity'] = $publicCapacity[
(int) $attachment['id']
] ?? CloudAdminPublicNetworkCapacityProjection::empty();
$attachment['dual_stack_ready'] = $attachment['ready'] === true
&& (int) $attachment['public_network_capacity']['bundles']
['available'] > 0;
$attachmentsById[(int) $attachment['id']] = $attachment;
}
unset($attachment);
foreach ($items as &$item) {
$attachment = $attachmentsById[
(int) ($item['network_attachment_id'] ?? 0)
] ?? null;
if ($attachment !== null) {
$item['attachment'] = $attachment;
$item['dual_stack_ready'] =
(bool) ($attachment['dual_stack_ready'] ?? false);
} else {
$item['dual_stack_ready'] = false;
}
}
unset($item);
return [
'host' => [
'id' => (int) $host->id,
'name' => self::safeText((string) $host->name, 80),
],
'attachments' => $attachments,
'items' => $items,
'count' => count($items),
'maximum' => self::MAX_POOLS,
'saved_pool_key' => $savedPoolKey,
];
}
/** The panel database is the sole catalog for scheduling and IP capacity. */
private function databaseCatalog(int $hostId): array
{
$rows = CloudPublicIpPool::where('host_id', $hostId)
->orderBy('priority')->orderBy('id')->get();
$attachmentIds = $rows->pluck('network_attachment_id')->filter()
->map(static fn ($id): int => (int) $id)->unique()->values()->all();
$attachments = $attachmentIds === [] ? collect()
: CloudHostNetworkAttachment::whereIn('id', $attachmentIds)
->get(['id', 'network_selector'])->keyBy('id');
$items = [];
foreach ($rows as $row) {
$items[] = [
'pool_key' => (string) $row->pool_key,
'revision' => max(0, (int) $row->desired_revision),
'network_attachment_id' => (int) $row->network_attachment_id,
'network_selector' => (string) (
$attachments[(int) $row->network_attachment_id]->network_selector
?? ''
),
...self::poolConfig($row),
'state' => (string) $row->state,
];
}
return ['items' => $items];
}
/** Return the line referenced by an active membership on this host. */
private static function assertMembershipLine($memberships,
int $lineId): CloudNetworkLine
{
$poolIds = [];
foreach ($memberships as $membership) {
if ((string) $membership->scheduler_state === 'active') {
$poolIds[] = (int) $membership->resource_pool_id;
}
}
$poolIds = array_values(array_unique($poolIds));
if ($poolIds === []) {
throw new CloudError(
'请先将宿主机加入该线路的资源池,再配置公网地址池',
409
);
}
$hasLine = CloudResourcePool::whereIn('id', $poolIds)
->where('line_id', $lineId)
->where('status', 'active')
->exists();
$line = CloudNetworkLine::find($lineId);
if (!$hasLine || $line === null) {
throw new CloudError(
'所选网络接入的线路没有启用中的资源池成员关系',
409
);
}
return $line;
}
/** Active pools require current, exact Agent evidence for the attachment. */
private static function assertAttachmentReady(
CloudHostNetworkAttachment $attachment,
?CloudHostAgent $agent
): void {
if ((string) $attachment->state !== 'active') {
throw new CloudError('所选网络接入未启用', 409);
}
if ($agent === null
|| (string) $attachment->verification_state !== 'verified'
|| (int) $attachment->last_verified_at < 1
|| !CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
)) {
throw new CloudError(
'所选网络接入没有当前 Agent 版本的有效验证证据,请重新测试',
409
);
}
}
private static function normalizeInput(array $body, int $status = 422): array
{
$attachmentId = $body['network_attachment_id'] ?? null;
$family = $body['address_family'] ?? null;
$name = $body['name'] ?? '';
$state = $body['state'] ?? null;
$prefix = $body['guest_prefix_length'] ?? null;
$gatewayOnLink = $body['gateway_on_link'] ?? null;
$dns = $body['dns_servers'] ?? null;
$reserved = $body['reserved_ips'] ?? null;
if (is_bool($attachmentId) || !is_int($attachmentId)
|| $attachmentId < 1) {
throw new CloudError('请选择有效的宿主机网络接入', $status);
}
if (!is_int($family) || !in_array($family, [4, 6], true)) {
throw new CloudError('请选择有效的公网地址族', $status);
}
if (!is_string($name) || trim($name) === ''
|| mb_strlen(trim($name)) > 80
|| preg_match('//u', $name) !== 1
|| preg_match('/[\x00-\x1f\x7f]/u', $name) === 1) {
throw new CloudError('地址池名称需为 1 至 80 个字符', $status);
}
if (!is_string($state) || !in_array($state, self::STATES, true)) {
throw new CloudError('公网地址池状态无效', $status);
}
if (is_bool($prefix) || !is_int($prefix)) {
throw new CloudError('客户机网络前缀无效', $status);
}
if (!is_bool($gatewayOnLink)) {
throw new CloudError('网关 on-link 标记无效', $status);
}
if (!is_array($dns) || !array_is_list($dns)
|| !is_array($reserved) || !array_is_list($reserved)) {
throw new CloudError('公网地址列表格式无效', $status);
}
$network = self::normalizeNetworkPrefix(
$body['cidr'] ?? null, $family, $status
);
$cidr = $network->networkCidr();
if ($prefix !== $network->prefixLength()) {
throw new CloudError('客户机网络前缀必须与地址池前缀一致', $status);
}
$gateway = self::normalizePublicAddress(
$body['gateway'] ?? null, $family, '公网网关', $status
);
$gatewayInPool = self::addressUsableInPrefix($network, $gateway);
if ($family === 4 && ($gatewayOnLink || !$gatewayInPool)) {
throw new CloudError('IPv4 网关必须位于地址池可用范围内且不能启用 on-link', $status);
}
if ($family === 6 && !$gatewayInPool && !$gatewayOnLink) {
throw new CloudError('地址池外的 IPv6 网关必须启用 on-link', $status);
}
if (count($dns) < 1 || count($dns) > 4) {
throw new CloudError('公网 DNS 必须填写 1 至 4 个地址', $status);
}
if (count($reserved) > 256) {
throw new CloudError('保留 IP 最多可填写 256 个地址', $status);
}
$dns = self::normalizePublicAddressList(
$dns, null, '公网 DNS', null, $status
);
$reserved = self::normalizePublicAddressList(
$reserved, $family, '保留 IP', $network, $status
);
$allocationStart = null;
$allocationEnd = null;
$maxAllocations = $body['max_allocations'] ?? null;
if ($family === 4) {
if (($body['allocation_start'] ?? null) !== null
|| ($body['allocation_end'] ?? null) !== null
|| $maxAllocations !== 0) {
throw new CloudError('IPv4 地址池不使用稀疏分配范围', $status);
}
$maxAllocations = 0;
} else {
if (is_bool($maxAllocations) || !is_int($maxAllocations)
|| $maxAllocations < 1
|| $maxAllocations > self::MAX_IPV6_ALLOCATIONS) {
throw new CloudError(
'IPv6 最大分配数量必须为 1 至 '
. self::MAX_IPV6_ALLOCATIONS,
$status
);
}
$start = self::normalizePublicAddress(
$body['allocation_start'] ?? null,
6,
'IPv6 分配起始地址',
$status
);
$end = self::normalizePublicAddress(
$body['allocation_end'] ?? null,
6,
'IPv6 分配结束地址',
$status
);
if (!self::addressUsableInPrefix($network, $start)
|| !self::addressUsableInPrefix($network, $end)
|| $start->compare($end) > 0) {
throw new CloudError('IPv6 稀疏分配范围必须位于地址池内且顺序有效', $status);
}
$blocked = [];
foreach (array_merge(
[$gateway->text()], $dns, $reserved
) as $blockedText) {
$blockedAddress = CloudIpAddress::parse($blockedText);
if ($blockedAddress->family() === 6
&& $blockedAddress->compare($start) >= 0
&& $blockedAddress->compare($end) <= 0) {
$blocked[$blockedAddress->text()] = true;
}
}
$candidate = $start;
$usable = 0;
while (true) {
if (!isset($blocked[$candidate->text()])) {
$usable++;
if ($usable >= $maxAllocations) {
break;
}
}
if ($candidate->equals($end)) {
throw new CloudError(
'IPv6 稀疏分配范围扣除网关、DNS 和保留地址后小于最大分配数量',
$status
);
}
$candidate = $candidate->next();
}
$allocationStart = $start->text();
$allocationEnd = $end->text();
}
return [
'network_attachment_id' => $attachmentId,
'address_family' => $family,
'name' => trim($name),
'cidr' => $cidr,
'gateway' => $gateway->text(),
'gateway_on_link' => $gatewayOnLink,
'dns_servers' => $dns,
'reserved_ips' => $reserved,
'allocation_start' => $allocationStart,
'allocation_end' => $allocationEnd,
'max_allocations' => $maxAllocations,
'guest_prefix_length' => $prefix,
'state' => $state,
];
}
private static function normalizeNetworkPrefix($value, int $family,
int $status): CloudIpPrefix
{
try {
$prefix = CloudIpPrefix::network($value);
} catch (\Throwable) {
throw new CloudError('公网地址池 CIDR 格式无效', $status);
}
if ($prefix->family() !== $family
|| !$prefix->networkAddress()->isPublicUnicast()) {
throw new CloudError('公网地址池必须使用所选地址族的可路由网段', $status);
}
$length = $prefix->prefixLength();
if (($family === 4 && ($length < 24 || $length > 30))
|| ($family === 6 && ($length < 48 || $length > 120))) {
throw new CloudError(
$family === 4
? 'IPv4 地址池前缀必须为 /24 至 /30'
: 'IPv6 地址池前缀必须为 /48 至 /120',
$status
);
}
return $prefix;
}
private static function normalizePublicAddressList(array $values,
?int $family, string $label, ?CloudIpPrefix $prefix,
int $status): array
{
$result = [];
foreach ($values as $value) {
$address = self::normalizePublicAddress(
$value, $family, $label, $status
);
if ($prefix !== null
&& !self::addressUsableInPrefix($prefix, $address)) {
throw new CloudError($label . '必须位于地址池的可用范围内', $status);
}
$result[$address->text()] = true;
}
return array_keys($result);
}
private static function normalizePublicAddress($value, ?int $family,
string $label, int $status): CloudIpAddress
{
try {
$address = CloudIpAddress::parse($value);
} catch (\Throwable) {
throw new CloudError($label . '必须是有效的公网 IP 地址', $status);
}
if (($family !== null && $address->family() !== $family)
|| !$address->isPublicUnicast()) {
throw new CloudError($label . '必须是有效的公网 IP 地址', $status);
}
return $address;
}
private static function addressUsableInPrefix(CloudIpPrefix $prefix,
CloudIpAddress $address): bool
{
return $address->isPublicUnicast()
&& $prefix->contains($address)
&& !$address->equals($prefix->networkAddress())
&& ($address->family() !== 4
|| !$address->equals($prefix->lastAddress()));
}
private static function overlaps(string $left, string $right): bool
{
try {
return CloudIpPrefix::network($left)->overlaps(
CloudIpPrefix::network($right)
);
} catch (\Throwable) {
return true;
}
}
private static function uint(string $address): int
{
$packed = inet_pton($address);
if ($packed === false || strlen($packed) !== 4) {
throw new CloudError('IPv4 地址格式无效', 422);
}
return (int) unpack('Naddress', $packed)['address'];
}
private static function mask(int $prefix): int
{
return (0xffffffff << (32 - $prefix)) & 0xffffffff;
}
private static function assertNoOverlap(string $poolKey, int $family,
string $cidr, $poolRows): void
{
$checked = [];
foreach ($poolRows as $row) {
if ((string) $row->pool_key === $poolKey) {
continue;
}
if ((int) $row->address_family !== $family) {
continue;
}
$checked[(string) $row->pool_key] = (string) $row->cidr;
}
foreach ($checked as $other) {
if (self::overlaps($cidr, $other)) {
throw new CloudError('同一宿主机的公网地址池不能重叠', 409);
}
}
}
/** Public addresses are globally unique in cloud_public_ips. */
private static function assertNoGlobalOverlap(int $hostId, int $family,
string $cidr): void
{
foreach (CloudPublicIpPool::where('host_id', '<>', $hostId)
->where('address_family', $family)
->get(['pool_key', 'cidr']) as $row) {
if (self::overlaps($cidr, (string) $row->cidr)) {
throw new CloudError(
'公网地址池地址段已被其他宿主机占用,不能重复配置',
409
);
}
}
}
private static function catalogCount($poolRows): int
{
$keys = [];
foreach ($poolRows as $row) {
$keys[(string) $row->pool_key] = true;
}
return count($keys);
}
private static function poolKeyForRequest(int $hostId,
string $requestKey): string
{
return substr(hash_hmac(
'sha256',
'host-public-pool:' . $hostId . ':' . $requestKey,
CloudSecrets::key('public-pool-key')
), 0, 32);
}
private static function sameCreateRequest(CloudPublicIpPool $pool,
array $desired): bool
{
return (string) $pool->name === $desired['name']
&& (string) $pool->state === $desired['state']
&& (int) $pool->address_family === $desired['address_family']
&& (int) $pool->network_attachment_id
=== $desired['network_attachment_id']
&& !self::runtimeChanged(self::poolConfig($pool), $desired);
}
private static function poolConfig(CloudPublicIpPool $pool): array
{
return [
'address_family' => (int) $pool->address_family,
'cidr' => (string) $pool->cidr,
'gateway' => (string) $pool->gateway,
'gateway_on_link' => (bool) $pool->gateway_on_link,
'dns_servers' => self::decodeIpList($pool->dns_servers_json),
'reserved_ips' => self::decodeIpList($pool->reserved_ips_json),
'allocation_start' => $pool->allocation_start === null
? null : (string) $pool->allocation_start,
'allocation_end' => $pool->allocation_end === null
? null : (string) $pool->allocation_end,
'max_allocations' => (int) $pool->max_allocations,
'guest_prefix_length' => (int) $pool->guest_prefix_length,
];
}
/**
* Every active pool on one attachment can participate in a dual-stack
* bundle. Keep resolver order and identity identical so any IPv4/IPv6
* pairing produces one deterministic network snapshot. Disabled or
* draining pools may be edited first and are checked when reactivated.
*/
private static function assertActiveAttachmentDnsContract(
?CloudPublicIpPool $currentPool,
array $desired,
$poolRows
): void {
if ($desired['state'] !== 'active') {
return;
}
foreach ($poolRows as $row) {
if (($currentPool !== null
&& (int) $row->id === (int) $currentPool->id)
|| (int) $row->network_attachment_id
!== $desired['network_attachment_id']
|| (string) $row->state !== 'active') {
continue;
}
if (self::decodeIpList($row->dns_servers_json)
!== $desired['dns_servers']) {
throw new CloudError(
'同一网络接入的启用地址池必须使用完全相同且顺序一致的 DNS;请先停用相关地址池再分步调整',
409
);
}
}
}
private static function runtimeChanged(array $current,
array $desired): bool
{
return self::occupiedUnsafeRuntimeChanged($current, $desired)
|| array_values($current['reserved_ips'] ?? [])
!== $desired['reserved_ips'];
}
/** Changes here can invalidate the network identity of an occupied IP. */
private static function occupiedUnsafeRuntimeChanged(array $current,
array $desired): bool
{
return (string) ($current['cidr'] ?? '') !== $desired['cidr']
|| (int) ($current['address_family'] ?? 0)
!== $desired['address_family']
|| (string) ($current['gateway'] ?? '') !== $desired['gateway']
|| (bool) ($current['gateway_on_link'] ?? false)
!== $desired['gateway_on_link']
|| array_values($current['dns_servers'] ?? []) !== $desired['dns_servers']
|| ($current['allocation_start'] ?? null)
!== $desired['allocation_start']
|| ($current['allocation_end'] ?? null)
!== $desired['allocation_end']
|| (int) ($current['max_allocations'] ?? 0)
!== $desired['max_allocations']
|| (int) ($current['guest_prefix_length'] ?? 0)
!== $desired['guest_prefix_length'];
}
/** Materialize the configured CIDR into the panel-owned address ledger. */
private static function materializeIpLedger(CloudPublicIpPool $pool): void
{
$config = self::poolConfig($pool);
$family = (int) $config['address_family'];
$blocked = array_fill_keys(array_merge(
[$config['gateway']], $config['dns_servers'], $config['reserved_ips']
), true);
$managementAddress = CloudPanelUsageService::managementAddress(
CloudHost::find((int) $pool->host_id)
);
if ($managementAddress !== null) {
try {
$management = CloudIpAddress::parse($managementAddress);
if ($management->family() === $family) {
$blocked[$management->text()] = true;
}
} catch (\Throwable) {
// Host usage validation owns malformed management metadata.
}
}
if ($family === 6) {
self::refreshSparseIpv6Ledger($pool, $config, $blocked);
return;
}
[$network, $prefix] = explode('/', $config['cidr'], 2);
$networkValue = self::uint($network);
$broadcast = $networkValue | (~self::mask((int) $prefix) & 0xffffffff);
$wanted = [];
for ($value = $networkValue + 1; $value < $broadcast; $value++) {
$address = long2ip($value);
if ($address !== false) {
$wanted[$address] = isset($blocked[$address]) ? 'disabled' : 'available';
}
}
$rows = CloudPublicIp::where('public_ip_pool_id', (int) $pool->id)
->orderBy('id')->lockForUpdate()->get();
$byAddress = [];
foreach ($rows as $row) {
$byAddress[(string) $row->address] = $row;
}
$now = time();
foreach ($wanted as $address => $state) {
$row = $byAddress[$address] ?? null;
if ($row === null) {
$row = new CloudPublicIp();
$row->host_id = (int) $pool->host_id;
$row->public_ip_pool_id = (int) $pool->id;
$row->address_family = 4;
$row->address = $address;
$row->address_binary = inet_pton($address);
$row->created_at = $now;
}
$row->prefix_length = (int) $config['guest_prefix_length'];
if ($row->reservation_id === null && $row->instance_id === null
&& $row->operation_id === null) {
$row->state = $state;
}
$row->updated_at = $now;
$row->save();
unset($byAddress[$address]);
}
foreach ($byAddress as $row) {
if ($row->reservation_id === null && $row->instance_id === null
&& $row->operation_id === null) {
$row->state = 'disabled';
$row->updated_at = $now;
$row->save();
}
}
}
/**
* IPv6 pools materialize claimed addresses and the bounded set of
* control-plane blocked addresses. The latter keeps administrator
* disabled-address projections exact without expanding the sparse range.
*/
private static function refreshSparseIpv6Ledger(CloudPublicIpPool $pool,
array $config, array $blocked): void
{
$network = CloudIpPrefix::network((string) $config['cidr']);
$start = CloudIpAddress::parse((string) $config['allocation_start']);
$end = CloudIpAddress::parse((string) $config['allocation_end']);
$now = time();
$rows = CloudPublicIp::where(
'public_ip_pool_id', (int) $pool->id
)->orderBy('id')->lockForUpdate()->get();
$byAddress = [];
foreach ($rows as $row) {
$byAddress[(string) $row->address] = true;
}
foreach (array_keys($blocked) as $blockedText) {
try {
$blockedAddress = CloudIpAddress::parse($blockedText);
} catch (\Throwable) {
continue;
}
if ($blockedAddress->family() !== 6
|| !$network->contains($blockedAddress)
|| isset($byAddress[$blockedAddress->text()])) {
continue;
}
$row = new CloudPublicIp();
$row->host_id = (int) $pool->host_id;
$row->public_ip_pool_id = (int) $pool->id;
$row->address_family = 6;
$row->address = $blockedAddress->text();
$row->address_binary = $blockedAddress->binary();
$row->prefix_length = (int) $config['guest_prefix_length'];
$row->state = 'disabled';
$row->created_at = $now;
$row->updated_at = $now;
$row->save();
$rows->push($row);
$byAddress[$blockedAddress->text()] = true;
}
foreach ($rows as $row) {
try {
$address = CloudIpAddress::parse((string) $row->address);
$inRange = $address->family() === 6
&& $address->compare($start) >= 0
&& $address->compare($end) <= 0;
} catch (\Throwable) {
$inRange = false;
$address = null;
}
$row->address_family = 6;
if ($address !== null) {
$row->address = $address->text();
$row->address_binary = $address->binary();
}
$row->prefix_length = (int) $config['guest_prefix_length'];
if ($row->reservation_id === null && $row->instance_id === null
&& $row->operation_id === null) {
$row->state = $inRange && $address !== null
&& !isset($blocked[$address->text()])
? 'available' : 'disabled';
}
$row->updated_at = $now;
$row->save();
}
}
private static function attachmentDto(
CloudHostNetworkAttachment $attachment,
?CloudNetworkLine $line,
?CloudHostAgent $agent,
array $activeLineIds
): array {
$storedVerification = (string) $attachment->verification_state;
$currentEvidence = $agent !== null
&& (int) $attachment->last_verified_at > 0
&& CloudAgentSettingsService::publicNetworkReady(
$agent,
(string) $attachment->network_selector,
(int) $attachment->verified_agent_revision
);
$verification = $storedVerification === 'verified'
&& !$currentEvidence ? 'stale' : $storedVerification;
$lineDto = $line === null ? null : [
'id' => (int) $line->id,
'name' => self::safeText((string) $line->name, 80),
'status' => self::safeText((string) $line->status, 16),
];
return [
'id' => (int) $attachment->id,
'attachment_key' => (string) $attachment->attachment_key,
'name' => self::safeText((string) $attachment->name, 80),
'line_id' => (int) $attachment->line_id,
'line_name' => $lineDto['name'] ?? '线路关系已失效',
'line' => $lineDto,
'network_selector' => (string) $attachment->network_selector,
'state' => (string) $attachment->state,
'config_revision' => (int) $attachment->config_revision,
'verified_agent_revision' =>
(int) $attachment->verified_agent_revision,
'verification_state' => $verification,
'ready' => $verification === 'verified'
&& (string) $attachment->state === 'active'
&& $line !== null && (string) $line->status === 'active'
&& isset($activeLineIds[(int) $attachment->line_id]),
'last_verified_at' => (int) $attachment->last_verified_at,
'verification_error_code' => self::safeText(
(string) $attachment->verification_error_code, 64
),
];
}
private static function missingAttachmentDto(int $attachmentId): array
{
return [
'id' => max(0, $attachmentId),
'attachment_key' => '',
'name' => '网络接入已缺失',
'line_id' => null,
'line_name' => '线路关系已失效',
'line' => null,
'network_selector' => '',
'state' => 'missing',
'config_revision' => 0,
'verified_agent_revision' => 0,
'verification_state' => 'missing',
'ready' => false,
'last_verified_at' => 0,
'verification_error_code' => 'network_attachment_missing',
];
}
private static function poolDto(?CloudPublicIpPool $row, ?array $live,
int $occupied, ?array $attachment, int $assigned = 0,
int $available = 0,
?array $activeReplacement = null,
int $replacementHistoryCount = 0): array
{
$desired = $row === null ? null : self::poolConfig($row);
$attachmentId = (int) (
$row?->network_attachment_id
?? ($live['network_attachment_id'] ?? 0)
);
$attachment ??= self::missingAttachmentDto($attachmentId);
return [
'pool_key' => (string) ($row?->pool_key ?? $live['pool_key']),
'name' => self::safeText(
(string) ($row?->name ?? $live['cidr']), 80
),
'cidr' => (string) ($desired['cidr'] ?? $live['cidr']),
'gateway' => (string) ($desired['gateway'] ?? $live['gateway']),
'address_family' => (int) (
$desired['address_family'] ?? $live['address_family'] ?? 0
),
'gateway_on_link' => (bool) (
$desired['gateway_on_link'] ?? $live['gateway_on_link'] ?? false
),
'dns_servers' => $desired['dns_servers'] ?? $live['dns_servers'],
'reserved_ips' => $desired['reserved_ips'] ?? $live['reserved_ips'],
'allocation_start' => $desired['allocation_start']
?? $live['allocation_start'] ?? null,
'allocation_end' => $desired['allocation_end']
?? $live['allocation_end'] ?? null,
'max_allocations' => (int) (
$desired['max_allocations'] ?? $live['max_allocations'] ?? 0
),
'guest_prefix_length' => (int) (
$desired['guest_prefix_length'] ?? $live['guest_prefix_length']
),
'state' => (string) ($row?->state ?? $live['state']),
'revision' => (int) ($row?->desired_revision ?? $live['revision']),
'expected_revision' => max(
(int) ($row?->desired_revision ?? 0),
(int) ($row?->observed_revision ?? 0),
(int) ($live['revision'] ?? 0)
),
'observed_revision' => (int) (
$row?->observed_revision ?? $live['revision']
),
'live_revision' => $row === null ? null : (int) $row->observed_revision,
'network_attachment_id' => $attachmentId,
'attachment' => $attachment,
'line' => $attachment['line'],
'network_selector' => (string) $attachment['network_selector'],
'sync_state' => (string) ($row?->sync_state ?? 'untracked'),
'sync_message' => self::syncMessage(
(string) ($row?->sync_state ?? 'untracked')
),
'occupied_count' => max(0, $occupied),
'available_count' => max(0, $available),
'assigned_instance_count' => max(0, $assigned),
'replacement_locked' => $activeReplacement !== null,
'active_replacement' => $activeReplacement,
'replacement_history_count' => max(
0,
$replacementHistoryCount
),
'has_replacement_history' => $replacementHistoryCount > 0,
'read_only' => false,
];
}
private static function availableCount(CloudPublicIpPool $pool,
int $occupied, int $concreteAvailable): int
{
if ((int) $pool->address_family === 6) {
return max(0, (int) $pool->max_allocations - $occupied);
}
return max(0, $concreteAvailable);
}
private static function decodeIpList($value): array
{
try {
$decoded = json_decode((string) $value, true, 32, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
return [];
}
return is_array($decoded) && array_is_list($decoded)
? array_values(array_filter($decoded, 'is_string')) : [];
}
private static function syncMessage(string $state): string
{
return [
'applied' => '已应用',
'pending' => '正在保存',
'uncertain' => '账本已锁定(任务失败)',
'failed' => '账本保存失败',
'never' => '尚未保存',
'untracked' => '面板配置',
][$state] ?? '应用状态未知';
}
private function host(int $hostId): CloudHost
{
if ($hostId < 1 || ($host = CloudHost::find($hostId)) === null) {
throw new CloudError('宿主机不存在', 404);
}
return $host;
}
private static function safeText(string $value, int $maximum): string
{
$value = preg_replace('/[\x00-\x1f\x7f]/u', '', $value) ?? '';
return mb_substr(trim($value), 0, $maximum);
}
}