You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-instance-configuratio...

814 lines
42 KiB
JavaScript

This file contains ambiguous Unicode characters!

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

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 parseIPv6(value) {
const raw = String(value ?? '').trim().toLowerCase();
if (!raw || raw.includes('%') || !/^[0-9a-f:]+$/.test(raw)
|| (raw.match(/::/g) || []).length > 1) return null;
const halves = raw.split('::');
const left = halves[0] ? halves[0].split(':') : [];
const right = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
if ([...left, ...right].some(part => !/^[0-9a-f]{1,4}$/.test(part))) return null;
const missing = 8 - left.length - right.length;
if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return null;
const words = [...left, ...Array(Math.max(0, missing)).fill('0'), ...right].map(part => Number.parseInt(part, 16));
return words.length === 8 && words.every(part => Number.isInteger(part) && part >= 0 && part <= 0xffff)
? words : null;
}
function ipv6Number(words) {
return words.reduce((value, word) => (value << 16n) | BigInt(word), 0n);
}
function normalizeIPv6Cidr(value, fallbackPrefix = 64) {
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 words = parseIPv6(parts[0]);
const prefix = parts.length === 2 ? Number(parts[1]) : Number(fallbackPrefix);
if (!words || !Number.isInteger(prefix) || prefix < 1 || prefix > 128) return null;
return { address: parts[0].toLowerCase(), prefix, value: `${parts[0].toLowerCase()}/${prefix}`, number: ipv6Number(words) };
}
function ipv6CidrContains(cidr, address) {
const network = normalizeIPv6Cidr(cidr, null);
const target = parseIPv6(String(address ?? '').split('/')[0]);
if (!network || !target) return false;
const shift = 128n - BigInt(network.prefix);
return (network.number >> shift) === (ipv6Number(target) >> shift);
}
function normalizeAddressCidr(value, family, fallbackPrefix = family === 4 ? 24 : 64) {
return family === 4 ? normalizeCidr(value, fallbackPrefix) : normalizeIPv6Cidr(value, fallbackPrefix);
}
function currentNetworkFromVm(vm = {}) {
const source = vm.public_network && typeof vm.public_network === 'object' ? vm.public_network : {};
const ipv4 = normalizeCidr(source.ipv4?.address_cidr || vm.public_ipv4_cidr || vm.public_ip_cidr || vm.public_ipv4 || vm.public_ip, 24);
const ipv6 = normalizeIPv6Cidr(source.ipv6?.address_cidr || vm.public_ipv6_cidr || vm.public_ipv6, 64);
return {
ipv4: { pool_key: publicPoolKey(source.ipv4?.pool_key), address_cidr: ipv4?.value || '' },
ipv6: { pool_key: publicPoolKey(source.ipv6?.pool_key), address_cidr: ipv6?.value || '' },
};
}
function normalizePool(value, family) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const poolKey = publicPoolKey(value.pool_key || value.public_pool_key);
const poolCidr = normalizeAddressCidr(value.pool_cidr || value.cidr, family, null);
const guestPrefix = Number(value.guest_prefix ?? value.prefix_length ?? poolCidr?.prefix);
if (!poolKey || !poolCidr || !Number.isInteger(guestPrefix)
|| guestPrefix !== poolCidr.prefix
|| guestPrefix > (family === 4 ? 30 : 120)) return null;
const pool = {
pool_key: poolKey, pool_cidr: poolCidr.value, guest_prefix: guestPrefix,
gateway: String(value.gateway || '').trim(),
dns_servers: Array.isArray(value.dns_servers) ? value.dns_servers.map(item => String(item).trim()).filter(Boolean) : [],
sparse: family === 6 && value.sparse === true,
allocation_start: '',
allocation_end: '',
allocation_start_number: null,
allocation_end_number: null,
excluded_addresses: [],
excluded_address_numbers: [],
available_options: [],
};
if (family === 4) {
const seen = new Set();
for (const option of Array.isArray(value.available_options) ? value.available_options : []) {
const cidr = normalizeCidr(option?.address_cidr || option?.public_ip_cidr, guestPrefix);
if (!cidr || cidr.prefix !== guestPrefix || !cidrContains(pool.pool_cidr, cidr.address)
|| seen.has(cidr.value)) continue;
seen.add(cidr.value); pool.available_options.push({ address_cidr: cidr.value });
}
} else {
const start = parseIPv6(value.allocation_start);
const end = parseIPv6(value.allocation_end);
const excluded = Array.isArray(value.excluded_addresses)
? value.excluded_addresses.map(item => parseIPv6(item)) : null;
if (!pool.sparse || !start || !end || !excluded || excluded.some(item => !item)
|| !ipv6CidrContains(pool.pool_cidr, value.allocation_start)
|| !ipv6CidrContains(pool.pool_cidr, value.allocation_end)) return null;
pool.allocation_start_number = ipv6Number(start);
pool.allocation_end_number = ipv6Number(end);
if (pool.allocation_start_number > pool.allocation_end_number) return null;
pool.allocation_start = String(value.allocation_start).trim().toLowerCase();
pool.allocation_end = String(value.allocation_end).trim().toLowerCase();
pool.excluded_addresses = value.excluded_addresses.map(item => String(item).trim().toLowerCase());
pool.excluded_address_numbers = excluded.map(ipv6Number);
}
return pool;
}
function normalizeAttachment(value, currentAttachmentId) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const attachmentId = String(value.attachment_id ?? '').trim();
if (!/^[1-9]\d*$/.test(attachmentId)) return null;
const families = {};
for (const [name, family] of [['ipv4', 4], ['ipv6', 6]]) {
const pools = [];
for (const poolValue of Array.isArray(value[name]?.pools) ? value[name].pools : []) {
const pool = normalizePool(poolValue, family); if (pool) pools.push(pool);
}
families[name] = { pools };
}
return {
attachment_id: attachmentId,
label: String(value.label || value.network_selector || `网络接入 #${attachmentId}`).trim(),
current: value.current === true || attachmentId === currentAttachmentId,
...families,
};
}
function networkOptionsFromVm(vm = {}) {
return {
current_public_network: currentNetworkFromVm(vm), current_attachment_id: '',
attachments: [], configuration_state: 'not_configured', can_change: false,
active_job: vm.active_job || null, message: '',
};
}
export function normalizeAdminNetworkOptions(payload, vm = {}) {
const source = payload?.network_options || payload?.network || payload || {};
const fallback = networkOptionsFromVm(vm);
const snapshot = source.current_public_network && typeof source.current_public_network === 'object'
? source.current_public_network : (source.public_network || {});
const current = currentNetworkFromVm({ ...vm, public_network: snapshot });
const requestedCurrent = String(source.current_attachment_id ?? '').trim();
const rawAttachments = Array.isArray(source.attachments) ? source.attachments : [];
let currentAttachmentId = /^[1-9]\d*$/.test(requestedCurrent) ? requestedCurrent : '';
let attachments = rawAttachments.map(value => normalizeAttachment(value, currentAttachmentId)).filter(Boolean);
if (!currentAttachmentId) currentAttachmentId = attachments.find(value => value.current)?.attachment_id || '';
attachments = attachments.map(value => ({ ...value, current: value.attachment_id === currentAttachmentId }));
const state = ['ready', 'not_configured', 'invalid', 'drift', 'unavailable']
.includes(source.configuration_state) ? source.configuration_state : 'unavailable';
const hasCandidate = attachments.some((attachment) => {
const hasIpv4 = attachment.ipv4.pools.some(pool => pool.available_options.length > 0);
const hasIpv6 = attachment.ipv6.pools.some(pool => pool.sparse);
return attachment.current ? (hasIpv4 || hasIpv6) : (hasIpv4 && hasIpv6);
});
return {
...fallback,
current_public_network: current,
current_attachment_id: currentAttachmentId,
attachments,
configuration_state: state,
can_change: source.can_change === true && state === 'ready' && hasCandidate,
active_job: source.active_job || fallback.active_job,
message: String(source.message || ''),
};
}
function encodedIpv4Target(poolKey, cidr) {
return `${poolKey}|${cidr}`;
}
function attachmentById(options, id) {
return (options.attachments || []).find(value => value.attachment_id === String(id));
}
export function buildAdminNetworkTargets(options, values = {}) {
if (options?.can_change !== true || options.configuration_state !== 'ready') {
throw new Error('宿主机网络配置尚未就绪,暂不能更换公网地址。');
}
const attachment = attachmentById(options, values.attachment_id);
if (!attachment) throw new Error('请选择有效的目标网络接入。');
const crossAttachment = attachment.attachment_id !== options.current_attachment_id;
const targets = {};
const ipv4Value = String(values.ipv4_target || '').trim();
if (ipv4Value) {
const separator = ipv4Value.indexOf('|');
const poolKey = publicPoolKey(ipv4Value.slice(0, separator));
const cidr = normalizeCidr(ipv4Value.slice(separator + 1), null);
const pool = attachment.ipv4.pools.find(item => item.pool_key === poolKey);
const available = pool && cidr && pool.available_options.some(item => item.address_cidr === cidr.value);
if (!pool || !cidr || !available) throw new Error('请选择列表中的可用 IPv4 地址。');
if (cidr.value === options.current_public_network.ipv4.address_cidr) throw new Error('新 IPv4 与当前地址相同。');
targets.ipv4 = { pool_key: poolKey, address_cidr: cidr.value };
}
const ipv6PoolKey = publicPoolKey(values.ipv6_pool_key);
const ipv6Raw = String(values.ipv6_address_cidr || '').trim();
if (ipv6PoolKey || ipv6Raw) {
if (!ipv6PoolKey || !ipv6Raw) throw new Error('选择 IPv6 地址池后必须填写完整的 IPv6 CIDR。');
const pool = attachment.ipv6.pools.find(item => item.pool_key === ipv6PoolKey);
const cidr = normalizeIPv6Cidr(ipv6Raw, pool?.guest_prefix);
if (!pool || !pool.sparse || !cidr || cidr.prefix !== pool.guest_prefix
|| !ipv6CidrContains(pool.pool_cidr, cidr.address)) {
throw new Error('IPv6 地址必须属于所选地址池,并使用该地址池的前缀。');
}
if (cidr.number < pool.allocation_start_number
|| cidr.number > pool.allocation_end_number) {
throw new Error('IPv6 地址必须位于所选地址池的可分配范围内。');
}
if (pool.excluded_address_numbers.some(value => value === cidr.number)) {
throw new Error('IPv6 地址属于网关、DNS、保留或管理地址,不能分配。');
}
const current = normalizeIPv6Cidr(options.current_public_network.ipv6.address_cidr, cidr.prefix);
if (current && current.number === cidr.number && current.prefix === cidr.prefix) throw new Error('新 IPv6 与当前地址相同。');
targets.ipv6 = { pool_key: ipv6PoolKey, address_cidr: cidr.value };
}
if (crossAttachment && (!targets.ipv4 || !targets.ipv6)) {
throw new Error('切换网络接入时必须同时指定新的 IPv4 和 IPv6。');
}
if (!targets.ipv4 && !targets.ipv6) throw new Error('请至少选择一项要更换的公网地址。');
return { attachment, targets };
}
export function createAdminInstanceConfiguration({
byId, actions, onNotice, onRefresh,
} = {}) {
if (typeof byId !== 'function' || typeof actions?.enqueue !== 'function') {
throw new TypeError('Instance configuration dependencies are incomplete');
}
const { read, enqueue, blockMessage } = actions;
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 ?? '';
const handle = actions.watch(result, {
title: '修改实例设置',
onUpdate: () => {
if (serial === state.settingsSerial && state.currentId === String(vm.id)) {
setSettingsFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted');
}
},
onResult: ({ succeeded, message }) => {
if (serial !== state.settingsSerial || state.currentId !== String(vm.id)) return;
state.settingsObserver = null;
void (async () => {
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, blockMessage(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 enqueue(`/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 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();
const currentAttachment = attachmentById(options, options.current_attachment_id);
const ipv4Count = (options.attachments || []).reduce((total, attachment) => total
+ attachment.ipv4.pools.reduce((count, pool) => count + pool.available_options.length, 0), 0);
const ipv6Pools = (options.attachments || []).reduce((total, attachment) => total
+ attachment.ipv6.pools.filter(pool => pool.sparse).length, 0);
[['当前接入', currentAttachment?.label || '未记录'], ['候选接入', `${options.attachments.length} 个`],
['可用 IPv4', `${ipv4Count} 个`], ['可选 IPv6 池', `${ipv6Pools} 个`]].forEach(([label, value]) => {
values.append(el('dt', '', label), el('dd', 'admin-mono', value));
});
const attachmentSelect = section.querySelector('[name="attachment_id"]');
const submit = section.querySelector('button[type="submit"]');
const canChange = options.can_change === true && options.configuration_state === 'ready';
if (attachmentSelect instanceof HTMLSelectElement) {
attachmentSelect.replaceChildren(new Option(
options.attachments.length ? '请选择目标网络接入' : '当前没有可用网络接入', ''
));
for (const attachment of options.attachments) {
attachmentSelect.add(new Option(
`${attachment.label}${attachment.current ? ' · 当前' : ''}`,
attachment.attachment_id
));
}
attachmentSelect.value = options.current_attachment_id;
attachmentSelect.disabled = !canChange;
}
populateNetworkTargetControls(section, options);
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 ? blockMessage(blockingJob, '更换公网 IP')
: (!canChange ? ({
invalid: '宿主机公网地址池配置无效,暂不能更换;请先修正宿主机配置。',
drift: '实例当前网络与宿主机地址池不一致,暂不能更换;请先核对网络配置。',
}[options.configuration_state] || '当前宿主机网络配置未就绪或实例已有任务,暂不能更换。')
: '当前网络接入可以只更换一个地址族;切换到其他接入时必须同时指定 IPv4 和 IPv6。');
empty.className = `form-text mb-2${canChange ? '' : ' text-warning'}`;
}
}
function populateNetworkTargetControls(section, options) {
const attachmentSelect = section.querySelector('[name="attachment_id"]');
const ipv4Select = section.querySelector('[name="ipv4_target"]');
const ipv6PoolSelect = section.querySelector('[name="ipv6_pool_key"]');
const ipv6Input = section.querySelector('[name="ipv6_address_cidr"]');
const attachment = attachmentById(options, attachmentSelect?.value);
const isCurrent = attachment?.attachment_id === options.current_attachment_id;
if (ipv4Select instanceof HTMLSelectElement) {
ipv4Select.replaceChildren(new Option(
isCurrent ? '保持当前 IPv4' : '请选择新的 IPv4', ''
));
for (const pool of attachment?.ipv4.pools || []) {
for (const option of pool.available_options) {
ipv4Select.add(new Option(
`${option.address_cidr} · ${pool.pool_cidr}`,
encodedIpv4Target(pool.pool_key, option.address_cidr)
));
}
}
ipv4Select.disabled = !attachment || attachment.ipv4.pools.every(pool => pool.available_options.length === 0);
ipv4Select.required = !isCurrent;
}
if (ipv6PoolSelect instanceof HTMLSelectElement) {
ipv6PoolSelect.replaceChildren(new Option(
isCurrent ? '保持当前 IPv6' : '请选择 IPv6 地址池', ''
));
for (const pool of attachment?.ipv6.pools || []) {
if (!pool.sparse) continue;
ipv6PoolSelect.add(new Option(
`${pool.pool_cidr} · 地址 /${pool.guest_prefix}`,
pool.pool_key
));
}
ipv6PoolSelect.disabled = !attachment || ipv6PoolSelect.options.length === 1;
ipv6PoolSelect.required = !isCurrent;
}
if (ipv6Input instanceof HTMLInputElement) {
ipv6Input.value = '';
ipv6Input.disabled = !ipv6PoolSelect?.value;
ipv6Input.required = !isCurrent;
ipv6Input.placeholder = '例如 2404:c140:156:3a::20/64';
}
updateIpv6TargetHelp(section, options);
}
function updateIpv6TargetHelp(section, options) {
const attachment = attachmentById(options, section.querySelector('[name="attachment_id"]')?.value);
const poolKey = publicPoolKey(section.querySelector('[name="ipv6_pool_key"]')?.value);
const pool = attachment?.ipv6.pools.find(item => item.pool_key === poolKey);
const hint = section.querySelector('[data-ipv6-target-help]');
if (!hint) return;
if (pool) {
hint.textContent = `可分配范围 ${pool.allocation_start} – ${pool.allocation_end},必须使用 /${pool.guest_prefix};网关、DNS、保留和管理地址不可用。`;
return;
}
hint.textContent = attachment?.attachment_id === options.current_attachment_id
? '如只更换 IPv4,可保持 IPv6 不变;选择 IPv6 地址池后填写完整 CIDR。'
: '切换网络接入时 IPv4 和 IPv6 都是必填项。';
}
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;
for (const control of form.querySelectorAll('select, input, button')) control.disabled = 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 = normalizeAdminNetworkOptions(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);
return buildAdminNetworkTargets(options, {
attachment_id: section.querySelector('[name="attachment_id"]')?.value,
ipv4_target: section.querySelector('[name="ipv4_target"]')?.value,
ipv6_pool_key: section.querySelector('[name="ipv6_pool_key"]')?.value,
ipv6_address_cidr: section.querySelector('[name="ipv6_address_cidr"]')?.value,
});
}
function makeNetworkConfirmation(section, vm, target, options) {
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 changes = [];
const currentAttachment = attachmentById(options, options.current_attachment_id);
changes.push(target.attachment.attachment_id === options.current_attachment_id
? `网络接入:保持 ${target.attachment.label}`
: `网络接入:${currentAttachment?.label || '当前接入'} → ${target.attachment.label}`);
if (target.targets.ipv4) changes.push(`IPv4:${options.current_public_network.ipv4.address_cidr || '未记录'} → ${target.targets.ipv4.address_cidr}`);
if (target.targets.ipv6) changes.push(`IPv6:${options.current_public_network.ipv6.address_cidr || '未记录'} → ${target.targets.ipv6.address_cidr}`);
summary.textContent = `${changes.join(';')}。运行中的实例会受控关机并重新启动,已关机实例保持关机;运行中连接会短暂中断。`;
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 ?? '';
const handle = actions.watch(result, {
title: '更换实例网络',
onUpdate: () => {
if (serial === state.networkSerial && state.currentId === String(vm.id)) {
setNetworkFeedback(section, `任务 #${jobId} 正在后台执行。`, 'muted');
}
},
onResult: ({ succeeded, message }) => {
if (serial !== state.networkSerial || state.currentId !== String(vm.id)) return;
state.networkObserver = null;
void (async () => {
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 current4 = el('span', 'admin-instance-network-current-value');
current4.append(el('strong', 'admin-mono', text(vm.public_ipv4_cidr, vm.public_ip_cidr, vm.public_ipv4, vm.public_ip, '未记录')));
if (vm.public_ipv4 || vm.public_ip) current4.append(copyButton(vm.public_ipv4 || vm.public_ip, '复制当前 IPv4'));
const current6 = el('span', 'admin-instance-network-current-value');
current6.append(el('strong', 'admin-mono', text(vm.public_ipv6_cidr, vm.public_ipv6, '未记录')));
if (vm.public_ipv6) current6.append(copyButton(vm.public_ipv6, '复制当前 IPv6'));
current.append(
el('span', 'text-muted fs-13', '当前 IPv4'), current4,
el('span', 'text-muted fs-13', '当前 IPv6'), current6
);
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 attachmentSelect = form.elements.namedItem('attachment_id');
const ipv4Select = form.elements.namedItem('ipv4_target');
const ipv6PoolSelect = form.elements.namedItem('ipv6_pool_key');
const ipv6Input = form.elements.namedItem('ipv6_address_cidr');
const feedback = section.querySelector('.admin-instance-network-feedback');
const submit = form.querySelector('button[type="submit"]');
const cancelButton = form.querySelector('[data-network-edit="cancel"]');
for (const control of [attachmentSelect, ipv4Select, ipv6PoolSelect, ipv6Input]) {
if (control) { control.value = ''; control.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 = blockMessage(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; attachmentSelect?.focus();
});
attachmentSelect?.addEventListener('change', () => {
populateNetworkTargetControls(section, section._networkOptions || networkOptionsFromVm(vm));
if (!feedback.hidden) setNetworkFeedback(section, '');
});
ipv6PoolSelect?.addEventListener('change', () => {
if (ipv6Input) {
ipv6Input.disabled = !ipv6PoolSelect.value;
ipv6Input.value = '';
if (!ipv6Input.disabled) ipv6Input.focus();
}
updateIpv6TargetHelp(section, section._networkOptions || networkOptionsFromVm(vm));
if (!feedback.hidden) setNetworkFeedback(section, '');
});
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'); attachmentSelect?.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();
});
for (const control of [ipv4Select, ipv6Input]) {
control?.addEventListener('input', () => { if (!feedback.hidden) setNetworkFeedback(section, ''); });
}
cancelButton?.addEventListener('click', () => {
form.hidden = true; confirmation.hidden = true; edit.hidden = false;
edit.setAttribute('aria-expanded', 'false');
populateNetworkTargetControls(section, section._networkOptions || networkOptionsFromVm(vm));
section._networkTarget = null;
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'); attachmentSelect?.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 enqueue(`/api/v1/admin/instances/${encodeURIComponent(vm.id)}/network`, {
targets: target.targets,
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 });
}