|
|
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, 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() };
|
|
|
const requestRuntime = window.VenixAdminRequestRuntime.create({
|
|
|
csrfToken: () => state.csrf,
|
|
|
taskReceiptValidator: taskUrl,
|
|
|
});
|
|
|
// 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`; }
|
|
|
async function requestJson(path, options = {}) {
|
|
|
const method = String(options.method || 'GET').toUpperCase();
|
|
|
try {
|
|
|
if (['GET', 'HEAD'].includes(method)) {
|
|
|
return await requestRuntime.read(path, {
|
|
|
method, signal: options.signal, timeoutMs: options.timeoutMs,
|
|
|
headers: options.headers, returnMeta: true,
|
|
|
});
|
|
|
}
|
|
|
return await requestRuntime.mutate(path, {
|
|
|
method, body: options.body, signal: options.signal,
|
|
|
timeoutMs: options.timeoutMs, headers: options.headers,
|
|
|
response: 'json', returnMeta: true,
|
|
|
idempotencyKey: options.idempotencyKey,
|
|
|
});
|
|
|
} catch (error) {
|
|
|
if (error?.status === 401) location.assign('/auth/login');
|
|
|
if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true;
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
async function api(path, options = {}) {
|
|
|
return (await requestJson(path, options)).payload;
|
|
|
}
|
|
|
async function acceptedTask(path, options = {}) {
|
|
|
try {
|
|
|
return await requestRuntime.mutate(path, {
|
|
|
method: options.method || 'POST', body: options.body,
|
|
|
signal: options.signal, timeoutMs: options.timeoutMs,
|
|
|
headers: options.headers, response: 'task',
|
|
|
});
|
|
|
} catch (error) {
|
|
|
if (error?.status === 401) location.assign('/auth/login');
|
|
|
if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true;
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
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; }
|
|
|
}
|
|
|
async function initialize() {
|
|
|
if (!root || root.dataset.cloudAdmin !== 'hosts') return;
|
|
|
window.addEventListener('pagehide', () => {
|
|
|
stopHostStorageObserver('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('会话令牌缺失,请重新登录。');
|
|
|
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 ? '请选择宿主机编辑,或添加新的宿主机。' : '当前管理员仅可查看配置。');
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
void initialize();
|