|
|
const root = document.querySelector('[data-cloud-admin]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', scanned: null, scanTarget: '', hostConfigured: false, busy: false, epoch: 0, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '' };
|
|
|
// Permission state is rendered by the server on the page. API endpoints keep
|
|
|
// the authoritative authorization check; this only controls the UI affordances.
|
|
|
const canManage = root?.dataset.canManage === '1';
|
|
|
const collection = (payload, key = 'items') => Array.isArray(payload) ? payload : Array.isArray(payload?.[key]) ? payload[key] : Array.isArray(payload?.items) ? payload.items : [];
|
|
|
function element(tag, className = '', content) { const node = document.createElement(tag); node.className = className; if (content !== undefined) node.textContent = String(content); return node; }
|
|
|
function notice(message, error = false) { const box = byId('cloud-admin-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; }
|
|
|
function errorMessage(payload, status) { if (Array.isArray(payload?.detail)) return payload.detail.map(item => item.msg || '输入错误').join(';'); return String(payload?.detail || payload?.message || payload?.msg || `请求失败 (${status})`); }
|
|
|
async function api(path, options = {}) {
|
|
|
const method = (options.method || 'GET').toUpperCase(); const headers = new Headers({ Accept: 'application/json' });
|
|
|
if (!['GET', 'HEAD'].includes(method)) { if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) throw new Error('请通过 HTTPS 修改宿主机及镜像配置。'); headers.set('X-CSRF-Token', state.csrf); headers.set('Content-Type', options.raw ? 'application/octet-stream' : 'application/json'); }
|
|
|
const response = await fetch(path, { ...options, method, headers, credentials: 'same-origin', cache: 'no-store', body: options.body === undefined ? undefined : options.raw ? options.body : JSON.stringify(options.body) });
|
|
|
let payload = null; if (response.status !== 204) { try { payload = await response.json(); } catch { throw new Error('服务返回非 JSON 响应,请检查 PHP 和反代配置。'); } }
|
|
|
if (response.status === 401) { location.assign('/auth/login'); throw new Error('登录已过期。'); }
|
|
|
if (!response.ok || payload?.ret === 0) throw new Error(errorMessage(payload, response.status)); return payload;
|
|
|
}
|
|
|
function uploadApi(path, file, onProgress) {
|
|
|
if (location.protocol !== 'https:' && !['localhost', '127.0.0.1', '[::1]'].includes(location.hostname)) return Promise.reject(new Error('请通过 HTTPS 上传云镜像。'));
|
|
|
return new Promise((resolve, reject) => {
|
|
|
const request = new XMLHttpRequest();
|
|
|
request.open('POST', path, true);
|
|
|
request.withCredentials = true;
|
|
|
request.setRequestHeader('Accept', 'application/json');
|
|
|
request.setRequestHeader('X-CSRF-Token', state.csrf);
|
|
|
request.setRequestHeader('Content-Type', 'application/octet-stream');
|
|
|
request.upload.addEventListener('progress', event => {
|
|
|
if (event.lengthComputable && typeof onProgress === 'function') onProgress(event.loaded, event.total);
|
|
|
});
|
|
|
request.addEventListener('load', () => {
|
|
|
let payload = null;
|
|
|
try { payload = request.responseText ? JSON.parse(request.responseText) : null; }
|
|
|
catch {
|
|
|
reject(new Error(request.status === 413
|
|
|
? '上传被 Web 服务器拒绝,请提高 PHP 与反代的请求体上限。'
|
|
|
: '服务返回非 JSON 响应,请检查 PHP 和反代配置。'));
|
|
|
return;
|
|
|
}
|
|
|
if (request.status === 401) { location.assign('/auth/login'); reject(new Error('登录已过期。')); return; }
|
|
|
if (request.status < 200 || request.status >= 300 || payload?.ret === 0) { reject(new Error(errorMessage(payload, request.status))); return; }
|
|
|
resolve(payload);
|
|
|
});
|
|
|
request.addEventListener('error', () => reject(new Error('云镜像上传失败,请检查网络或反代限制。')));
|
|
|
request.addEventListener('abort', () => reject(new Error('云镜像上传已取消。')));
|
|
|
request.send(file);
|
|
|
});
|
|
|
}
|
|
|
function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); }
|
|
|
function profile(host) { return { ...host, ...(host.profile || host.config || {}) }; }
|
|
|
async function loadHosts() { state.hosts = collection(await api('/api/v1/admin/hosts'), 'hosts').map(profile); return state.hosts; }
|
|
|
async function loadUserIsoSettings() {
|
|
|
const settings = await api('/api/v1/admin/user-iso/settings');
|
|
|
byId('user-iso-enabled').checked = settings?.enabled === true;
|
|
|
}
|
|
|
async function saveUserIsoSettings(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.busy) return;
|
|
|
const button = byId('user-iso-settings-save');
|
|
|
state.busy = true;
|
|
|
button.disabled = true;
|
|
|
try {
|
|
|
const settings = await api('/api/v1/admin/user-iso/settings', {
|
|
|
method: 'PUT', body: { enabled: byId('user-iso-enabled').checked },
|
|
|
});
|
|
|
byId('user-iso-enabled').checked = settings?.enabled === true;
|
|
|
notice(settings?.enabled ? '用户 ISO 功能已开放。' : '用户 ISO 功能已关闭。');
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
button.disabled = !canManage;
|
|
|
}
|
|
|
}
|
|
|
function resetScan() { state.scanned = null; state.scanTarget = ''; if (byId('host-fingerprint')) byId('host-fingerprint').textContent = ''; if (byId('host-fingerprint-confirm')) byId('host-fingerprint-confirm').checked = false; }
|
|
|
function fillHost(host) {
|
|
|
byId('host-form').reset(); resetScan(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机';
|
|
|
state.hostConfigured = h.configured === true;
|
|
|
const fields = { 'host-name': h.name || '', 'host-country-code': h.country_code || '', 'host-region': h.region || '', 'host-address': h.host || '', 'host-port': h.port || 22, 'host-storage-pool': h.storage_pool || '/home/kvm', 'host-iso-pool': h.iso_pool || '/home/iso', 'host-rescue-pool': h.rescue_iso_pool || '/home/rescue-iso', 'host-network': h.default_network || 'bridge:br0', 'host-fabric-endpoint-ip': h.fabric_endpoint_ip || '' };
|
|
|
for (const [id, value] of Object.entries(fields)) byId(id).value = value;
|
|
|
byId('host-private-key-help').textContent = state.hostConfigured
|
|
|
? '已保存 SSH 私钥;编辑时留空将保留现有私钥。仅通过 HTTPS 提交,请勿粘贴到工单或日志。'
|
|
|
: host
|
|
|
? '该宿主机尚未完成引擎配置,必须重新粘贴现有 SSH 私钥。仅通过 HTTPS 提交,请勿粘贴到工单或日志。'
|
|
|
: '首次添加必须粘贴现有 SSH 私钥。仅通过 HTTPS 提交,请勿粘贴到工单或日志。';
|
|
|
byId('host-private-key').value = ''; byId('host-passphrase').value = ''; byId('host-enabled').checked = h.enabled !== false; byId('host-form-error').textContent = '';
|
|
|
}
|
|
|
function renderHosts() {
|
|
|
const list = byId('host-list'); list.replaceChildren(); if (!state.hosts.length) list.append(element('p', 'text-muted', '暂无宿主机。'));
|
|
|
for (const host of state.hosts) {
|
|
|
const row = element('div', 'd-grid gap-2');
|
|
|
const button = element('button', 'btn btn-light cloud-admin-host');
|
|
|
button.type = 'button';
|
|
|
button.append(element('strong', '', host.name || `宿主机 ${host.id}`), element('div', 'text-muted', `${host.region || '地区未设置'} · #${host.id} · ${host.enabled ? '连接启用' : '连接停用'} · ${schedulerLabel(host.scheduler_state)}`));
|
|
|
button.addEventListener('click', async () => { if (state.busy) return; try { fillHost(profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(host.id)}`))); notice('已读取配置。若需保存,请重新扫描并核对主机指纹。'); } catch (error) { notice(error.message, true); } });
|
|
|
const actions = element('div', 'd-grid gap-2');
|
|
|
const scheduling = element('button', 'btn btn-outline-primary btn-sm', '资源池与调度策略');
|
|
|
scheduling.type = 'button'; scheduling.addEventListener('click', () => openHostScheduling(host.id, scheduling));
|
|
|
const networkPools = element('button', 'btn btn-outline-primary btn-sm', '公网地址池');
|
|
|
networkPools.type = 'button'; networkPools.addEventListener('click', () => openHostNetworkPools(host.id, networkPools));
|
|
|
actions.append(scheduling, networkPools); row.append(button, actions); list.append(row);
|
|
|
}
|
|
|
}
|
|
|
function schedulerLabel(value) { return ({ active: '调度启用', draining: '正在排空', disabled: '调度停用' })[value] || '调度未配置'; }
|
|
|
function hostSchedulingNotice(message, error = false) { const box = byId('host-scheduling-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`; }
|
|
|
function setSchedulingWarnings(warnings) {
|
|
|
const box = byId('host-scheduling-warnings'); box.replaceChildren(); const entries = Array.isArray(warnings) ? warnings.filter(Boolean) : [];
|
|
|
box.hidden = entries.length === 0; if (!entries.length) return;
|
|
|
const list = element('ul', 'mb-0'); for (const warning of entries) list.append(element('li', '', warning)); box.append(list);
|
|
|
}
|
|
|
function renderPanelCapacity(capacity) {
|
|
|
const list = byId('host-panel-capacity'); list.replaceChildren();
|
|
|
const rows = capacity ? [
|
|
|
['数据来源', '面板配置、预留和公网 IP 账本'],
|
|
|
['CPU', `${capacity.cpu.allocated} 核已分配,${capacity.cpu.reserved} 核预留,${capacity.cpu.free} 核可用`],
|
|
|
['内存', `${capacity.memory.allocated} MiB 已分配,${capacity.memory.reserved} MiB 预留,${capacity.memory.free} MiB 可用`],
|
|
|
['磁盘', `${capacity.disk.allocated} GiB 已分配,${capacity.disk.reserved} GiB 预留,${capacity.disk.free} GiB 可用`],
|
|
|
['实例', `${capacity.instances.allocated} 台已提交,${capacity.instances.reserved} 台预留`],
|
|
|
['公网 IP', `${capacity.ip.available} 个账本可用 / ${capacity.ip.total} 个总数`],
|
|
|
] : [['面板容量', '尚未配置']];
|
|
|
for (const [label, value] of rows) list.append(element('dt', '', label), element('dd', '', value));
|
|
|
}
|
|
|
function renderHostScheduling(payload) {
|
|
|
const host = payload?.host || {}; const policy = payload?.policy || {}; const pools = Array.isArray(payload?.pools) ? payload.pools : [];
|
|
|
byId('host-scheduling-title').textContent = `${host.name || `宿主机 #${host.id}`} · 资源池与调度策略`;
|
|
|
byId('host-scheduling-host-id').value = host.id || '';
|
|
|
const select = byId('host-resource-pool'); select.replaceChildren(); const empty = element('option', '', '不加入资源池'); empty.value = ''; select.append(empty);
|
|
|
for (const pool of pools) { const option = element('option', '', `${pool.region_name} / ${pool.line_name} / ${pool.name}${pool.status === 'active' && pool.line_status === 'active' && pool.region_status === 'active' ? '' : '(不可调度)'}`); option.value = String(pool.id); option.selected = Number(host.resource_pool_id) === Number(pool.id); select.append(option); }
|
|
|
byId('host-scheduler-state').value = ['active', 'draining', 'disabled'].includes(host.scheduler_state) ? host.scheduler_state : 'disabled';
|
|
|
const fields = { 'host-capacity-cpu': policy.configured_cpu_cores, 'host-capacity-memory': policy.configured_memory_mib, 'host-capacity-disk': policy.configured_disk_gib, 'host-safety-cpu': policy.safety_cpu_cores, 'host-safety-memory': policy.safety_memory_mib, 'host-safety-disk': policy.safety_disk_gib, 'host-max-instances': policy.max_instances };
|
|
|
for (const [id, value] of Object.entries(fields)) byId(id).value = Number(value || 0);
|
|
|
byId('host-resource-pool-help').textContent = payload?.network_lines_enabled ? '线路功能已开启,可选择任意启用线路下的资源池。' : '线路功能关闭,只允许启用地区的默认线路参与调度。';
|
|
|
setSchedulingWarnings(payload?.warnings); renderPanelCapacity(payload?.capacity);
|
|
|
hostSchedulingNotice(`连接:${host.enabled ? '启用' : '停用'} · ${schedulerLabel(host.scheduler_state)}`);
|
|
|
}
|
|
|
function lockSchedulingScroll() { state.schedulingScroll = { x: window.scrollX, y: window.scrollY }; document.body.style.setProperty('--admin-instance-scroll-top', `${-state.schedulingScroll.y}px`); document.documentElement.classList.add('admin-instance-detail-open'); }
|
|
|
function finishSchedulingClose() { document.documentElement.classList.remove('admin-instance-detail-open'); document.body.style.removeProperty('--admin-instance-scroll-top'); if (state.schedulingScroll) { window.scrollTo({ left: state.schedulingScroll.x, top: state.schedulingScroll.y, behavior: 'instant' }); state.schedulingScroll = null; } if (state.schedulingOpener?.isConnected) state.schedulingOpener.focus({ preventScroll: true }); state.schedulingOpener = null; }
|
|
|
function closeHostScheduling() { const dialog = byId('host-scheduling-drawer'); if (!dialog?.open) return; void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => { if (closed) finishSchedulingClose(); }); }
|
|
|
async function openHostScheduling(hostId, opener) {
|
|
|
if (state.schedulingBusy) return; state.schedulingBusy = true; const dialog = byId('host-scheduling-drawer'); state.schedulingOpener = opener; hostSchedulingNotice('正在读取面板资源池和容量配置…'); setSchedulingWarnings([]); renderPanelCapacity(null);
|
|
|
if (!dialog.open) { lockSchedulingScroll(); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
|
|
|
try { renderHostScheduling(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`)); }
|
|
|
catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; }
|
|
|
}
|
|
|
function schedulingBody() { return { resource_pool_id: byId('host-resource-pool').value ? Number(byId('host-resource-pool').value) : null, scheduler_state: byId('host-scheduler-state').value, configured_cpu_cores: Number(byId('host-capacity-cpu').value), configured_memory_mib: Number(byId('host-capacity-memory').value), configured_disk_gib: Number(byId('host-capacity-disk').value), safety_cpu_cores: Number(byId('host-safety-cpu').value), safety_memory_mib: Number(byId('host-safety-memory').value), safety_disk_gib: Number(byId('host-safety-disk').value), max_instances: Number(byId('host-max-instances').value) }; }
|
|
|
async function saveHostScheduling(event) {
|
|
|
event.preventDefault(); if (!canManage || state.schedulingBusy) return; const hostId = byId('host-scheduling-host-id').value; if (!hostId) return;
|
|
|
state.schedulingBusy = true; const button = byId('host-scheduling-save'); if (button) button.disabled = true; hostSchedulingNotice('正在保存调度配置…');
|
|
|
try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling`, { method: 'PUT', body: schedulingBody() }); renderHostScheduling(payload); const host = state.hosts.find(item => Number(item.id) === Number(hostId)); if (host) { host.resource_pool_id = payload.host.resource_pool_id; host.scheduler_state = payload.host.scheduler_state; renderHosts(); } hostSchedulingNotice('调度配置已保存,容量将按面板预留和 IP 账本实时计算。'); }
|
|
|
catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; if (button) button.disabled = false; }
|
|
|
}
|
|
|
function hostNetworkPoolNotice(message, error = false) {
|
|
|
const box = byId('host-network-pools-status');
|
|
|
box.textContent = message;
|
|
|
box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`;
|
|
|
}
|
|
|
function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; }
|
|
|
function networkPoolInput(type, name, value, options = {}) {
|
|
|
const control = document.createElement(type === 'textarea' ? 'textarea' : type === 'select' ? 'select' : 'input');
|
|
|
control.className = type === 'select' ? 'form-select' : 'form-control';
|
|
|
control.name = name;
|
|
|
if (type === 'textarea') control.rows = options.rows || 3;
|
|
|
else if (type !== 'select') control.type = type;
|
|
|
if (options.mono) control.classList.add('admin-mono');
|
|
|
if (options.required) control.required = true;
|
|
|
if (options.min !== undefined) control.min = String(options.min);
|
|
|
if (options.max !== undefined) control.max = String(options.max);
|
|
|
if (options.maxLength !== undefined) control.maxLength = options.maxLength;
|
|
|
if (options.placeholder) control.placeholder = options.placeholder;
|
|
|
if (type === 'select') {
|
|
|
for (const [optionValue, label] of [['active', '启用分配'], ['draining', '排空'], ['disabled', '停用']]) {
|
|
|
const option = element('option', '', label); option.value = optionValue; control.append(option);
|
|
|
}
|
|
|
}
|
|
|
control.value = value ?? '';
|
|
|
return control;
|
|
|
}
|
|
|
function networkPoolField(label, control, wide = false) {
|
|
|
const wrapper = element('div', wide ? 'cloud-admin-full' : '');
|
|
|
const caption = element('label', 'form-label', label);
|
|
|
caption.htmlFor = control.id || '';
|
|
|
wrapper.append(caption, control);
|
|
|
return wrapper;
|
|
|
}
|
|
|
function networkPoolBody(form) {
|
|
|
const value = name => form.elements.namedItem(name)?.value ?? '';
|
|
|
const prefix = Number(value('guest_prefix_length'));
|
|
|
const expectedRevision = Number(value('expected_revision'));
|
|
|
if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。');
|
|
|
if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new Error('地址池版本无效,请刷新后重试。');
|
|
|
return {
|
|
|
name: value('name').trim(), cidr: value('cidr').trim(), gateway: value('gateway').trim(),
|
|
|
dns_servers: formList(value('dns_servers')), reserved_ips: formList(value('reserved_ips')),
|
|
|
guest_prefix_length: prefix, state: value('state'), expected_revision: expectedRevision,
|
|
|
};
|
|
|
}
|
|
|
function renderNetworkPoolForm(pool) {
|
|
|
const form = element('form', 'cloud-admin-form-section');
|
|
|
form.dataset.poolKey = pool.pool_key;
|
|
|
const expectedRevision = networkPoolInput('hidden', 'expected_revision', Number(pool.expected_revision || pool.revision || 0));
|
|
|
const heading = element('div', 'd-flex align-items-start justify-content-between gap-3 flex-wrap mb-3');
|
|
|
const copy = element('div', 'min-w-0');
|
|
|
copy.append(element('h6', 'mb-1', pool.name || pool.cidr), element('div', 'text-muted admin-mono fs-13', pool.pool_key));
|
|
|
const badge = element('span', 'badge bg-light text-dark', `${networkPoolStateLabel(pool.state)} · ${pool.sync_message || '等待应用'}`);
|
|
|
heading.append(copy, badge);
|
|
|
const grid = element('div', 'cloud-admin-form-grid');
|
|
|
const name = networkPoolInput('text', 'name', pool.name, { required: true, maxLength: 80 });
|
|
|
const cidr = networkPoolInput('text', 'cidr', pool.cidr, { required: true, mono: true });
|
|
|
const gateway = networkPoolInput('text', 'gateway', pool.gateway, { required: true, mono: true });
|
|
|
const prefix = networkPoolInput('number', 'guest_prefix_length', pool.guest_prefix_length, { required: true, min: 24, max: 30 });
|
|
|
const status = networkPoolInput('select', 'state', pool.state);
|
|
|
const dns = networkPoolInput('text', 'dns_servers', Array.isArray(pool.dns_servers) ? pool.dns_servers.join(', ') : '', { required: true, mono: true });
|
|
|
const reserved = networkPoolInput('textarea', 'reserved_ips', Array.isArray(pool.reserved_ips) ? pool.reserved_ips.join(', ') : '', { mono: true, rows: 3 });
|
|
|
for (const [control, suffix] of [[name, 'name'], [cidr, 'cidr'], [gateway, 'gateway'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`;
|
|
|
grid.append(networkPoolField('地址池名称', name, true), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true));
|
|
|
const metadata = element('p', 'form-text mb-0', `面板版本 ${Number(pool.revision || 0)} · 已应用版本 ${pool.live_revision === null ? '未确认' : Number(pool.live_revision)} · 占用 ${Number(pool.occupied_count || 0)} 个地址`);
|
|
|
const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3');
|
|
|
actions.append(metadata);
|
|
|
if (!pool.read_only) {
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存此地址池'); save.type = 'submit'; save.disabled = !canManage; actions.append(save);
|
|
|
form.addEventListener('submit', event => saveHostNetworkPool(event, pool.pool_key));
|
|
|
}
|
|
|
form.append(expectedRevision, heading, grid);
|
|
|
const runtimeLocked = Number(pool.occupied_count || 0) > 0;
|
|
|
if (runtimeLocked) {
|
|
|
for (const control of [cidr, gateway, prefix, dns, reserved]) control.disabled = true;
|
|
|
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用,只能修改名称和运行状态。'));
|
|
|
}
|
|
|
if (pool.read_only || !canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true;
|
|
|
form.append(actions);
|
|
|
return form;
|
|
|
}
|
|
|
function networkPoolContextCurrent(hostId, epoch) {
|
|
|
const dialog = byId('host-network-pools-drawer');
|
|
|
return dialog?.open === true && state.networkPoolEpoch === epoch
|
|
|
&& String(state.networkPoolHostId) === String(hostId);
|
|
|
}
|
|
|
function syncNetworkPoolButtons() {
|
|
|
const payload = state.networkPoolPayload; const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
const add = byId('host-network-pool-add');
|
|
|
if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || payload.compatibility_mode === true || !payload.line || items.length >= Number(payload.maximum || 32);
|
|
|
const submit = byId('host-network-pool-create-submit');
|
|
|
if (submit) submit.disabled = state.networkPoolBusy || !canManage;
|
|
|
}
|
|
|
function clearNetworkPoolPayload() {
|
|
|
state.networkPoolPayload = null; state.networkPoolHostId = '';
|
|
|
const form = byId('host-network-pool-create-form');
|
|
|
if (form) { form.hidden = true; delete form.dataset.requestKey; }
|
|
|
byId('host-network-pools-list')?.replaceChildren(); byId('host-network-pools-summary')?.replaceChildren();
|
|
|
if (byId('host-network-pools-legacy')) byId('host-network-pools-legacy').hidden = true;
|
|
|
syncNetworkPoolButtons();
|
|
|
}
|
|
|
function renderHostNetworkPools(payload, hostId, epoch) {
|
|
|
if (!networkPoolContextCurrent(hostId, epoch)) return false;
|
|
|
if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机地址池响应与当前抽屉不一致,请重新打开。');
|
|
|
state.networkPoolPayload = payload;
|
|
|
const host = payload?.host || {}; const line = payload?.line || null; const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
byId('host-network-pools-title').textContent = `${host.name || `宿主机 #${host.id}`} · 公网地址池`;
|
|
|
const summary = byId('host-network-pools-summary'); summary.replaceChildren();
|
|
|
for (const [label, value] of [['默认网络', host.default_network || '未配置'], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '默认网络' ? 'admin-mono' : '', value));
|
|
|
byId('host-network-pools-legacy').hidden = payload?.compatibility_mode !== true;
|
|
|
const list = byId('host-network-pools-list'); list.replaceChildren();
|
|
|
if (!items.length) list.append(element('p', 'text-muted py-3', '暂无公网地址池。添加后面板会生成并维护可用 IP 账本。'));
|
|
|
for (const pool of items) list.append(renderNetworkPoolForm(pool));
|
|
|
const createForm = byId('host-network-pool-create-form'); createForm.hidden = true; delete createForm.dataset.requestKey;
|
|
|
syncNetworkPoolButtons();
|
|
|
hostNetworkPoolNotice(payload?.compatibility_mode ? '检测到旧版 legacy-default 开发数据;本项目不执行旧数据迁移,请先清空并按新版结构重建。' : '每个地址池由面板保存并维护 IP 账本,引擎只负责应用宿主机网络配置。');
|
|
|
return true;
|
|
|
}
|
|
|
function lockNetworkPoolScroll() {
|
|
|
state.networkPoolScroll = { x: window.scrollX, y: window.scrollY };
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.networkPoolScroll.y}px`);
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
}
|
|
|
function finishNetworkPoolClose() {
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.networkPoolScroll) { window.scrollTo({ left: state.networkPoolScroll.x, top: state.networkPoolScroll.y, behavior: 'instant' }); state.networkPoolScroll = null; }
|
|
|
if (state.networkPoolOpener?.isConnected) state.networkPoolOpener.focus({ preventScroll: true });
|
|
|
state.networkPoolOpener = null;
|
|
|
}
|
|
|
function closeHostNetworkPools() {
|
|
|
++state.networkPoolEpoch; state.networkPoolBusy = false; clearNetworkPoolPayload();
|
|
|
const dialog = byId('host-network-pools-drawer'); if (!dialog?.open) { finishNetworkPoolClose(); return; }
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => { if (closed) finishNetworkPoolClose(); });
|
|
|
}
|
|
|
async function openHostNetworkPools(hostId, opener) {
|
|
|
if (state.networkPoolBusy) return;
|
|
|
const epoch = ++state.networkPoolEpoch; clearNetworkPoolPayload(); state.networkPoolHostId = String(hostId);
|
|
|
state.networkPoolBusy = true; state.networkPoolOpener = opener; syncNetworkPoolButtons();
|
|
|
const dialog = byId('host-network-pools-drawer'); hostNetworkPoolNotice('正在读取公网地址池…');
|
|
|
if (!dialog.open) { lockNetworkPoolScroll(); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools`);
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) renderHostNetworkPools(payload, hostId, epoch);
|
|
|
} catch (error) {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) hostNetworkPoolNotice(error.message, true);
|
|
|
} finally {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) { state.networkPoolBusy = false; syncNetworkPoolButtons(); }
|
|
|
}
|
|
|
}
|
|
|
function newNetworkPoolRequestKey() {
|
|
|
if (!globalThis.crypto?.getRandomValues) throw new Error('浏览器无法生成安全的创建请求标识,请升级浏览器后重试。');
|
|
|
const bytes = new Uint8Array(16); globalThis.crypto.getRandomValues(bytes);
|
|
|
return Array.from(bytes, value => value.toString(16).padStart(2, '0')).join('');
|
|
|
}
|
|
|
function showNetworkPoolCreate() {
|
|
|
if (!canManage || state.networkPoolBusy || state.networkPoolPayload?.compatibility_mode) return;
|
|
|
const form = byId('host-network-pool-create-form'); form.reset();
|
|
|
try { form.dataset.requestKey = newNetworkPoolRequestKey(); }
|
|
|
catch (error) { hostNetworkPoolNotice(error.message, true); return; }
|
|
|
byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-state').value = 'active'; form.hidden = false;
|
|
|
byId('host-network-pool-new-name').focus({ preventScroll: true }); form.scrollIntoView({ behavior: 'smooth', block: 'start' });
|
|
|
}
|
|
|
function hideNetworkPoolCreate() { const form = byId('host-network-pool-create-form'); form.hidden = true; delete form.dataset.requestKey; }
|
|
|
function newNetworkPoolBody(form) {
|
|
|
const prefix = Number(byId('host-network-pool-new-prefix').value);
|
|
|
if (!Number.isInteger(prefix) || prefix < 24 || prefix > 30) throw new Error('客户机网络前缀必须是 24 至 30 的整数。');
|
|
|
const requestKey = form.dataset.requestKey || '';
|
|
|
if (!/^[0-9a-f]{32}$/.test(requestKey)) throw new Error('创建请求标识已失效,请取消后重新添加。');
|
|
|
return { name: byId('host-network-pool-new-name').value.trim(), cidr: byId('host-network-pool-new-cidr').value.trim(), gateway: byId('host-network-pool-new-gateway').value.trim(), dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), guest_prefix_length: prefix, state: byId('host-network-pool-new-state').value, request_key: requestKey };
|
|
|
}
|
|
|
async function createHostNetworkPool(event) {
|
|
|
event.preventDefault(); if (!canManage || state.networkPoolBusy) return;
|
|
|
const form = event.currentTarget; const hostId = state.networkPoolPayload?.host?.id; const epoch = state.networkPoolEpoch; if (!hostId) return;
|
|
|
let body; try { body = newNetworkPoolBody(form); } catch (error) { hostNetworkPoolNotice(error.message, true); return; }
|
|
|
const requestKey = body.request_key;
|
|
|
state.networkPoolBusy = true; byId('host-network-pool-create-submit').disabled = true; hostNetworkPoolNotice('正在创建公网地址池…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools`, { method: 'POST', body });
|
|
|
if (!networkPoolContextCurrent(hostId, epoch)) return;
|
|
|
delete form.dataset.requestKey; renderHostNetworkPools(payload, hostId, epoch);
|
|
|
hostNetworkPoolNotice('公网地址池已提交,面板已按配置生成 IP 账本。');
|
|
|
} catch (error) {
|
|
|
if (!networkPoolContextCurrent(hostId, epoch)) return;
|
|
|
let refreshError = null;
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools`);
|
|
|
if (!networkPoolContextCurrent(hostId, epoch)) return;
|
|
|
renderHostNetworkPools(payload, hostId, epoch);
|
|
|
if (payload?.compatibility_mode !== true) { form.dataset.requestKey = requestKey; form.hidden = false; }
|
|
|
} catch (refreshFailure) { refreshError = refreshFailure; }
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) hostNetworkPoolNotice(refreshError ? `${error.message};列表刷新失败:${refreshError.message}` : error.message, true);
|
|
|
} finally {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) { state.networkPoolBusy = false; syncNetworkPoolButtons(); }
|
|
|
}
|
|
|
}
|
|
|
async function saveHostNetworkPool(event, poolKey) {
|
|
|
event.preventDefault(); if (!canManage || state.networkPoolBusy) return;
|
|
|
const hostId = state.networkPoolPayload?.host?.id; const epoch = state.networkPoolEpoch; if (!hostId) return;
|
|
|
let body; try { body = networkPoolBody(event.currentTarget); } catch (error) { hostNetworkPoolNotice(error.message, true); return; }
|
|
|
state.networkPoolBusy = true; const button = event.currentTarget.querySelector('[type="submit"]'); if (button) button.disabled = true; hostNetworkPoolNotice('正在保存所选公网地址池…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools/${encodeURIComponent(poolKey)}`, { method: 'PUT', body });
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) { renderHostNetworkPools(payload, hostId, epoch); hostNetworkPoolNotice('所选公网地址池已提交,面板账本已更新。'); }
|
|
|
} catch (error) {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) hostNetworkPoolNotice(error.message, true);
|
|
|
} finally {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) { state.networkPoolBusy = false; if (button?.isConnected) button.disabled = !canManage; syncNetworkPoolButtons(); }
|
|
|
}
|
|
|
}
|
|
|
async function scanHost() {
|
|
|
if (state.busy) return; const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); if (!host || port < 1 || port > 65535) return notice('请输入正确的 SSH 地址和端口。', true);
|
|
|
state.busy = true; byId('host-scan').disabled = true; resetScan(); notice('正在扫描 SSH 主机指纹…');
|
|
|
try { const result = await api('/api/v1/admin/hosts/scan', { method: 'POST', body: { host, port } }); if (byId('host-address').value.trim() !== host || Number(byId('host-port').value) !== port) throw new Error('扫描期间地址发生变化,请重新扫描。'); if (!result.host_key || !result.fingerprint) throw new Error('扫描响应缺少主机公钥或指纹。'); state.scanned = result; state.scanTarget = `${host}:${port}`; byId('host-fingerprint').textContent = `${result.key_type || 'SSH'}\n${result.fingerprint}`; notice('请通过宿主机控制台等可信渠道核对指纹,勾选确认后再保存。'); }
|
|
|
catch (error) { notice(error.message, true); } finally { state.busy = false; byId('host-scan').disabled = !canManage; }
|
|
|
}
|
|
|
async function saveHost(event) {
|
|
|
event.preventDefault(); if (state.busy) return;
|
|
|
const host = byId('host-address').value.trim(); const port = Number(byId('host-port').value); const id = byId('host-id').value;
|
|
|
if (!state.scanned || state.scanTarget !== `${host}:${port}` || !byId('host-fingerprint-confirm').checked) return notice('请先扫描并核对 SSH 主机指纹。', true);
|
|
|
const privateKey = byId('host-private-key').value.trim();
|
|
|
if (!state.hostConfigured && !privateKey) return notice(id
|
|
|
? '该宿主机尚未完成引擎配置,请重新粘贴现有 SSH 私钥。'
|
|
|
: '首次添加宿主机必须粘贴现有 SSH 私钥。', true);
|
|
|
const body = { name: byId('host-name').value.trim(), enabled: byId('host-enabled').checked, host, port, host_key: state.scanned.host_key, confirmed_fingerprint: state.scanned.fingerprint, private_key: privateKey, private_key_passphrase: byId('host-passphrase').value, country_code: byId('host-country-code').value, region: byId('host-region').value.trim(), storage_pool: byId('host-storage-pool').value.trim(), iso_pool: byId('host-iso-pool').value.trim(), rescue_iso_pool: byId('host-rescue-pool').value.trim(), default_network: byId('host-network').value.trim(), fabric_endpoint_ip: byId('host-fabric-endpoint-ip').value.trim() };
|
|
|
state.busy = true; byId('host-save').disabled = true; notice('正在测试连接并保存…');
|
|
|
try {
|
|
|
const result = await api(`/api/v1/admin/hosts${id ? '/' + encodeURIComponent(id) : ''}`, { method: id ? 'PUT' : 'POST', body });
|
|
|
await loadHosts(); renderHosts(); fillHost(result?.id ? profile(result) : null);
|
|
|
const warnings = Array.isArray(result?.warnings) ? result.warnings.filter(Boolean) : [];
|
|
|
notice(`宿主机配置已保存。请在“资源调度”中将宿主机加入资源池,并在“商品管理”为资源池配置销售方案。${warnings.length ? ` 提示:${warnings.join(';')}` : ''}`, warnings.length > 0);
|
|
|
}
|
|
|
catch (error) { byId('host-form-error').textContent = error.message; notice(error.message, true); }
|
|
|
finally { delete body.private_key; delete body.private_key_passphrase; byId('host-private-key').value = ''; byId('host-passphrase').value = ''; state.busy = false; byId('host-save').disabled = !canManage; }
|
|
|
}
|
|
|
function catalogPath() { return root.dataset.cloudAdmin === 'rescue' ? '/api/v1/admin/rescue-templates' : '/api/v1/admin/cloud-templates'; }
|
|
|
function isRescueCatalog() { return root.dataset.cloudAdmin === 'rescue'; }
|
|
|
const startupScriptState = { epoch: 0, templateId: '', createdAt: 0, revision: null, saving: false, opener: null };
|
|
|
function startupScriptNotice(message, error = false) {
|
|
|
const box = byId('template-startup-status');
|
|
|
box.textContent = message;
|
|
|
box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`;
|
|
|
}
|
|
|
function startupScriptContextCurrent(templateId, epoch) {
|
|
|
return byId('template-startup-dialog').open
|
|
|
&& startupScriptState.templateId === templateId && startupScriptState.epoch === epoch;
|
|
|
}
|
|
|
function updateStartupScriptControls() {
|
|
|
const ready = startupScriptState.revision !== null;
|
|
|
byId('template-startup-script').readOnly = !canManage || !ready || startupScriptState.saving;
|
|
|
byId('template-startup-save').disabled = !canManage || !ready || startupScriptState.saving;
|
|
|
byId('template-startup-close').disabled = startupScriptState.saving;
|
|
|
byId('template-startup-bytes').textContent = `${new TextEncoder().encode(byId('template-startup-script').value.replace(/\r\n/g, '\n')).length} / 32768 字节`;
|
|
|
}
|
|
|
function closeStartupScript() {
|
|
|
if (startupScriptState.saving) return;
|
|
|
const dialog = byId('template-startup-dialog');
|
|
|
++startupScriptState.epoch;
|
|
|
startupScriptState.templateId = '';
|
|
|
startupScriptState.revision = null;
|
|
|
byId('template-startup-script').value = '';
|
|
|
dialog.close();
|
|
|
if (startupScriptState.opener?.isConnected) startupScriptState.opener.focus();
|
|
|
startupScriptState.opener = null;
|
|
|
}
|
|
|
function applyStartupScriptPayload(payload, createdAt) {
|
|
|
if (!payload || typeof payload.startup_script !== 'string'
|
|
|
|| !Number.isSafeInteger(payload.revision) || payload.revision < 0
|
|
|
|| !Number.isSafeInteger(payload.created_at) || payload.created_at !== createdAt) {
|
|
|
throw new Error('镜像或脚本版本已变化,请刷新镜像目录后重新打开设置。');
|
|
|
}
|
|
|
byId('template-startup-script').value = payload.startup_script;
|
|
|
startupScriptState.createdAt = payload.created_at;
|
|
|
startupScriptState.revision = payload.revision;
|
|
|
}
|
|
|
async function openStartupScript(entry, opener) {
|
|
|
if (startupScriptState.saving) return;
|
|
|
const templateId = String(entry.id);
|
|
|
const epoch = ++startupScriptState.epoch;
|
|
|
Object.assign(startupScriptState, { templateId, revision: null, createdAt: Number(entry.created_at), opener });
|
|
|
byId('template-startup-title').textContent = `启动脚本 · ${entry.name || entry.id}`;
|
|
|
byId('template-startup-script').value = '';
|
|
|
startupScriptNotice('正在读取此镜像的启动脚本…');
|
|
|
updateStartupScriptControls();
|
|
|
const dialog = byId('template-startup-dialog');
|
|
|
if (!dialog.open) dialog.showModal();
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/cloud-templates/${encodeURIComponent(templateId)}/startup-script`);
|
|
|
if (!startupScriptContextCurrent(templateId, epoch)) return;
|
|
|
applyStartupScriptPayload(payload, Number(entry.created_at));
|
|
|
startupScriptNotice(canManage ? '保存后用于此镜像随后新建的实例;留空保存可停用。' : '当前管理员仅可查看此镜像的启动脚本。');
|
|
|
} catch (error) {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) startupScriptNotice(error.message, true);
|
|
|
} finally {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) updateStartupScriptControls();
|
|
|
}
|
|
|
}
|
|
|
async function saveStartupScript(event) {
|
|
|
event.preventDefault();
|
|
|
if (!canManage || startupScriptState.saving || startupScriptState.revision === null) return;
|
|
|
const script = byId('template-startup-script').value.replace(/\r\n/g, '\n');
|
|
|
if (script.includes('\0')) return startupScriptNotice('启动脚本不能包含 NUL 字符。', true);
|
|
|
if (new TextEncoder().encode(script).length > 32768) return startupScriptNotice('启动脚本不能超过 32 KiB。', true);
|
|
|
const { templateId, epoch, createdAt, revision } = startupScriptState;
|
|
|
startupScriptState.saving = true;
|
|
|
updateStartupScriptControls();
|
|
|
startupScriptNotice('正在保存启动脚本…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/cloud-templates/${encodeURIComponent(templateId)}/startup-script`, {
|
|
|
method: 'PATCH', body: { script, expected_revision: revision, created_at: createdAt },
|
|
|
});
|
|
|
if (!startupScriptContextCurrent(templateId, epoch)) return;
|
|
|
applyStartupScriptPayload(payload, createdAt);
|
|
|
startupScriptNotice(script.length > 0 ? '启动脚本已保存,仅在随后新建实例的首次启动时执行。' : '已停用此镜像的启动脚本。');
|
|
|
} catch (error) {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) startupScriptNotice(error.message, true);
|
|
|
} finally {
|
|
|
startupScriptState.saving = false;
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) updateStartupScriptControls();
|
|
|
}
|
|
|
}
|
|
|
async function loadCatalog() {
|
|
|
const rescue = isRescueCatalog();
|
|
|
const hostId = rescue ? byId('catalog-host')?.value || '' : '';
|
|
|
state.selectedHost = hostId;
|
|
|
const epoch = ++state.epoch;
|
|
|
const list = byId('catalog-list');
|
|
|
list.replaceChildren();
|
|
|
if (rescue && !hostId) return list.append(element('p', 'text-muted', '请先添加宿主机。'));
|
|
|
notice(rescue ? '正在读取所选宿主机的模版…' : '正在读取全局云镜像目录…');
|
|
|
const url = rescue ? `${catalogPath()}?host_id=${encodeURIComponent(hostId)}` : catalogPath();
|
|
|
try { const entries = collection(await api(url), 'templates'); if (epoch !== state.epoch) return;
|
|
|
if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。'));
|
|
|
for (const entry of entries) { const row = element('form', 'cloud-admin-row'); const name = element('input', 'form-control'); name.value = entry.name || ''; name.maxLength = 64; name.required = true; name.setAttribute('aria-label', '模版名称'); name.disabled = !canManage; const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage; const remove = element('button', 'btn btn-outline-danger', '删除'); remove.type = 'button'; remove.disabled = !canManage; const imageBytes = Number(entry.image_bytes || entry.size_bytes || 0);
|
|
|
row.append(name, save, remove);
|
|
|
if (!rescue) {
|
|
|
const startup = element('button', 'btn btn-outline-secondary cloud-admin-startup-button', canManage ? '设置启动脚本' : '查看启动脚本');
|
|
|
startup.type = 'button';
|
|
|
startup.addEventListener('click', () => openStartupScript(entry, startup));
|
|
|
row.append(startup);
|
|
|
}
|
|
|
row.append(element('small', 'cloud-admin-meta', `${entry.os_family || '镜像'} ${entry.os_version || ''} · ${imageBytes > 0 ? (imageBytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`));
|
|
|
if (rescue) { name.readOnly = true; save.hidden = true; save.disabled = true; }
|
|
|
row.addEventListener('submit', async event => { event.preventDefault(); if (rescue) return; if (state.busy) return notice('请等待当前导入任务完成。', true); save.disabled = true; try { await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, { method: 'PATCH', body: { name: name.value.trim() } }); notice('名称已保存。'); } catch (error) { notice(error.message, true); } finally { save.disabled = !canManage; } });
|
|
|
remove.addEventListener('click', async () => {
|
|
|
if (state.busy) return notice('请等待当前导入任务完成。', true);
|
|
|
const message = rescue
|
|
|
? `删除所选宿主机上的模版“${entry.name}”?正在使用的模版可能不能删除。`
|
|
|
: `删除全局云镜像模版“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`;
|
|
|
if (!confirm(message)) return;
|
|
|
remove.disabled = true;
|
|
|
const deleteUrl = rescue
|
|
|
? `${catalogPath()}/${encodeURIComponent(entry.id)}?host_id=${encodeURIComponent(hostId)}`
|
|
|
: `${catalogPath()}/${encodeURIComponent(entry.id)}`;
|
|
|
try {
|
|
|
const result = await api(deleteUrl, rescue
|
|
|
? { method: 'DELETE' }
|
|
|
: { method: 'DELETE', body: { created_at: Number(entry.created_at) } });
|
|
|
await loadCatalog();
|
|
|
notice(result?.cache_cleanup_pending
|
|
|
? '云镜像模版已删除,宿主机缓存正在后台清理;离线宿主机会在恢复连接后继续清理。'
|
|
|
: '镜像模版已删除。');
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
remove.disabled = !canManage;
|
|
|
}
|
|
|
}); list.append(row);
|
|
|
} notice(rescue ? `已加载 ${entries.length} 个模版。` : `已加载 ${entries.length} 个全局云镜像。`);
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
async function importProgress(result) {
|
|
|
if (!result?.job_id) return;
|
|
|
const suffix = isRescueCatalog() ? `?host_id=${encodeURIComponent(state.selectedHost)}` : '';
|
|
|
const fallback = `${catalogPath()}/import-jobs/${encodeURIComponent(result.job_id)}${suffix}`;
|
|
|
const url = String(result.status_url || '').startsWith('/api/v1/') ? result.status_url : fallback;
|
|
|
for (let i = 0; i < 1800; i++) { const job = await api(url); notice(job.phase || `导入状态:${job.status}`); if (['succeeded', 'completed', 'done'].includes(job.status)) return; if (['failed', 'uncertain', 'cancelled'].includes(job.status)) throw new Error(job.error || '导入未完成,请核查宿主机状态后再操作。'); await new Promise(resolve => setTimeout(resolve, 2000)); } throw new Error('导入仍在进行,请稍后刷新查看。不要重复提交。');
|
|
|
}
|
|
|
async function importTemplate(event) {
|
|
|
event.preventDefault(); if (state.busy) return;
|
|
|
const sha256 = byId('template-sha256').value.trim().toLowerCase();
|
|
|
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
|
|
|
const body = { name: byId('template-name').value.trim(), url: byId('template-url').value.trim() };
|
|
|
if (sha256) body.sha256 = sha256;
|
|
|
const button = byId('template-import-button'); state.busy = true; button.disabled = true;
|
|
|
try { const result = await api('/api/v1/admin/cloud-templates/import', { method: 'POST', body }); await importProgress(result); await loadCatalog(); notice('镜像导入已完成。'); }
|
|
|
catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; }
|
|
|
}
|
|
|
async function uploadCloudTemplate(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.busy) return;
|
|
|
const name = byId('template-upload-name').value.trim();
|
|
|
const selection = byId('template-upload-system').value;
|
|
|
const separator = selection.indexOf('|');
|
|
|
const osFamily = separator > 0 ? selection.slice(0, separator) : '';
|
|
|
const osVersion = separator > 0 ? selection.slice(separator + 1) : '';
|
|
|
const file = byId('template-upload-file').files?.[0];
|
|
|
if (!name || name.length > 64) return notice('请填写 1 至 64 个字符的模版名称。', true);
|
|
|
if (!osFamily || !osVersion) return notice('请选择镜像实际对应的系统和版本。', true);
|
|
|
if (!file || !file.name.toLowerCase().endsWith('.qcow2')) return notice('请选择扩展名为 .qcow2 的云镜像文件。', true);
|
|
|
if (file.size < 1024 ** 2 || file.size > 4 * 1024 ** 3) return notice('QCOW2 文件必须在 1 MiB 至 4 GiB 之间。', true);
|
|
|
const button = byId('template-upload-button');
|
|
|
const system = byId('template-upload-system');
|
|
|
const input = byId('template-upload-file');
|
|
|
state.busy = true;
|
|
|
button.disabled = true;
|
|
|
system.disabled = true;
|
|
|
input.disabled = true;
|
|
|
notice('正在上传云镜像,请勿关闭页面…');
|
|
|
const query = new URLSearchParams({ name, os_family: osFamily, os_version: osVersion, filename: file.name });
|
|
|
try {
|
|
|
const result = await uploadApi(`/api/v1/admin/cloud-templates/upload?${query}`, file, (loaded, total) => {
|
|
|
const percent = total > 0 ? Math.min(100, loaded * 100 / total) : 0;
|
|
|
notice(percent >= 100 ? '文件已上传至面板,正在校验并保存云镜像…' : `正在上传云镜像 ${percent.toFixed(1)}%,请勿关闭页面…`);
|
|
|
});
|
|
|
await importProgress(result);
|
|
|
input.value = '';
|
|
|
await loadCatalog();
|
|
|
notice('本地云镜像上传并导入完成。');
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
button.disabled = !canManage;
|
|
|
system.disabled = !canManage;
|
|
|
input.disabled = !canManage;
|
|
|
}
|
|
|
}
|
|
|
async function uploadRescue(event) {
|
|
|
event.preventDefault(); if (state.busy) return; const hostId = byId('catalog-host').value; const file = byId('rescue-file').files?.[0]; if (!hostId || !file) return notice('请选择宿主机和 ISO。', true); if (!file.name.toLowerCase().endsWith('.iso') || file.size > 8 * 1024 ** 3 || file.size < 32768) return notice('请选择小于 8 GiB 的有效 ISO 文件。', true);
|
|
|
const button = byId('rescue-upload-button'); state.busy = true; button.disabled = true; byId('catalog-host').disabled = true; notice('正在上传救援 ISO,请勿关闭页面…');
|
|
|
try { const result = await api(`/api/v1/admin/rescue-templates/upload?host_id=${encodeURIComponent(hostId)}&name=${encodeURIComponent(byId('rescue-name').value.trim())}`, { method: 'POST', body: file, raw: true }); await importProgress(result); byId('rescue-file').value = ''; await loadCatalog(); notice('救援 ISO 导入已完成。'); }
|
|
|
catch (error) { notice(error.message, true); } finally { state.busy = false; button.disabled = !canManage; byId('catalog-host').disabled = !canManage; }
|
|
|
}
|
|
|
async function initialize() {
|
|
|
if (!root) return;
|
|
|
try { const session = await api('/api/v1/session'); state.csrf = session.csrf_token || state.csrf; if (!session.admin) throw new Error('需要管理员权限。'); if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
|
|
|
if (root.dataset.cloudAdmin === 'hosts') {
|
|
|
await Promise.all([loadHosts(), loadUserIsoSettings()]); renderHosts(); fillHost(null);
|
|
|
byId('host-new').addEventListener('click', () => fillHost(null)); byId('host-scan').addEventListener('click', scanHost); byId('host-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings);
|
|
|
byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-scheduling-close').addEventListener('click', closeHostScheduling);
|
|
|
const schedulingDrawer = byId('host-scheduling-drawer'); schedulingDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostScheduling(); }); schedulingDrawer.addEventListener('click', event => { if (event.target === schedulingDrawer) closeHostScheduling(); });
|
|
|
byId('host-network-pools-close').addEventListener('click', closeHostNetworkPools); byId('host-network-pool-add')?.addEventListener('click', showNetworkPoolCreate); byId('host-network-pool-create-cancel').addEventListener('click', hideNetworkPoolCreate); byId('host-network-pool-create-form').addEventListener('submit', createHostNetworkPool);
|
|
|
const networkDrawer = byId('host-network-pools-drawer'); networkDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkPools(); }); networkDrawer.addEventListener('click', event => { if (event.target === networkDrawer) closeHostNetworkPools(); });
|
|
|
for (const id of ['host-address', 'host-port']) byId(id).addEventListener('input', resetScan);
|
|
|
if (!canManage) { byId('host-form').querySelectorAll('input,textarea,button').forEach(input => { input.disabled = true; }); byId('user-iso-settings-form').querySelectorAll('input,button').forEach(input => { input.disabled = true; }); }
|
|
|
notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。');
|
|
|
}
|
|
|
else if (root.dataset.cloudAdmin === 'templates') {
|
|
|
byId('template-import')?.addEventListener('submit', importTemplate);
|
|
|
byId('template-upload')?.addEventListener('submit', uploadCloudTemplate);
|
|
|
byId('template-startup-form').addEventListener('submit', saveStartupScript);
|
|
|
byId('template-startup-close').addEventListener('click', closeStartupScript);
|
|
|
byId('template-startup-script').addEventListener('input', updateStartupScriptControls);
|
|
|
byId('template-startup-dialog').addEventListener('cancel', event => { event.preventDefault(); closeStartupScript(); });
|
|
|
await loadCatalog();
|
|
|
}
|
|
|
else if (root.dataset.cloudAdmin === 'rescue') { await loadHosts(); const select = byId('catalog-host'); select.replaceChildren(); for (const host of state.hosts) { const option = element('option', '', `${host.name} · ${host.region || '地区未设置'}`); option.value = String(host.id); select.append(option); } select.addEventListener('change', loadCatalog); byId('rescue-upload')?.addEventListener('submit', uploadRescue); await loadCatalog(); }
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
void initialize();
|