From 669ca962269300acfc212d0d61c4eced75cfe5a9 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 20:28:11 +0800 Subject: [PATCH] feat: bind public pools to network attachments --- .../CloudAdminHostNetworkController.php | 10 +- .../Cloud/CloudAdminHostNetworkService.php | 436 +++++++++--------- web/public/cloud/admin-hosts.js | 261 ++++++++++- .../views/venix/admin/hosts/index.tpl | 43 +- web/resources/views/venix/layout_assets.tpl | 2 +- ...dminHostNetworkAttachmentsContractTest.php | 28 ++ web/tests/AdminHostNetworkBehaviorTest.mjs | 57 ++- .../AdminHostNetworkPoolsContractTest.php | 56 ++- .../CloudAdminHostNetworkServiceTest.php | 303 +++++++++++- web/tests/CloudFinancialWorkflowTest.php | 7 +- .../CloudSpecialTaskSingleDispatchTest.php | 3 +- 11 files changed, 941 insertions(+), 265 deletions(-) diff --git a/web/app/Controllers/CloudAdminHostNetworkController.php b/web/app/Controllers/CloudAdminHostNetworkController.php index 3ea969b6..795b0e02 100644 --- a/web/app/Controllers/CloudAdminHostNetworkController.php +++ b/web/app/Controllers/CloudAdminHostNetworkController.php @@ -36,8 +36,9 @@ final class CloudAdminHostNetworkController } else { $body = CloudInput::object($request); CloudInput::only($body, [ - 'name', 'cidr', 'gateway', 'dns_servers', 'reserved_ips', - 'guest_prefix_length', 'state', 'request_key', + 'network_attachment_id', 'name', 'cidr', 'gateway', + 'dns_servers', 'reserved_ips', 'guest_prefix_length', + 'state', 'request_key', ]); $result = $service->create($hostId, $actor, $body); $status = 201; @@ -52,8 +53,9 @@ final class CloudAdminHostNetworkController $actor = $this->actor($request, true); $body = CloudInput::object($request); CloudInput::only($body, [ - 'name', 'cidr', 'gateway', 'dns_servers', 'reserved_ips', - 'guest_prefix_length', 'state', 'expected_revision', + 'network_attachment_id', 'name', 'cidr', 'gateway', + 'dns_servers', 'reserved_ips', 'guest_prefix_length', + 'state', 'expected_revision', ]); $result = (new CloudAdminHostNetworkService())->update( (int) ($args['id'] ?? 0), diff --git a/web/app/Services/Cloud/CloudAdminHostNetworkService.php b/web/app/Services/Cloud/CloudAdminHostNetworkService.php index fe7ee7f6..8ec650dc 100644 --- a/web/app/Services/Cloud/CloudAdminHostNetworkService.php +++ b/web/app/Services/Cloud/CloudAdminHostNetworkService.php @@ -3,6 +3,7 @@ namespace App\Services\Cloud; use App\Models\CloudHost; +use App\Models\CloudHostAgent; use App\Models\CloudHostNetworkAttachment; use App\Models\CloudHostResourcePoolMembership; use App\Models\CloudNetworkLine; @@ -126,35 +127,14 @@ final class CloudAdminHostNetworkService } $memberships = CloudHostPoolMembershipService::lockedRows($lockedHost); - $membership = CloudHostPoolMembershipService::selected( - $memberships - ); - if ($membership === null) { - throw new CloudError( - '请先将宿主机加入资源池,再配置该线路的公网地址池', - 409 - ); - } - $resourcePool = CloudResourcePool::where( - 'id', (int) $membership->resource_pool_id + $agent = CloudHostAgent::where( + 'host_id', (int) $lockedHost->id )->lockForUpdate()->first(); - if ($resourcePool === null || (int) $resourcePool->line_id < 1) { - throw new CloudError('宿主机资源池或线路配置已失效', 409); - } - - $selector = (string) $lockedHost->default_network; - if (!CloudNetworkSelector::isValid($selector)) { - throw new CloudError( - '请先在面板配置 bridge:网桥名 或 network:libvirt网络名;旧选择器须核对实际映射后迁移', - 409 - ); - } - $attachmentKey = substr(hash('sha256', $selector), 0, 32); $attachments = CloudHostNetworkAttachment::where( 'host_id', (int) $lockedHost->id )->orderBy('id')->lockForUpdate()->get(); $attachment = $attachments->first(static fn ($row): bool => - hash_equals((string) $row->attachment_key, $attachmentKey) + (int) $row->id === $desired['network_attachment_id'] ); $poolRows = CloudPublicIpPool::where( @@ -185,12 +165,7 @@ final class CloudAdminHostNetworkService if ($creating) { if ($pool !== null || $live !== null) { if ($pool !== null && self::sameCreateRequest( - $pool, - $originalAttachment, - $desired, - $attachmentKey, - $selector, - (int) $resourcePool->line_id + $pool, $desired )) { if ((string) $pool->sync_state === 'applied') { return [ @@ -225,6 +200,19 @@ final class CloudAdminHostNetworkService } } + 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 个公网地址池', @@ -265,35 +253,11 @@ final class CloudAdminHostNetworkService } $occupied = $pool === null ? 0 : ($occupiedByPool[(int) $pool->id] ?? 0); - $attachmentLineChanged = $attachment !== null - && (int) $attachment->line_id - !== (int) $resourcePool->line_id; - if ($attachmentLineChanged) { - foreach ($poolRows as $row) { - if ((int) $row->network_attachment_id - === (int) $attachment->id - && ($occupiedByPool[(int) $row->id] ?? 0) > 0) { - throw new CloudError( - '公网接入仍有关联地址被占用,不能切换所属线路', - 409 - ); - } - } - } - $current = $live ?? ($pool === null ? null : [ - ...self::poolConfig($pool), - 'network_selector' => (string) ( - $originalAttachment?->network_selector ?? '' - ), - ]); + $current = $live ?? ($pool === null + ? null : self::poolConfig($pool)); $attachmentChanged = $pool !== null && ( $originalAttachment === null - || (string) $originalAttachment->attachment_key - !== $attachmentKey - || (string) $originalAttachment->network_selector - !== $selector - || (int) $originalAttachment->line_id - !== (int) $resourcePool->line_id + || (int) $originalAttachment->id !== (int) $attachment->id ); $occupiedAddresses = $pool === null ? [] : ($occupiedAddressesByPool[(int) $pool->id] ?? []); @@ -313,7 +277,7 @@ final class CloudAdminHostNetworkService if ($occupied > 0 && ($attachmentChanged || ($current !== null && self::occupiedUnsafeRuntimeChanged( - $current, $desired, $selector + $current, $desired )))) { throw new CloudError( '该地址池仍有实例或任务占用,只能修改名称、运行状态和未占用的保留 / 禁用 IP', @@ -327,25 +291,6 @@ final class CloudAdminHostNetworkService $revision = $revisionBase + 1; $now = time(); - if ($attachment === null) { - $attachment = new CloudHostNetworkAttachment(); - $attachment->attachment_key = $attachmentKey; - $attachment->host_id = (int) $lockedHost->id; - $attachment->vlan_id = null; - $attachment->routing_table = null; - $attachment->state = 'disabled'; - $attachment->priority = 0; - $attachment->desired_revision = 0; - $attachment->observed_revision = 0; - $attachment->sync_state = 'never'; - $attachment->last_error_code = ''; - $attachment->created_at = $now; - } - $attachment->line_id = (int) $resourcePool->line_id; - $attachment->name = mb_substr($selector, 0, 80); - $attachment->network_mode = 'selector'; - $attachment->network_selector = $selector; - if ($pool === null) { $pool = new CloudPublicIpPool(); $pool->pool_key = $poolKey; @@ -377,20 +322,9 @@ final class CloudAdminHostNetworkService $pool->last_error_code = ''; $pool->updated_at = $now; - // The attachment row must exist before its identifier can be - // referenced by the pool row. Both remain inside this transaction. - // Pool revisions are independent. The parent revision represents - // evidence for the shared selector, so another child mutation - // must not invalidate an already confirmed egress attachment. - $attachment->desired_revision = max( - 1, (int) $attachment->desired_revision - ); - $attachment->updated_at = $now; - $attachment->save(); $pool->network_attachment_id = (int) $attachment->id; $pool->save(); self::materializeIpLedger($pool); - self::refreshAttachmentAggregate($attachment); return [ 'replay' => false, @@ -398,7 +332,8 @@ final class CloudAdminHostNetworkService 'payload' => [ 'revision' => $revision, 'state' => $desired['state'], - 'network_selector' => $selector, + 'network_attachment_id' => (int) $attachment->id, + 'network_selector' => (string) $attachment->network_selector, 'cidr' => $desired['cidr'], 'gateway' => $desired['gateway'], 'dns_servers' => $desired['dns_servers'], @@ -414,6 +349,41 @@ final class CloudAdminHostNetworkService { $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); + $testedSelectors = $agent === null ? [] + : CloudAgentSettingsService::testedNetworkSelectors($agent); + $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, + $testedSelectors, + $activeLineIds + ); + $attachments[] = $dto; + $attachmentsById[(int) $attachmentRow->id] = $dto; + } $byKey = []; foreach ($dbRows as $row) { $byKey[(string) $row->pool_key] = $row; @@ -438,10 +408,16 @@ final class CloudAdminHostNetworkService 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) + $row === null ? 0 : ($occupied[(int) $row->id] ?? 0), + $attachmentsById[$attachmentId] + ?? self::missingAttachmentDto($attachmentId) ); $seen[$key] = true; } @@ -453,20 +429,20 @@ final class CloudAdminHostNetworkService $items[] = self::poolDto( $row, null, - $occupied[(int) $row->id] ?? 0 + $occupied[(int) $row->id] ?? 0, + $attachmentsById[(int) $row->network_attachment_id] + ?? self::missingAttachmentDto( + (int) $row->network_attachment_id + ) ); } - $context = $this->lineContext((int) $host->id); return [ 'host' => [ 'id' => (int) $host->id, 'name' => self::safeText((string) $host->name, 80), - 'default_network' => self::safeText( - (string) $host->default_network, 128 - ), ], - 'line' => $context, + 'attachments' => $attachments, 'items' => $items, 'count' => count($items), 'maximum' => self::MAX_POOLS, @@ -474,24 +450,6 @@ final class CloudAdminHostNetworkService ]; } - private function lineContext(int $hostId): ?array - { - $host = CloudHost::find($hostId); - $rows = CloudHostResourcePoolMembership::where('host_id', $hostId) - ->orderBy('resource_pool_id')->orderBy('id')->get(); - $membership = $host === null ? null - : CloudHostPoolMembershipService::selected($rows); - $resourcePool = $membership === null ? null - : CloudResourcePool::find((int) $membership->resource_pool_id); - $lineId = $resourcePool === null ? null : (int) $resourcePool->line_id; - $line = $lineId === null ? null : CloudNetworkLine::find($lineId); - return $line === null ? null : [ - 'id' => (int) $line->id, - 'name' => self::safeText((string) $line->name, 80), - 'status' => self::safeText((string) $line->status, 16), - ]; - } - /** The panel database is the sole catalog for scheduling and IP capacity. */ private function databaseCatalog(int $hostId): array { @@ -507,6 +465,7 @@ final class CloudAdminHostNetworkService $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 ?? '' @@ -518,13 +477,76 @@ final class CloudAdminHostNetworkService 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); + } + $testedSelectors = $agent === null ? [] + : CloudAgentSettingsService::testedNetworkSelectors($agent); + if ($agent === null || !$agent->isReady() + || (string) $attachment->verification_state !== 'verified' + || (int) $attachment->verified_agent_revision + !== (int) $agent->revision + || (int) $attachment->last_verified_at < 1 + || !in_array( + (string) $attachment->network_selector, + $testedSelectors, + true + )) { + throw new CloudError( + '所选网络接入没有当前 Agent 版本的有效验证证据,请重新测试', + 409 + ); + } + } + private static function normalizeInput(array $body, int $status = 422): array { + $attachmentId = $body['network_attachment_id'] ?? null; $name = $body['name'] ?? ''; $state = $body['state'] ?? null; $prefix = $body['guest_prefix_length'] ?? 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_string($name) || trim($name) === '' || mb_strlen(trim($name)) > 80 || preg_match('//u', $name) !== 1 @@ -570,6 +592,7 @@ final class CloudAdminHostNetworkService $reserved, '保留 IP', true, $cidr, $status ); return [ + 'network_attachment_id' => $attachmentId, 'name' => trim($name), 'cidr' => $cidr, 'gateway' => $gateway, @@ -727,20 +750,13 @@ final class CloudAdminHostNetworkService } private static function sameCreateRequest(CloudPublicIpPool $pool, - ?CloudHostNetworkAttachment $attachment, array $desired, - string $attachmentKey, string $selector, int $lineId): bool + array $desired): bool { return (string) $pool->name === $desired['name'] && (string) $pool->state === $desired['state'] - && !self::runtimeChanged([ - ...self::poolConfig($pool), - 'network_selector' => (string) ( - $attachment?->network_selector ?? '' - ), - ], $desired, $selector) - && $attachment !== null - && (string) $attachment->attachment_key === $attachmentKey - && (int) $attachment->line_id === $lineId; + && (int) $pool->network_attachment_id + === $desired['network_attachment_id'] + && !self::runtimeChanged(self::poolConfig($pool), $desired); } private static function poolConfig(CloudPublicIpPool $pool): array @@ -754,103 +770,25 @@ final class CloudAdminHostNetworkService ]; } - private static function runtimeChanged(array $current, array $desired, - string $selector): bool + private static function runtimeChanged(array $current, + array $desired): bool { - return self::occupiedUnsafeRuntimeChanged( - $current, $desired, $selector - ) || array_values($current['reserved_ips'] ?? []) + 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, string $selector): bool + array $desired): bool { - return (string) ($current['network_selector'] ?? $selector) !== $selector - || (string) ($current['cidr'] ?? '') !== $desired['cidr'] + return (string) ($current['cidr'] ?? '') !== $desired['cidr'] || (string) ($current['gateway'] ?? '') !== $desired['gateway'] || array_values($current['dns_servers'] ?? []) !== $desired['dns_servers'] || (int) ($current['guest_prefix_length'] ?? 0) !== $desired['guest_prefix_length']; } - /** Recompute selector availability without coupling independent pools. */ - private static function refreshAttachmentAggregate( - CloudHostNetworkAttachment $attachment): void - { - $pools = CloudPublicIpPool::where( - 'network_attachment_id', (int) $attachment->id - )->orderBy('id')->get(); - $states = $pools->pluck('state')->all(); - $attachment->state = in_array('active', $states, true) - ? 'active' - : (in_array('draining', $states, true) ? 'draining' : 'disabled'); - - $rank = [ - 'applied' => 0, - 'never' => 1, - 'pending' => 2, - 'failed' => 3, - 'uncertain' => 4, - ]; - $aggregate = $pools->isEmpty() ? 'never' : 'applied'; - $aggregateRank = $rank[$aggregate]; - $errorCode = ''; - $confirmedRevision = 0; - $desiredRevision = max(1, (int) $attachment->desired_revision); - $observedRevision = max(0, (int) $attachment->observed_revision); - foreach ($pools as $pool) { - $desiredRevision = max( - $desiredRevision, (int) $pool->desired_revision - ); - $observedRevision = max( - $observedRevision, (int) $pool->observed_revision - ); - $childState = (string) $pool->sync_state; - if ($childState === 'applied' - && (int) $pool->observed_revision - < (int) $pool->desired_revision) { - $childState = 'pending'; - } - if (!isset($rank[$childState])) { - $childState = 'uncertain'; - } - if ($childState === 'applied') { - $confirmedRevision = max( - $confirmedRevision, - (int) $pool->observed_revision - ); - } - if ($rank[$childState] > $aggregateRank) { - $aggregate = $childState; - $aggregateRank = $rank[$childState]; - $candidate = (string) $pool->last_error_code; - $errorCode = preg_match('/^[a-z0-9_]{1,64}$/D', $candidate) === 1 - ? $candidate : 'host_public_pool_child_' . $childState; - } - } - if ($confirmedRevision > 0) { - // One applied child is sufficient to keep the shared selector - // usable; a failed sibling does not rewrite another pool's intent. - $evidenceRevision = max( - $desiredRevision, $observedRevision, $confirmedRevision - ); - $attachment->desired_revision = $evidenceRevision; - $attachment->observed_revision = $evidenceRevision; - $attachment->sync_state = 'applied'; - $attachment->last_error_code = ''; - } else { - $attachment->desired_revision = $desiredRevision; - $attachment->observed_revision = min( - $observedRevision, max(0, $desiredRevision - 1) - ); - $attachment->sync_state = $aggregate; - $attachment->last_error_code = $errorCode; - } - $attachment->save(); - } - /** Materialize the configured CIDR into the panel-owned address ledger. */ private static function materializeIpLedger(CloudPublicIpPool $pool): void { @@ -909,10 +847,83 @@ final class CloudAdminHostNetworkService } } + private static function attachmentDto( + CloudHostNetworkAttachment $attachment, + ?CloudNetworkLine $line, + ?CloudHostAgent $agent, + array $testedSelectors, + array $activeLineIds + ): array { + $storedVerification = (string) $attachment->verification_state; + $currentEvidence = $agent !== null && $agent->isReady() + && (int) $attachment->verified_agent_revision + === (int) $agent->revision + && (int) $attachment->last_verified_at > 0 + && in_array( + (string) $attachment->network_selector, + $testedSelectors, + true + ); + $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 + int $occupied, ?array $attachment): 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( @@ -936,7 +947,10 @@ final class CloudAdminHostNetworkService $row?->observed_revision ?? $live['revision'] ), 'live_revision' => $row === null ? null : (int) $row->observed_revision, - 'network_selector' => (string) ($live['network_selector'] ?? ''), + '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') diff --git a/web/public/cloud/admin-hosts.js b/web/public/cloud/admin-hosts.js index e8edd99b..6ee756cd 100644 --- a/web/public/cloud/admin-hosts.js +++ b/web/public/cloud/admin-hosts.js @@ -14,7 +14,7 @@ const { const root = document.querySelector('[data-cloud-admin]'); const byId = id => document.getElementById(id); -const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, configBusy: false, configOpener: null, configScroll: null, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], taskObservers: new Set() }; +const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, configBusy: false, configOpener: null, configScroll: null, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkAttachmentBusy: false, networkAttachmentOpener: null, networkAttachmentScroll: null, networkAttachmentPayload: null, networkAttachmentCandidates: [], networkAttachmentEpoch: 0, networkAttachmentHostId: '', networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], taskObservers: new Set() }; const requestRuntime = window.VenixAdminRequestRuntime.create({ csrfToken: () => state.csrf, taskReceiptValidator: taskUrl, @@ -235,6 +235,7 @@ function hostDrawerNotice(id, message, error = false) { } const hostStorageNotice = hostDrawerNotice.bind(null, 'host-storage-status'); const hostSchedulingNotice = hostDrawerNotice.bind(null, 'host-scheduling-status'); +const hostNetworkAttachmentNotice = hostDrawerNotice.bind(null, 'host-network-attachments-status'); const hostNetworkPoolNotice = hostDrawerNotice.bind(null, 'host-network-pools-status'); const hostVpcTransportNotice = hostDrawerNotice.bind(null, 'host-vpc-transport-status'); function lockHostDrawerScroll(drawer) { @@ -330,6 +331,7 @@ function openHostConfigTool(kind) { if (!hostId || state.configBusy) return; const openers = { scheduling: openHostScheduling, + networkAttachments: openHostNetworkAttachments, networkPools: openHostNetworkPools, vpc: openHostVpcTransport, storage: openHostStorage, @@ -662,6 +664,195 @@ async function deleteHostMembership(item, button) { } catch (error) { hostSchedulingNotice(error.message, true); } finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; } } +function networkAttachmentStateLabel(value) { return ({ active: '启用', draining: '排空', disabled: '停用' })[value] || '状态异常'; } +function networkAttachmentVerificationLabel(value) { return ({ verified: '已验证', stale: '验证已过期', failed: '验证失败', never: '尚未验证' })[value] || '验证状态异常'; } +function addSelectOption(select, value, label, disabled = false) { + const option = element('option', '', label); option.value = String(value); option.disabled = disabled; select.append(option); return option; +} +function fillNetworkAttachmentLineSelect(select, selected = '') { + select.replaceChildren(); + const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : []; + addSelectOption(select, '', lines.length ? '请选择宿主机有效线路' : '当前宿主机没有可用线路', true); + for (const line of lines) addSelectOption(select, Number(line.id), `${line.name}(${line.status || 'active'})`); + const current = String(selected || ''); + if (current && !lines.some(line => String(line.id) === current)) addSelectOption(select, current, `线路 #${current}(关系已失效)`, true); + select.value = current; +} +function fillNetworkAttachmentSelectorSelect(select, selected = '') { + select.replaceChildren(); + const candidates = Array.isArray(state.networkAttachmentCandidates) ? state.networkAttachmentCandidates : []; + addSelectOption(select, '', candidates.length ? '请选择 Agent 已测试候选' : 'Agent 没有已测试候选', true); + for (const selector of candidates) addSelectOption(select, selector, selector); + const current = String(selected || ''); + if (current && !candidates.includes(current)) addSelectOption(select, current, `${current}(候选已失效)`, true); + select.value = current; +} +function networkAttachmentStateSelect(name, value) { + const select = document.createElement('select'); select.className = 'form-select'; select.name = name; + for (const [stateValue, label] of [['active', '启用'], ['draining', '排空'], ['disabled', '停用']]) addSelectOption(select, stateValue, label); + select.value = value || 'disabled'; return select; +} +function networkAttachmentBody(form, creating = false) { + const value = name => form.elements.namedItem(name)?.value ?? ''; + const lineId = Number(value('line_id')); const priority = Number(value('priority')); + if (!Number.isInteger(lineId) || lineId < 1) throw new Error('请选择有效线路。'); + if (!Number.isInteger(priority) || priority < -1000000 || priority > 1000000) throw new Error('优先级必须是 -1000000 至 1000000 的整数。'); + const selector = value('network_selector'); + if (!state.networkAttachmentCandidates.includes(selector)) throw new Error('请选择 Agent 最近一次完整能力测试中的网络候选。'); + const body = { name: value('name').trim(), line_id: lineId, network_selector: selector, state: value('state'), priority }; + if (creating) body.request_key = form.dataset.requestKey || ''; + else body.expected_revision = Number(value('expected_revision')); + if (creating && !/^[0-9a-f]{32}$/.test(body.request_key)) throw new Error('创建请求标识已失效,请重新打开网络接入。'); + if (!creating && (!Number.isInteger(body.expected_revision) || body.expected_revision < 1)) throw new Error('网络接入版本无效,请刷新后重试。'); + return body; +} +function renderNetworkAttachmentForm(item) { + const form = element('form', 'cloud-admin-form-section'); form.dataset.attachmentKey = item.attachment_key; + const expected = networkPoolInput('hidden', 'expected_revision', Number(item.config_revision || 0)); + const heading = element('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap mb-3'); + const copy = element('div', 'min-w-0'); copy.append(element('h6', 'mb-1', item.name || item.network_selector), element('div', 'text-muted admin-mono fs-13', item.attachment_key)); + const badge = element('span', `badge ${item.ready === true ? 'bg-success-subtle text-success' : 'bg-light text-dark'}`, `${networkAttachmentStateLabel(item.state)} · ${networkAttachmentVerificationLabel(item.verification_state)}`); + heading.append(copy, badge); + const name = networkPoolInput('text', 'name', item.name, { required: true, maxLength: 80 }); + const line = document.createElement('select'); line.className = 'form-select'; line.name = 'line_id'; line.required = true; fillNetworkAttachmentLineSelect(line, item.line_id); + const selector = document.createElement('select'); selector.className = 'form-select admin-mono'; selector.name = 'network_selector'; selector.required = true; fillNetworkAttachmentSelectorSelect(selector, item.network_selector); + const status = networkAttachmentStateSelect('state', item.state); + const priority = networkPoolInput('number', 'priority', Number(item.priority || 0), { required: true, min: -1000000, max: 1000000 }); + for (const [control, suffix] of [[name, 'name'], [line, 'line'], [selector, 'selector'], [status, 'state'], [priority, 'priority']]) control.id = `host-network-attachment-${item.attachment_key}-${suffix}`; + const grid = element('div', 'cloud-admin-form-grid'); + grid.append(networkPoolField('接入名称', name, true), networkPoolField('所属线路', line), networkPoolField('Agent 网络候选', selector), networkPoolField('运行状态', status), networkPoolField('优先级', priority)); + const verifiedAt = Number(item.last_verified_at || 0) > 0 ? new Date(Number(item.last_verified_at) * 1000).toLocaleString() : '从未'; + const error = item.verification_error_code ? ` · ${item.verification_error_code}` : ''; + const metadata = element('p', 'form-text mb-0', `配置版本 ${Number(item.config_revision || 0)} · Agent 验证版本 ${Number(item.verified_agent_revision || 0)} · 最近验证 ${verifiedAt}${error}`); + const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3'); actions.append(metadata); + const buttons = element('div', 'd-flex gap-2 flex-wrap'); + const test = element('button', 'btn btn-light', '验证接入'); test.type = 'button'; test.disabled = !canManage; test.addEventListener('click', () => testHostNetworkAttachment(item.attachment_key, Number(item.config_revision || 0), test)); + const save = element('button', 'btn btn-outline-primary', '保存接入'); save.type = 'submit'; save.disabled = !canManage; buttons.append(test, save); actions.append(buttons); + form.addEventListener('submit', event => saveHostNetworkAttachment(event, item.attachment_key)); + form.append(expected, heading, grid, actions); + if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true; + return form; +} +function networkAttachmentContextCurrent(hostId, epoch) { + const dialog = byId('host-network-attachments-drawer'); + return dialog?.open === true && state.networkAttachmentEpoch === epoch && String(state.networkAttachmentHostId) === String(hostId); +} +function syncNetworkAttachmentButtons() { + const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : []; + const form = byId('host-network-attachment-create-form'); + const ready = state.networkAttachmentCandidates.length > 0 && lines.length > 0 && /^[0-9a-f]{32}$/.test(form?.dataset?.requestKey || ''); + byId('host-network-attachment-discover').disabled = !canManage || state.networkAttachmentBusy; + byId('host-network-attachment-create-submit').disabled = !canManage || state.networkAttachmentBusy || !ready; +} +function prepareNetworkAttachmentCreateForm(reset = true) { + const form = byId('host-network-attachment-create-form'); + if (reset) { + form.reset(); + try { form.dataset.requestKey = newNetworkAttachmentRequestKey(); } + catch { delete form.dataset.requestKey; } + } + fillNetworkAttachmentLineSelect(byId('host-network-attachment-new-line')); + fillNetworkAttachmentSelectorSelect(byId('host-network-attachment-new-selector')); + byId('host-network-attachment-new-state').value = 'disabled'; byId('host-network-attachment-new-priority').value = '0'; + syncNetworkAttachmentButtons(); +} +function clearNetworkAttachmentPayload() { + state.networkAttachmentPayload = null; state.networkAttachmentCandidates = []; state.networkAttachmentHostId = ''; + byId('host-network-attachments-list')?.replaceChildren(); byId('host-network-attachments-summary')?.replaceChildren(); + syncNetworkAttachmentButtons(); +} +function renderHostNetworkAttachments(payload, hostId, epoch, resetCreate = true) { + if (!networkAttachmentContextCurrent(hostId, epoch)) return false; + if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机网络接入响应与当前抽屉不一致,请重新打开。'); + state.networkAttachmentPayload = payload; + state.networkAttachmentCandidates = Array.isArray(payload?.agent?.network_selectors) ? [...new Set(payload.agent.network_selectors)] : []; + const items = Array.isArray(payload.items) ? payload.items : []; + byId('host-network-attachments-title').textContent = `${payload.host.name || `宿主机 #${payload.host.id}`} · 网络接入`; + const cachedHost = state.hosts.find(host => Number(host.id) === Number(hostId)); + const summary = byId('host-network-attachments-summary'); summary.replaceChildren(); + for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network || payload.host.default_network)], ['Agent 版本 / 已测试版本', `${Number(payload?.agent?.revision || 0)} / ${Number(payload?.agent?.tested_revision || 0)}`], ['网络接入', `${items.length} / ${Number(payload.maximum || 64)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? 'admin-mono' : '', value)); + const list = byId('host-network-attachments-list'); list.replaceChildren(); + if (!items.length) list.append(element('p', 'text-muted py-3', '暂无网络接入。请先确认 Agent 已完成当前版本能力测试,再从候选中创建。')); + for (const item of items) list.append(renderNetworkAttachmentForm(item)); + prepareNetworkAttachmentCreateForm(resetCreate); + hostNetworkAttachmentNotice('网络接入的线路与 selector 独立验证;公网地址池只能绑定已验证且启用的接入。'); + return true; +} +function closeHostNetworkAttachments() { + ++state.networkAttachmentEpoch; state.networkAttachmentBusy = false; clearNetworkAttachmentPayload(); + const dialog = byId('host-network-attachments-drawer'); if (!dialog?.open) { finishHostDrawerClose('networkAttachment'); return; } + closeHostDrawer('host-network-attachments-drawer', 'networkAttachment'); +} +async function openHostNetworkAttachments(hostId, opener) { + if (state.networkAttachmentBusy) return; + const epoch = ++state.networkAttachmentEpoch; clearNetworkAttachmentPayload(); state.networkAttachmentHostId = String(hostId); + state.networkAttachmentBusy = true; state.networkAttachmentOpener = opener; syncNetworkAttachmentButtons(); + const dialog = byId('host-network-attachments-drawer'); hostNetworkAttachmentNotice('正在读取宿主机网络接入…'); + if (!dialog.open) { lockHostDrawerScroll('networkAttachment'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); } + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`); + if (networkAttachmentContextCurrent(hostId, epoch)) renderHostNetworkAttachments(payload, hostId, epoch); + } catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); } + finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } } +} +function newNetworkAttachmentRequestKey() { + if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器无法生成安全的创建请求标识,请升级浏览器后重试。'); + const bytes = new Uint8Array(16); globalThis.crypto.getRandomValues(bytes); + return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join(''); +} +async function discoverHostNetworkAttachments() { + const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch; + if (!hostId || !canManage || state.networkAttachmentBusy) return; + state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在从 Agent 重新发现网络候选…'); + try { + const discovered = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/discover`, { method: 'POST', body: {} }); + if (!networkAttachmentContextCurrent(hostId, epoch)) return; + const tested = Array.isArray(state.networkAttachmentPayload?.agent?.network_selectors) ? state.networkAttachmentPayload.agent.network_selectors : []; + const live = Array.isArray(discovered?.network_selectors) ? discovered.network_selectors : []; + state.networkAttachmentCandidates = live.filter(selector => tested.includes(selector)); + const list = byId('host-network-attachments-list'); list.replaceChildren(); + for (const item of state.networkAttachmentPayload?.items || []) list.append(renderNetworkAttachmentForm(item)); + prepareNetworkAttachmentCreateForm(false); + const omitted = live.length - state.networkAttachmentCandidates.length; + hostNetworkAttachmentNotice(omitted > 0 ? `已发现 ${live.length} 个候选,其中 ${omitted} 个尚无完整 Agent 测试证据;请先重新测试 Agent。` : `已核对 ${live.length} 个 Agent 候选。`, omitted > 0); + } catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); } + finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } } +} +async function createHostNetworkAttachment(event) { + event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch; + if (!hostId || !canManage || state.networkAttachmentBusy) return; + let body; try { body = networkAttachmentBody(form, true); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; } + state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在创建网络接入…'); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`, { method: 'POST', body }); + if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已创建,请完成精确验证后再绑定公网地址池。'); } + } catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); } + finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } } +} +async function saveHostNetworkAttachment(event, attachmentKey) { + event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch; + if (!hostId || !canManage || state.networkAttachmentBusy) return; + let body; try { body = networkAttachmentBody(form); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; } + state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在保存网络接入…'); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}`, { method: 'PUT', body }); + if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已保存;selector 变化后必须重新验证。'); } + } catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); } + finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } } +} +async function testHostNetworkAttachment(attachmentKey, expectedRevision, button) { + const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch; + if (!hostId || !canManage || state.networkAttachmentBusy) return; + state.networkAttachmentBusy = true; if (button) button.disabled = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在精确验证网络接入…'); + try { + const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}/test`, { method: 'POST', body: { expected_revision: expectedRevision } }); + if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已通过当前 Agent 版本验证。'); } + } catch (error) { + if (!networkAttachmentContextCurrent(hostId, epoch)) return; + try { renderHostNetworkAttachments(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`), hostId, epoch); } catch {} + hostNetworkAttachmentNotice(error.message, true); + } finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; if (button?.isConnected) button.disabled = false; syncNetworkAttachmentButtons(); } } +} function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; } function networkPoolInput(type, name, value, options = {}) { const control = document.createElement(type === 'textarea' ? 'textarea' : type === 'select' ? 'select' : 'input'); @@ -690,13 +881,45 @@ function networkPoolField(label, control, wide = false) { wrapper.append(caption, control); return wrapper; } +function networkPoolAttachmentId(attachment) { return Number(attachment?.id ?? attachment?.network_attachment_id ?? 0); } +function networkPoolAttachments() { return Array.isArray(state.networkPoolPayload?.attachments) ? state.networkPoolPayload.attachments : []; } +function networkPoolAttachmentById(id) { return networkPoolAttachments().find(attachment => networkPoolAttachmentId(attachment) === Number(id)) || null; } +function networkPoolAttachmentLabel(attachment) { + const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`; + return `${attachment?.name || attachment?.network_selector || '未命名接入'} · ${line}${attachment?.ready === true ? '' : '(未就绪)'}`; +} +function fillNetworkPoolAttachmentSelect(select, selected = '', currentAttachment = null) { + select.replaceChildren(); + const attachments = networkPoolAttachments(); const selectedId = Number(selected || 0); + addSelectOption(select, '', attachments.length ? '请选择已验证网络接入' : '暂无网络接入', true); + for (const attachment of attachments) { + const id = networkPoolAttachmentId(attachment); const isCurrent = id === selectedId; + addSelectOption(select, id, networkPoolAttachmentLabel(attachment), attachment.ready !== true && !isCurrent); + } + if (selectedId > 0 && !attachments.some(attachment => networkPoolAttachmentId(attachment) === selectedId)) { + addSelectOption(select, selectedId, networkPoolAttachmentLabel(currentAttachment || { id: selectedId, name: `接入 #${selectedId}`, line_name: '关系已失效' }), false); + } + select.value = selectedId > 0 ? String(selectedId) : ''; +} +function networkPoolAttachmentDetail(id, fallback = null) { + const attachment = networkPoolAttachmentById(id) || fallback; + if (!attachment) return '选择后显示派生线路与 selector。'; + const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`; + return `派生线路:${line} · selector:${attachment.network_selector || '已失效'} · ${attachment.ready === true ? '已验证就绪' : networkAttachmentVerificationLabel(attachment.verification_state)}`; +} +function networkPoolAttachmentField(select, detail, wide = true) { + const wrapper = networkPoolField('网络接入', select, wide); wrapper.append(detail); return wrapper; +} function networkPoolBody(form) { const value = name => form.elements.namedItem(name)?.value ?? ''; const prefix = Number(value('guest_prefix_length')); const expectedRevision = Number(value('expected_revision')); + const networkAttachmentId = Number(value('network_attachment_id')); if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。'); if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new Error('地址池版本无效,请刷新后重试。'); + if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择有效的宿主机网络接入。'); return { + network_attachment_id: networkAttachmentId, name: value('name').trim(), cidr: value('cidr').trim(), gateway: value('gateway').trim(), dns_servers: formList(value('dns_servers')), reserved_ips: formList(value('reserved_ips')), guest_prefix_length: prefix, state: value('state'), expected_revision: expectedRevision, @@ -712,6 +935,10 @@ function renderNetworkPoolForm(pool) { const badge = element('span', 'badge bg-light text-dark', `${networkPoolStateLabel(pool.state)} · ${pool.sync_message || '等待应用'}`); heading.append(copy, badge); const grid = element('div', 'cloud-admin-form-grid'); + const attachment = document.createElement('select'); attachment.className = 'form-select'; attachment.name = 'network_attachment_id'; attachment.required = true; + fillNetworkPoolAttachmentSelect(attachment, pool.network_attachment_id, pool.attachment); + const attachmentDetail = element('div', 'form-text', networkPoolAttachmentDetail(pool.network_attachment_id, pool.attachment)); + attachment.addEventListener('change', () => { attachmentDetail.textContent = networkPoolAttachmentDetail(attachment.value, pool.attachment); }); const name = networkPoolInput('text', 'name', pool.name, { required: true, maxLength: 80 }); const cidr = networkPoolInput('text', 'cidr', pool.cidr, { required: true, mono: true }); const gateway = networkPoolInput('text', 'gateway', pool.gateway, { required: true, mono: true }); @@ -719,8 +946,8 @@ function renderNetworkPoolForm(pool) { const status = networkPoolInput('select', 'state', pool.state); const dns = networkPoolInput('text', 'dns_servers', Array.isArray(pool.dns_servers) ? pool.dns_servers.join(', ') : '', { required: true, mono: true }); const reserved = networkPoolInput('textarea', 'reserved_ips', Array.isArray(pool.reserved_ips) ? pool.reserved_ips.join(', ') : '', { mono: true, rows: 3 }); - for (const [control, suffix] of [[name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`; - grid.append(networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true)); + for (const [control, suffix] of [[attachment, 'attachment'], [name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`; + grid.append(networkPoolAttachmentField(attachment, attachmentDetail), networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true)); const metadata = element('p', 'form-text mb-0', `面板版本 ${Number(pool.revision || 0)} · 已应用版本 ${pool.live_revision === null ? '未确认' : Number(pool.live_revision)} · 占用 ${Number(pool.occupied_count || 0)} 个地址`); const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3'); actions.append(metadata); @@ -729,8 +956,8 @@ function renderNetworkPoolForm(pool) { form.append(expectedRevision, heading, grid); const runtimeLocked = Number(pool.occupied_count || 0) > 0; if (runtimeLocked) { - for (const control of [cidr, gateway, prefix, dns]) control.disabled = true; - form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。')); + for (const control of [attachment, cidr, gateway, prefix, dns]) control.disabled = true; + form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;网络接入、CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。')); } if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true; form.append(actions); @@ -743,10 +970,11 @@ function networkPoolContextCurrent(hostId, epoch) { } function syncNetworkPoolButtons() { const payload = state.networkPoolPayload; const items = Array.isArray(payload?.items) ? payload.items : []; + const readyAttachments = networkPoolAttachments().filter(attachment => attachment.ready === true); const add = byId('host-network-pool-add'); - if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || !payload.line || items.length >= Number(payload.maximum || 32); + if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || readyAttachments.length === 0 || items.length >= Number(payload.maximum || 32); const submit = byId('host-network-pool-create-submit'); - if (submit) submit.disabled = state.networkPoolBusy || !canManage; + if (submit) submit.disabled = state.networkPoolBusy || !canManage || readyAttachments.length === 0; } function clearNetworkPoolPayload() { state.networkPoolPayload = null; state.networkPoolHostId = ''; @@ -759,13 +987,16 @@ function renderHostNetworkPools(payload, hostId, epoch) { if (!networkPoolContextCurrent(hostId, epoch)) return false; if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机地址池响应与当前抽屉不一致,请重新打开。'); state.networkPoolPayload = payload; - const host = payload?.host || {}; const line = payload?.line || null; const items = Array.isArray(payload?.items) ? payload.items : []; + const host = payload?.host || {}; const items = Array.isArray(payload?.items) ? payload.items : []; const attachments = networkPoolAttachments(); byId('host-network-pools-title').textContent = `${host.name || `宿主机 #${host.id}`} · 公网地址池`; const summary = byId('host-network-pools-summary'); summary.replaceChildren(); - for (const [label, value] of [['默认网络接入', hostNetworkLabel(host.default_network)], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '默认网络接入' ? 'admin-mono' : '', value)); + const cachedHost = state.hosts.find(item => Number(item.id) === Number(hostId)); + for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network)], ['可用网络接入', `${attachments.filter(item => item.ready === true).length} / ${attachments.length}`], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? 'admin-mono' : '', value)); const list = byId('host-network-pools-list'); list.replaceChildren(); if (!items.length) list.append(element('p', 'text-muted py-3', '暂无公网地址池。添加后面板会生成并维护可用 IP 账本。')); for (const pool of items) list.append(renderNetworkPoolForm(pool)); + fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment')); + byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(''); const createForm = byId('host-network-pool-create-form'); createForm.hidden = true; delete createForm.dataset.requestKey; syncNetworkPoolButtons(); hostNetworkPoolNotice('每个地址池由面板保存并维护 IP 账本,宿主机 Agent 只执行明确下发的网络操作。'); @@ -802,15 +1033,21 @@ function showNetworkPoolCreate() { try { form.dataset.requestKey = newNetworkPoolRequestKey(); } catch (error) { hostNetworkPoolNotice(error.message, true); return; } byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-state').value = 'active'; form.hidden = false; + fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment')); + const firstReady = networkPoolAttachments().find(attachment => attachment.ready === true); + if (firstReady) byId('host-network-pool-new-attachment').value = String(networkPoolAttachmentId(firstReady)); + byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(byId('host-network-pool-new-attachment').value); byId('host-network-pool-new-name').focus({ preventScroll: true }); form.scrollIntoView({ behavior: 'smooth', block: 'start' }); } function hideNetworkPoolCreate() { const form = byId('host-network-pool-create-form'); form.hidden = true; delete form.dataset.requestKey; } function newNetworkPoolBody(form) { const prefix = Number(byId('host-network-pool-new-prefix').value); + const networkAttachmentId = Number(byId('host-network-pool-new-attachment').value); if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。'); + if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择已验证的宿主机网络接入。'); const requestKey = form.dataset.requestKey || ''; if (!/^[0-9a-f]{32}$/.test(requestKey)) throw new Error('创建请求标识已失效,请取消后重新添加。'); - return { name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey }; + return { network_attachment_id: networkAttachmentId, name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey }; } async function createHostNetworkPool(event) { event.preventDefault(); if (!canManage || state.networkPoolBusy) return; @@ -979,6 +1216,7 @@ async function initialize() { byId('host-new').addEventListener('click', event => openNewHostConfig(event.currentTarget)); byId('host-form').addEventListener('submit', saveHost); byId('host-config-close').addEventListener('click', closeHostConfig); const configDrawer = byId('host-config-drawer'); configDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostConfig(); }); configDrawer.addEventListener('click', event => { if (event.target === configDrawer) closeHostConfig(); }); byId('host-config-scheduling').addEventListener('click', () => openHostConfigTool('scheduling')); + byId('host-config-network-attachments').addEventListener('click', () => openHostConfigTool('networkAttachments')); byId('host-config-network-pools').addEventListener('click', () => openHostConfigTool('networkPools')); byId('host-config-vpc').addEventListener('click', () => openHostConfigTool('vpc')); byId('host-config-storage')?.addEventListener('click', () => openHostConfigTool('storage')); @@ -988,7 +1226,10 @@ async function initialize() { const storageDrawer = byId('host-storage-drawer'); storageDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostStorage(); }); storageDrawer.addEventListener('click', event => { if (event.target === storageDrawer) closeHostStorage(); }); byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-membership-create-form').addEventListener('submit', createHostMembership); byId('host-scheduling-close').addEventListener('click', closeHostScheduling); const schedulingDrawer = byId('host-scheduling-drawer'); schedulingDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostScheduling(); }); schedulingDrawer.addEventListener('click', event => { if (event.target === schedulingDrawer) closeHostScheduling(); }); + byId('host-network-attachments-close').addEventListener('click', closeHostNetworkAttachments); byId('host-network-attachment-create-form').addEventListener('submit', createHostNetworkAttachment); byId('host-network-attachment-discover').addEventListener('click', discoverHostNetworkAttachments); + const attachmentDrawer = byId('host-network-attachments-drawer'); attachmentDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkAttachments(); }); attachmentDrawer.addEventListener('click', event => { if (event.target === attachmentDrawer) closeHostNetworkAttachments(); }); byId('host-network-pools-close').addEventListener('click', closeHostNetworkPools); byId('host-network-pool-add')?.addEventListener('click', showNetworkPoolCreate); byId('host-network-pool-create-cancel').addEventListener('click', hideNetworkPoolCreate); byId('host-network-pool-create-form').addEventListener('submit', createHostNetworkPool); + byId('host-network-pool-new-attachment').addEventListener('change', event => { byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(event.currentTarget.value); }); const networkDrawer = byId('host-network-pools-drawer'); networkDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkPools(); }); networkDrawer.addEventListener('click', event => { if (event.target === networkDrawer) closeHostNetworkPools(); }); byId('host-vpc-transport-close').addEventListener('click', closeHostVpcTransport); byId('host-vpc-transport-form').addEventListener('submit', saveHostVpcTransport); byId('host-vpc-transport-discover').addEventListener('click', discoverHostVpcTransport); byId('host-vpc-transport-test').addEventListener('click', testHostVpcTransport); byId('host-vpc-transport-candidate').addEventListener('change', selectHostVpcTransportCandidate); const vpcTransportDrawer = byId('host-vpc-transport-drawer'); vpcTransportDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostVpcTransport(); }); vpcTransportDrawer.addEventListener('click', event => { if (event.target === vpcTransportDrawer) closeHostVpcTransport(); }); diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index 49913947..913ff164 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -47,6 +47,7 @@
+ {if $admin_can_manage|default:false}{/if} @@ -64,7 +65,7 @@
-
默认网络接入

选择宿主机已经存在的网桥或 libvirt 网络;面板不会创建或修改宿主机网卡。

+
兼容默认网络接入

仅供旧入口和未迁移功能兼容;公网地址池必须在“网络接入”中绑定经过 Agent 验证的线路与 selector。

@@ -207,6 +208,43 @@ + +
+
+

Network Attachments

+

网络接入

+
+ +
+
+

请选择宿主机。

+
+ +
+
+ +
新增网络接入

selector 只能从 Agent 最近一次完整能力测试的候选列表中选择,不能手工填写。

+
+
+
+
+
+
+
+
+
+ + +
+
+ +
+
+
+ default_network 仅为兼容默认值,不是公网地址池的线路或 selector 事实来源。 +
+
+
@@ -224,9 +262,10 @@