|
|
import { announceTaskAccepted, observeTask, taskUrl } from './task-observer.js?v=2026101903';
|
|
|
|
|
|
const root = document.querySelector('[data-cloud-admin]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], selectedHost: '', busy: false, epoch: 0, storageBusy: false, storageOpener: null, storageScroll: null, storageObserver: null, schedulingBusy: false, schedulingOpener: null, schedulingScroll: null, networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', taskObservers: new Set() };
|
|
|
// 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 requestJson(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, status: response.status };
|
|
|
}
|
|
|
async function api(path, options = {}) {
|
|
|
return (await requestJson(path, options)).payload;
|
|
|
}
|
|
|
async function acceptedTask(path, options = {}) {
|
|
|
const { payload, status } = await requestJson(path, options);
|
|
|
if (status !== 202 || !taskUrl(payload)) {
|
|
|
const error = new Error('请求已送达,但服务未返回严格的 202 任务回执。请勿再次提交,并联系管理员核查。');
|
|
|
error.keepMutationLocked = true;
|
|
|
throw error;
|
|
|
}
|
|
|
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 parseHostNetwork(value) {
|
|
|
const text = String(value || '');
|
|
|
const match = /^(bridge|network):([A-Za-z0-9][A-Za-z0-9_.-]*)$/.exec(text);
|
|
|
if (!match || match[0] !== text || match[2].length > (match[1] === 'bridge' ? 15 : 64)) return null;
|
|
|
return { type: match[1], name: match[2] };
|
|
|
}
|
|
|
function updateHostNetworkControls() {
|
|
|
const type = byId('host-network-type').value;
|
|
|
const name = byId('host-network-name');
|
|
|
name.maxLength = type === 'bridge' ? 15 : 64;
|
|
|
name.pattern = `[A-Za-z0-9][A-Za-z0-9_.\\-]{0,${name.maxLength - 1}}`;
|
|
|
name.placeholder = type === 'network' ? '例如 default' : '例如 br0';
|
|
|
}
|
|
|
function hostNetworkValue() {
|
|
|
const value = `${byId('host-network-type').value}:${byId('host-network-name').value.trim()}`;
|
|
|
if (!parseHostNetwork(value)) throw new Error('请选择网络接入类型并填写有效名称:网桥为 1 至 15 字符,libvirt 网络为 1 至 64 字符;以字母或数字开头,仅可包含字母、数字、点、下划线和短横线。');
|
|
|
return value;
|
|
|
}
|
|
|
function hostNetworkLabel(value) {
|
|
|
const network = parseHostNetwork(value);
|
|
|
return network ? `${network.type === 'bridge' ? 'Linux 网桥' : 'libvirt 网络'} · ${network.name}` : `待重新配置(${value || '未配置'})`;
|
|
|
}
|
|
|
function fillHost(host) {
|
|
|
byId('host-form').reset(); const h = host || {}; byId('host-id').value = h.id || ''; byId('host-form-title').textContent = host ? `编辑宿主机 · ${h.name}` : '添加宿主机';
|
|
|
const network = parseHostNetwork(host ? h.default_network : 'bridge:br0');
|
|
|
const fields = { 'host-name': h.name || '', 'host-country-code': h.country_code || '', 'host-region': h.region || '', 'host-network-type': network?.type || '', 'host-network-name': network?.name || '' };
|
|
|
for (const [id, value] of Object.entries(fields)) byId(id).value = value;
|
|
|
updateHostNetworkControls();
|
|
|
const warning = byId('host-network-warning');
|
|
|
warning.hidden = network !== null;
|
|
|
warning.textContent = network ? '' : `原网络接入“${h.default_network || '未配置'}”需要重新配置。请先核实该宿主机实际使用的网桥或 libvirt 网络,再选择类型并填写名称;不会自动改为 br0。已有实例或任务占用的地址池需要受控迁移。`;
|
|
|
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('已读取宿主机面板配置。Agent 地址和密钥请在“Agent API”页面维护。'); } 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);
|
|
|
if (canManage) {
|
|
|
const storage = element('button', 'btn btn-outline-primary btn-sm', '存储目录');
|
|
|
storage.type = 'button'; storage.addEventListener('click', () => openHostStorage(host.id, storage)); actions.append(storage);
|
|
|
}
|
|
|
row.append(button, actions); list.append(row);
|
|
|
}
|
|
|
}
|
|
|
const storageFields = {
|
|
|
managed_directory: 'host-storage-managed', template_directory: 'host-storage-template',
|
|
|
seed_directory: 'host-storage-seed', user_iso_directory: 'host-storage-user-iso',
|
|
|
rescue_directory: 'host-storage-rescue',
|
|
|
};
|
|
|
function hostDrawerNotice(id, message, error = false) {
|
|
|
const box = byId(id);
|
|
|
box.textContent = message;
|
|
|
box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`;
|
|
|
}
|
|
|
const hostStorageNotice = hostDrawerNotice.bind(null, 'host-storage-status');
|
|
|
const hostSchedulingNotice = hostDrawerNotice.bind(null, 'host-scheduling-status');
|
|
|
const hostNetworkPoolNotice = hostDrawerNotice.bind(null, 'host-network-pools-status');
|
|
|
function lockHostDrawerScroll(drawer) {
|
|
|
const scroll = { x: window.scrollX, y: window.scrollY };
|
|
|
state[`${drawer}Scroll`] = scroll;
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-scroll.y}px`);
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
}
|
|
|
function finishHostDrawerClose(drawer) {
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
const scroll = state[`${drawer}Scroll`];
|
|
|
if (scroll) window.scrollTo({ left: scroll.x, top: scroll.y, behavior: 'instant' });
|
|
|
state[`${drawer}Scroll`] = null;
|
|
|
const opener = state[`${drawer}Opener`];
|
|
|
if (opener?.isConnected) opener.focus({ preventScroll: true });
|
|
|
state[`${drawer}Opener`] = null;
|
|
|
}
|
|
|
function closeHostDrawer(id, drawer) {
|
|
|
const dialog = byId(id);
|
|
|
if (!dialog?.open) return;
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (closed) finishHostDrawerClose(drawer);
|
|
|
});
|
|
|
}
|
|
|
function renderHostStorage(payload) {
|
|
|
if (!payload?.host_id) throw new Error('宿主机存储响应无效。');
|
|
|
byId('host-storage-title').textContent = `${payload.host_name || `宿主机 #${payload.host_id}`} · 存储目录`;
|
|
|
byId('host-storage-host-id').value = payload.host_id;
|
|
|
byId('host-storage-revision').value = Number(payload.revision || 0);
|
|
|
const validState = ['unconfigured', 'applying', 'failed', 'applied'].includes(payload.state);
|
|
|
const canSubmit = validState && payload.can_submit === true;
|
|
|
const locked = !canSubmit;
|
|
|
for (const [field, id] of Object.entries(storageFields)) {
|
|
|
const input = byId(id); input.value = payload[field] || ''; input.readOnly = locked; input.disabled = !canManage;
|
|
|
}
|
|
|
const labels = { unconfigured: '尚未配置', applying: '正在等待 Agent 完成', failed: '上一次任务已失败且不会自动重试;新任务须沿用已定义固定池的路径,只可修正尚未定义的角色', applied: '已应用' };
|
|
|
let message = labels[payload.state] || '状态协议无效,资源已安全锁定,需管理员人工处理';
|
|
|
if (payload.state === 'failed' && !canSubmit) {
|
|
|
message = '应用失败,但任务账本状态不完整,请联系管理员核查';
|
|
|
}
|
|
|
if (payload.operation_id && payload.state !== 'applied') message += ` · operation_id ${payload.operation_id}`;
|
|
|
if (payload.requires_agent_retest) message += ' · 请前往 Agent API 重新测试后再启用调度';
|
|
|
hostStorageNotice(message, payload.state === 'failed' || !validState);
|
|
|
const save = byId('host-storage-save'); if (save) { save.dataset.applied = payload.configured === true ? '1' : '0'; save.dataset.taskPending = '0'; save.disabled = !canManage || !canSubmit; }
|
|
|
if (payload.state === 'applying' && payload.task_id && payload.status_url) {
|
|
|
observeHostStorageTask({ task_id: payload.task_id, status_url: payload.status_url }, payload.host_id);
|
|
|
} else if (state.storageObserver && !state.storageObserver.active) {
|
|
|
state.storageObserver = null;
|
|
|
}
|
|
|
}
|
|
|
function lockHostStorageForTask(locked) {
|
|
|
for (const id of Object.values(storageFields)) byId(id).readOnly = locked;
|
|
|
const save = byId('host-storage-save');
|
|
|
if (!save) return;
|
|
|
save.dataset.taskPending = locked ? '1' : '0';
|
|
|
save.disabled = locked || !canManage || save.dataset.applied === '1';
|
|
|
}
|
|
|
function closeHostStorage() {
|
|
|
stopHostStorageObserver('drawer-close');
|
|
|
closeHostDrawer('host-storage-drawer', 'storage');
|
|
|
}
|
|
|
async function openHostStorage(hostId, opener) {
|
|
|
if (!canManage || state.storageBusy) return; state.storageBusy = true; stopHostStorageObserver('drawer-reopen'); state.storageOpener = opener; const dialog = byId('host-storage-drawer'); const form = byId('host-storage-form'); const save = byId('host-storage-save'); form.reset(); byId('host-storage-host-id').value = ''; byId('host-storage-revision').value = '0'; if (save) { save.disabled = true; save.dataset.applied = '0'; save.dataset.taskPending = '0'; } hostStorageNotice('正在读取面板存储配置…');
|
|
|
if (!dialog.open) { lockHostDrawerScroll('storage'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
|
|
|
try { renderHostStorage(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/storage-configuration`)); }
|
|
|
catch (error) { hostStorageNotice(error.message, true); }
|
|
|
finally { state.storageBusy = false; }
|
|
|
}
|
|
|
function stopHostStorageObserver(reason = 'replaced') {
|
|
|
const active = state.storageObserver;
|
|
|
state.storageObserver = null;
|
|
|
if (active?.active) active.stop(reason);
|
|
|
}
|
|
|
function refreshHostStorageAfterTask(hostId, task, message) {
|
|
|
const currentHost = () => String(byId('host-storage-host-id').value) === String(hostId);
|
|
|
return api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/storage-configuration`)
|
|
|
.then(payload => {
|
|
|
if (!currentHost()) return;
|
|
|
renderHostStorage(payload);
|
|
|
hostStorageNotice(message(payload), task?.status === 'failed'
|
|
|
|| payload.state === 'failed');
|
|
|
})
|
|
|
.catch(error => {
|
|
|
if (currentHost()) hostStorageNotice(`刷新存储配置失败:${error.message}`, true);
|
|
|
});
|
|
|
}
|
|
|
function observeHostStorageTask(receipt, hostId) {
|
|
|
const url = taskUrl(receipt);
|
|
|
if (!url) return;
|
|
|
if (state.storageObserver?.active && state.storageObserver.url === url) return;
|
|
|
stopHostStorageObserver();
|
|
|
lockHostStorageForTask(true);
|
|
|
const currentHost = () => String(byId('host-storage-host-id').value) === String(hostId);
|
|
|
const handle = observeTask(receipt, {
|
|
|
// Storage helpers have a 120 second execution budget and the panel has a
|
|
|
// 180 second receipt deadline. Observation is GET-only and stops after a
|
|
|
// final bounded convergence read; it never replays the mutation.
|
|
|
maxDurationMs: 300000,
|
|
|
onUpdate: task => {
|
|
|
if (currentHost() && !task.terminal) hostStorageNotice(`任务 #${task.id} 正在后台应用存储配置。`);
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
if (!currentHost()) return;
|
|
|
void refreshHostStorageAfterTask(hostId, task, payload => {
|
|
|
if (task.status === 'succeeded') return `任务 #${task.id} 已成功,存储配置已刷新。`;
|
|
|
const failure = task.error || '宿主机存储配置失败。';
|
|
|
const partial = task.effect_may_have_applied === true
|
|
|
? ' 部分固定存储池可能已经应用;新任务只会核验并补全,不会迁移或删除数据。' : '';
|
|
|
const next = payload.state === 'failed' && payload.can_submit === true
|
|
|
? ' 旧任务已终止且不会重放;现在可以提交新的独立任务。'
|
|
|
: ' 当前任务账本状态异常,请联系管理员核查。';
|
|
|
return `${failure}${partial}${next}`;
|
|
|
});
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (!currentHost() || reason !== 'deadline') return;
|
|
|
void refreshHostStorageAfterTask(hostId, null, payload => payload.state === 'failed' && payload.can_submit === true
|
|
|
? '任务未在截止时间内返回终态回执,已按失败结束;现在可以提交新的独立任务。'
|
|
|
: '任务观察已结束,存储状态已刷新。');
|
|
|
},
|
|
|
});
|
|
|
state.storageObserver = handle;
|
|
|
state.taskObservers.add(handle);
|
|
|
void handle.done.finally(() => {
|
|
|
state.taskObservers.delete(handle);
|
|
|
if (state.storageObserver === handle) state.storageObserver = null;
|
|
|
});
|
|
|
}
|
|
|
function storageBody() {
|
|
|
const body = { expected_revision: Number(byId('host-storage-revision').value) };
|
|
|
for (const [field, id] of Object.entries(storageFields)) body[field] = byId(id).value.trim();
|
|
|
if (!Number.isInteger(body.expected_revision) || body.expected_revision < 0) throw new Error('存储配置版本无效,请重新打开。');
|
|
|
return body;
|
|
|
}
|
|
|
async function saveHostStorage(event) {
|
|
|
event.preventDefault(); if (!canManage || state.storageBusy) return; const hostId = byId('host-storage-host-id').value; if (!hostId) return;
|
|
|
let body; try { body = storageBody(); } catch (error) { hostStorageNotice(error.message, true); return; }
|
|
|
state.storageBusy = true; const button = byId('host-storage-save'); if (button) button.disabled = true; hostStorageNotice('正在保存目录并请求 Agent 注册 libvirt 存储池…');
|
|
|
try {
|
|
|
const receipt = await acceptedTask(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/storage-configuration`, { method: 'PUT', body });
|
|
|
announceTaskAccepted(receipt, { title: '配置宿主机存储' });
|
|
|
observeHostStorageTask(receipt, hostId);
|
|
|
hostStorageNotice(`任务 #${receipt.task_id} 已接收,正在后台应用存储配置。`);
|
|
|
} catch (error) {
|
|
|
if (error.keepMutationLocked === true) lockHostStorageForTask(true);
|
|
|
hostStorageNotice(error.message, true);
|
|
|
} finally {
|
|
|
state.storageBusy = false;
|
|
|
if (button) button.disabled = !canManage || button.dataset.applied === '1' || button.dataset.taskPending === '1';
|
|
|
}
|
|
|
}
|
|
|
function schedulerLabel(value) { return ({ active: '调度启用', draining: '正在排空', disabled: '调度停用' })[value] || '调度未配置'; }
|
|
|
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 closeHostScheduling() { closeHostDrawer('host-scheduling-drawer', 'scheduling'); }
|
|
|
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) { lockHostDrawerScroll('scheduling'); 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 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);
|
|
|
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 (!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.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();
|
|
|
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 [['默认网络接入', hostNetworkLabel(host.default_network)], ['所属线路', line ? `${line.name}(${line.status})` : '尚未加入资源池'], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label === '默认网络接入' ? 'admin-mono' : '', value));
|
|
|
const 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('每个地址池由面板保存并维护 IP 账本,宿主机 Agent 只执行明确下发的网络操作。');
|
|
|
return true;
|
|
|
}
|
|
|
function closeHostNetworkPools() {
|
|
|
++state.networkPoolEpoch; state.networkPoolBusy = false; clearNetworkPoolPayload();
|
|
|
const dialog = byId('host-network-pools-drawer'); if (!dialog?.open) { finishHostDrawerClose('networkPool'); return; }
|
|
|
closeHostDrawer('host-network-pools-drawer', 'networkPool');
|
|
|
}
|
|
|
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) { lockHostDrawerScroll('networkPool'); 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) 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);
|
|
|
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 saveHost(event) {
|
|
|
event.preventDefault(); if (!canManage || state.busy) return;
|
|
|
const id = byId('host-id').value;
|
|
|
let network;
|
|
|
try { network = hostNetworkValue(); }
|
|
|
catch (error) { byId('host-form-error').textContent = error.message; notice(error.message, true); return; }
|
|
|
const body = { name: byId('host-name').value.trim(), enabled: byId('host-enabled').checked, country_code: byId('host-country-code').value, region: byId('host-region').value.trim(), default_network: network };
|
|
|
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);
|
|
|
notice('宿主机配置已保存。网络接入变更后请前往 Agent API 重新测试,再启用调度。');
|
|
|
}
|
|
|
catch (error) { byId('host-form-error').textContent = error.message; notice(error.message, true); }
|
|
|
finally { 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: '', generationToken: '', 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.generationToken = '';
|
|
|
startupScriptState.revision = null;
|
|
|
byId('template-startup-script').value = '';
|
|
|
dialog.close();
|
|
|
if (startupScriptState.opener?.isConnected) startupScriptState.opener.focus();
|
|
|
startupScriptState.opener = null;
|
|
|
}
|
|
|
function applyStartupScriptPayload(payload, generationToken = '') {
|
|
|
if (!payload || typeof payload.startup_script !== 'string'
|
|
|
|| !Number.isSafeInteger(payload.revision) || payload.revision < 1
|
|
|
|| !/^[a-f0-9]{32}$/.test(payload.generation_token || '')
|
|
|
|| (generationToken && payload.generation_token !== generationToken)) {
|
|
|
throw new Error('镜像或脚本版本已变化,请刷新镜像目录后重新打开设置。');
|
|
|
}
|
|
|
byId('template-startup-script').value = payload.startup_script;
|
|
|
startupScriptState.generationToken = payload.generation_token;
|
|
|
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, generationToken: String(entry.generation_token || ''), 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, startupScriptState.generationToken);
|
|
|
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, generationToken, 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, generation_token: generationToken },
|
|
|
});
|
|
|
if (!startupScriptContextCurrent(templateId, epoch)) return;
|
|
|
applyStartupScriptPayload(payload, generationToken);
|
|
|
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 catalogState = String(entry.state || '').toLowerCase(); const active = rescue || catalogState === 'active'; const name = element('input', 'form-control'); name.value = entry.name || ''; name.maxLength = 64; name.required = true; name.setAttribute('aria-label', '模版名称'); name.disabled = !canManage || !active; const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage || !active; 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.disabled = !active; startup.addEventListener('click', () => openStartupScript(entry, startup)); row.append(startup); }
|
|
|
const stateLabel = rescue ? '' : ({ active: '已就绪', importing: '导入中', error: '导入失败' }[catalogState] || '状态未知') + ' · ';
|
|
|
row.dataset.catalogState = catalogState || 'unknown';
|
|
|
row.append(element('small', 'cloud-admin-meta', `${stateLabel}${entry.os_family || '镜像'} ${entry.os_version || ''} · ${imageBytes > 0 ? (imageBytes / 1024 ** 3).toFixed(2) + ' GiB' : entry.id}`));
|
|
|
if (!rescue && Array.isArray(entry.replicas)) for (const replica of entry.replicas) {
|
|
|
const replicaState = String(replica?.state || 'unknown').toLowerCase();
|
|
|
const replicaLabel = ({ active: '已就绪', pending: '等待同步', failed: '失败,资源已安全锁定', stale: '等待同步' }[replicaState] || '状态协议无效');
|
|
|
const details = [replica?.error_code, replica?.operation_id].filter(value => String(value || '').trim() !== '').map(String);
|
|
|
row.append(element('small', 'cloud-admin-meta', `宿主机 #${Number(replica?.host_id || 0)} · ${replicaLabel}${details.length ? ' · ' + details.join(' · ') : ''}`));
|
|
|
}
|
|
|
if (rescue) { name.readOnly = true; save.hidden = true; save.disabled = true; }
|
|
|
row.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (rescue) return;
|
|
|
if (!active) return notice('镜像尚未就绪,不能修改名称。', true);
|
|
|
if (state.busy) return notice('请等待当前导入任务完成。', true);
|
|
|
save.disabled = true;
|
|
|
state.busy = true;
|
|
|
try {
|
|
|
const receipt = await acceptedTask(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'PATCH', body: { name: name.value.trim(), expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
const handle = importProgress(receipt, '同步镜像名称', async () => {
|
|
|
await loadCatalog();
|
|
|
notice('名称已保存。');
|
|
|
}, task => {
|
|
|
save.disabled = !canManage || !active || task.safe_to_resubmit !== true;
|
|
|
});
|
|
|
if (handle) notice(`名称同步任务已接收(#${receipt.task_id}),正在后台执行。`);
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
save.disabled = !canManage || !active || error.keepMutationLocked === true;
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
}
|
|
|
});
|
|
|
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)}`;
|
|
|
state.busy = true;
|
|
|
try {
|
|
|
const result = await api(deleteUrl, rescue
|
|
|
? { method: 'DELETE' }
|
|
|
: { method: 'DELETE', body: { expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') } });
|
|
|
if (result?.deleted === true) {
|
|
|
await loadCatalog();
|
|
|
notice('镜像模版及其受管文件已确认删除。');
|
|
|
} else {
|
|
|
importProgress(result, '删除镜像模版', async () => {
|
|
|
await loadCatalog();
|
|
|
notice('镜像模版及其受管文件已确认删除。');
|
|
|
});
|
|
|
notice('任务已接收,正在后台删除;可在任务中心 API 查看结果。');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
remove.disabled = !canManage;
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
}
|
|
|
}); list.append(row);
|
|
|
} notice(rescue ? `已加载 ${entries.length} 个模版。` : `已加载 ${entries.length} 个全局云镜像。`);
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
function taskFailureMessage(task, fallback) {
|
|
|
const message = task?.error || fallback;
|
|
|
if (task?.effect_may_have_applied) {
|
|
|
return `${message} 操作效果可能已经发生,请勿再次提交,并将任务编号交由管理员核查。`;
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? `${message} 此任务不可再次提交,请联系管理员核查。` : message;
|
|
|
}
|
|
|
function importProgress(result, title = '导入镜像', onSuccess = loadCatalog, onFailure = null) {
|
|
|
announceTaskAccepted(result, { title });
|
|
|
const handle = observeTask(result, {
|
|
|
onUpdate: () => notice(`${title}任务正在后台执行。`),
|
|
|
onTerminal: task => {
|
|
|
if (task.status === 'succeeded') {
|
|
|
void Promise.resolve(onSuccess()).catch(error => notice(error.message, true));
|
|
|
} else {
|
|
|
notice(taskFailureMessage(task, `${title}失败。`), true);
|
|
|
if (typeof onFailure === 'function') void Promise.resolve(onFailure(task)).catch(error => notice(error.message, true));
|
|
|
}
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'deadline') notice('自动观察已停止。任务仍在后台执行,请通过任务中心 API 刷新结果。');
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
notice(`${title}任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。`, true);
|
|
|
return null;
|
|
|
}
|
|
|
state.taskObservers.add(handle);
|
|
|
void handle.done.finally(() => state.taskObservers.delete(handle));
|
|
|
return handle;
|
|
|
}
|
|
|
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 }); if (importProgress(result, '导入云镜像', async () => { await loadCatalog(); notice('镜像导入已完成。'); })) 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)}%,请勿关闭页面…`);
|
|
|
});
|
|
|
input.value = '';
|
|
|
if (importProgress(result, '导入本地云镜像', async () => { await loadCatalog(); notice('本地云镜像上传并导入完成。'); })) {
|
|
|
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 }); byId('rescue-file').value = ''; if (importProgress(result, '导入救援 ISO', async () => { await loadCatalog(); notice('救援 ISO 导入已完成。'); })) 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;
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
for (const observer of state.taskObservers) observer.stop('pagehide');
|
|
|
state.taskObservers.clear();
|
|
|
});
|
|
|
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-form').addEventListener('submit', saveHost); byId('user-iso-settings-form').addEventListener('submit', saveUserIsoSettings);
|
|
|
byId('host-network-type').addEventListener('change', updateHostNetworkControls);
|
|
|
byId('host-storage-form').addEventListener('submit', saveHostStorage); byId('host-storage-close').addEventListener('click', closeHostStorage);
|
|
|
const storageDrawer = byId('host-storage-drawer'); storageDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostStorage(); }); storageDrawer.addEventListener('click', event => { if (event.target === storageDrawer) closeHostStorage(); });
|
|
|
byId('host-scheduling-form').addEventListener('submit', saveHostScheduling); byId('host-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(); });
|
|
|
if (!canManage) { byId('host-form').querySelectorAll('input,select,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();
|