diff --git a/web/public/cloud/admin-instance-configuration.js b/web/public/cloud/admin-instance-configuration.js new file mode 100644 index 00000000..e23a060b --- /dev/null +++ b/web/public/cloud/admin-instance-configuration.js @@ -0,0 +1,614 @@ +function el(tag, className = '', text) { + const node = document.createElement(tag); + node.className = className; + if (text !== undefined) node.textContent = String(text); + return node; +} + +function text(...values) { + return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—'; +} + +function copyButton(value, label = '复制') { + const button = el('button', 'btn btn-light btn-sm'); + button.type = 'button'; button.dataset.copy = String(value); + button.setAttribute('aria-label', `${label} ${value}`); + const icon = el('i', 'mdi mdi-content-copy'); icon.setAttribute('aria-hidden', 'true'); + button.append(icon); return button; +} + +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 || (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 publicPoolKey(value) { + const key = String(value ?? '').trim(); + return /^[a-f0-9]{32}$/.test(key) ? key : ''; +} + +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 : [], + current_public_pool_key: '', public_pool_cidr: '', available_count: 0, + available_ips: [], available_ip_options: [], pools: [], + 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 pools = []; const poolsByKey = new Map(); + for (const value of Array.isArray(source.pools) ? source.pools : []) { + if (!value || typeof value !== 'object' || Array.isArray(value)) continue; + const key = publicPoolKey(value.public_pool_key || value.pool_key); + const poolCidr = normalizeCidr(value.pool_cidr, null); + const poolPrefix = Number(value.guest_prefix); + const poolGateway = parseIPv4(value.gateway)?.join('.') || ''; + if (!key || !poolCidr || !Number.isInteger(poolPrefix) + || poolPrefix < 24 || poolPrefix > 30 || !poolGateway) continue; + const pool = { + public_pool_key: key, pool_cidr: poolCidr.value, guest_prefix: poolPrefix, + gateway: poolGateway, + dns_servers: Array.isArray(value.dns_servers) + ? value.dns_servers.map(item => parseIPv4(item)?.join('.')).filter(Boolean) : [], + available_count: Math.max(0, Number(value.available_count) || 0), + }; + pools.push(pool); poolsByKey.set(key, pool); + } + const availableOptions = []; const seenOptions = new Set(); + for (const value of Array.isArray(source.available_ip_options) ? source.available_ip_options : []) { + if (!value || typeof value !== 'object' || Array.isArray(value)) continue; + const key = publicPoolKey(value.public_pool_key || value.pool_key); + const pool = poolsByKey.get(key); + const cidr = normalizeCidr(value.public_ip_cidr || value.cidr, pool?.guest_prefix); + const optionKey = cidr ? `${key}:${cidr.value}` : ''; + if (!pool || !cidr || cidr.prefix !== pool.guest_prefix + || !cidrContains(pool.pool_cidr, cidr.address) || seenOptions.has(optionKey)) continue; + seenOptions.add(optionKey); + availableOptions.push({ public_pool_key: key, public_ip_cidr: cidr.value }); + } + const availableIps = availableOptions.map(value => value.public_ip_cidr); + return { + ...fallback, ...source, + current_ip_cidr: current?.value || fallback.current_ip_cidr, + current_public_pool_key: publicPoolKey(source.current_public_pool_key), + 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: availableIps, available_ip_options: availableOptions, pools, + 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, selectedPool = null) { + const pools = Array.isArray(options.pools) ? options.pools : []; + const selected = selectedPool || (pools.length === 1 ? pools[0] : null); + const pool = selected?.pool_cidr || (pools.length > 1 ? `${pools.length} 个启用地址池` + : (options.public_pool_cidr + || (options.configuration_state === 'not_configured' ? '未配置' : '提交时由 Agent 校验'))); + const prefix = selected?.guest_prefix ? `/${selected.guest_prefix}` + : (pools.length > 1 ? '按所选地址池' : (options.guest_prefix ? `/${options.guest_prefix}` : '未记录')); + const gateway = selected?.gateway || (pools.length > 1 ? '按所选地址池' + : (options.gateway || '提交时由宿主机配置决定')); + const dnsValues = selected?.dns_servers || (pools.length > 1 ? [] : options.dns_servers); + const dns = dnsValues?.length ? dnsValues.join('、') + : (pools.length > 1 ? '按所选地址池' : '宿主机默认 DNS'); + const available = options.available_ip_options?.length + ? `${options.available_ip_options.length} 个` : '暂无可用地址'; + return { pool, prefix, gateway, dns, available }; +} + +export function createAdminInstanceConfiguration({ + byId, read, mutate, announceTaskAccepted, observeTask, + taskSucceededWithoutRecovery, taskFailureMessage, mutationBlockMessage, + onNotice, onRefresh, +} = {}) { + if (typeof byId !== 'function' || typeof read !== 'function' || typeof mutate !== 'function') { + throw new TypeError('Instance configuration dependencies are incomplete'); + } + const state = { + currentId: null, + networkRequest: null, networkOptionsRequest: null, networkObserver: null, networkSerial: 0, + settingsRequest: null, settingsObserver: null, settingsSerial: 0, + }; + + 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 setSettingsFeedback(section, message, tone = 'muted') { + const node = section?.querySelector('[data-settings-feedback]'); + if (!node) return; + node.hidden = !message; node.className = `admin-instance-settings-feedback text-${tone} fs-13 mb-2`; + node.textContent = message || ''; + } + + function cancelNetwork(reason = 'cancelled') { + state.networkOptionsRequest?.abort(reason); state.networkRequest?.abort(reason); + state.networkOptionsRequest = null; state.networkRequest = null; + state.networkObserver?.stop(reason); state.networkObserver = null; state.networkSerial += 1; + } + + function cancelSettings(reason = 'cancelled') { + state.settingsRequest?.abort(reason); state.settingsRequest = null; + state.settingsObserver?.stop(reason); state.settingsObserver = null; state.settingsSerial += 1; + } + + function cancel(reason = 'cancelled') { + cancelNetwork(reason); cancelSettings(reason); state.currentId = null; + } + + function settingsFormValues(form) { + const hostname = String(form.elements.namedItem('hostname')?.value || '').trim().toLowerCase(); + const password = String(form.elements.namedItem('root_password')?.value || ''); + const confirmation = String(form.elements.namedItem('root_password_confirmation')?.value || ''); + const publicKey = String(form.elements.namedItem('ssh_public_key')?.value || '').trim(); + if (!hostname && !password && !publicKey) throw new Error('请至少填写一项要修改的实例设置。'); + if (hostname && !/^(?=.{1,253}$)[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/.test(hostname)) { + throw new Error('主机名只能包含英文、数字、连字符和点,每段不能以连字符开头或结尾,最多 253 个字符。'); + } + if (password || confirmation) { + if (!password) throw new Error('请输入新的实例密码。'); + if (password !== confirmation) throw new Error('两次输入的实例密码不一致。'); + if (password.length < 12 || password.length > 128 || !/^[\x21-\x7e]+$/.test(password) + || !/[A-Z]/.test(password) || !/[a-z]/.test(password) + || !/[0-9]/.test(password) || !/[^A-Za-z0-9]/.test(password)) { + throw new Error('实例密码需为 12 至 128 位可打印字符,并包含大写、小写、数字和符号。'); + } + } + if (publicKey) { + if (publicKey.length > 16384 || /[\r\n\x00-\x1f\x7f]/.test(publicKey)) { + throw new Error('SSH 公钥必须是一行且不能包含控制字符。'); + } + if (!/^(?:ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521)\s+[A-Za-z0-9+/]+={0,3}(?:\s+[^\r\n]*)?$/.test(publicKey)) { + throw new Error('请输入有效的单行 OpenSSH 公钥,不要粘贴私钥。'); + } + } + const body = { confirm_restart: true }; + if (hostname) body.hostname = hostname; + if (password) body.root_password = password; + if (publicKey) body.ssh_public_key = publicKey; + return body; + } + + function settingsSetBusy(form, busy) { + for (const control of form.querySelectorAll('input, textarea, button')) control.disabled = busy; + } + + function unlockSettingsForm(form, activeJob = false) { + if (!form) return; + for (const control of form.querySelectorAll('input, textarea, button')) control.disabled = activeJob; + } + + function pollSettingsJob(vm, section, result) { + const serial = state.settingsSerial; const jobId = result?.task_id ?? ''; + announceTaskAccepted(result, { title: '修改实例设置' }); + const handle = observeTask(result, { + onUpdate: () => { + if (serial === state.settingsSerial && state.currentId === String(vm.id)) { + setSettingsFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted'); + } + }, + onTerminal: task => { + if (serial !== state.settingsSerial || state.currentId !== String(vm.id)) return; + state.settingsObserver = null; + void (async () => { + const succeeded = taskSucceededWithoutRecovery(task); + const message = succeeded ? `实例设置任务 #${jobId} 已成功。` + : taskFailureMessage(task, `任务 #${jobId} 执行失败。`); + await onRefresh?.(vm.id); onNotice?.(message, !succeeded); + })(); + }, + onStop: reason => { + if (state.settingsObserver === handle) state.settingsObserver = null; + if (reason === 'pagehide' || serial !== state.settingsSerial) return; + void (async () => { + await onRefresh?.(vm.id); + onNotice?.(`任务 #${jobId} 自动观察已停止,已按服务端最新状态更新设置入口;请在任务记录刷新最终结果。`, true); + })(); + }, + }); + if (!handle.url) { + setSettingsFeedback(section, '任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。', 'danger'); + return; + } + state.settingsObserver = handle; + } + + function settingsEditor(vm) { + const template = byId('admin-instance-settings-controls'); + const controls = template?.content?.cloneNode(true); + const section = controls?.querySelector('[data-instance-settings]'); + if (!section) return el('section'); + const form = section.querySelector('[data-instance-settings-form]'); + const current = section.querySelector('[data-settings-current-hostname]'); + if (current) current.textContent = `当前主机名:${text(vm.guest_hostname, vm.hostname, '未记录')}`; + if (!form) return section; + if (vm.instance_settings_supported !== true) { + form.remove(); + const description = section.querySelector('.admin-instance-settings-heading p'); + if (description) { + description.className = 'text-warning fs-13 mb-0'; + description.textContent = vm.instance_status && vm.instance_status !== 'active' + ? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能修改主机名、密码或 SSH 公钥。` + : '当前实例缺少已验证的面板云镜像元数据,暂不能修改主机名、密码或 SSH 公钥。请先核对实例元数据。'; + } + return section; + } + const mutationBlocked = vm.active_job?.blocks_mutation === true; + if (mutationBlocked) { + unlockSettingsForm(form, true); + setSettingsFeedback(section, mutationBlockMessage(vm.active_job, '修改实例设置'), 'warning'); + } + form.addEventListener('submit', async event => { + event.preventDefault(); + if (state.settingsRequest || mutationBlocked) return; + let body; + try { + body = settingsFormValues(form); + if (!form.elements.namedItem('confirm_restart')?.checked) throw new Error('请先确认实例会重启。'); + } catch (error) { setSettingsFeedback(section, error.message, 'danger'); return; } + const controller = new AbortController(); state.settingsRequest = controller; + settingsSetBusy(form, true); + setSettingsFeedback(section, '正在创建实例设置任务,请勿重复提交…', 'muted'); + try { + const result = await mutate(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/settings`, body, controller); + const jobId = result?.task_id; + form.elements.namedItem('root_password').value = ''; + form.elements.namedItem('root_password_confirmation').value = ''; + form.elements.namedItem('ssh_public_key').value = ''; + form.elements.namedItem('confirm_restart').checked = false; + setSettingsFeedback(section, `任务 #${jobId || '—'} 已接收,运行中的实例将在后台重启并应用设置。`, 'muted'); + onNotice?.('实例设置任务已接收,可在任务记录查看结果。'); + pollSettingsJob(vm, section, result); + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + setSettingsFeedback(section, error.message, 'danger'); + if (error?.mutationMayHaveApplied === true) { + await onRefresh?.(vm.id); onNotice?.(error.message, true); + } else unlockSettingsForm(form); + } finally { + if (state.settingsRequest === controller) state.settingsRequest = null; + } + }); + form.addEventListener('reset', () => window.setTimeout(() => setSettingsFeedback(section, ''), 0)); + for (const control of form.querySelectorAll('input, textarea')) { + control.addEventListener('input', () => { + const feedback = section.querySelector('[data-settings-feedback]'); + if (feedback?.classList.contains('text-danger')) setSettingsFeedback(section, ''); + }); + } + return section; + } + + function networkOptionsView(section, options) { + const summary = networkOptionSummary(options); + const status = section.querySelector('[data-network-options-status]'); + if (status) { + status.textContent = options.message || '已读取宿主机地址池约束,提交前仍会再次实时校验。'; + status.className = 'text-muted fs-12 mb-0'; + } + 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_ip_options?.length > 0; + const canChange = options.can_change === true && options.configuration_state === 'ready' && hasAvailable; + if (select instanceof HTMLSelectElement) { + select.replaceChildren(new Option(hasAvailable ? '请选择新的公网 IP' : '当前没有可用公网 IP', '')); + const poolsByKey = new Map((options.pools || []).map(pool => [pool.public_pool_key, pool])); + for (const value of options.available_ip_options || []) { + const pool = poolsByKey.get(value.public_pool_key); + const label = options.pools?.length > 1 && pool?.pool_cidr + ? `${value.public_ip_cidr} · ${pool.pool_cidr}` : value.public_ip_cidr; + const option = new Option(label, value.public_ip_cidr); + option.dataset.publicPoolKey = value.public_pool_key; select.add(option); + } + 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 blockingJob = options.active_job?.blocks_mutation === true ? options.active_job : null; + empty.textContent = blockingJob ? mutationBlockMessage(blockingJob, '更换公网 IP') + : (!hasAvailable ? '当前没有可用地址,无法提交更换;请先检查地址池和占用记录。' + : (!canChange ? ({ + invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。', + drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。', + }[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。') + : '只显示该宿主机当前未分配的公网 IP。')); + empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`; + } + } + + function networkOptionsErrorView(section, message) { + section._networkOptions = null; + section.querySelector('[data-network-options-values]')?.replaceChildren(); + const status = section.querySelector('[data-network-options-status]'); + if (status) { status.textContent = message; status.className = 'text-warning fs-12 mb-0'; } + const edit = section.querySelector('[data-network-edit="open"]'); + if (edit instanceof HTMLButtonElement) { + edit.disabled = true; edit.setAttribute('aria-expanded', 'false'); edit.title = message; + } + const form = section.querySelector('.admin-instance-network-form'); + if (form) form.hidden = true; + } + + async function loadNetworkOptions(vm, section) { + const serial = state.networkSerial; const controller = new AbortController(); + state.networkOptionsRequest = controller; + try { + const payload = await read(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network-options`, controller); + if (serial !== state.networkSerial || controller.signal.aborted) return; + const options = networkOptionsPayload(payload, vm); + if (state.currentId !== String(vm.id)) return; + section._networkOptions = options; networkOptionsView(section, options); + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + if (serial !== state.networkSerial || state.currentId !== String(vm.id)) return; + networkOptionsErrorView(section, error.status === 409 + ? error.message : '无法读取宿主机地址池,暂不能选择新的公网 IP。'); + } finally { + if (state.networkOptionsRequest === controller) state.networkOptionsRequest = null; + } + } + + function targetNetworkValue(section, vm) { + const options = section._networkOptions || networkOptionsFromVm(vm); + const input = section.querySelector('[name="public_ip_cidr"]'); + if (options.can_change === false || options.configuration_state !== 'ready') { + throw new Error('宿主机网络配置尚未就绪,暂不能更换公网 IP。'); + } + if (!Array.isArray(options.available_ip_options) || options.available_ip_options.length === 0) { + throw new Error('当前宿主机没有可用公网 IP,请先补充地址池或释放地址后重试。'); + } + if (!input?.value) throw new Error('请选择新的公网 IP。'); + const selectedOption = input instanceof HTMLSelectElement ? input.selectedOptions[0] : null; + const selectedPoolKey = publicPoolKey(selectedOption?.dataset.publicPoolKey); + const selectedPool = (options.pools || []).find(pool => pool.public_pool_key === selectedPoolKey); + const parsed = normalizeCidr(input.value, selectedPool?.guest_prefix); + const available = parsed && options.available_ip_options.some(option => ( + option.public_ip_cidr === parsed.value && option.public_pool_key === selectedPoolKey + )); + if (!parsed || !selectedPool || !available) throw new Error('请选择列表中的可用公网 IP,不支持手动填写。'); + if (parsed.prefix !== Number(selectedPool.guest_prefix)) { + throw new Error(`地址前缀必须为 /${selectedPool.guest_prefix},请不要修改宿主机分配的前缀。`); + } + if (!cidrContains(selectedPool.pool_cidr, parsed.address)) { + throw new Error(`目标地址不在宿主机地址池 ${selectedPool.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 = [selectedPool.gateway, ...(selectedPool.dns_servers || [])] + .map(value => parseIPv4(value)?.join('.')).filter(Boolean); + if (blocked.includes(parsed.address)) throw new Error('目标地址是网关、DNS 或保留地址,不能分配给虚拟机。'); + return { public_ip_cidr: parsed.value, public_pool_key: selectedPoolKey, pool: selectedPool }; + } + + 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, target.pool); + summary.textContent = `公网地址将从 ${current} 更换为 ${target.public_ip_cidr}。运行中的实例会受控关机并重新启动,已关机实例保持关机;地址池 ${network.pool}、网关 ${network.gateway}、DNS ${network.dns} 将按宿主机配置应用。运行中实例的网络会短暂中断。`; + check.checked = false; submit.disabled = true; confirmation.hidden = false; + return { confirmation, check, submit }; + } + + function pollNetworkJob(vm, section, result) { + const serial = state.networkSerial; const jobId = result?.task_id ?? ''; + announceTaskAccepted(result, { title: '更换实例网络' }); + const handle = observeTask(result, { + onUpdate: () => { + if (serial === state.networkSerial && state.currentId === String(vm.id)) { + setNetworkFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted'); + } + }, + onTerminal: task => { + if (serial !== state.networkSerial || state.currentId !== String(vm.id)) return; + state.networkObserver = null; + void (async () => { + const succeeded = taskSucceededWithoutRecovery(task); + const message = succeeded ? `网络变更任务 #${jobId} 已成功。` + : taskFailureMessage(task, `任务 #${jobId} 执行失败。`); + await onRefresh?.(vm.id); onNotice?.(message, !succeeded); + })(); + }, + onStop: reason => { + if (state.networkObserver === handle) state.networkObserver = null; + if (reason === 'pagehide' || serial !== state.networkSerial) return; + void (async () => { + await onRefresh?.(vm.id); + onNotice?.(`任务 #${jobId} 自动观察已停止,已按服务端最新状态更新网络入口;请在任务记录刷新最终结果。`, true); + })(); + }, + }); + if (!handle.url) { + setNetworkFeedback(section, '任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。', 'danger'); + return; + } + state.networkObserver = handle; + } + + 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'); 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 && vm.network_change_supported === true) heading.append(edit); + section.append(heading); + const current = el('div', 'admin-instance-network-current mt-3'); + 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); + if (!edit) { if (controls) section.append(controls); return section; } + if (vm.network_change_supported !== true) { + section.append(el('p', 'text-warning fs-13 mt-3 mb-0', + vm.instance_status && vm.instance_status !== 'active' + ? `当前实例处于“${text(vm.display?.lifecycle, vm.instance_status)}”状态,暂不能更换公网 IP。` + : '当前实例缺少已验证的面板云镜像元数据,暂不能更换公网 IP。请先核对实例元数据。')); + return section; + } + 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; + const input = form.elements.namedItem('public_ip_cidr'); + const feedback = section.querySelector('.admin-instance-network-feedback'); + const submit = form.querySelector('button[type="submit"]'); + const cancelButton = form.querySelector('[data-network-edit="cancel"]'); + 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 mutationBlocked = vm.active_job?.blocks_mutation === true; + if (mutationBlocked) { + edit.disabled = true; edit.title = mutationBlockMessage(vm.active_job, '更换公网 IP'); + setNetworkFeedback(section, edit.title, 'warning'); + } + edit.addEventListener('click', () => { + if (edit.disabled) return; + form.hidden = false; edit.setAttribute('aria-expanded', 'true'); + feedback.hidden = true; input?.focus(); + }); + form.addEventListener('submit', event => { + event.preventDefault(); + if (state.networkRequest || mutationBlocked) return; + let target; + try { target = targetNetworkValue(section, vm); } + catch (error) { setNetworkFeedback(section, error.message, 'danger'); input.focus(); return; } + const options = section._networkOptions || networkOptionsFromVm(vm); + form.hidden = true; 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, ''); }); + cancelButton?.addEventListener('click', () => { + form.hidden = true; confirmation.hidden = true; 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; edit.hidden = false; + edit.setAttribute('aria-expanded', 'true'); input.focus(); + }); + confirmSubmit.addEventListener('click', async () => { + if (!check.checked || state.networkRequest || mutationBlocked) 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: target.public_ip_cidr, + public_pool_key: target.public_pool_key, + confirm_restart: true, + }, controller); + const jobId = result?.task_id; + confirmation.hidden = true; + setNetworkFeedback(section, `任务 #${jobId || '—'} 已接收,实例将在后台重启并应用新地址。`, 'muted'); + onNotice?.('网络变更任务已接收,可在任务记录查看结果。'); + edit.hidden = true; edit.disabled = true; state.networkRequest = null; + pollNetworkJob(vm, section, result); + } catch (error) { + if (controller.signal.aborted && controller.signal.reason !== 'timeout') return; + setNetworkFeedback(section, error.message, 'danger'); + if (error?.mutationMayHaveApplied === true) { + await onRefresh?.(vm.id); onNotice?.(error.message, true); + } else { + 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; + } + + function render(vm) { + state.currentId = String(vm.id); + return [networkEditor(vm), settingsEditor(vm)]; + } + + return Object.freeze({ render, cancel, dispose: cancel }); +} diff --git a/web/public/cloud/admin-instances.js b/web/public/cloud/admin-instances.js index b1e1cbc0..b4234fcb 100644 --- a/web/public/cloud/admin-instances.js +++ b/web/public/cloud/admin-instances.js @@ -11,11 +11,12 @@ const [{ announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl, taskSucceededWithoutRecovery, }, { createAdminInstanceTransport }, { createAdminInstanceDirectory }, -{ createAdminInstanceDetail }] = await Promise.all([ +{ createAdminInstanceDetail }, { createAdminInstanceConfiguration }] = await Promise.all([ import(versionedModuleUrl('./task-observer.js')), import(versionedModuleUrl('./admin-instance-transport.js')), import(versionedModuleUrl('./admin-instance-directory.js')), import(versionedModuleUrl('./admin-instance-detail.js')), + import(versionedModuleUrl('./admin-instance-configuration.js')), ]); const { read: api, mutate } = createAdminInstanceTransport({ taskUrl }); @@ -35,6 +36,7 @@ const state = { }; let directory = null; let detail = null; +let configuration = null; function el(tag, className = '', text) { const node = document.createElement(tag); @@ -1860,27 +1862,7 @@ if (root) { let bootstrap = null; try { bootstrap = JSON.parse(byId('admin-instances-bootstrap').textContent); } catch { /* Directory retries the canonical endpoint. */ } - const dialog = byId('instance-detail'); const libraryDialog = byId('backup-library'); - dialog.addEventListener('click', event => { - const networkAction = event.target.closest('[data-network-edit]'); - if (networkAction) { - const section = networkAction.closest('.admin-instance-network-settings'); - const form = section?.querySelector('.admin-instance-network-form'); - const input = form?.elements?.namedItem('public_ip_cidr'); - const feedback = section?.querySelector('.admin-instance-network-feedback'); - if (form && networkAction.dataset.networkEdit === 'open') { - form.hidden = false; networkAction.setAttribute('aria-expanded', 'true'); - feedback.hidden = true; input?.focus(); - } else if (form && networkAction.dataset.networkEdit === 'cancel') { - form.hidden = true; - const opener = section.querySelector('[data-network-edit="open"]'); - opener?.setAttribute('aria-expanded', 'false'); - if (input) form.reset(); - if (feedback) feedback.hidden = true; - } - } - }); byId('backup-library-close').addEventListener('click', closeBackupLibrary); byId('backup-library-previous').addEventListener('click', () => { void loadBackupLibrary(state.libraryPagination.page - 1, true); @@ -1911,14 +1893,23 @@ if (root) { onOpenBackupLibrary: openBackupLibrary, onCopy: value => { void copy(value); }, }); + configuration = createAdminInstanceConfiguration({ + byId, + read: api, + mutate, + announceTaskAccepted, + observeTask, + taskSucceededWithoutRecovery, + taskFailureMessage, + mutationBlockMessage, + onNotice: detailNotice, + onRefresh: refreshDetail, + }); detail = createAdminInstanceDetail({ byId, read: api, - renderConfiguration: vm => [networkEditor(vm), settingsEditor(vm)], - cancelConfiguration: reason => { - cancelNetworkActivity(reason); - cancelSettingsActivity(reason); - }, + renderConfiguration: vm => configuration.render(vm), + cancelConfiguration: reason => configuration.cancel(reason), loadBackups: (id, force = false) => { void loadBackups(id, force); }, cancelBackups: cancelBackupActivity, onSelectionChange: id => { state.detailId = id; }, diff --git a/web/tests/AdminInstanceViewTest.php b/web/tests/AdminInstanceViewTest.php index 0ae12463..0aef77c7 100644 --- a/web/tests/AdminInstanceViewTest.php +++ b/web/tests/AdminInstanceViewTest.php @@ -104,6 +104,7 @@ $html = $render($page); $clientScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instances.js'); $directoryScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instance-directory.js'); $detailScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instance-detail.js'); +$configurationScript = file_get_contents(dirname(__DIR__) . '/public/cloud/admin-instance-configuration.js'); $assert(is_string($directoryScript) && str_contains($clientScript, "import(versionedModuleUrl('./admin-instance-directory.js'))") @@ -132,13 +133,21 @@ $drawerOpen = strpos($openDetailSource, $assert($scrollReset !== false && $drawerOpen !== false && $scrollReset < $drawerOpen, 'Opening or switching instance detail must reset the reusable drawer body to the top.'); -$assert(str_contains($clientScript, - 'if (vm.network_change_supported !== true)') +$assert(is_string($configurationScript) && str_contains($clientScript, + "import(versionedModuleUrl('./admin-instance-configuration.js'))") + && str_contains($configurationScript, + 'export function createAdminInstanceConfiguration(') + && str_contains($configurationScript, + 'return Object.freeze({ render, cancel, dispose: cancel })'), + 'Network and guest settings must share one cancellable configuration interface.'); +$assert(str_contains($configurationScript, + 'if (vm.network_change_supported !== true)') + && str_contains($configurationScript, 'if (vm.instance_settings_supported !== true)') - && str_contains($clientScript, "vm.instance_status !== 'active'") - && str_contains($clientScript, 'function networkOptionsErrorView(') - && !str_contains($clientScript, + && str_contains($configurationScript, "vm.instance_status !== 'active'") + && str_contains($configurationScript, 'function networkOptionsErrorView(') + && !str_contains($configurationScript, 'Older deployments can still use the existing detail fields'), 'Unsupported, inactive or failed administrator controls must not render guessed network constraints or actionable settings.'); if (in_array('--fixture', $argv ?? [], true)) { diff --git a/web/tests/CloudNetworkIpLedgerContractTest.php b/web/tests/CloudNetworkIpLedgerContractTest.php index 33200887..d0d2790c 100644 --- a/web/tests/CloudNetworkIpLedgerContractTest.php +++ b/web/tests/CloudNetworkIpLedgerContractTest.php @@ -7,7 +7,10 @@ $jobs = file_get_contents($root . '/app/Services/Cloud/CloudJobService.php'); $placement = file_get_contents($root . '/app/Services/Cloud/CloudPlacementService.php'); $worker = file_get_contents($root . '/app/Services/Cloud/CloudWorkerService.php'); $input = file_get_contents($root . '/app/Services/Cloud/CloudInput.php'); -$adminInstances = file_get_contents($root . '/public/cloud/admin-instances.js'); +$adminInstances = file_get_contents($root . '/public/cloud/admin-instances.js') + . "\n" . file_get_contents( + $root . '/public/cloud/admin-instance-configuration.js' + ); $pendingStart = is_string($placement) ? strpos($placement, 'private static function pendingUsageByHost') : false; $pendingEnd = is_string($placement) diff --git a/web/tests/CloudTaskObserverBehaviorTest.mjs b/web/tests/CloudTaskObserverBehaviorTest.mjs index 0d262dca..ebfe35da 100644 --- a/web/tests/CloudTaskObserverBehaviorTest.mjs +++ b/web/tests/CloudTaskObserverBehaviorTest.mjs @@ -12,6 +12,7 @@ const adminUrl = new URL('../public/cloud/admin.js', import.meta.url); const detailUrl = new URL('../public/cloud/detail.js', import.meta.url); const adminInstancesUrl = new URL('../public/cloud/admin-instances.js', import.meta.url); const adminInstanceTransportUrl = new URL('../public/cloud/admin-instance-transport.js', import.meta.url); +const adminInstanceConfigurationUrl = new URL('../public/cloud/admin-instance-configuration.js', import.meta.url); const runtimeUrl = new URL('../public/cloud/runtime.js', import.meta.url); const isoImagesUrl = new URL('../public/cloud/iso-images.js', import.meta.url); const invoiceDetailRuntimeUrl = new URL('../public/cloud/invoice-detail-runtime.js', import.meta.url); @@ -508,7 +509,7 @@ const protocolFailure = task => { assert.match(detailSource, /taskSucceededWithoutRecovery\(task\)/); assert.doesNotMatch(detailSource, /task\.status === 'succeeded'/); - const adminInstancesSource = `${await readFile(adminInstancesUrl, 'utf8')}\n${await readFile(adminInstanceTransportUrl, 'utf8')}`; + const adminInstancesSource = `${await readFile(adminInstancesUrl, 'utf8')}\n${await readFile(adminInstanceTransportUrl, 'utf8')}\n${await readFile(adminInstanceConfigurationUrl, 'utf8')}`; assert.doesNotMatch(adminInstancesSource, /state\.networkRequest \|\| activeJob/); assert.match(adminInstancesSource, /response\.status !== 202 \|\| !taskUrl\(payload\)/); assert.match(adminInstancesSource, /await refreshDetail\(vm\.id\)/);