|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const {
|
|
|
announceTaskAccepted, observeTask, recoveryTaskFailureNotice,
|
|
|
taskSucceededWithoutRecovery, taskUrl,
|
|
|
} = await import(versionedModuleUrl('./task-observer.js'));
|
|
|
|
|
|
const root = document.querySelector('[data-cloud-admin]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', hosts: [], hostRegions: [], hostSummary: {}, expandedHostRegions: new Set(), hostRegionsInitialized: false, selectedHost: '', busy: false, epoch: 0, configBusy: false, configOpener: null, configScroll: null, 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: '', vpcTransportBusy: false, vpcTransportOpener: null, vpcTransportScroll: null, vpcTransportHostId: '', vpcTransportCandidates: [], 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() {
|
|
|
const payload = await api('/api/v1/admin/hosts');
|
|
|
state.hosts = collection(payload, 'hosts').map(profile);
|
|
|
state.hostRegions = collection(payload, 'regions').map(region => ({ ...region, hosts: collection(region, 'hosts').map(profile) }));
|
|
|
state.hostSummary = payload?.summary && typeof payload.summary === 'object' ? payload.summary : {};
|
|
|
if (!state.hostRegionsInitialized) {
|
|
|
const first = state.hostRegions[0];
|
|
|
if (first) state.expandedHostRegions.add(hostRegionKey(first));
|
|
|
for (const region of state.hostRegions) {
|
|
|
if (Number(region?.summary?.attention_hosts || 0) > 0) state.expandedHostRegions.add(hostRegionKey(region));
|
|
|
}
|
|
|
state.hostRegionsInitialized = true;
|
|
|
}
|
|
|
return state.hosts;
|
|
|
}
|
|
|
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}` : '添加计算节点'; byId('host-save').lastChild.textContent = host ? '保存节点' : '创建节点';
|
|
|
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 hostRegionKey(region) { return region?.id === null || region?.id === undefined ? 'unclassified' : `region:${region.id}`; }
|
|
|
function agentLabel(value) { return ({ ready: 'Agent 已就绪', pending: 'Agent 待验证', failed: 'Agent 测试失败', disabled: 'Agent 已停用', unconfigured: 'Agent 未配置' })[value] || 'Agent 状态未知'; }
|
|
|
function hostStateBadge(label, tone) { return element('span', `cloud-admin-host-badge is-${tone}`, label); }
|
|
|
function renderHostSummary() {
|
|
|
const summary = byId('host-summary');
|
|
|
if (!summary) return;
|
|
|
const data = state.hostSummary || {};
|
|
|
const items = [
|
|
|
['map-marker-radius-outline', '地区', data.regions_total || 0],
|
|
|
['server-network', '计算节点', data.hosts_total || 0],
|
|
|
['check-decagram-outline', '可调度', data.placement_ready_hosts || 0],
|
|
|
['timer-sand', '正在排空', data.scheduler_draining || 0],
|
|
|
['alert-circle-outline', '需要处理', data.attention_hosts || 0],
|
|
|
];
|
|
|
summary.replaceChildren(...items.map(([icon, label, value]) => {
|
|
|
const card = element('article', 'cloud-admin-host-summary-card');
|
|
|
const copy = element('div'); copy.append(element('span', '', label), element('strong', '', value));
|
|
|
const badge = element('span', 'cloud-admin-host-summary-icon'); badge.innerHTML = `<i class="mdi mdi-${icon}" aria-hidden="true"></i>`;
|
|
|
card.append(badge, copy); return card;
|
|
|
}));
|
|
|
}
|
|
|
function syncHostRegionFilter() {
|
|
|
const select = byId('host-region-filter');
|
|
|
if (!select) return;
|
|
|
const selected = select.value;
|
|
|
select.replaceChildren(new Option('全部地区', ''));
|
|
|
for (const region of state.hostRegions) {
|
|
|
const value = region.id === null || region.id === undefined ? 'unclassified' : String(region.id);
|
|
|
const count = Number(region?.summary?.hosts_total || collection(region, 'hosts').length);
|
|
|
select.append(new Option(`${region.country_flag || '🌐'} ${region.name || '未分类节点'}(${count})`, value));
|
|
|
}
|
|
|
select.value = Array.from(select.options).some(option => option.value === selected) ? selected : '';
|
|
|
}
|
|
|
function hostMatchesFilter(host, search, regionValue, stateValue) {
|
|
|
const placement = host?.placement || {};
|
|
|
const regionId = placement.region_id === null || placement.region_id === undefined ? 'unclassified' : String(placement.region_id);
|
|
|
if (regionValue && regionId !== regionValue) return false;
|
|
|
if (stateValue === 'ready' && host?.readiness?.placement_ready !== true) return false;
|
|
|
if (stateValue === 'attention' && host?.needs_attention !== true) return false;
|
|
|
if (['active', 'draining', 'disabled'].includes(stateValue) && host.scheduler_state !== stateValue) return false;
|
|
|
if (!search) return true;
|
|
|
return [host.name, host.id, host.region, host.country_code, placement.region_name, placement.line_name, placement.pool_name]
|
|
|
.some(value => String(value || '').toLocaleLowerCase().includes(search));
|
|
|
}
|
|
|
function renderHostNode(host) {
|
|
|
const row = element('article', 'cloud-admin-host-node');
|
|
|
const button = element('button', 'cloud-admin-host');
|
|
|
button.type = 'button';
|
|
|
button.dataset.hostId = String(host.id);
|
|
|
button.setAttribute('aria-label', `配置计算节点 ${host.name || host.id}`);
|
|
|
button.setAttribute('aria-controls', 'host-config-drawer');
|
|
|
button.setAttribute('aria-haspopup', 'dialog');
|
|
|
if (String(state.selectedHost) === String(host.id)) button.setAttribute('aria-current', 'true');
|
|
|
const heading = element('span', 'cloud-admin-host-heading');
|
|
|
heading.append(element('strong', '', host.name || `计算节点 ${host.id}`), element('small', '', `#${host.id} · ${host?.location?.physical_label || host.region || '物理位置未设置'}`));
|
|
|
const status = element('span', 'cloud-admin-host-statuses');
|
|
|
status.append(
|
|
|
hostStateBadge(agentLabel(host?.agent?.state), host?.agent?.ready ? 'success' : 'warning'),
|
|
|
hostStateBadge(host.enabled ? '服务启用' : '服务停用', host.enabled ? 'success' : 'muted'),
|
|
|
hostStateBadge(schedulerLabel(host.scheduler_state), host.scheduler_state === 'active' ? 'success' : host.scheduler_state === 'draining' ? 'warning' : 'muted')
|
|
|
);
|
|
|
const path = element('span', 'cloud-admin-host-path', [host?.placement?.line_name, host?.placement?.pool_name].filter(Boolean).join(' · ') || '尚未选择资源池');
|
|
|
const capacity = host?.capacity || {};
|
|
|
const metrics = element('span', 'cloud-admin-host-metrics');
|
|
|
metrics.append(
|
|
|
element('span', '', `实例 ${Number(capacity?.instances?.allocated || 0)}`),
|
|
|
element('span', '', `CPU ${Number(capacity?.cpu?.allocated || 0)}/${Number(capacity?.cpu?.configured || 0)} 核`),
|
|
|
element('span', '', `公网 IP ${Number(capacity?.ip?.available || 0)}/${Number(capacity?.ip?.total || 0)}`)
|
|
|
);
|
|
|
button.append(heading, status, path, metrics);
|
|
|
button.addEventListener('click', () => openHostConfig(host.id, button));
|
|
|
row.append(button);
|
|
|
return row;
|
|
|
}
|
|
|
function renderHosts() {
|
|
|
renderHostSummary(); syncHostRegionFilter();
|
|
|
const list = byId('host-list'); list.replaceChildren();
|
|
|
if (!state.hosts.length) { list.append(element('p', 'cloud-admin-host-empty', '暂无计算节点。')); return; }
|
|
|
const search = String(byId('host-search')?.value || '').trim().toLocaleLowerCase();
|
|
|
const regionValue = String(byId('host-region-filter')?.value || '');
|
|
|
const stateValue = String(byId('host-state-filter')?.value || '');
|
|
|
let visible = 0;
|
|
|
for (const region of state.hostRegions) {
|
|
|
const hosts = collection(region, 'hosts').filter(host => hostMatchesFilter(host, search, regionValue, stateValue));
|
|
|
if (!hosts.length) continue;
|
|
|
visible += hosts.length;
|
|
|
const key = hostRegionKey(region);
|
|
|
const group = element('details', 'cloud-admin-host-region');
|
|
|
group.open = search !== '' || regionValue !== '' || stateValue !== '' || state.expandedHostRegions.has(key);
|
|
|
group.addEventListener('toggle', () => group.open ? state.expandedHostRegions.add(key) : state.expandedHostRegions.delete(key));
|
|
|
const header = element('summary', 'cloud-admin-host-region-head');
|
|
|
const identity = element('span', 'cloud-admin-host-region-identity');
|
|
|
identity.append(element('span', 'cloud-admin-host-region-flag', region.country_flag || '🌐'), element('span', '', region.name || '未分类节点'));
|
|
|
const meta = element('span', 'cloud-admin-host-region-meta');
|
|
|
const attention = Number(region?.summary?.attention_hosts || 0);
|
|
|
meta.append(element('span', '', `${hosts.length} 台节点`), element('span', '', `${Number(region?.summary?.agent_ready_hosts || 0)} 台 Agent 就绪`));
|
|
|
if (attention > 0) meta.append(hostStateBadge(`${attention} 项需处理`, 'warning'));
|
|
|
header.append(identity, meta);
|
|
|
const capacity = region?.capacity || {};
|
|
|
const overview = element('div', 'cloud-admin-host-region-capacity');
|
|
|
overview.append(
|
|
|
element('span', '', `CPU ${Number(capacity?.cpu?.allocated || 0)}/${Number(capacity?.cpu?.configured || 0)} 核`),
|
|
|
element('span', '', `内存 ${Number(capacity?.memory?.allocated || 0)}/${Number(capacity?.memory?.configured || 0)} MiB`),
|
|
|
element('span', '', `公网 IP ${Number(capacity?.ip?.available || 0)}/${Number(capacity?.ip?.total || 0)}`)
|
|
|
);
|
|
|
const nodes = element('div', 'cloud-admin-host-region-nodes');
|
|
|
nodes.append(...hosts.map(renderHostNode));
|
|
|
group.append(header, overview, nodes); list.append(group);
|
|
|
}
|
|
|
if (visible === 0) list.append(element('p', 'cloud-admin-host-empty', '没有符合当前筛选条件的计算节点。'));
|
|
|
}
|
|
|
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');
|
|
|
const hostVpcTransportNotice = hostDrawerNotice.bind(null, 'host-vpc-transport-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 closeHostConfig() { closeHostDrawer('host-config-drawer', 'config'); }
|
|
|
function renderHostConfigOverview(host) {
|
|
|
const overview = byId('host-config-overview');
|
|
|
if (!overview) return;
|
|
|
overview.hidden = !host;
|
|
|
if (!host) {
|
|
|
byId('host-config-metrics').replaceChildren();
|
|
|
return;
|
|
|
}
|
|
|
const placement = host.placement || {};
|
|
|
const capacity = host.capacity || {};
|
|
|
const location = host.location || {};
|
|
|
const placementPath = [placement.region_name, placement.line_name, placement.pool_name].filter(Boolean).join(' / ');
|
|
|
byId('host-config-placement').textContent = `${location.country_flag || '🌐'} ${placementPath || '尚未加入资源池'} · 物理位置 ${location.physical_label || host.region || '未设置'}`;
|
|
|
const rows = [
|
|
|
['Agent', `${agentLabel(host?.agent?.state)}${host?.agent?.version ? ` · ${host.agent.version}` : ''}`],
|
|
|
['服务状态', host.enabled ? '已启用' : '已停用'],
|
|
|
['调度状态', schedulerLabel(host.scheduler_state)],
|
|
|
['实例', `${Number(capacity?.instances?.allocated || 0)} 台已分配`],
|
|
|
['CPU', `${Number(capacity?.cpu?.allocated || 0)} / ${Number(capacity?.cpu?.configured || 0)} 核`],
|
|
|
['内存', `${Number(capacity?.memory?.allocated || 0)} / ${Number(capacity?.memory?.configured || 0)} MiB`],
|
|
|
['磁盘', `${Number(capacity?.disk?.allocated || 0)} / ${Number(capacity?.disk?.configured || 0)} GiB`],
|
|
|
['公网 IP', `${Number(capacity?.ip?.available || 0)} / ${Number(capacity?.ip?.total || 0)} 个可用`],
|
|
|
];
|
|
|
const metrics = byId('host-config-metrics');
|
|
|
metrics.replaceChildren();
|
|
|
for (const [label, value] of rows) metrics.append(element('dt', '', label), element('dd', '', value));
|
|
|
}
|
|
|
function showHostConfig(opener) {
|
|
|
state.configOpener = opener || null;
|
|
|
const dialog = byId('host-config-drawer');
|
|
|
if (!dialog.open) {
|
|
|
lockHostDrawerScroll('config');
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
}
|
|
|
}
|
|
|
function openNewHostConfig(opener) {
|
|
|
if (state.configBusy) return;
|
|
|
state.selectedHost = '';
|
|
|
renderHostConfigOverview(null);
|
|
|
fillHost(null);
|
|
|
renderHosts();
|
|
|
showHostConfig(opener);
|
|
|
}
|
|
|
async function openHostConfig(hostId, opener) {
|
|
|
if (state.configBusy) return;
|
|
|
state.configBusy = true;
|
|
|
renderHostConfigOverview(state.hosts.find(host => Number(host.id) === Number(hostId)) || null);
|
|
|
showHostConfig(opener);
|
|
|
byId('host-form-title').textContent = '正在读取计算节点…';
|
|
|
byId('host-save').disabled = true;
|
|
|
try {
|
|
|
const host = profile(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}`));
|
|
|
state.selectedHost = String(host.id);
|
|
|
fillHost(host);
|
|
|
renderHosts();
|
|
|
notice('已读取计算节点配置。Agent 地址和密钥请在“Agent API”页面维护。');
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
closeHostConfig();
|
|
|
} finally {
|
|
|
state.configBusy = false;
|
|
|
byId('host-save').disabled = !canManage;
|
|
|
}
|
|
|
}
|
|
|
function openHostConfigTool(kind) {
|
|
|
const hostId = byId('host-id').value;
|
|
|
if (!hostId || state.configBusy) return;
|
|
|
const openers = {
|
|
|
scheduling: openHostScheduling,
|
|
|
networkPools: openHostNetworkPools,
|
|
|
vpc: openHostVpcTransport,
|
|
|
storage: openHostStorage,
|
|
|
};
|
|
|
const open = openers[kind];
|
|
|
if (typeof open !== 'function') return;
|
|
|
const returnOpener = state.configOpener;
|
|
|
const dialog = byId('host-config-drawer');
|
|
|
if (!dialog?.open) {
|
|
|
void open(hostId, returnOpener);
|
|
|
return;
|
|
|
}
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (!closed) return;
|
|
|
finishHostDrawerClose('config');
|
|
|
void open(hostId, returnOpener);
|
|
|
});
|
|
|
}
|
|
|
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?.terminal === true
|
|
|
&& !taskSucceededWithoutRecovery(task)
|
|
|
|| 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 (taskSucceededWithoutRecovery(task)) return `任务 #${task.id} 已成功,存储配置已刷新。`;
|
|
|
const recoveryNotice = recoveryTaskFailureNotice(task);
|
|
|
if (recoveryNotice) return recoveryNotice;
|
|
|
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]) control.disabled = true;
|
|
|
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。'));
|
|
|
}
|
|
|
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(); }
|
|
|
}
|
|
|
}
|
|
|
function vpcTransportStateLabel(payload) {
|
|
|
if (!payload?.configured) return '尚未保存传输配置';
|
|
|
if (payload.ready === true) return `版本 ${payload.desired_revision} 已验证就绪`;
|
|
|
const states = { pending: '配置已保存,等待验证', failed: '验证失败', applying: '正在应用', unknown: '结果未知,已锁定', never: '尚未验证' };
|
|
|
const error = payload.last_error_code ? ` · ${payload.last_error_code}` : '';
|
|
|
return `${states[payload.sync_state] || '状态异常'}${error}`;
|
|
|
}
|
|
|
function renderVpcTransportCandidates(candidates) {
|
|
|
state.vpcTransportCandidates = Array.isArray(candidates) ? candidates : [];
|
|
|
const select = byId('host-vpc-transport-candidate'); select.replaceChildren();
|
|
|
const empty = element('option', '', state.vpcTransportCandidates.length ? '请选择 Agent 候选地址' : '尚未读取 Agent 候选'); empty.value = ''; select.append(empty);
|
|
|
state.vpcTransportCandidates.forEach((candidate, index) => {
|
|
|
const option = element('option', '', `${candidate.interface} · ${candidate.address_cidr} · MTU ${candidate.mtu}${candidate.is_bridge ? ' · 网桥' : ''}${candidate.selectable ? '' : '(MTU 超出面板范围)'}`);
|
|
|
option.value = String(index); option.disabled = candidate.selectable !== true; select.append(option);
|
|
|
});
|
|
|
}
|
|
|
function renderHostVpcTransport(payload) {
|
|
|
if (!payload?.host?.id) throw new Error('宿主机 VPC 传输响应无效。');
|
|
|
state.vpcTransportHostId = String(payload.host.id);
|
|
|
byId('host-vpc-transport-title').textContent = `${payload.host.name || `宿主机 #${payload.host.id}`} · VPC 私网传输`;
|
|
|
byId('host-vpc-transport-revision').value = Number(payload.desired_revision || 0);
|
|
|
byId('host-vpc-transport-address').value = payload.transport_address || '';
|
|
|
byId('host-vpc-transport-prefix').value = payload.transport_prefix_length ?? '';
|
|
|
byId('host-vpc-transport-interface').value = payload.transport_interface || '';
|
|
|
byId('host-vpc-transport-mtu').value = Number(payload.mtu || 1500);
|
|
|
const summary = byId('host-vpc-transport-summary'); summary.replaceChildren();
|
|
|
const verified = Number(payload.last_verified_at || 0) > 0 ? new Date(Number(payload.last_verified_at) * 1000).toLocaleString() : '从未';
|
|
|
for (const [label, value] of [['模式', 'direct_l3'], ['期望 / 已观察版本', `${Number(payload.desired_revision || 0)} / ${Number(payload.observed_revision || 0)}`], ['最近验证', verified]]) summary.append(element('dt', '', label), element('dd', label === '模式' ? 'admin-mono' : '', value));
|
|
|
hostVpcTransportNotice(vpcTransportStateLabel(payload), payload.sync_state === 'failed' || payload.sync_state === 'unknown');
|
|
|
byId('host-vpc-transport-test').dataset.configured = payload.configured === true ? '1' : '0';
|
|
|
syncVpcTransportButtons();
|
|
|
}
|
|
|
function syncVpcTransportButtons() {
|
|
|
byId('host-vpc-transport-discover').disabled = !canManage || state.vpcTransportBusy;
|
|
|
byId('host-vpc-transport-save').disabled = !canManage || state.vpcTransportBusy;
|
|
|
byId('host-vpc-transport-test').disabled = !canManage || state.vpcTransportBusy || byId('host-vpc-transport-test').dataset.configured !== '1';
|
|
|
}
|
|
|
function closeHostVpcTransport() {
|
|
|
state.vpcTransportHostId = ''; state.vpcTransportCandidates = [];
|
|
|
closeHostDrawer('host-vpc-transport-drawer', 'vpcTransport');
|
|
|
}
|
|
|
async function openHostVpcTransport(hostId, opener) {
|
|
|
if (state.vpcTransportBusy) return;
|
|
|
state.vpcTransportBusy = true; state.vpcTransportOpener = opener; state.vpcTransportHostId = String(hostId); byId('host-vpc-transport-test').dataset.configured = '0'; renderVpcTransportCandidates([]); hostVpcTransportNotice('正在读取面板 VPC 私网传输配置…');
|
|
|
const dialog = byId('host-vpc-transport-drawer');
|
|
|
if (!dialog.open) { lockHostDrawerScroll('vpcTransport'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
|
|
|
try { renderHostVpcTransport(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/vpc-transport`)); }
|
|
|
catch (error) { hostVpcTransportNotice(error.message, true); }
|
|
|
finally { state.vpcTransportBusy = false; syncVpcTransportButtons(); }
|
|
|
}
|
|
|
async function discoverHostVpcTransport() {
|
|
|
const hostId = state.vpcTransportHostId; if (!hostId || !canManage || state.vpcTransportBusy) return;
|
|
|
state.vpcTransportBusy = true; byId('host-vpc-transport-discover').disabled = true; byId('host-vpc-transport-save').disabled = true; byId('host-vpc-transport-test').disabled = true; hostVpcTransportNotice('正在通过认证 Agent 会话读取私网候选…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/vpc-transport/discover`, { method: 'POST', body: {} });
|
|
|
renderVpcTransportCandidates(payload.transport_candidates);
|
|
|
const details = [`候选 ${state.vpcTransportCandidates.length} 个`, payload.ipv4_forwarding ? 'IPv4 转发已启用' : 'IPv4 转发未启用', payload.apply_supported ? '路由应用能力可用' : '路由应用能力尚未提供'];
|
|
|
hostVpcTransportNotice(details.join(' · '), !payload.ipv4_forwarding || !payload.apply_supported);
|
|
|
} catch (error) { renderVpcTransportCandidates([]); hostVpcTransportNotice(error.message, true); }
|
|
|
finally { state.vpcTransportBusy = false; syncVpcTransportButtons(); }
|
|
|
}
|
|
|
function selectHostVpcTransportCandidate() {
|
|
|
const index = Number(byId('host-vpc-transport-candidate').value);
|
|
|
const candidate = Number.isInteger(index) ? state.vpcTransportCandidates[index] : null;
|
|
|
if (!candidate?.selectable) return;
|
|
|
byId('host-vpc-transport-address').value = candidate.address;
|
|
|
byId('host-vpc-transport-prefix').value = candidate.prefix_length;
|
|
|
byId('host-vpc-transport-interface').value = candidate.interface;
|
|
|
byId('host-vpc-transport-mtu').value = candidate.mtu;
|
|
|
}
|
|
|
function vpcTransportBody() {
|
|
|
const prefix = Number(byId('host-vpc-transport-prefix').value); const mtu = Number(byId('host-vpc-transport-mtu').value); const revision = Number(byId('host-vpc-transport-revision').value);
|
|
|
if (!Number.isInteger(prefix) || prefix < 1 || prefix > 32) throw new Error('私网地址前缀必须是 1 至 32 的整数。');
|
|
|
if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9216) throw new Error('MTU 必须是 576 至 9216 的整数。');
|
|
|
if (!Number.isInteger(revision) || revision < 0) throw new Error('VPC 传输配置版本无效,请重新打开。');
|
|
|
return { transport_address: byId('host-vpc-transport-address').value.trim(), transport_prefix_length: prefix, transport_interface: byId('host-vpc-transport-interface').value.trim(), transport_mode: 'direct_l3', mtu, expected_revision: revision };
|
|
|
}
|
|
|
async function saveHostVpcTransport(event) {
|
|
|
event.preventDefault(); const hostId = state.vpcTransportHostId; if (!hostId || !canManage || state.vpcTransportBusy) return;
|
|
|
let body; try { body = vpcTransportBody(); } catch (error) { hostVpcTransportNotice(error.message, true); return; }
|
|
|
state.vpcTransportBusy = true; byId('host-vpc-transport-save').disabled = true; byId('host-vpc-transport-test').disabled = true; hostVpcTransportNotice('正在保存面板 VPC 私网传输期望配置…');
|
|
|
try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/vpc-transport`, { method: 'PUT', body }); renderHostVpcTransport(payload); hostVpcTransportNotice('配置已保存。请执行验证;验证通过前该节点不会承载 VPC。'); }
|
|
|
catch (error) { hostVpcTransportNotice(error.message, true); }
|
|
|
finally { state.vpcTransportBusy = false; syncVpcTransportButtons(); }
|
|
|
}
|
|
|
async function testHostVpcTransport() {
|
|
|
const hostId = state.vpcTransportHostId; if (!hostId || !canManage || state.vpcTransportBusy) return;
|
|
|
state.vpcTransportBusy = true; byId('host-vpc-transport-save').disabled = true; byId('host-vpc-transport-test').disabled = true; hostVpcTransportNotice('正在精确核对地址、接口、前缀、MTU、转发和路由能力…');
|
|
|
try { const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/vpc-transport/test`, { method: 'POST', body: {} }); renderHostVpcTransport(payload); hostVpcTransportNotice('宿主机 VPC 私网传输配置已验证就绪。'); }
|
|
|
catch (error) {
|
|
|
try { renderHostVpcTransport(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/vpc-transport`)); } catch {}
|
|
|
hostVpcTransportNotice(error.message, true);
|
|
|
} finally { state.vpcTransportBusy = false; syncVpcTransportButtons(); }
|
|
|
}
|
|
|
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 });
|
|
|
state.selectedHost = result?.id ? String(result.id) : '';
|
|
|
await loadHosts(); renderHosts(); fillHost(result?.id ? profile(result) : null);
|
|
|
closeHostConfig();
|
|
|
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();
|
|
|
}
|
|
|
}
|
|
|
function catalogStateView(value) {
|
|
|
const stateName = String(value || 'unknown').toLowerCase();
|
|
|
return ({
|
|
|
active: ['已就绪', 'is-ready'], degraded: ['部分可用', 'is-warning'],
|
|
|
error: ['不可用', 'is-error'], preparing: ['准备源文件', 'is-running'],
|
|
|
validating: ['首台校验', 'is-running'], distributing: ['分发中', 'is-running'],
|
|
|
source_failed: ['源文件失败', 'is-error'], source_unknown: ['源文件待核查', 'is-error'],
|
|
|
retiring: ['退役清理中', 'is-running'], retired: ['已退役', 'is-muted'],
|
|
|
importing: ['分发中', 'is-running'], syncing: ['同步中', 'is-running'],
|
|
|
deleting: ['删除中', 'is-running'], delete_failed: ['删除失败', 'is-error'],
|
|
|
}[stateName] || ['状态未知', 'is-muted']);
|
|
|
}
|
|
|
function replicaStateView(replica) {
|
|
|
if (replica?.host_record_present === false) return ['宿主机记录缺失', 'is-error'];
|
|
|
if (replica?.host_eligible !== true) return ['宿主机未就绪', 'is-muted'];
|
|
|
if (replica?.exact === true) return ['精确副本', 'is-ready'];
|
|
|
if (replica?.repair_reason === 'content_divergent') return ['内容分歧', 'is-error'];
|
|
|
const stateName = String(replica?.state || 'unknown').toLowerCase();
|
|
|
return ({
|
|
|
missing: ['缺少副本', 'is-warning'], stale: ['元数据落后', 'is-warning'],
|
|
|
pending: ['等待分发', 'is-running'], importing: ['正在分发', 'is-running'],
|
|
|
syncing: ['正在同步', 'is-running'], failed: ['失败并已锁定', 'is-error'],
|
|
|
deleting: ['正在删除', 'is-running'], delete_succeeded: ['已删除', 'is-muted'],
|
|
|
delete_failed: ['删除待核查', 'is-error'], active: ['投影不一致', 'is-error'],
|
|
|
}[stateName] || ['状态待核查', 'is-error']);
|
|
|
}
|
|
|
function catalogTime(value) {
|
|
|
const timestamp = Number(value || 0);
|
|
|
return timestamp > 0 ? new Date(timestamp * 1000).toLocaleString() : '尚未核对';
|
|
|
}
|
|
|
function compactIdentifier(value, size = 12) {
|
|
|
const text = String(value || '');
|
|
|
return text.length > size ? `${text.slice(0, size)}…` : text;
|
|
|
}
|
|
|
async function repairTemplateReplica(entry, replica, button) {
|
|
|
if (state.busy) return notice('请等待当前镜像任务完成。', true);
|
|
|
const action = String(replica?.repair_action || '');
|
|
|
if (!['import', 'metadata'].includes(action)) return;
|
|
|
const verb = action === 'metadata' ? '同步元数据' : '补齐副本';
|
|
|
if (!confirm(`确定为“${entry.name}”在 ${replica.host_name || `宿主机 #${replica.host_id}`}执行${verb}?`)) return;
|
|
|
state.busy = true;
|
|
|
button.disabled = true;
|
|
|
try {
|
|
|
const { payload, status } = await requestJson(
|
|
|
`/api/v1/admin/cloud-templates/${encodeURIComponent(entry.id)}/replicas/${encodeURIComponent(replica.host_id)}/repair`,
|
|
|
{ method: 'POST', body: {} },
|
|
|
);
|
|
|
if (status === 200 && payload?.scheduled === false) {
|
|
|
await loadCatalog();
|
|
|
notice('副本已是目标版本,无需重复处理。');
|
|
|
return;
|
|
|
}
|
|
|
if (status !== 202 || !taskUrl(payload)) throw new Error('修复请求未返回严格的任务回执,请勿重复提交并联系管理员核查。');
|
|
|
const handle = importProgress(payload, verb, async () => {
|
|
|
await loadCatalog();
|
|
|
notice(`${verb}已完成。`);
|
|
|
});
|
|
|
if (handle) notice(`${verb}任务已接收(#${payload.task_id})。`);
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
button.disabled = !canManage;
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
}
|
|
|
}
|
|
|
function replicaMatrix(entry) {
|
|
|
const details = element('details', 'cloud-template-matrix');
|
|
|
const replicas = Array.isArray(entry.replicas) ? entry.replicas : [];
|
|
|
const summaryData = entry.replica_summary || {};
|
|
|
const eligible = Number(summaryData.eligible || replicas.filter(item => item?.host_eligible === true).length);
|
|
|
const ready = Number(summaryData.ready || replicas.filter(item => item?.exact === true).length);
|
|
|
const attention = Number(summaryData.attention || Math.max(0, eligible - ready));
|
|
|
details.open = attention > 0;
|
|
|
const summary = element('summary', 'cloud-template-matrix-summary');
|
|
|
const summaryCopy = element('span');
|
|
|
summaryCopy.append(
|
|
|
element('strong', '', '宿主机副本'),
|
|
|
element('small', '', `${ready} / ${eligible} 台就绪${attention > 0 ? ` · ${attention} 台需处理` : ''}`),
|
|
|
);
|
|
|
summary.append(summaryCopy, element('span', 'cloud-template-matrix-arrow'));
|
|
|
details.append(summary);
|
|
|
if (!replicas.length) {
|
|
|
details.append(element('p', 'cloud-template-matrix-empty', '当前还没有计算节点记录。'));
|
|
|
return details;
|
|
|
}
|
|
|
const wrap = element('div', 'cloud-template-matrix-scroll');
|
|
|
const table = element('table', 'cloud-template-matrix-table');
|
|
|
const head = element('thead');
|
|
|
const headRow = element('tr');
|
|
|
for (const title of ['宿主机', '目标 / 实际', '状态', '最近核对', '操作']) headRow.append(element('th', '', title));
|
|
|
head.append(headRow);
|
|
|
const body = element('tbody');
|
|
|
for (const replica of replicas) {
|
|
|
const row = element('tr');
|
|
|
const host = element('td', 'cloud-template-host-cell'); host.setAttribute('data-label', '宿主机');
|
|
|
const hostContent = element('span', 'cloud-template-cell-content');
|
|
|
hostContent.append(element('strong', '', replica.host_name || `宿主机 #${replica.host_id}`));
|
|
|
hostContent.append(element('small', '', [replica.host_region, `#${Number(replica.host_id || 0)}`].filter(Boolean).join(' · ')));
|
|
|
host.append(hostContent);
|
|
|
const versions = element('td', 'cloud-template-version-cell'); versions.setAttribute('data-label', '目标 / 实际');
|
|
|
const versionContent = element('span', 'cloud-template-cell-content');
|
|
|
versionContent.append(element('strong', '', `r${Number(entry.revision || 0)} / ${Number(replica.revision || 0) > 0 ? `r${Number(replica.revision)}` : '—'}`));
|
|
|
versionContent.append(element('small', '', Number(replica.observed_revision || 0) > 0 ? `宿主机核对 r${Number(replica.observed_revision)}` : '暂无宿主机核对版本'));
|
|
|
versions.append(versionContent);
|
|
|
const stateCell = element('td'); stateCell.setAttribute('data-label', '状态');
|
|
|
const stateContent = element('span', 'cloud-template-cell-content');
|
|
|
const [stateLabel, stateClass] = replicaStateView(replica);
|
|
|
stateContent.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
const diagnostics = [replica.error_code, compactIdentifier(replica.operation_id)].filter(Boolean).join(' · ');
|
|
|
if (diagnostics) stateContent.append(element('small', 'cloud-template-diagnostic', diagnostics));
|
|
|
stateCell.append(stateContent);
|
|
|
const verified = element('td'); verified.setAttribute('data-label', '最近核对'); verified.append(element('span', 'cloud-template-cell-content', catalogTime(replica.last_verified_at)));
|
|
|
const actionCell = element('td', 'cloud-template-replica-action'); actionCell.setAttribute('data-label', '操作');
|
|
|
if (canManage && ['import', 'metadata'].includes(String(replica.repair_action || ''))) {
|
|
|
const actionLabel = replica.repair_action === 'metadata' ? '同步元数据' : '补齐副本';
|
|
|
const actionButton = element('button', 'btn btn-sm btn-outline-primary', actionLabel);
|
|
|
actionButton.type = 'button';
|
|
|
actionButton.addEventListener('click', () => repairTemplateReplica(entry, replica, actionButton));
|
|
|
actionCell.append(actionButton);
|
|
|
} else {
|
|
|
actionCell.append(element('span', 'text-muted', '—'));
|
|
|
}
|
|
|
row.append(host, versions, stateCell, verified, actionCell);
|
|
|
body.append(row);
|
|
|
}
|
|
|
table.append(head, body); wrap.append(table); details.append(wrap);
|
|
|
return details;
|
|
|
}
|
|
|
function bindCloudTemplateActions(entry, form, name, save, remove, startup) {
|
|
|
const catalogState = String(entry.state || '').toLowerCase();
|
|
|
const active = catalogState === 'active';
|
|
|
const cleanupReason = String(entry.cleanup_reason || '');
|
|
|
const partialCleanup = ['partial_import', 'partial_delete'].includes(cleanupReason);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
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; }
|
|
|
});
|
|
|
startup.addEventListener('click', () => openStartupScript(entry, startup));
|
|
|
remove.addEventListener('click', async () => {
|
|
|
if (state.busy) return notice('请等待当前镜像任务完成。', true);
|
|
|
const message = cleanupReason === 'partial_import'
|
|
|
? `云镜像模版“${entry.name}”仅在部分宿主机导入成功。确定清理已存在的剩余副本?`
|
|
|
: cleanupReason === 'partial_delete'
|
|
|
? `云镜像模版“${entry.name}”仍有部分宿主机副本未删除。确定继续清理剩余副本?`
|
|
|
: cleanupReason === 'artifact_delete_attention'
|
|
|
? `云镜像模版“${entry.name}”的宿主机副本已删除,但对象存储主副本需要重新核对。确定只重试主副本清理?不会再次向宿主机发送删除请求。`
|
|
|
: `删除全局云镜像模版“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`;
|
|
|
if (!confirm(message)) return;
|
|
|
remove.disabled = true; state.busy = true;
|
|
|
try {
|
|
|
const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'DELETE', body: { expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
if (result?.deleted === true) { await loadCatalog(); notice('镜像模版及其受管文件已确认删除。'); }
|
|
|
else if (result?.recovery_restarted === true) {
|
|
|
await loadCatalog();
|
|
|
notice('主副本清理已重新进入安全核对;不会再次删除宿主机副本。');
|
|
|
}
|
|
|
else {
|
|
|
importProgress(result, partialCleanup ? '清理镜像模版' : '删除镜像模版', async () => {
|
|
|
await loadCatalog(); notice(partialCleanup ? '镜像模版剩余宿主机副本已清理。' : '镜像模版及其受管文件已确认删除。');
|
|
|
});
|
|
|
notice('任务已接收,正在后台删除。');
|
|
|
}
|
|
|
} catch (error) { notice(error.message, true); remove.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
});
|
|
|
}
|
|
|
function cloudTemplateVersion(entry) {
|
|
|
const card = element('article', 'cloud-template-version-card');
|
|
|
card.dataset.catalogState = String(entry.state || 'unknown').toLowerCase();
|
|
|
const header = element('div', 'cloud-template-version-head');
|
|
|
const identity = element('div', 'cloud-template-version-identity');
|
|
|
const badges = element('div', 'cloud-template-version-badges');
|
|
|
const [stateLabel, stateClass] = catalogStateView(entry.state);
|
|
|
badges.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
if (entry.is_default === true) badges.append(element('span', 'cloud-template-default', '当前默认版本'));
|
|
|
identity.append(badges, element('strong', '', entry.name || entry.id));
|
|
|
identity.append(element('small', '', `版本 ${entry.version_label || '未标记'} · 目录修订 r${Number(entry.revision || 0)}`));
|
|
|
const imageBytes = Number(entry.image_bytes || 0);
|
|
|
const master = element('div', 'cloud-template-master-meta');
|
|
|
const artifactState = String(entry.artifact?.state || 'missing');
|
|
|
master.append(
|
|
|
element('span', '', imageBytes > 0 ? `${(imageBytes / 1024 ** 3).toFixed(2)} GiB` : '大小待确认'),
|
|
|
element('span', 'admin-mono', `SHA ${compactIdentifier(entry.sha256, 14) || '—'}`),
|
|
|
element('span', 'admin-mono', `GEN ${compactIdentifier(entry.generation_token, 10) || '—'}`),
|
|
|
element('span', 'admin-mono', `MASTER ${artifactState}`),
|
|
|
);
|
|
|
header.append(identity, master);
|
|
|
const form = element('form', 'cloud-template-version-form');
|
|
|
const nameWrap = element('div', 'cloud-template-name-field');
|
|
|
const nameLabel = element('label', 'form-label', '显示名称'); nameLabel.setAttribute('for', `template-name-${entry.id}`);
|
|
|
const name = element('input', 'form-control'); name.id = `template-name-${entry.id}`; name.value = entry.name || ''; name.maxLength = 64; name.required = true;
|
|
|
const active = String(entry.state || '').toLowerCase() === 'active'; name.disabled = !canManage || !active;
|
|
|
nameWrap.append(nameLabel, name);
|
|
|
const actions = element('div', 'cloud-template-version-actions');
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage || !active;
|
|
|
const startup = element('button', 'btn btn-outline-secondary', canManage ? '启动脚本' : '查看脚本'); startup.type = 'button'; startup.disabled = !active;
|
|
|
const cleanupReason = String(entry.cleanup_reason || '');
|
|
|
const partialCleanup = ['partial_import', 'partial_delete'].includes(cleanupReason);
|
|
|
const removeLabel = cleanupReason === 'artifact_delete_attention' ? '重新核对主副本' : (partialCleanup ? '清理残留' : '删除版本');
|
|
|
const remove = element('button', 'btn btn-outline-danger', removeLabel); remove.type = 'button'; remove.disabled = !canManage;
|
|
|
actions.append(save, startup, remove); form.append(nameWrap, actions);
|
|
|
bindCloudTemplateActions(entry, form, name, save, remove, startup);
|
|
|
card.append(header, form, replicaMatrix(entry));
|
|
|
return card;
|
|
|
}
|
|
|
function cloudTemplateAvailable(entry) {
|
|
|
return ['active', 'degraded'].includes(String(entry?.state || '').toLowerCase());
|
|
|
}
|
|
|
function renderCloudTemplates(list, entries) {
|
|
|
const groups = new Map();
|
|
|
for (const entry of entries) {
|
|
|
const key = String(entry.catalog_key || `${entry.os_family || '镜像'}-${entry.os_version || ''}`);
|
|
|
if (!groups.has(key)) groups.set(key, { key, family: entry.os_family || '云镜像', version: entry.os_version || '', entries: [] });
|
|
|
groups.get(key).entries.push(entry);
|
|
|
}
|
|
|
for (const group of groups.values()) {
|
|
|
const section = element('section', 'cloud-template-family');
|
|
|
const head = element('div', 'cloud-template-family-head');
|
|
|
const title = element('div'); title.append(element('h6', '', `${group.family} ${group.version}`.trim()), element('small', 'admin-mono', group.key));
|
|
|
const available = group.entries.filter(cloudTemplateAvailable).length;
|
|
|
head.append(title, element('span', 'cloud-template-version-count', `${available} 可用 / ${group.entries.length} 条记录`));
|
|
|
const versions = element('div', 'cloud-template-version-list');
|
|
|
group.entries.sort((left, right) => Number(right.is_default === true) - Number(left.is_default === true) || Number(right.created_at || 0) - Number(left.created_at || 0));
|
|
|
for (const entry of group.entries) versions.append(cloudTemplateVersion(entry));
|
|
|
section.append(head, versions); list.append(section);
|
|
|
}
|
|
|
}
|
|
|
function rescueReplicaStateView(entry, replica) {
|
|
|
const stateName = String(replica?.state || 'missing').toLowerCase();
|
|
|
if (stateName === 'deleted') return ['已清理', 'is-muted'];
|
|
|
if (stateName === 'deleting') return ['正在清理', 'is-running'];
|
|
|
if (stateName === 'delete_unknown') return ['删除效果待核查', 'is-error'];
|
|
|
if (stateName === 'delete_failed') return ['删除失败', 'is-error'];
|
|
|
if (replica?.host_record_present === false) return ['宿主机记录缺失', 'is-error'];
|
|
|
if (replica?.host_eligible !== true) return ['宿主机未就绪', 'is-muted'];
|
|
|
if (replica?.exact === true) return ['精确副本', 'is-ready'];
|
|
|
return ({
|
|
|
missing: ['缺少副本', 'is-warning'], stale: ['版本不一致', 'is-error'],
|
|
|
pending: ['等待分发', 'is-running'], importing: ['正在分发', 'is-running'],
|
|
|
import_unknown: ['导入效果待核查', 'is-error'], failed: ['导入失败', 'is-error'],
|
|
|
active: ['内容不一致', 'is-error'],
|
|
|
}[stateName] || [String(entry?.state || '') === 'retiring' ? '等待清理' : '状态待核查', 'is-error']);
|
|
|
}
|
|
|
async function repairRescueReplica(entry, replica, button) {
|
|
|
if (state.busy || replica?.repair_action !== 'import') return;
|
|
|
if (!confirm(`确定在 ${replica.host_name || `宿主机 #${replica.host_id}`} 补齐救援 ISO“${entry.name}”的精确副本?`)) return;
|
|
|
state.busy = true; button.disabled = true;
|
|
|
try {
|
|
|
const { payload, status } = await requestJson(
|
|
|
`/api/v1/admin/rescue-templates/${encodeURIComponent(entry.id)}/replicas/${encodeURIComponent(replica.host_id)}/repair`,
|
|
|
{ method: 'POST', body: {} },
|
|
|
);
|
|
|
if (status === 200 && payload?.scheduled === false) {
|
|
|
await loadCatalog(); notice('宿主机已经具有精确副本,无需重复处理。'); return;
|
|
|
}
|
|
|
if (status !== 202 || !taskUrl(payload)) throw new Error('补齐请求未返回严格的任务回执,请勿重复提交并联系管理员核查。');
|
|
|
const handle = importProgress(payload, '补齐救援 ISO 副本', async () => {
|
|
|
await loadCatalog(); notice('救援 ISO 副本已补齐。');
|
|
|
});
|
|
|
if (handle) notice(`副本补齐任务已接收(#${payload.task_id})。`);
|
|
|
} catch (error) { notice(error.message, true); button.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
}
|
|
|
function rescueReplicaMatrix(entry) {
|
|
|
const details = element('details', 'cloud-template-matrix');
|
|
|
const replicas = Array.isArray(entry.replicas) ? entry.replicas : [];
|
|
|
const totals = entry.replica_summary || {};
|
|
|
const summary = element('summary', 'cloud-template-matrix-summary');
|
|
|
const label = element('span');
|
|
|
label.append(
|
|
|
element('strong', '', '宿主机副本'),
|
|
|
element('small', '', `${Number(totals.ready || 0)} / ${Number(totals.eligible || 0)} 台精确`),
|
|
|
);
|
|
|
if (Number(totals.cleanup_debt || 0) > 0) label.append(element('small', 'text-danger', `${Number(totals.cleanup_debt)} 台待清理`));
|
|
|
summary.append(label, element('span', 'cloud-template-matrix-arrow'));
|
|
|
details.append(summary);
|
|
|
if (!replicas.length) {
|
|
|
details.append(element('p', 'cloud-template-matrix-empty', '尚无宿主机记录。'));
|
|
|
return details;
|
|
|
}
|
|
|
const wrap = element('div', 'cloud-template-matrix-scroll');
|
|
|
const table = element('table', 'cloud-template-matrix-table');
|
|
|
const head = element('thead'); const headRow = element('tr');
|
|
|
for (const title of ['宿主机', '目录 / 实际', '状态', '最近核对', '操作']) headRow.append(element('th', '', title));
|
|
|
head.append(headRow); const body = element('tbody');
|
|
|
for (const replica of replicas) {
|
|
|
const row = element('tr');
|
|
|
const host = element('td', 'cloud-template-host-cell'); host.setAttribute('data-label', '宿主机');
|
|
|
host.append(element('strong', '', replica.host_name || `宿主机 #${replica.host_id}`), element('small', '', replica.host_region || (replica.host_enabled ? '地区未设置' : '已停用')));
|
|
|
const versions = element('td', 'cloud-template-version-cell'); versions.setAttribute('data-label', '目录 / 实际');
|
|
|
versions.append(
|
|
|
element('strong', 'admin-mono', `r${Number(entry.revision || 0)} / r${Number(replica.revision || 0)}`),
|
|
|
element('small', 'admin-mono', `GEN ${compactIdentifier(replica.generation_token, 10) || '—'}`),
|
|
|
element('small', 'admin-mono', `OBS r${Number(replica.observed_revision || 0)} · ${compactIdentifier(replica.observed_generation_token, 10) || '—'}`),
|
|
|
);
|
|
|
const status = element('td'); status.setAttribute('data-label', '状态');
|
|
|
const statusContent = element('span', 'cloud-template-cell-content');
|
|
|
const [statusLabel, statusClass] = rescueReplicaStateView(entry, replica);
|
|
|
statusContent.append(element('span', `cloud-template-state ${statusClass}`, statusLabel));
|
|
|
const diagnostics = [replica.error_code, compactIdentifier(replica.operation_id)].filter(Boolean).join(' · ');
|
|
|
if (diagnostics) statusContent.append(element('small', 'cloud-template-diagnostic', diagnostics));
|
|
|
status.append(statusContent);
|
|
|
const verified = element('td'); verified.setAttribute('data-label', '最近核对');
|
|
|
verified.append(element('span', 'cloud-template-cell-content', catalogTime(replica.last_verified_at)));
|
|
|
const actions = element('td', 'cloud-template-replica-action'); actions.setAttribute('data-label', '操作');
|
|
|
if (canManage && replica.repair_action === 'import') {
|
|
|
const repair = element('button', 'btn btn-sm btn-outline-primary', '补齐副本'); repair.type = 'button';
|
|
|
repair.addEventListener('click', () => repairRescueReplica(entry, replica, repair)); actions.append(repair);
|
|
|
} else actions.append(element('span', 'text-muted', '—'));
|
|
|
row.append(host, versions, status, verified, actions); body.append(row);
|
|
|
}
|
|
|
table.append(head, body); wrap.append(table); details.append(wrap);
|
|
|
return details;
|
|
|
}
|
|
|
function rescueTemplateCard(entry) {
|
|
|
const card = element('article', 'cloud-template-version-card');
|
|
|
card.dataset.catalogState = String(entry.state || 'unknown').toLowerCase();
|
|
|
const header = element('div', 'cloud-template-version-head');
|
|
|
const identity = element('div', 'cloud-template-version-identity');
|
|
|
const badges = element('div', 'cloud-template-version-badges');
|
|
|
const [stateLabel, stateClass] = catalogStateView(entry.state);
|
|
|
badges.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
identity.append(badges, element('strong', '', entry.name || entry.id));
|
|
|
identity.append(element('small', '', `目录修订 r${Number(entry.revision || 0)} · ${catalogTime(entry.created_at)}`));
|
|
|
const metadata = element('div', 'cloud-template-master-meta');
|
|
|
const bytes = Number(entry.size_bytes || 0);
|
|
|
metadata.append(
|
|
|
element('span', '', bytes > 0 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB` : '大小待确认'),
|
|
|
element('span', 'admin-mono', `SHA ${compactIdentifier(entry.sha256, 14) || '—'}`),
|
|
|
element('span', 'admin-mono', `GEN ${compactIdentifier(entry.generation_token, 10) || '—'}`),
|
|
|
element('span', 'admin-mono', `MASTER ${String(entry.artifact?.state || 'missing')}`),
|
|
|
);
|
|
|
header.append(identity, metadata);
|
|
|
const actionBar = element('div', 'cloud-rescue-version-actions');
|
|
|
const warning = element('p', 'cloud-rescue-version-note', String(entry.state || '') === 'retiring'
|
|
|
? `正在清理:${Number(entry.replica_summary?.cleanup_debt || 0)} 台宿主机仍有清理债务。`
|
|
|
: '删除后会立即停止新挂载;已经挂载救援介质的实例必须先退出救援。');
|
|
|
const remove = element('button', 'btn btn-outline-danger', String(entry.state || '') === 'retiring' ? '正在退役' : '退役并清理');
|
|
|
remove.type = 'button'; remove.disabled = !canManage || String(entry.state || '') === 'retiring';
|
|
|
remove.addEventListener('click', async () => {
|
|
|
if (state.busy || !confirm(`退役全局救援 ISO“${entry.name}”?系统会停止新挂载,并异步删除全部宿主机副本和对象存储精确版本。`)) return;
|
|
|
state.busy = true; remove.disabled = true;
|
|
|
try {
|
|
|
const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'DELETE', body: { expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
await loadCatalog();
|
|
|
const scheduled = Array.isArray(result?.tasks) ? result.tasks.length : 0;
|
|
|
notice(scheduled > 0 ? `救援 ISO 已停止使用,并调度 ${scheduled} 个宿主机清理任务。` : '救援 ISO 已停止使用,后台将继续核对清理。');
|
|
|
} catch (error) { notice(error.message, true); remove.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
});
|
|
|
actionBar.append(warning, remove);
|
|
|
card.append(header, actionBar, rescueReplicaMatrix(entry));
|
|
|
return card;
|
|
|
}
|
|
|
function renderRescueTemplates(list, entries) {
|
|
|
for (const entry of entries) list.append(rescueTemplateCard(entry));
|
|
|
}
|
|
|
async function loadCatalog() {
|
|
|
const rescue = isRescueCatalog();
|
|
|
const epoch = ++state.epoch;
|
|
|
const list = byId('catalog-list'); list.replaceChildren();
|
|
|
notice(rescue ? '正在读取救援 ISO 目录与副本矩阵…' : '正在读取云镜像版本与副本矩阵…');
|
|
|
try {
|
|
|
const payload = await api(catalogPath()); if (epoch !== state.epoch) return;
|
|
|
const entries = collection(payload, 'templates');
|
|
|
if (!entries.length) list.append(element('p', 'text-muted', '暂无模版。'));
|
|
|
else if (rescue) renderRescueTemplates(list, entries);
|
|
|
else renderCloudTemplates(list, entries);
|
|
|
if (rescue) {
|
|
|
const available = entries.filter(entry => ['active', 'degraded'].includes(String(entry.state || ''))).length;
|
|
|
notice(`已加载 ${entries.length} 个救援 ISO:${available} 个可挂载,${entries.length - available} 个正在处理或需核查。`);
|
|
|
}
|
|
|
else {
|
|
|
const available = entries.filter(cloudTemplateAvailable).length;
|
|
|
notice(`已加载 ${entries.length} 条云镜像记录:${available} 个可用,${entries.length - available} 个不可用。`);
|
|
|
}
|
|
|
} catch (error) { if (epoch === state.epoch) notice(error.message, true); }
|
|
|
}
|
|
|
function taskFailureMessage(task, fallback) {
|
|
|
const message = task?.error || fallback;
|
|
|
const recoveryNotice = recoveryTaskFailureNotice(task);
|
|
|
if (recoveryNotice) return recoveryNotice;
|
|
|
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 (taskSucceededWithoutRecovery(task)) {
|
|
|
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 importRescue(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.busy) return;
|
|
|
const name = byId('rescue-name').value.trim();
|
|
|
const url = byId('rescue-url').value.trim();
|
|
|
const sha256 = byId('rescue-sha256').value.trim().toLowerCase();
|
|
|
if (!name || name.length > 64) return notice('请填写 1 至 64 个字符的模版名称。', true);
|
|
|
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
|
|
|
try {
|
|
|
const parsed = new URL(url);
|
|
|
if (parsed.protocol !== 'https:' || (parsed.port && parsed.port !== '443') || parsed.username || parsed.password || parsed.hash || !parsed.pathname.toLowerCase().endsWith('.iso')) throw new Error();
|
|
|
} catch { return notice('请填写无需账号、使用 443 端口并以 .iso 结尾的 HTTPS 直链。', true); }
|
|
|
const body = { name, url }; if (sha256) body.sha256 = sha256;
|
|
|
const button = byId('rescue-import-button'); state.busy = true; button.disabled = true;
|
|
|
notice('正在隔离下载并保存救援 ISO,请勿重复提交…');
|
|
|
try {
|
|
|
const result = await api(catalogPath(), { method: 'POST', body });
|
|
|
byId('rescue-import').reset();
|
|
|
if (result?.validation_scheduled === true && taskUrl(result)) {
|
|
|
const handle = importProgress(result, '首台宿主机校验', async () => {
|
|
|
await loadCatalog(); notice('首台宿主机校验完成,正在向其余宿主机分发。');
|
|
|
});
|
|
|
if (handle) notice(`救援 ISO 已进入隔离目录,首台校验任务已接收(#${result.task_id})。`);
|
|
|
} else {
|
|
|
await loadCatalog();
|
|
|
notice('救援 ISO 已进入隔离目录;首台校验未立即调度,后台协调器会继续核对。');
|
|
|
}
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
finally { state.busy = false; button.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 loadHosts(); renderHosts(); fillHost(null); renderHostConfigOverview(null);
|
|
|
byId('host-new').addEventListener('click', event => openNewHostConfig(event.currentTarget)); byId('host-form').addEventListener('submit', saveHost);
|
|
|
byId('host-config-close').addEventListener('click', closeHostConfig); const configDrawer = byId('host-config-drawer'); configDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostConfig(); }); configDrawer.addEventListener('click', event => { if (event.target === configDrawer) closeHostConfig(); });
|
|
|
byId('host-config-scheduling').addEventListener('click', () => openHostConfigTool('scheduling'));
|
|
|
byId('host-config-network-pools').addEventListener('click', () => openHostConfigTool('networkPools'));
|
|
|
byId('host-config-vpc').addEventListener('click', () => openHostConfigTool('vpc'));
|
|
|
byId('host-config-storage')?.addEventListener('click', () => openHostConfigTool('storage'));
|
|
|
byId('host-search').addEventListener('input', renderHosts); byId('host-region-filter').addEventListener('change', renderHosts); byId('host-state-filter').addEventListener('change', renderHosts);
|
|
|
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(); });
|
|
|
byId('host-vpc-transport-close').addEventListener('click', closeHostVpcTransport); byId('host-vpc-transport-form').addEventListener('submit', saveHostVpcTransport); byId('host-vpc-transport-discover').addEventListener('click', discoverHostVpcTransport); byId('host-vpc-transport-test').addEventListener('click', testHostVpcTransport); byId('host-vpc-transport-candidate').addEventListener('change', selectHostVpcTransportCandidate);
|
|
|
const vpcTransportDrawer = byId('host-vpc-transport-drawer'); vpcTransportDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostVpcTransport(); }); vpcTransportDrawer.addEventListener('click', event => { if (event.target === vpcTransportDrawer) closeHostVpcTransport(); });
|
|
|
if (!canManage) { byId('host-form').querySelectorAll('input,select,textarea,button').forEach(input => { input.disabled = true; }); byId('host-enabled').disabled = true; }
|
|
|
notice(canManage ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。');
|
|
|
}
|
|
|
else if (root.dataset.cloudAdmin === 'templates') { byId('template-import')?.addEventListener('submit', importTemplate); byId('template-upload')?.addEventListener('submit', uploadCloudTemplate); byId('template-catalog-refresh')?.addEventListener('click', loadCatalog); 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') { byId('rescue-import')?.addEventListener('submit', importRescue); byId('rescue-catalog-refresh')?.addEventListener('click', loadCatalog); await loadCatalog(); }
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
void initialize();
|