From 982aa16449d503d5fbcc78175cd187c2e162e16e Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 2 Oct 2026 05:22:10 +0800 Subject: [PATCH] feat: select available host public IPs --- engine/tests/test_app.py | 38 ++ engine/tests/test_engine_boundary.py | 12 + engine/virsh_panel/app.py | 109 ++++ engine/virsh_panel/internal.py | 2 +- .../CloudAdminInstanceController.php | 170 ++++++ web/config/routes_cloud.php | 1 + web/public/cloud/admin-instances.js | 492 ++++++++++++++++-- web/public/theme/venix/css/admin-home.css | 80 +++ .../views/venix/admin/cloud/instances.tpl | 4 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/CloudProtocolTest.php | 16 +- 11 files changed, 886 insertions(+), 40 deletions(-) diff --git a/engine/tests/test_app.py b/engine/tests/test_app.py index f58a4170..2dc9b507 100644 --- a/engine/tests/test_app.py +++ b/engine/tests/test_app.py @@ -719,6 +719,44 @@ def test_host_public_pool_round_trips_and_rejects_invalid_networks(web): assert manager.current()["public_pool_cidr"] == body["public_pool_cidr"] +def test_host_network_options_lists_only_unallocated_public_ips(web): + client, _, token, service, _manager, _ = web + csrf = setup_admin(client, token) + assert client.put("/api/v1/host", json=HOST_BODY, + headers={"X-CSRF-Token": csrf}).status_code == 200 + before = client.get("/api/v1/host/network-options") + assert before.status_code == 200 + assert before.json()["configuration_state"] == "not_configured" + body = { + **HOST_BODY, + "default_network": "bridge:br0", + "public_pool_cidr": "8.8.8.0/29", + "public_gateway": "8.8.8.1", + "public_dns_servers": ["1.1.1.1"], + "public_reserved_ips": ["8.8.8.2"], + "public_vm_prefix": 29, + } + assert client.put("/api/v1/host", json=body, + headers={"X-CSRF-Token": csrf}).status_code == 200 + service.vm["public_ip_cidr"] = "8.8.8.3/29" + service.other_vms.append({ + "uuid": "00000000-0000-4000-8000-000000000002", + "name": "other-vm", "state": "running", "public_ip_cidr": "8.8.8.4/29", + }) + response = client.get("/api/v1/host/network-options") + assert response.status_code == 200, response.text + result = response.json() + assert result["configuration_state"] == "ready" + assert result["pool_cidr"] == "8.8.8.0/29" + assert result["guest_prefix"] == 29 + assert result["available_ips"] == ["8.8.8.5/29", "8.8.8.6/29"] + assert result["available_count"] == 2 + assert "8.8.8.1/29" not in result["available_ips"] + assert "8.8.8.2/29" not in result["available_ips"] + assert "8.8.8.3/29" not in result["available_ips"] + assert "8.8.8.4/29" not in result["available_ips"] + + def test_host_accepts_provider_28_and_gateway_address_form(web): client, _, token, _service, manager, _ = web csrf = setup_admin(client, token) diff --git a/engine/tests/test_engine_boundary.py b/engine/tests/test_engine_boundary.py index 20e7699c..2f94baab 100644 --- a/engine/tests/test_engine_boundary.py +++ b/engine/tests/test_engine_boundary.py @@ -255,6 +255,18 @@ def import_user_iso_for_test(client, tmp_path, name, *, digest="e" * 64): return job["iso"]["id"] +def test_host_network_options_is_admin_read_only_and_bounded(boundary): + client, _engine, _store, _logs, _services = boundary + denied = call(client, "GET", "/internal/v1/hosts/hk/host/network-options", USER) + assert denied.status_code == 403 + response = call(client, "GET", "/internal/v1/hosts/hk/host/network-options", SUPER) + assert response.status_code == 200, response.text + payload = response.json() + assert payload["configuration_state"] == "not_configured" + assert payload["available_ips"] == [] + assert "private_key" not in response.text + + def import_cloud_template_for_test(client, tmp_path, name="Delete Cloud Image"): payload = name.encode("utf-8") digest = hashlib.sha256(payload).hexdigest() diff --git a/engine/virsh_panel/app.py b/engine/virsh_panel/app.py index caef2891..a70ad25d 100644 --- a/engine/virsh_panel/app.py +++ b/engine/virsh_panel/app.py @@ -573,6 +573,110 @@ def create_app( return f"{address}/{guest_prefix}" raise VMError("公网地址池中没有可分配的 IP,请检查已用和保留地址", 409) + def public_network_options(profile: dict, service: VMService) -> dict: + """Return a bounded, non-secret snapshot for the admin IP selector. + + The list is advisory only. The network mutation endpoint still + performs its own validation and atomic claim immediately before + changing libvirt, so a stale selector can never allocate an address + twice. + """ + pool_value = profile.get("public_pool_cidr", "") + gateway_value = profile.get("public_gateway", "") + dns_values = profile.get("public_dns_servers", []) + reserved_values = profile.get("public_reserved_ips", []) + # A host without a public pool is a valid configuration for legacy or + # private-only hosts. Return an explicit, bounded state so the admin + # drawer can explain why the selector is unavailable instead of + # turning a normal setup state into a generic 500 error. + if (not pool_value and not gateway_value and not dns_values + and not reserved_values + and profile.get("public_vm_prefix") is None): + return { + "configuration_state": "not_configured", + "pool_cidr": "", + "guest_prefix": None, + "gateway": "", + "dns_servers": [], + "available_ips": [], + "available_count": 0, + "message": "宿主机尚未配置公网地址池,暂时无法更换公网 IP。", + } + try: + network = ipaddress.IPv4Network( + profile["public_pool_cidr"], strict=True) + gateway = ipaddress.IPv4Address(profile["public_gateway"]) + guest_prefix = profile.get("public_vm_prefix") + if guest_prefix is None: + guest_prefix = network.prefixlen + if (not 24 <= network.prefixlen <= 30 + or not network.network_address.is_global + or not network.broadcast_address.is_global + or gateway not in network + or gateway in (network.network_address, network.broadcast_address) + or isinstance(guest_prefix, bool) + or not isinstance(guest_prefix, int) + or not 24 <= guest_prefix <= network.prefixlen + or not isinstance(dns_values, list) + or not isinstance(reserved_values, list)): + raise ValueError + dns = [ipaddress.IPv4Address(value) for value in dns_values] + reserved = [ipaddress.IPv4Address(value) for value in reserved_values] + if not dns or len(dns) > 4 or len(reserved) > 254: + raise ValueError + if any(not address.is_global for address in dns): + raise ValueError + if any(address not in network + or address in (network.network_address, network.broadcast_address) + for address in reserved): + raise ValueError + blocked = {network.network_address, network.broadcast_address, gateway, + *dns, *reserved} + try: + host_address = ipaddress.IPv4Address(profile.get("host", "")) + except (TypeError, ValueError): + host_address = None + if host_address is not None: + blocked.add(host_address) + except (KeyError, TypeError, ValueError) as exc: + raise VMError("宿主机公网地址池配置损坏,请管理员重新保存设置", 500) from exc + + for existing_vm in service.list_vms(): + configured = existing_vm.get("public_ip_cidr") + if not isinstance(configured, str): + continue + try: + address = ipaddress.IPv4Address(configured.split("/", 1)[0]) + except ValueError: + continue + if address in network: + blocked.add(address) + + scope_prefix = f"{host_scope(profile)}." + if data_store is not None: + for key in data_store.list("ip_claim"): + if not key.startswith(scope_prefix): + continue + try: + address = ipaddress.IPv4Address(key[len(scope_prefix):]) + except ValueError: + continue + if address in network: + blocked.add(address) + + available = [f"{address}/{guest_prefix}" for address in network.hosts() + if address not in blocked] + return { + "configuration_state": "ready", + "pool_cidr": str(network), + "guest_prefix": guest_prefix, + "gateway": str(gateway), + "dns_servers": [str(value) for value in dns], + "available_ips": available, + "available_count": len(available), + "message": "目标地址仍会由引擎在提交时再次校验并原子占用。", + } + def claim_explicit_public_ip(profile: dict, public_ip_cidr: str, vm_id: str) -> None: if data_store is None: @@ -1478,6 +1582,11 @@ def create_app( def host(_session: Session = Depends(require_admin)): return _public_host(manager.current()) + @app.get("/api/v1/host/network-options") + def host_network_options(_session: Session = Depends(require_admin)): + profile = current_profile() + return public_network_options(profile, current_service()) + @app.post("/api/v1/host/scan") def scan_host(body: HostScanBody, _session: Session = Depends(require_admin_write)): return manager.scan(body.host, body.port) diff --git a/engine/virsh_panel/internal.py b/engine/virsh_panel/internal.py index 3a75c0a5..4f40db9c 100644 --- a/engine/virsh_panel/internal.py +++ b/engine/virsh_panel/internal.py @@ -59,7 +59,7 @@ JSON_LIMIT = 1024 * 1024 CLOUD_UPLOAD_IDLE_SECONDS = 60 CLOUD_UPLOAD_WRITE_BYTES = 1024 * 1024 READ_PATHS = ( - r"host", r"resources", r"vm-templates", r"rescue-templates", r"user-isos", r"vms", + r"host", r"host/network-options", r"resources", r"vm-templates", r"rescue-templates", r"user-isos", r"vms", r"vm-states", r"vm-metadata", r"user-isos/[0-9a-f]{32}", rf"vms/{VM_ID}(?:/state|/metrics|/traffic/daily|/rescue)?", diff --git a/web/app/Controllers/CloudAdminInstanceController.php b/web/app/Controllers/CloudAdminInstanceController.php index a951d70f..5a39827e 100644 --- a/web/app/Controllers/CloudAdminInstanceController.php +++ b/web/app/Controllers/CloudAdminInstanceController.php @@ -2,9 +2,12 @@ namespace App\Controllers; +use App\Models\CloudHost; +use App\Models\CloudJob; use App\Services\Cloud\CloudAccess; use App\Services\Cloud\CloudAdminInstanceService; use App\Services\Cloud\CloudError; +use App\Services\Cloud\CloudEngineClient; use App\Services\Cloud\CloudInput; use App\Services\Cloud\CloudJobService; @@ -27,6 +30,94 @@ final class CloudAdminInstanceController ))->withHeader('Cache-Control', 'private, no-store'); } + /** + * Return only the current host network choices needed by the IP selector. + * The normal instance detail stays database-only; this endpoint explicitly + * asks the private engine for a fresh, non-secret address-pool snapshot. + */ + public function networkOptions($request, $response, $args) + { + $actor = $request->getAttribute('cloud_actor') ?? CloudAccess::actor(false); + CloudAccess::manage($actor); + $instance = CloudAccess::instance((string) ($args['id'] ?? ''), $actor); + $spec = json_decode((string) $instance->spec_json, true); + if (!is_array($spec) || array_is_list($spec) + || ($spec['managed'] ?? false) !== true + || ($spec['os_source'] ?? null) !== 'cloud_template' + || !is_string($spec['public_ip_cidr'] ?? null) + || trim($spec['public_ip_cidr']) === '') { + throw new CloudError('当前虚拟机不是支持网络配置的面板云镜像实例', 409); + } + $host = CloudHost::find($instance->host_id); + if ($host === null) { + throw new CloudError('虚拟机所属宿主机不存在,无法读取地址池', 409); + } + $profile = (new CloudEngineClient())->host( + (int) $host->id, 'GET', 'host/network-options', $actor + ); + $gateway = self::safeIpv4($profile['gateway'] ?? null); + $dnsServers = self::safeIpv4List($profile['dns_servers'] ?? null, 4); + $guestPrefix = self::safePrefix($profile['guest_prefix'] ?? null); + $blocked = array_values(array_filter([$gateway, ...$dnsServers])); + $rawAvailable = $profile['available_ips'] ?? null; + $availableOverflow = is_array($rawAvailable) && count($rawAvailable) > 254; + $available = []; + foreach (is_array($rawAvailable) ? array_slice($rawAvailable, 0, 254) : [] as $value) { + $cidr = self::safePublicIpCidr($value); + $address = $cidr === null ? null : explode('/', $cidr, 2)[0]; + $parts = $cidr === null ? [] : explode('/', $cidr, 2); + if ($cidr !== null && $guestPrefix !== null + && (int) ($parts[1] ?? 0) === $guestPrefix + && self::cidrInPool($cidr, $profile['pool_cidr'] ?? null) + && !in_array($address, $blocked, true)) { + $available[] = $cidr; + } + } + $available = array_values(array_unique($available)); + $configurationState = in_array($profile['configuration_state'] ?? null, + ['ready', 'not_configured', 'invalid', 'drift'], true) + ? $profile['configuration_state'] : 'unavailable'; + if (!is_array($rawAvailable) || $availableOverflow) { + $configurationState = 'unavailable'; + $available = []; + } + $currentCidr = self::safePublicIpCidr($spec['public_ip_cidr']); + $message = !is_array($rawAvailable) + ? '宿主机返回的可用公网 IP 列表格式异常,请先检查引擎状态。' + : ($availableOverflow + ? '宿主机返回的可用公网 IP 列表超出安全上限,请先检查地址池配置。' + : (is_string($profile['message'] ?? null) + ? mb_substr($profile['message'], 0, 240) : '')); + $activeJob = CloudJob::where('instance_id', $instance->id) + ->whereIn('status', ['queued', 'running', 'uncertain']) + ->orderByDesc('id')->first(['id', 'kind', 'status', 'updated_at']); + $active = (string) $instance->status === 'active'; + return $response->withJson([ + 'instance_id' => (string) $instance->id, + 'host_id' => (string) $host->id, + 'host_name' => (string) $host->name, + 'region' => (string) $host->region, + 'current_ip_cidr' => $currentCidr, + 'pool_cidr' => self::safeText($profile['pool_cidr'] ?? null, 32), + 'guest_prefix' => $guestPrefix, + 'gateway' => $gateway, + 'dns_servers' => $dnsServers, + 'available_ips' => $available, + 'available_count' => count($available), + 'configuration_state' => $configurationState, + 'active_job' => $activeJob === null ? null : [ + 'id' => (string) $activeJob->id, + 'kind' => (string) $activeJob->kind, + 'status' => (string) $activeJob->status, + 'updated_at' => max(0, (int) $activeJob->updated_at), + ], + 'can_change' => $active && $activeJob === null + && $configurationState === 'ready' + && $available !== [], + 'message' => $message, + ])->withHeader('Cache-Control', 'private, no-store'); + } + /** * Queue a controlled same-host public IPv4 replacement. * @@ -69,4 +160,83 @@ final class CloudAdminInstanceController 'public_ip_cidr' => $cidr, ], 202)->withHeader('Cache-Control', 'no-store'); } + + private static function safeText($value, int $length): ?string + { + if (!is_string($value) || trim($value) !== $value || $value === '' + || strlen($value) > $length || preg_match('/[\x00-\x1f\x7f]/', $value) === 1) { + return null; + } + return $value; + } + + private static function safePrefix($value): ?int + { + return is_int($value) && $value >= 24 && $value <= 30 ? $value : null; + } + + private static function safeIpv4($value): ?string + { + return is_string($value) && trim($value) === $value + && filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) !== false + ? $value : null; + } + + private static function safeIpv4List($value, int $limit): array + { + if (!is_array($value)) { + return []; + } + $result = []; + foreach (array_slice($value, 0, $limit) as $item) { + $ip = self::safeIpv4($item); + if ($ip !== null) { + $result[] = $ip; + } + } + return array_values(array_unique($result)); + } + + private static function safePublicIpCidr($value): ?string + { + try { + $cidr = CloudInput::publicIpCidr($value); + } catch (\Throwable $error) { + return null; + } + [$address, $prefix] = explode('/', $cidr, 2); + $prefix = (int) $prefix; + return $prefix >= 24 && $prefix <= 30 ? $address . '/' . $prefix : null; + } + + private static function cidrInPool(string $cidr, $pool): bool + { + $target = self::ipv4Number(explode('/', $cidr, 2)[0]); + $parts = is_string($pool) ? explode('/', trim($pool), 2) : []; + $network = isset($parts[0], $parts[1]) ? self::ipv4Number($parts[0]) : null; + $prefix = isset($parts[1]) && ctype_digit($parts[1]) ? (int) $parts[1] : -1; + if ($target === null || $network === null || $prefix < 24 || $prefix > 30) { + return false; + } + $block = 2 ** (32 - $prefix); + if (floor($target / $block) !== floor($network / $block)) { + return false; + } + $networkBase = floor($network / $block) * $block; + return $target !== $networkBase && $target !== $networkBase + $block - 1; + } + + private static function ipv4Number($value): ?int + { + if (!is_string($value) || filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { + return null; + } + $packed = inet_pton($value); + if ($packed === false || strlen($packed) !== 4) { + return null; + } + $parts = unpack('Nnumber', $packed); + return is_array($parts) && isset($parts['number']) + ? (int) sprintf('%u', $parts['number']) : null; + } } diff --git a/web/config/routes_cloud.php b/web/config/routes_cloud.php index a13bdd67..bd3b6bb1 100644 --- a/web/config/routes_cloud.php +++ b/web/config/routes_cloud.php @@ -51,6 +51,7 @@ $app->group('/api/v1', function () { $this->post('/admin/hosts/scan', 'App\Controllers\CloudAdminController:scan'); $this->get('/admin/instances', 'App\Controllers\CloudAdminInstanceController:index'); $this->get('/admin/instances/{id:[0-9]+}', 'App\Controllers\CloudAdminInstanceController:detail'); + $this->get('/admin/instances/{id:[0-9]+}/network-options', 'App\Controllers\CloudAdminInstanceController:networkOptions'); $this->patch('/admin/instances/{id:[0-9]+}/network', 'App\Controllers\CloudAdminInstanceController:network'); $this->get('/admin/operations', 'App\Controllers\CloudAdminOperationsController:index'); $this->get('/admin/operations/health', 'App\Controllers\CloudAdminRuntimeController:index'); diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index 86a0ef6a..d7a7d3cb 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -7,7 +7,8 @@ const state = { items: [], pagination: { page: 1, per_page: 20, total: 0, total_pages: 1 }, request: null, serial: 0, loading: false, hasData: false, active: true, timer: null, statusRequest: null, statusFailures: 0, detailRequest: null, detailId: null, - opener: null, scroll: null, networkRequest: null, + opener: null, scroll: null, networkRequest: null, networkOptionsRequest: null, + networkPollRequest: null, networkPollTimer: null, networkPollResolve: null, networkSerial: 0, }; function el(tag, className = '', text) { @@ -47,6 +48,98 @@ function date(value, short = false) { return short ? parsed.toLocaleDateString('zh-CN') : parsed.toLocaleString('zh-CN', { hour12: false }); } +function parseIPv4(value) { + const parts = String(value ?? '').trim().split('.'); + if (parts.length !== 4 || parts.some(part => !/^\d{1,3}$/.test(part))) return null; + const octets = parts.map(Number); + return octets.every(part => part >= 0 && part <= 255) ? octets : null; +} + +function ipv4Number(octets) { + return (((octets[0] << 24) >>> 0) + (octets[1] << 16) + (octets[2] << 8) + octets[3]) >>> 0; +} + +function normalizeCidr(value, fallbackPrefix = 24) { + const raw = String(value ?? '').trim(); + if (!raw) return null; + const parts = raw.split('/'); + if (parts.length > 2) return null; + if (parts.length === 2 && !/^\d+$/.test(parts[1])) return null; + const octets = parseIPv4(parts[0]); + if (!octets) return null; + const prefix = parts.length === 2 && parts[1] !== '' ? Number(parts[1]) : Number(fallbackPrefix); + if (!Number.isInteger(prefix) || prefix < 1 || prefix > 30) return null; + return { address: octets.join('.'), prefix, value: `${octets.join('.')}/${prefix}` }; +} + +function cidrContains(cidr, address) { + const network = normalizeCidr(cidr, null); + const ip = parseIPv4(address); + if (!network || !ip) return false; + const mask = network.prefix === 32 ? 0xffffffff : (0xffffffff << (32 - network.prefix)) >>> 0; + return (ipv4Number(parseIPv4(network.address)) & mask) === (ipv4Number(ip) & mask); +} + +function networkOptionsFromVm(vm) { + const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24); + const prefix = current?.prefix || 24; + return { + configured: false, + current_ip_cidr: current?.value || '', + guest_prefix: prefix, + gateway: vm.gateway || '', + dns_servers: Array.isArray(vm.dns_servers) ? vm.dns_servers : [], + public_pool_cidr: '', + available_count: 0, + available_ips: [], + configuration_state: 'not_configured', + can_change: false, + }; +} + +function networkOptionsPayload(payload, vm) { + const source = payload?.network_options || payload?.network || payload || {}; + const fallback = networkOptionsFromVm(vm); + const current = normalizeCidr(source.current_ip_cidr || vm.public_ip_cidr || vm.public_ip, fallback.guest_prefix); + const guestPrefix = Number(source.guest_prefix ?? source.public_vm_prefix ?? current?.prefix ?? fallback.guest_prefix); + const dns = Array.isArray(source.dns_servers) ? source.dns_servers.filter(value => parseIPv4(value)) : fallback.dns_servers; + const normalizedGuestPrefix = Number.isInteger(guestPrefix) && guestPrefix >= 24 && guestPrefix <= 30 + ? guestPrefix : fallback.guest_prefix; + const available = Array.isArray(source.available_ips) ? source.available_ips : []; + const availableIps = available.map(value => { + if (value && typeof value === 'object') return value.cidr || value.public_ip_cidr || value.ip || ''; + return value; + }).map(value => normalizeCidr(value, normalizedGuestPrefix)) + .filter(value => value && value.prefix === normalizedGuestPrefix) + .map(value => value.value); + return { + ...fallback, + ...source, + current_ip_cidr: current?.value || fallback.current_ip_cidr, + guest_prefix: normalizedGuestPrefix, + public_pool_cidr: String(source.public_pool_cidr || source.pool_cidr || '').trim(), + gateway: String(source.gateway || fallback.gateway || '').trim(), + dns_servers: dns, + available_count: Number.isFinite(Number(source.available_count)) + ? Math.max(0, Number(source.available_count)) : availableIps.length, + available_ips: [...new Set(availableIps)], + configuration_state: ['ready', 'not_configured', 'invalid', 'drift', 'unavailable'] + .includes(source.configuration_state) ? source.configuration_state : 'unavailable', + can_change: source.can_change === true, + }; +} + +function networkOptionSummary(options) { + const pool = options.public_pool_cidr + || (options.configuration_state === 'not_configured' ? '未配置' : '提交时由引擎校验'); + const prefix = options.guest_prefix ? `/${options.guest_prefix}` : '未记录'; + const gateway = options.gateway || '提交时由宿主机配置决定'; + const dns = options.dns_servers?.length ? options.dns_servers.join('、') : '宿主机默认 DNS'; + const available = options.available_ips?.length + ? `${options.available_ips.length} 个` : '暂无可用地址'; + return { pool, prefix, gateway, dns, available }; +} + function bytes(value) { const number = Number(value); if (value === null || value === undefined || !Number.isFinite(number) || number < 0) return '未记录'; @@ -73,7 +166,9 @@ async function api(path, controller) { try { payload = await response.json(); } catch { throw new Error('服务返回异常,请检查服务器日志后重试。'); } if (!response.ok || payload?.ret === 0) { - throw new Error(typeof payload?.detail === 'string' ? payload.detail : (payload?.message || `请求失败 (${response.status})`)); + const error = new Error(typeof payload?.detail === 'string' ? payload.detail : (payload?.message || `请求失败 (${response.status})`)); + error.status = response.status; + throw error; } return payload; } catch (error) { @@ -106,7 +201,9 @@ async function mutate(path, body, controller) { const detail = Array.isArray(payload?.detail) ? payload.detail.map(item => item?.msg || '输入错误').join(';') : payload?.detail; - throw new Error(typeof detail === 'string' ? detail : (payload?.message || `请求失败 (${response.status})`)); + const error = new Error(typeof detail === 'string' ? detail : (payload?.message || `请求失败 (${response.status})`)); + error.status = response.status; + throw error; } return payload; } catch (error) { @@ -360,21 +457,292 @@ function detailNotice(message, error = false) { node.setAttribute('role', error ? 'alert' : 'status'); } +function setNetworkFeedback(section, message, tone = 'muted') { + const node = section?.querySelector('.admin-instance-network-feedback'); + if (!node) return; + node.hidden = !message; + node.className = `admin-instance-network-feedback text-${tone} fs-13 mb-2`; + node.textContent = message || ''; +} + +function cancelNetworkActivity(reason = 'cancelled') { + clearTimeout(state.networkPollTimer); + state.networkPollTimer = null; + state.networkPollResolve?.(false); + state.networkPollResolve = null; + state.networkOptionsRequest?.abort(reason); + state.networkPollRequest?.abort(reason); + state.networkRequest?.abort(reason); + state.networkOptionsRequest = null; + state.networkPollRequest = null; + state.networkRequest = null; + state.networkSerial += 1; +} + +function networkJobState(job) { + return String(job?.status || job?.job?.status || '').toLowerCase(); +} + +function networkOptionsView(section, options, fallback = false, fallbackMessage = '') { + const summary = networkOptionSummary(options); + const status = section.querySelector('[data-network-options-status]'); + if (status) { + status.textContent = fallback + ? (fallbackMessage || '地址池详情暂不可用,暂不能选择新的公网 IP。') + : (options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。'); + status.className = `text-muted fs-12 mb-0${fallback ? ' text-warning' : ''}`; + } + const values = section.querySelector('[data-network-options-values]'); + if (!values) return; + values.replaceChildren(); + [ + ['地址池', summary.pool], + ['虚拟机前缀', summary.prefix], + ['网关', summary.gateway], + ['DNS', summary.dns], + ['可用地址', summary.available], + ].forEach(([label, value]) => { + values.append(el('dt', '', label), el('dd', 'admin-mono', value)); + }); + const select = section.querySelector('[name="public_ip_cidr"]'); + const submit = section.querySelector('button[type="submit"]'); + const hasAvailable = options.available_ips?.length > 0; + const canChange = options.can_change === true && options.configuration_state === 'ready' && hasAvailable; + if (select instanceof HTMLSelectElement) { + select.replaceChildren(new Option( + hasAvailable ? '请选择新的公网 IP' : '当前没有可用公网 IP', '')); + for (const value of options.available_ips || []) select.add(new Option(value, value)); + select.disabled = !canChange; + if (!hasAvailable || !canChange) select.setAttribute('aria-describedby', 'network-options-empty'); + else select.removeAttribute('aria-describedby'); + } + if (submit instanceof HTMLButtonElement) submit.disabled = !canChange; + const empty = section.querySelector('[data-network-options-empty]'); + if (empty) { + empty.id = 'network-options-empty'; + const activeJob = options.active_job; + empty.textContent = activeJob + ? `实例已有任务 #${activeJob.id || ''}(${jobStatus(activeJob.status)}),请等待完成后再更换。` + : (!hasAvailable + ? '当前没有可用地址,无法提交更换;请先检查地址池和占用记录。' + : (!canChange ? ({ + invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。', + drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。', + }[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。') + : '只显示该宿主机当前未分配的公网 IP。')); + empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`; + } +} + +async function loadNetworkOptions(vm, section) { + const serial = state.networkSerial; + const controller = new AbortController(); + state.networkOptionsRequest = controller; + let options = networkOptionsFromVm(vm); + let fallback = true; + let fallbackMessage = ''; + try { + const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network-options`, controller); + if (serial !== state.networkSerial || controller.signal.aborted) return; + options = networkOptionsPayload(payload, vm); + fallback = false; + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + if (serial !== state.networkSerial) return; + // The options endpoint is additive. Older deployments can still use the + // existing detail fields while the engine remains the final validator. + options = networkOptionsFromVm(vm); + fallbackMessage = error.status === 409 + ? error.message : '无法读取宿主机地址池,暂不能选择新的公网 IP。'; + } finally { + if (state.networkOptionsRequest === controller) state.networkOptionsRequest = null; + } + if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return; + section._networkOptions = options; + networkOptionsView(section, options, fallback, fallbackMessage); +} + +function targetNetworkValue(section, vm) { + const options = section._networkOptions || networkOptionsFromVm(vm); + const input = section.querySelector('[name="public_ip_cidr"]'); + const fallbackPrefix = Number(options.guest_prefix) || normalizeCidr(vm.public_ip_cidr || vm.public_ip, 24)?.prefix || 24; + if (options.can_change === false || options.configuration_state !== 'ready') { + throw new Error('宿主机网络配置尚未就绪,暂不能更换公网 IP。'); + } + if (!Array.isArray(options.available_ips) || options.available_ips.length === 0) { + throw new Error('当前宿主机没有可用公网 IP,请先补充地址池或释放地址后重试。'); + } + if (!input?.value) throw new Error('请选择新的公网 IP。'); + const parsed = normalizeCidr(input?.value, fallbackPrefix); + if (!parsed || !options.available_ips.includes(parsed.value)) { + throw new Error('请选择列表中的可用公网 IP,不支持手动填写。'); + } + if (Number(options.guest_prefix) && parsed.prefix !== Number(options.guest_prefix)) { + throw new Error(`地址前缀必须为 /${options.guest_prefix},请不要修改宿主机分配的前缀。`); + } + if (options.public_pool_cidr && !cidrContains(options.public_pool_cidr, parsed.address)) { + throw new Error(`目标地址不在宿主机地址池 ${options.public_pool_cidr} 内。`); + } + const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, parsed.prefix); + if (current?.value === parsed.value) throw new Error('新公网 IP 与当前配置相同。'); + const blocked = [options.gateway, ...(options.dns_servers || []), ...(options.public_reserved_ips || options.reserved_ips || [])] + .map(value => parseIPv4(value)?.join('.')).filter(Boolean); + if (blocked.includes(parsed.address)) throw new Error('目标地址是网关、DNS 或保留地址,不能分配给虚拟机。'); + return parsed.value; +} + +function makeNetworkConfirmation(section, vm, target, options) { + const current = normalizeCidr(vm.public_ip_cidr || vm.public_ip, options.guest_prefix || 24)?.value || '未记录'; + const confirmation = section.querySelector('[data-network-confirmation]'); + const summary = confirmation?.querySelector('[data-network-confirm-summary]'); + const check = confirmation?.querySelector('[data-network-confirm-check]'); + const submit = confirmation?.querySelector('[data-network-confirm-submit]'); + if (!confirmation || !summary || !check || !submit) return null; + const network = networkOptionSummary(options); + summary.textContent = `公网地址将从 ${current} 更换为 ${target}。运行中的实例会受控关机并重新启动,已关机实例保持关机;网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`; + check.checked = false; + submit.disabled = true; + confirmation.hidden = false; + return { confirmation, check, submit }; +} + +function waitForNetworkPoll(ms, serial) { + return new Promise(resolve => { + clearTimeout(state.networkPollTimer); + state.networkPollResolve = resolve; + state.networkPollTimer = setTimeout(() => { + state.networkPollTimer = null; + state.networkPollResolve = null; + resolve(serial === state.networkSerial); + }, ms); + }); +} + +async function refreshDetail(id) { + if (state.detailId !== String(id)) return; + state.detailRequest?.abort('refresh'); + const controller = new AbortController(); + state.detailRequest = controller; + detailNotice('正在刷新网络配置…'); + try { + const payload = await api(`/api/v1/admin/instances/${encodeURIComponent(id)}`, controller); + if (controller.signal.aborted || state.detailId !== String(id)) return; + cancelNetworkActivity('detail-refresh'); + renderDetail(payload); + detailNotice(''); + const vm = payload.instance; + const item = state.items.find(entry => String(entry.id) === String(id)); + if (item && vm) { + item.public_ip = vm.public_ip || String(vm.public_ip_cidr || '').split('/', 1)[0]; + item.public_ip_cidr = vm.public_ip_cidr; + const rowNode = Array.from(byId('instances-body').rows).find(row => row.dataset.instanceId === String(id)); + const ipNode = rowNode?.querySelector('.admin-instance-ip'); + if (ipNode) { + ipNode.replaceChildren(el('span', 'admin-mono', text(item.public_ip, '未记录'))); + if (item.public_ip) ipNode.append(copyButton(item.public_ip, '复制公网 IP')); + } + } + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + if (state.detailId === String(id)) detailNotice(`${error.message} 当前网络任务结果请在任务记录中核对。`, true); + } finally { + if (state.detailRequest === controller) state.detailRequest = null; + } +} + +async function pollNetworkJob(vm, section, target, jobId, statusUrl) { + const serial = state.networkSerial; + const path = typeof statusUrl === 'string' && statusUrl.startsWith('/api/v1/') + ? statusUrl : `/api/v1/jobs/${encodeURIComponent(jobId)}`; + for (let attempt = 0; attempt < 150; attempt += 1) { + if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return; + const controller = new AbortController(); + state.networkPollRequest = controller; + try { + const job = await api(path, controller); + if (serial !== state.networkSerial || state.detailId !== String(vm.id)) return; + const status = networkJobState(job); + const phase = job?.phase || job?.job?.phase || job?.error; + if (status === 'succeeded' || status === 'completed' || status === 'done') { + setNetworkFeedback(section, `任务 #${jobId} 已完成,正在刷新实例网络配置…`, 'success'); + detailNotice(`网络变更任务 #${jobId} 已完成,正在刷新当前公网 IP。`); + state.networkPollRequest = null; + clearTimeout(state.networkPollTimer); + state.networkPollTimer = null; + await refreshDetail(vm.id); + return; + } + if (status === 'failed' || status === 'cancelled') { + setNetworkFeedback(section, `任务 #${jobId}${phase ? `:${phase}` : '执行失败'}。请确认地址池后修改并重试。`, 'danger'); + const form = section.querySelector('.admin-instance-network-form'); + form?.removeAttribute('hidden'); + const edit = section.querySelector('[data-network-edit="open"]'); + if (edit) { edit.hidden = false; edit.disabled = false; edit.setAttribute('aria-expanded', 'true'); } + return; + } + if (status === 'uncertain') { + setNetworkFeedback(section, `任务 #${jobId} 状态待核对,不能重复提交;请先在任务记录确认宿主机结果。`, 'warning'); + const form = section.querySelector('.admin-instance-network-form'); + const select = form?.elements?.namedItem('public_ip_cidr'); + const submit = form?.querySelector('button[type="submit"]'); + form?.removeAttribute('hidden'); + if (select) select.disabled = true; + if (submit) submit.disabled = true; + const edit = section.querySelector('[data-network-edit="open"]'); + if (edit) { edit.hidden = false; edit.disabled = true; edit.title = '任务待核对,请先确认任务结果'; } + const feedback = section.querySelector('.admin-instance-network-feedback'); + if (feedback && !feedback.querySelector('[data-network-refresh]')) { + const refresh = el('button', 'btn btn-light btn-sm mt-2', '刷新任务状态'); + refresh.type = 'button'; refresh.dataset.networkRefresh = ''; + refresh.addEventListener('click', () => { refresh.disabled = true; void refreshDetail(vm.id); }); + feedback.append(document.createElement('br'), refresh); + } + return; + } + setNetworkFeedback(section, `任务 #${jobId} ${jobStatus(status || 'queued')}${phase ? ` · ${phase}` : ''}…`, 'muted'); + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + if (serial !== state.networkSerial) return; + setNetworkFeedback(section, `${error.message},将继续等待任务结果。`, 'warning'); + } finally { + if (state.networkPollRequest === controller) state.networkPollRequest = null; + } + if (!await waitForNetworkPoll(Math.min(10000, 2000 + attempt * 250), serial)) return; + } + setNetworkFeedback(section, `任务 #${jobId} 仍在执行,请稍后刷新任务记录;不要重复提交。`, 'warning'); +} + function networkEditor(vm) { const section = el('section', 'admin-instance-network-settings mt-4'); section.setAttribute('aria-labelledby', 'instance-network-title'); const heading = el('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap'); const copy = el('div'); - copy.append(el('h3', 'h6 fw-semibold mb-1', '网络配置'), el('p', 'text-muted fs-13 mb-0', '更换公网 IP 会触发一次受控重启,网关和 DNS 由宿主机地址池自动校验。')); + const title = el('h3', 'h6 fw-semibold mb-1', '网络配置'); + title.id = 'instance-network-title'; + copy.append(title, el('p', 'text-muted fs-13 mb-0', '运行中的实例会受控重启,已关机实例保持关机;地址池、网关和 DNS 由宿主机最终校验。')); heading.append(copy); const template = byId('admin-instance-network-controls'); const controls = template?.content?.cloneNode(true); const edit = controls?.querySelector('[data-network-edit="open"]'); if (edit) heading.append(edit); section.append(heading); + const current = el('div', 'admin-instance-network-current mt-3'); - current.append(el('span', 'text-muted fs-13', '当前公网地址'), el('strong', 'admin-mono', text(vm.public_ip_cidr, vm.public_ip, '未记录'))); + const currentValue = el('span', 'admin-instance-network-current-value'); + currentValue.append(el('strong', 'admin-mono', text(vm.public_ip_cidr, vm.public_ip, '未记录'))); + if (vm.public_ip) currentValue.append(copyButton(vm.public_ip, '复制当前公网 IP')); + current.append(el('span', 'text-muted fs-13', '当前公网地址'), currentValue); section.append(current); + + const optionsBox = el('div', 'admin-instance-network-options-box mt-3'); + optionsBox.append(el('p', 'text-muted fs-13 mb-2', '宿主机网络约束')); + const optionsValues = el('dl', 'admin-instance-network-options'); + optionsValues.dataset.networkOptionsValues = ''; + optionsBox.append(optionsValues, el('p', 'text-muted fs-12 mb-0', '正在读取地址池配置…')); + optionsBox.lastChild.dataset.networkOptionsStatus = ''; + optionsBox.lastChild.setAttribute('role', 'status'); + section.append(optionsBox); + if (controls) section.append(controls); const form = section.querySelector('.admin-instance-network-form'); if (!form) return section; @@ -382,43 +750,99 @@ function networkEditor(vm) { const feedback = section.querySelector('.admin-instance-network-feedback'); const submit = form.querySelector('button[type="submit"]'); const cancel = form.querySelector('[data-network-edit="cancel"]'); - input.value = String(vm.public_ip_cidr || vm.public_ip || ''); - form.addEventListener('submit', async event => { + input.value = ''; + input.disabled = true; + submit.disabled = true; + + const confirmation = el('div', 'admin-instance-network-confirmation mt-3'); + confirmation.hidden = true; + confirmation.dataset.networkConfirmation = ''; + confirmation.setAttribute('role', 'alertdialog'); + confirmation.setAttribute('aria-labelledby', `network-confirm-title-${vm.id}`); + confirmation.append(el('h4', 'h6 fw-semibold mb-2', '确认更换公网 IP')); + confirmation.lastChild.id = `network-confirm-title-${vm.id}`; + const summary = el('p', 'text-muted fs-13 mb-2'); + summary.dataset.networkConfirmSummary = ''; + confirmation.append(summary); + const checkLabel = el('label', 'admin-instance-network-confirm-check'); + const check = document.createElement('input'); + check.type = 'checkbox'; check.dataset.networkConfirmCheck = ''; + checkLabel.append(check, document.createTextNode('我确认运行中的实例会短暂重启(已关机实例保持关机),并确认目标公网 IP 无误。')); + confirmation.append(checkLabel); + const confirmActions = el('div', 'd-flex justify-content-end gap-2 flex-wrap mt-3'); + const back = el('button', 'btn btn-light btn-sm', '返回修改'); + back.type = 'button'; back.dataset.networkConfirmCancel = ''; + const confirmSubmit = el('button', 'btn btn-primary btn-sm', '确认并提交'); + confirmSubmit.type = 'button'; confirmSubmit.dataset.networkConfirmSubmit = ''; confirmSubmit.disabled = true; + confirmActions.append(back, confirmSubmit); confirmation.append(confirmActions); + section.append(confirmation); + + const activeJob = vm.active_job && ['queued', 'running', 'uncertain'].includes(String(vm.active_job.status)); + if (activeJob && edit) { + edit.disabled = true; + edit.title = `实例已有任务 #${vm.active_job.id},请等待任务结束`; + setNetworkFeedback(section, `实例已有任务 #${vm.active_job.id}(${jobStatus(vm.active_job.status)}),完成前不能更换公网 IP。`, 'warning'); + } + + const showValidationError = message => { + setNetworkFeedback(section, message, 'danger'); + input.focus(); + }; + form.addEventListener('submit', event => { event.preventDefault(); - if (state.networkRequest) return; - const value = input.value.trim(); - if (!/^\d{1,3}(?:\.\d{1,3}){3}\/\d{1,2}$/.test(value)) { - feedback.hidden = false; feedback.className = 'admin-instance-network-feedback text-danger fs-13 mb-2'; - feedback.textContent = '请输入有效的 IPv4 CIDR,例如 216.236.1.20/24。'; - input.focus(); return; - } - const controller = new AbortController(); state.networkRequest = controller; - input.disabled = true; submit.disabled = true; cancel.disabled = true; - feedback.hidden = false; feedback.className = 'admin-instance-network-feedback text-muted fs-13 mb-2'; - feedback.textContent = '正在提交网络变更任务,请勿重复提交…'; + if (state.networkRequest || activeJob) return; + let target; + try { target = targetNetworkValue(section, vm); } + catch (error) { showValidationError(error.message); return; } + const options = section._networkOptions || networkOptionsFromVm(vm); + form.hidden = true; + if (edit) edit.hidden = true; + setNetworkFeedback(section, ''); + makeNetworkConfirmation(section, vm, target, options); + section._networkTarget = target; + section.querySelector('[data-network-confirm-check]')?.focus(); + }); + input.addEventListener('input', () => { if (!feedback.hidden) setNetworkFeedback(section, ''); }); + cancel?.addEventListener('click', () => { + form.hidden = true; + confirmation.hidden = true; + if (edit) { edit.hidden = false; edit.setAttribute('aria-expanded', 'false'); } + input.value = ''; + setNetworkFeedback(section, ''); + }); + check.addEventListener('change', () => { confirmSubmit.disabled = !check.checked; }); + back.addEventListener('click', () => { + confirmation.hidden = true; form.hidden = false; if (edit) edit.hidden = false; + edit?.setAttribute('aria-expanded', 'true'); input.focus(); + }); + confirmSubmit.addEventListener('click', async () => { + if (!check.checked || state.networkRequest || activeJob) return; + const target = section._networkTarget; + const controller = new AbortController(); + state.networkRequest = controller; + check.disabled = true; confirmSubmit.disabled = true; back.disabled = true; + setNetworkFeedback(section, '正在创建网络变更任务,请勿重复提交…', 'muted'); try { const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, { - public_ip_cidr: value, confirm_restart: true, + public_ip_cidr: target, confirm_restart: true, }, controller); const jobId = result?.job_id ?? result?.job?.id ?? result?.operation_id; - const status = result?.job?.status || result?.status; - feedback.className = `admin-instance-network-feedback ${status === 'failed' ? 'text-danger' : 'text-success'} fs-13 mb-2`; - feedback.textContent = jobId - ? `网络变更任务已创建 #${jobId}(${jobStatus(status || 'queued')})。实例将在后台重启应用新地址。` - : '网络变更请求已提交,实例将在后台重启应用新地址。'; - form.hidden = true; - const edit = section.querySelector('[data-network-edit="open"]'); - if (edit) { edit.disabled = false; edit.setAttribute('aria-expanded', 'false'); } - detailNotice(jobId ? `网络变更任务已创建 #${jobId},请在任务记录中核对执行结果。` : '网络变更请求已提交,请在任务记录中核对执行结果。'); + if (!jobId) throw new Error('服务器未返回网络变更任务编号,请在任务记录中核对。'); + confirmation.hidden = true; + setNetworkFeedback(section, `任务 #${jobId} 已创建,实例将在后台重启并应用新地址…`, 'muted'); + detailNotice(`网络变更任务 #${jobId} 已创建,正在等待执行结果。`); + if (edit) { edit.hidden = true; edit.disabled = true; } + state.networkRequest = null; + void pollNetworkJob(vm, section, target, jobId, result.status_url); } catch (error) { if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; - feedback.className = 'admin-instance-network-feedback text-danger fs-13 mb-2'; - feedback.textContent = error.message; - input.disabled = false; submit.disabled = false; cancel.disabled = false; + setNetworkFeedback(section, error.message, 'danger'); + confirmation.hidden = false; check.disabled = false; confirmSubmit.disabled = !check.checked; back.disabled = false; } finally { if (state.networkRequest === controller) state.networkRequest = null; } }); + void loadNetworkOptions(vm, section); return section; } @@ -499,8 +923,7 @@ function lockDetailScroll() { function closeDetail() { state.detailRequest?.abort(); state.detailRequest = null; - state.networkRequest?.abort('closed'); - state.networkRequest = null; + cancelNetworkActivity('closed'); state.detailId = null; const dialog = byId('instance-detail'); if (dialog.open) dialog.close(); @@ -517,6 +940,7 @@ function closeDetail() { async function openDetail(id, opener) { if (!/^[1-9][0-9]*$/.test(id)) return; state.detailRequest?.abort(); + cancelNetworkActivity('detail-switch'); state.detailId = id; state.opener = opener; const controller = new AbortController(); @@ -612,7 +1036,7 @@ if (root) { // Native modal dialog traps focus; background scrolling is locked separately for iOS. window.addEventListener('popstate', () => { closeDetail(); void loadPage(new URL(location.href), 'none'); }); document.addEventListener('visibilitychange', () => { if (document.hidden) stopStatuses(); else void refreshStatuses(); }); - window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); }); + window.addEventListener('pagehide', () => { state.active = false; stopStatuses(); state.request?.abort(); state.detailRequest?.abort(); cancelNetworkActivity('pagehide'); }); window.addEventListener('pageshow', event => { state.active = true; if (event.persisted) { closeDetail(); void loadPage(new URL(location.href), 'none'); } }); if (bootstrapped) void refreshStatuses(); else void loadPage(new URL(location.href), 'none'); diff --git a/web/public/theme/venix/css/admin-home.css b/web/public/theme/venix/css/admin-home.css index 9aad6baa..fb6c66b6 100644 --- a/web/public/theme/venix/css/admin-home.css +++ b/web/public/theme/venix/css/admin-home.css @@ -346,6 +346,14 @@ html.admin-instance-detail-open body { background: #fbfcfe; } +[data-admin-instance-drawer] .admin-instance-network-current-value { + display: inline-flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + min-width: 0; +} + [data-admin-instance-drawer] .admin-instance-network-current strong { min-width: 0; color: #08785b; @@ -371,6 +379,54 @@ html.admin-instance-detail-open body { line-height: 1.5; } +[data-admin-instance-drawer] .admin-instance-network-options-box { + padding: 12px 14px; + border: 1px solid #dce5ef; + border-radius: 8px; + background: #f8fafc; +} + +[data-admin-instance-drawer] .admin-instance-network-options { + display: grid; + grid-template-columns: minmax(84px, 0.35fr) minmax(0, 1fr); + gap: 7px 12px; + margin: 0 0 8px; + font-size: 13px; +} + +[data-admin-instance-drawer] .admin-instance-network-options dt { + color: #7d8a9c; + font-weight: 600; +} + +[data-admin-instance-drawer] .admin-instance-network-options dd { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; + color: #344054; +} + +[data-admin-instance-drawer] .admin-instance-network-confirmation { + padding: 14px; + border: 1px solid rgba(224, 146, 54, 0.42); + border-radius: 8px; + background: rgba(255, 243, 218, 0.72); +} + +[data-admin-instance-drawer] .admin-instance-network-confirm-check { + display: flex; + align-items: flex-start; + gap: 8px; + color: #344054; + font-size: 13px; + line-height: 1.5; +} + +[data-admin-instance-drawer] .admin-instance-network-confirm-check input { + flex: 0 0 auto; + margin-top: 3px; +} + [data-admin-instance-drawer] .admin-instance-network-feedback { margin-top: 8px; overflow-wrap: anywhere; @@ -428,6 +484,30 @@ html.admin-instance-detail-open body { [data-admin-instance-drawer] .admin-instance-network-current strong { text-align: left; } + + [data-admin-instance-drawer] .admin-instance-network-current-value { + width: 100%; + justify-content: space-between; + } + + [data-admin-instance-drawer] .admin-instance-network-form, + [data-admin-instance-drawer] .admin-instance-network-confirmation { + padding: 12px; + } + + [data-admin-instance-drawer] .admin-instance-network-form .d-flex, + [data-admin-instance-drawer] .admin-instance-network-confirmation .d-flex { + flex-direction: column; + } + + [data-admin-instance-drawer] .admin-instance-network-form .btn, + [data-admin-instance-drawer] .admin-instance-network-confirmation .btn { + width: 100%; + } + + [data-admin-instance-drawer] .admin-instance-network-options { + grid-template-columns: minmax(76px, 0.4fr) minmax(0, 1fr); + } } .admin-stat-card h3 { diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl index 437b4aee..5ee2ca62 100644 --- a/web/resources/views/venix/admin/cloud/instances.tpl +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -61,8 +61,8 @@ {if $admin_can_manage|default:false} diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index ac5b8236..8c3a9bf7 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1,2 +1,2 @@ {* Shared Venix CSS/JS cache key. Increment whenever a shared browser asset changes. *} -{assign var=venix_asset_version value='2026100202' scope='global'} +{assign var=venix_asset_version value='2026100203' scope='global'} diff --git a/web/tests/CloudProtocolTest.php b/web/tests/CloudProtocolTest.php index 2a8b8ad1..6a0f2795 100644 --- a/web/tests/CloudProtocolTest.php +++ b/web/tests/CloudProtocolTest.php @@ -78,22 +78,34 @@ namespace { } } $controllerSource = file_get_contents(dirname(__DIR__) . '/app/Controllers/CloudAdminInstanceController.php'); + $routesSource = file_get_contents(dirname(__DIR__) . '/config/routes_cloud.php'); $workerSource = file_get_contents(dirname(__DIR__) . '/app/Services/Cloud/CloudWorkerService.php'); $adminInstanceTemplate = file_get_contents(dirname(__DIR__) . '/resources/views/venix/admin/cloud/instances.tpl'); $adminInstanceScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instances.js'); $assert(is_string($controllerSource) && str_contains($controllerSource, "CloudAccess::manage($actor)") && str_contains($controllerSource, "'network_change'") && str_contains($controllerSource, "'/network'") + && is_string($routesSource) + && str_contains($routesSource, "/admin/instances/{id:[0-9]+}/network-options") && is_string($workerSource) && str_contains($workerSource, "\$job->kind === 'network_change'") && str_contains($workerSource, "引擎成功结果缺少已确认的公网 IP"), 'Administrator network-change route lost its super-admin queue or post-engine confirmation contract.'); $assert(is_string($adminInstanceTemplate) && str_contains($adminInstanceTemplate, '{if $admin_can_manage|default:false}') && str_contains($adminInstanceTemplate, 'admin-instance-network-controls') + && str_contains($adminInstanceTemplate, 'name="public_ip_cidr"') + && str_contains($adminInstanceTemplate, '