|
|
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, networkAttachmentBusy: false, networkAttachmentOpener: null, networkAttachmentScroll: null, networkAttachmentPayload: null, networkAttachmentCandidates: [], networkAttachmentEpoch: 0, networkAttachmentHostId: '', networkPoolBusy: false, networkPoolOpener: null, networkPoolScroll: null, networkPoolPayload: null, networkPoolEpoch: 0, networkPoolHostId: '', networkPoolReplacementBusy: new Set(), networkPoolReplacementObservers: new Map(), 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 = '';
|
|
|
const maintenance = byId('host-config-maintenance-notice');
|
|
|
if (maintenance) {
|
|
|
maintenance.href = host && Number(h.id) > 0
|
|
|
? `/admin/maintenance-notices?scope_type=host&host_id=${encodeURIComponent(h.id)}`
|
|
|
: '/admin/maintenance-notices';
|
|
|
}
|
|
|
}
|
|
|
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', '', `公网双栈 ${Number(capacity?.ip?.bundles?.available || 0)} 可用 / ${Number(capacity?.ip?.bundles?.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', '', `公网双栈 ${Number(capacity?.ip?.bundles?.available || 0)} 可用 / ${Number(capacity?.ip?.bundles?.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 hostNetworkAttachmentNotice = hostDrawerNotice.bind(null, 'host-network-attachments-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`],
|
|
|
['公网双栈', `${Number(capacity?.ip?.bundles?.available || 0)} 个可用 / ${Number(capacity?.ip?.bundles?.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,
|
|
|
networkAttachments: openHostNetworkAttachments,
|
|
|
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 schedulingPoolLabel(pool) {
|
|
|
const path = [pool?.region_name, pool?.line_name, pool?.name].filter(Boolean).join(' / ') || `资源池 #${pool?.id || '?'}`;
|
|
|
return `${path}${pool?.status === 'active' && pool?.line_status === 'active' && pool?.region_status === 'active' ? '' : '(不可调度)'}`;
|
|
|
}
|
|
|
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 schedulingInput(type, name, value, options = {}) {
|
|
|
const control = document.createElement(type === 'select' ? 'select' : 'input');
|
|
|
control.className = type === 'select' ? 'form-select' : 'form-control';
|
|
|
control.name = name;
|
|
|
if (type === 'select') {
|
|
|
for (const [optionValue, label] of [['active', '启用调度'], ['draining', '排空(不接收新实例)'], ['disabled', '停用调度']]) {
|
|
|
const option = element('option', '', label); option.value = optionValue; control.append(option);
|
|
|
}
|
|
|
} else {
|
|
|
control.type = 'number'; control.required = true;
|
|
|
control.min = String(options.min); control.max = String(options.max);
|
|
|
}
|
|
|
control.value = String(value ?? ''); control.disabled = !canManage;
|
|
|
return control;
|
|
|
}
|
|
|
function schedulingField(label, control) {
|
|
|
const wrapper = element('div'); wrapper.append(element('label', 'form-label', label), control); return wrapper;
|
|
|
}
|
|
|
function membershipPath(item) {
|
|
|
return [item?.region_name, item?.line_name, item?.pool_name].filter(Boolean).join(' / ') || `资源池 #${item?.resource_pool_id || '?'}`;
|
|
|
}
|
|
|
function renderHostMemberships(payload) {
|
|
|
const memberships = Array.isArray(payload?.memberships) ? payload.memberships : [];
|
|
|
const pools = Array.isArray(payload?.pools) ? payload.pools : [];
|
|
|
const assigned = new Set(memberships.map(item => Number(item.resource_pool_id)));
|
|
|
const poolSelect = byId('host-membership-pool'); poolSelect.replaceChildren();
|
|
|
const placeholder = element('option', '', '选择要加入的资源池'); placeholder.value = ''; poolSelect.append(placeholder);
|
|
|
for (const pool of pools) {
|
|
|
if (assigned.has(Number(pool.id))) continue;
|
|
|
const option = element('option', '', schedulingPoolLabel(pool)); option.value = String(pool.id); poolSelect.append(option);
|
|
|
}
|
|
|
poolSelect.value = ''; poolSelect.disabled = !canManage || poolSelect.children.length < 2;
|
|
|
const addButton = byId('host-membership-add'); if (addButton) addButton.disabled = poolSelect.disabled;
|
|
|
byId('host-membership-new-state').value = 'disabled';
|
|
|
byId('host-membership-new-priority').value = '0';
|
|
|
byId('host-membership-new-weight').value = '100';
|
|
|
byId('host-membership-pool-help').textContent = poolSelect.children.length < 2
|
|
|
? '当前没有可新增的资源池成员。'
|
|
|
: (payload?.network_lines_enabled ? '仅显示尚未加入的资源池;同一宿主机的启用或排空成员必须位于同一地区。' : '线路功能关闭时,只有地区默认线路可以启用调度。');
|
|
|
|
|
|
const list = byId('host-membership-list'); list.replaceChildren();
|
|
|
if (!memberships.length) {
|
|
|
list.append(element('p', 'text-muted mb-0', '当前宿主机尚未加入任何资源池。'));
|
|
|
return;
|
|
|
}
|
|
|
for (const item of memberships) {
|
|
|
const card = element('article', 'card mb-3'); card.dataset.hostMembership = String(item.resource_pool_id);
|
|
|
const body = element('div', 'card-body');
|
|
|
const header = element('div', 'd-flex justify-content-between align-items-start gap-3 flex-wrap');
|
|
|
const identity = element('div'); identity.append(
|
|
|
element('h6', 'mb-1', membershipPath(item)),
|
|
|
element('p', 'text-muted fs-13 mb-0', `资源池 #${item.resource_pool_id} · revision ${item.revision}`)
|
|
|
);
|
|
|
const badge = element('span', `badge ${item.scheduler_state === 'active' ? 'text-bg-success' : item.scheduler_state === 'draining' ? 'text-bg-warning' : 'text-bg-light'}`, schedulerLabel(item.scheduler_state));
|
|
|
header.append(identity, badge); body.append(header);
|
|
|
|
|
|
const form = element('form', 'cloud-admin-form-grid mt-3');
|
|
|
form.dataset.hostMembershipForm = ''; form.dataset.poolId = String(item.resource_pool_id); form.dataset.revision = String(item.revision);
|
|
|
const stateControl = schedulingInput('select', 'scheduler_state', item.scheduler_state);
|
|
|
const priority = schedulingInput('number', 'priority', item.priority, { min: -1000000, max: 1000000 });
|
|
|
const weight = schedulingInput('number', 'weight', item.weight, { min: 1, max: 1000 });
|
|
|
form.append(schedulingField('调度状态', stateControl), schedulingField('优先级', priority), schedulingField('权重', weight));
|
|
|
if (canManage) {
|
|
|
const actions = element('div', 'cloud-admin-full d-flex justify-content-end gap-2');
|
|
|
const remove = element('button', 'btn btn-outline-danger', '删除成员'); remove.type = 'button'; remove.dataset.hostMembershipDelete = '';
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存此成员'); save.type = 'submit'; save.dataset.hostMembershipSave = '';
|
|
|
remove.addEventListener('click', () => deleteHostMembership(item, remove));
|
|
|
actions.append(remove, save); form.append(actions);
|
|
|
}
|
|
|
form.addEventListener('submit', saveHostMembership);
|
|
|
body.append(form);
|
|
|
const warnings = Array.isArray(item.warnings) ? item.warnings.filter(Boolean) : [];
|
|
|
if (warnings.length) body.append(element('p', 'alert alert-warning mt-3 mb-0', warnings.join(' ')));
|
|
|
card.append(body); list.append(card);
|
|
|
}
|
|
|
}
|
|
|
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} 台预留`],
|
|
|
['公网双栈', `${Number(capacity?.ip?.bundles?.available || 0)} 个可用 / ${Number(capacity?.ip?.bundles?.total || 0)} 个已登记`],
|
|
|
] : [['面板容量', '尚未配置']];
|
|
|
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 memberships = Array.isArray(payload?.memberships) ? payload.memberships : [];
|
|
|
byId('host-scheduling-title').textContent = `${host.name || `宿主机 #${host.id}`} · 资源池成员与调度容量`;
|
|
|
byId('host-scheduling-host-id').value = host.id || '';
|
|
|
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);
|
|
|
renderHostMemberships(payload); setSchedulingWarnings(payload?.warnings); renderPanelCapacity(payload?.capacity);
|
|
|
const active = memberships.filter(item => item.scheduler_state === 'active').length;
|
|
|
const draining = memberships.filter(item => item.scheduler_state === 'draining').length;
|
|
|
hostSchedulingNotice(`连接:${host.enabled ? '启用' : '停用'} · 成员 ${memberships.length} 个 · 启用 ${active} 个 · 排空 ${draining} 个`);
|
|
|
}
|
|
|
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); byId('host-membership-list').replaceChildren();
|
|
|
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 { 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 syncCachedHostScheduling(hostId, payload) {
|
|
|
if (!payload?.host) return;
|
|
|
const update = host => {
|
|
|
if (!host || Number(host.id) !== Number(hostId)) return;
|
|
|
host.resource_pool_id = payload.host.resource_pool_id;
|
|
|
host.scheduler_state = payload.host.scheduler_state;
|
|
|
host.placement = payload.placement || null;
|
|
|
host.memberships = Array.isArray(payload.memberships) ? payload.memberships : [];
|
|
|
if (payload.capacity) host.capacity = payload.capacity;
|
|
|
};
|
|
|
state.hosts.forEach(update);
|
|
|
for (const region of state.hostRegions) collection(region, 'hosts').forEach(update);
|
|
|
// Read the complete projection back after a confirmed mutation. The
|
|
|
// scheduling response intentionally owns only capacity and memberships;
|
|
|
// readiness, attention flags and regional/global summaries are projected by
|
|
|
// the host-list read model and must not be guessed independently here.
|
|
|
try { await loadHosts(); } catch (_) { /* Keep the confirmed local fields; a later refresh will reconcile summaries. */ }
|
|
|
renderHosts();
|
|
|
}
|
|
|
async function saveHostScheduling(event) {
|
|
|
event.preventDefault(); if (!canManage || state.schedulingBusy) return; const hostId = byId('host-scheduling-host-id').value; if (!hostId) return;
|
|
|
if (event.currentTarget?.reportValidity && !event.currentTarget.reportValidity()) 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); await syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('全局容量已保存,资源池成员配置未被改动。'); }
|
|
|
catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; if (button) button.disabled = !canManage; }
|
|
|
}
|
|
|
function membershipBody(form) {
|
|
|
return {
|
|
|
scheduler_state: form.elements.namedItem('scheduler_state').value,
|
|
|
priority: Number(form.elements.namedItem('priority').value),
|
|
|
weight: Number(form.elements.namedItem('weight').value),
|
|
|
expected_revision: Number(form.dataset.revision),
|
|
|
};
|
|
|
}
|
|
|
async function createHostMembership(event) {
|
|
|
event.preventDefault(); if (!canManage || state.schedulingBusy) return;
|
|
|
const form = event.currentTarget; if (form.reportValidity && !form.reportValidity()) return;
|
|
|
const hostId = byId('host-scheduling-host-id').value; const poolId = byId('host-membership-pool').value;
|
|
|
if (!hostId || !poolId) return;
|
|
|
const button = byId('host-membership-add'); state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice('正在新增资源池成员…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(poolId)}`, { method: 'PUT', body: { scheduler_state: byId('host-membership-new-state').value, priority: Number(byId('host-membership-new-priority').value), weight: Number(byId('host-membership-new-weight').value), expected_revision: 0 } });
|
|
|
renderHostScheduling(payload); await syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员已新增。');
|
|
|
} catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = !canManage || byId('host-membership-pool').disabled; }
|
|
|
}
|
|
|
async function saveHostMembership(event) {
|
|
|
event.preventDefault(); if (!canManage || state.schedulingBusy) return;
|
|
|
const form = event.currentTarget; if (form.reportValidity && !form.reportValidity()) return;
|
|
|
const hostId = byId('host-scheduling-host-id').value; const poolId = form.dataset.poolId;
|
|
|
if (!hostId || !poolId) return;
|
|
|
const button = form.querySelector('[data-host-membership-save]'); state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice(`正在保存资源池 #${poolId} 的成员配置…`);
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(poolId)}`, { method: 'PUT', body: membershipBody(form) });
|
|
|
renderHostScheduling(payload); await syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员配置已保存。');
|
|
|
} catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; }
|
|
|
}
|
|
|
async function deleteHostMembership(item, button) {
|
|
|
if (!canManage || state.schedulingBusy) return;
|
|
|
const confirmed = await window.VenixAdminDangerDialog.confirm({ tone: 'warning', title: '删除资源池成员', message: `将从宿主机移除“${membershipPath(item)}”成员关系。存在实例或资源预留时服务端会拒绝删除。`, confirmText: '删除成员' });
|
|
|
if (!confirmed) return;
|
|
|
const hostId = byId('host-scheduling-host-id').value; if (!hostId) return;
|
|
|
state.schedulingBusy = true; if (button) button.disabled = true; hostSchedulingNotice(`正在删除资源池 #${item.resource_pool_id} 的成员关系…`);
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/scheduling/memberships/${encodeURIComponent(item.resource_pool_id)}`, { method: 'DELETE', body: { expected_revision: Number(item.revision) } });
|
|
|
renderHostScheduling(payload); await syncCachedHostScheduling(hostId, payload); hostSchedulingNotice('资源池成员已删除。');
|
|
|
} catch (error) { hostSchedulingNotice(error.message, true); }
|
|
|
finally { state.schedulingBusy = false; if (button?.isConnected) button.disabled = false; }
|
|
|
}
|
|
|
function networkAttachmentStateLabel(value) { return ({ active: '启用', draining: '排空', disabled: '停用' })[value] || '状态异常'; }
|
|
|
function networkAttachmentVerificationLabel(value) { return ({ verified: '已验证', stale: '验证已过期', failed: '验证失败', never: '尚未验证' })[value] || '验证状态异常'; }
|
|
|
function addSelectOption(select, value, label, disabled = false) {
|
|
|
const option = element('option', '', label); option.value = String(value); option.disabled = disabled; select.append(option); return option;
|
|
|
}
|
|
|
function fillNetworkAttachmentLineSelect(select, selected = '') {
|
|
|
select.replaceChildren();
|
|
|
const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : [];
|
|
|
addSelectOption(select, '', lines.length ? '请选择宿主机有效线路' : '当前宿主机没有可用线路', true);
|
|
|
for (const line of lines) addSelectOption(select, Number(line.id), `${line.name}(${line.status || 'active'})`);
|
|
|
const current = String(selected || '');
|
|
|
if (current && !lines.some(line => String(line.id) === current)) addSelectOption(select, current, `线路 #${current}(关系已失效)`, true);
|
|
|
select.value = current;
|
|
|
}
|
|
|
function fillNetworkAttachmentSelectorSelect(select, selected = '') {
|
|
|
select.replaceChildren();
|
|
|
const candidates = Array.isArray(state.networkAttachmentCandidates) ? state.networkAttachmentCandidates : [];
|
|
|
addSelectOption(select, '', candidates.length ? '请选择 Agent 已测试候选' : 'Agent 没有已测试候选', true);
|
|
|
for (const selector of candidates) addSelectOption(select, selector, selector);
|
|
|
const current = String(selected || '');
|
|
|
if (current && !candidates.includes(current)) addSelectOption(select, current, `${current}(候选已失效)`, true);
|
|
|
select.value = current;
|
|
|
}
|
|
|
function networkAttachmentStateSelect(name, value) {
|
|
|
const select = document.createElement('select'); select.className = 'form-select'; select.name = name;
|
|
|
for (const [stateValue, label] of [['active', '启用'], ['draining', '排空'], ['disabled', '停用']]) addSelectOption(select, stateValue, label);
|
|
|
select.value = value || 'disabled'; return select;
|
|
|
}
|
|
|
function networkAttachmentBody(form, creating = false) {
|
|
|
const value = name => form.elements.namedItem(name)?.value ?? '';
|
|
|
const lineId = Number(value('line_id')); const priority = Number(value('priority'));
|
|
|
if (!Number.isInteger(lineId) || lineId < 1) throw new Error('请选择有效线路。');
|
|
|
if (!Number.isInteger(priority) || priority < -1000000 || priority > 1000000) throw new Error('优先级必须是 -1000000 至 1000000 的整数。');
|
|
|
const selector = value('network_selector');
|
|
|
if (!state.networkAttachmentCandidates.includes(selector)) throw new Error('请选择 Agent 最近一次完整能力测试中的网络候选。');
|
|
|
const body = { name: value('name').trim(), line_id: lineId, network_selector: selector, state: value('state'), priority };
|
|
|
if (creating) body.request_key = form.dataset.requestKey || '';
|
|
|
else body.expected_revision = Number(value('expected_revision'));
|
|
|
if (creating && !/^[0-9a-f]{32}$/.test(body.request_key)) throw new Error('创建请求标识已失效,请重新打开网络接入。');
|
|
|
if (!creating && (!Number.isInteger(body.expected_revision) || body.expected_revision < 1)) throw new Error('网络接入版本无效,请刷新后重试。');
|
|
|
return body;
|
|
|
}
|
|
|
function renderNetworkAttachmentForm(item) {
|
|
|
const form = element('form', 'cloud-admin-form-section'); form.dataset.attachmentKey = item.attachment_key;
|
|
|
const expected = networkPoolInput('hidden', 'expected_revision', Number(item.config_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', item.name || item.network_selector), element('div', 'text-muted admin-mono fs-13', item.attachment_key));
|
|
|
const badge = element('span', `badge ${item.ready === true ? 'bg-success-subtle text-success' : 'bg-light text-dark'}`, `${networkAttachmentStateLabel(item.state)} · ${networkAttachmentVerificationLabel(item.verification_state)}`);
|
|
|
heading.append(copy, badge);
|
|
|
const name = networkPoolInput('text', 'name', item.name, { required: true, maxLength: 80 });
|
|
|
const line = document.createElement('select'); line.className = 'form-select'; line.name = 'line_id'; line.required = true; fillNetworkAttachmentLineSelect(line, item.line_id);
|
|
|
const selector = document.createElement('select'); selector.className = 'form-select admin-mono'; selector.name = 'network_selector'; selector.required = true; fillNetworkAttachmentSelectorSelect(selector, item.network_selector);
|
|
|
const status = networkAttachmentStateSelect('state', item.state);
|
|
|
const priority = networkPoolInput('number', 'priority', Number(item.priority || 0), { required: true, min: -1000000, max: 1000000 });
|
|
|
for (const [control, suffix] of [[name, 'name'], [line, 'line'], [selector, 'selector'], [status, 'state'], [priority, 'priority']]) control.id = `host-network-attachment-${item.attachment_key}-${suffix}`;
|
|
|
const grid = element('div', 'cloud-admin-form-grid');
|
|
|
grid.append(networkPoolField('接入名称', name, true), networkPoolField('所属线路', line), networkPoolField('Agent 网络候选', selector), networkPoolField('运行状态', status), networkPoolField('优先级', priority));
|
|
|
const verifiedAt = Number(item.last_verified_at || 0) > 0 ? new Date(Number(item.last_verified_at) * 1000).toLocaleString() : '从未';
|
|
|
const error = item.verification_error_code ? ` · ${item.verification_error_code}` : '';
|
|
|
const metadata = element('p', 'form-text mb-0', `配置版本 ${Number(item.config_revision || 0)} · Agent 验证版本 ${Number(item.verified_agent_revision || 0)} · 最近验证 ${verifiedAt}${error}`);
|
|
|
const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3'); actions.append(metadata);
|
|
|
const buttons = element('div', 'd-flex gap-2 flex-wrap');
|
|
|
const test = element('button', 'btn btn-light', '验证接入'); test.type = 'button'; test.disabled = !canManage; test.addEventListener('click', () => testHostNetworkAttachment(item.attachment_key, Number(item.config_revision || 0), test));
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存接入'); save.type = 'submit'; save.disabled = !canManage; buttons.append(test, save); actions.append(buttons);
|
|
|
form.addEventListener('submit', event => saveHostNetworkAttachment(event, item.attachment_key));
|
|
|
form.append(expected, heading, grid, actions);
|
|
|
if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true;
|
|
|
return form;
|
|
|
}
|
|
|
function networkAttachmentContextCurrent(hostId, epoch) {
|
|
|
const dialog = byId('host-network-attachments-drawer');
|
|
|
return dialog?.open === true && state.networkAttachmentEpoch === epoch && String(state.networkAttachmentHostId) === String(hostId);
|
|
|
}
|
|
|
function syncNetworkAttachmentButtons() {
|
|
|
const lines = Array.isArray(state.networkAttachmentPayload?.lines) ? state.networkAttachmentPayload.lines : [];
|
|
|
const form = byId('host-network-attachment-create-form');
|
|
|
const ready = state.networkAttachmentCandidates.length > 0 && lines.length > 0 && /^[0-9a-f]{32}$/.test(form?.dataset?.requestKey || '');
|
|
|
byId('host-network-attachment-discover').disabled = !canManage || state.networkAttachmentBusy;
|
|
|
byId('host-network-attachment-create-submit').disabled = !canManage || state.networkAttachmentBusy || !ready;
|
|
|
}
|
|
|
function prepareNetworkAttachmentCreateForm(reset = true) {
|
|
|
const form = byId('host-network-attachment-create-form');
|
|
|
if (reset) {
|
|
|
form.reset();
|
|
|
try { form.dataset.requestKey = newNetworkAttachmentRequestKey(); }
|
|
|
catch { delete form.dataset.requestKey; }
|
|
|
}
|
|
|
fillNetworkAttachmentLineSelect(byId('host-network-attachment-new-line'));
|
|
|
fillNetworkAttachmentSelectorSelect(byId('host-network-attachment-new-selector'));
|
|
|
byId('host-network-attachment-new-state').value = 'disabled'; byId('host-network-attachment-new-priority').value = '0';
|
|
|
syncNetworkAttachmentButtons();
|
|
|
}
|
|
|
function clearNetworkAttachmentPayload() {
|
|
|
state.networkAttachmentPayload = null; state.networkAttachmentCandidates = []; state.networkAttachmentHostId = '';
|
|
|
byId('host-network-attachments-list')?.replaceChildren(); byId('host-network-attachments-summary')?.replaceChildren();
|
|
|
syncNetworkAttachmentButtons();
|
|
|
}
|
|
|
function renderHostNetworkAttachments(payload, hostId, epoch, resetCreate = true) {
|
|
|
if (!networkAttachmentContextCurrent(hostId, epoch)) return false;
|
|
|
if (!payload?.host?.id || String(payload.host.id) !== String(hostId)) throw new Error('宿主机网络接入响应与当前抽屉不一致,请重新打开。');
|
|
|
state.networkAttachmentPayload = payload;
|
|
|
state.networkAttachmentCandidates = Array.isArray(payload?.agent?.network_selectors) ? [...new Set(payload.agent.network_selectors)] : [];
|
|
|
const items = Array.isArray(payload.items) ? payload.items : [];
|
|
|
byId('host-network-attachments-title').textContent = `${payload.host.name || `宿主机 #${payload.host.id}`} · 网络接入`;
|
|
|
const cachedHost = state.hosts.find(host => Number(host.id) === Number(hostId));
|
|
|
const summary = byId('host-network-attachments-summary'); summary.replaceChildren();
|
|
|
for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network || payload.host.default_network)], ['Agent 版本 / 已测试版本', `${Number(payload?.agent?.revision || 0)} / ${Number(payload?.agent?.tested_revision || 0)}`], ['网络接入', `${items.length} / ${Number(payload.maximum || 64)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? 'admin-mono' : '', value));
|
|
|
const list = byId('host-network-attachments-list'); list.replaceChildren();
|
|
|
if (!items.length) list.append(element('p', 'text-muted py-3', '暂无网络接入。请先确认 Agent 已完成当前版本能力测试,再从候选中创建。'));
|
|
|
for (const item of items) list.append(renderNetworkAttachmentForm(item));
|
|
|
prepareNetworkAttachmentCreateForm(resetCreate);
|
|
|
hostNetworkAttachmentNotice('网络接入的线路与 selector 独立验证;公网地址池只能绑定已验证且启用的接入。');
|
|
|
return true;
|
|
|
}
|
|
|
function closeHostNetworkAttachments() {
|
|
|
++state.networkAttachmentEpoch; state.networkAttachmentBusy = false; clearNetworkAttachmentPayload();
|
|
|
const dialog = byId('host-network-attachments-drawer'); if (!dialog?.open) { finishHostDrawerClose('networkAttachment'); return; }
|
|
|
closeHostDrawer('host-network-attachments-drawer', 'networkAttachment');
|
|
|
}
|
|
|
async function openHostNetworkAttachments(hostId, opener) {
|
|
|
if (state.networkAttachmentBusy) return;
|
|
|
const epoch = ++state.networkAttachmentEpoch; clearNetworkAttachmentPayload(); state.networkAttachmentHostId = String(hostId);
|
|
|
state.networkAttachmentBusy = true; state.networkAttachmentOpener = opener; syncNetworkAttachmentButtons();
|
|
|
const dialog = byId('host-network-attachments-drawer'); hostNetworkAttachmentNotice('正在读取宿主机网络接入…');
|
|
|
if (!dialog.open) { lockHostDrawerScroll('networkAttachment'); window.VenixDrawerMotion.openDrawerWithMotion(dialog); }
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`);
|
|
|
if (networkAttachmentContextCurrent(hostId, epoch)) renderHostNetworkAttachments(payload, hostId, epoch);
|
|
|
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
|
|
|
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
|
|
|
}
|
|
|
function newNetworkAttachmentRequestKey() {
|
|
|
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('');
|
|
|
}
|
|
|
async function discoverHostNetworkAttachments() {
|
|
|
const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
|
|
|
if (!hostId || !canManage || state.networkAttachmentBusy) return;
|
|
|
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在从 Agent 重新发现网络候选…');
|
|
|
try {
|
|
|
const discovered = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/discover`, { method: 'POST', body: {} });
|
|
|
if (!networkAttachmentContextCurrent(hostId, epoch)) return;
|
|
|
const tested = Array.isArray(state.networkAttachmentPayload?.agent?.network_selectors) ? state.networkAttachmentPayload.agent.network_selectors : [];
|
|
|
const live = Array.isArray(discovered?.network_selectors) ? discovered.network_selectors : [];
|
|
|
state.networkAttachmentCandidates = live.filter(selector => tested.includes(selector));
|
|
|
const list = byId('host-network-attachments-list'); list.replaceChildren();
|
|
|
for (const item of state.networkAttachmentPayload?.items || []) list.append(renderNetworkAttachmentForm(item));
|
|
|
prepareNetworkAttachmentCreateForm(false);
|
|
|
const omitted = live.length - state.networkAttachmentCandidates.length;
|
|
|
hostNetworkAttachmentNotice(omitted > 0 ? `已发现 ${live.length} 个候选,其中 ${omitted} 个尚无完整 Agent 测试证据;请先重新测试 Agent。` : `已核对 ${live.length} 个 Agent 候选。`, omitted > 0);
|
|
|
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
|
|
|
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
|
|
|
}
|
|
|
async function createHostNetworkAttachment(event) {
|
|
|
event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
|
|
|
if (!hostId || !canManage || state.networkAttachmentBusy) return;
|
|
|
let body; try { body = networkAttachmentBody(form, true); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; }
|
|
|
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在创建网络接入…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`, { method: 'POST', body });
|
|
|
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已创建,请完成精确验证后再绑定公网地址池。'); }
|
|
|
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
|
|
|
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
|
|
|
}
|
|
|
async function saveHostNetworkAttachment(event, attachmentKey) {
|
|
|
event.preventDefault(); const form = event.currentTarget; const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
|
|
|
if (!hostId || !canManage || state.networkAttachmentBusy) return;
|
|
|
let body; try { body = networkAttachmentBody(form); } catch (error) { hostNetworkAttachmentNotice(error.message, true); return; }
|
|
|
state.networkAttachmentBusy = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在保存网络接入…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}`, { method: 'PUT', body });
|
|
|
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已保存;selector 变化后必须重新验证。'); }
|
|
|
} catch (error) { if (networkAttachmentContextCurrent(hostId, epoch)) hostNetworkAttachmentNotice(error.message, true); }
|
|
|
finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; syncNetworkAttachmentButtons(); } }
|
|
|
}
|
|
|
async function testHostNetworkAttachment(attachmentKey, expectedRevision, button) {
|
|
|
const hostId = state.networkAttachmentHostId; const epoch = state.networkAttachmentEpoch;
|
|
|
if (!hostId || !canManage || state.networkAttachmentBusy) return;
|
|
|
state.networkAttachmentBusy = true; if (button) button.disabled = true; syncNetworkAttachmentButtons(); hostNetworkAttachmentNotice('正在精确验证网络接入…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments/${encodeURIComponent(attachmentKey)}/test`, { method: 'POST', body: { expected_revision: expectedRevision } });
|
|
|
if (networkAttachmentContextCurrent(hostId, epoch)) { renderHostNetworkAttachments(payload, hostId, epoch); hostNetworkAttachmentNotice('网络接入已通过当前 Agent 版本验证。'); }
|
|
|
} catch (error) {
|
|
|
if (!networkAttachmentContextCurrent(hostId, epoch)) return;
|
|
|
try { renderHostNetworkAttachments(await api(`/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-attachments`), hostId, epoch); } catch {}
|
|
|
hostNetworkAttachmentNotice(error.message, true);
|
|
|
} finally { if (networkAttachmentContextCurrent(hostId, epoch)) { state.networkAttachmentBusy = false; if (button?.isConnected) button.disabled = false; syncNetworkAttachmentButtons(); } }
|
|
|
}
|
|
|
function networkPoolStateLabel(value) { return ({ active: '启用分配', draining: '排空', disabled: '停用' })[value] || '状态异常'; }
|
|
|
function networkPoolFamilyLabel(value) { return Number(value) === 6 ? 'IPv6' : 'IPv4'; }
|
|
|
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 networkPoolAttachmentId(attachment) { return Number(attachment?.id ?? attachment?.network_attachment_id ?? 0); }
|
|
|
function networkPoolAttachments() { return Array.isArray(state.networkPoolPayload?.attachments) ? state.networkPoolPayload.attachments : []; }
|
|
|
function networkPoolAttachmentById(id) { return networkPoolAttachments().find(attachment => networkPoolAttachmentId(attachment) === Number(id)) || null; }
|
|
|
function networkPoolAttachmentLabel(attachment) {
|
|
|
const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`;
|
|
|
return `${attachment?.name || attachment?.network_selector || '未命名接入'} · ${line}${attachment?.ready === true ? '' : '(未就绪)'}`;
|
|
|
}
|
|
|
function fillNetworkPoolAttachmentSelect(select, selected = '', currentAttachment = null) {
|
|
|
select.replaceChildren();
|
|
|
const attachments = networkPoolAttachments(); const selectedId = Number(selected || 0);
|
|
|
addSelectOption(select, '', attachments.length ? '请选择已验证网络接入' : '暂无网络接入', true);
|
|
|
for (const attachment of attachments) {
|
|
|
const id = networkPoolAttachmentId(attachment); const isCurrent = id === selectedId;
|
|
|
addSelectOption(select, id, networkPoolAttachmentLabel(attachment), attachment.ready !== true && !isCurrent);
|
|
|
}
|
|
|
if (selectedId > 0 && !attachments.some(attachment => networkPoolAttachmentId(attachment) === selectedId)) {
|
|
|
addSelectOption(select, selectedId, networkPoolAttachmentLabel(currentAttachment || { id: selectedId, name: `接入 #${selectedId}`, line_name: '关系已失效' }), false);
|
|
|
}
|
|
|
select.value = selectedId > 0 ? String(selectedId) : '';
|
|
|
}
|
|
|
function networkPoolAttachmentDetail(id, fallback = null) {
|
|
|
const attachment = networkPoolAttachmentById(id) || fallback;
|
|
|
if (!attachment) return '选择后显示派生线路与 selector。';
|
|
|
const line = attachment?.line?.name || attachment?.line_name || `线路 #${Number(attachment?.line_id || 0)}`;
|
|
|
return `派生线路:${line} · selector:${attachment.network_selector || '已失效'} · ${attachment.ready === true ? '已验证就绪' : networkAttachmentVerificationLabel(attachment.verification_state)}`;
|
|
|
}
|
|
|
function networkPoolAttachmentField(select, detail, wide = true) {
|
|
|
const wrapper = networkPoolField('网络接入', select, wide); wrapper.append(detail); return wrapper;
|
|
|
}
|
|
|
function networkPoolBody(form) {
|
|
|
const value = name => form.elements.namedItem(name)?.value ?? '';
|
|
|
const family = Number(value('address_family'));
|
|
|
const prefix = Number(value('guest_prefix_length'));
|
|
|
const maxAllocations = Number(value('max_allocations'));
|
|
|
const expectedRevision = Number(value('expected_revision'));
|
|
|
const networkAttachmentId = Number(value('network_attachment_id'));
|
|
|
if (![4, 6].includes(family)) throw new Error('请选择 IPv4 或 IPv6 地址族。');
|
|
|
if (!Number.isInteger(prefix) || (family === 4 ? prefix < 24 || prefix > 30 : prefix < 48 || prefix > 120)) throw new Error(family === 4 ? 'IPv4 前缀必须是 24 至 30 的整数。' : 'IPv6 前缀必须是 48 至 120 的整数。');
|
|
|
if (family === 6 && (!Number.isInteger(maxAllocations) || maxAllocations < 1 || maxAllocations > 65535)) throw new Error('IPv6 最大分配数量必须是 1 至 65535 的整数。');
|
|
|
if (!Number.isInteger(expectedRevision) || expectedRevision < 1) throw new Error('地址池版本无效,请刷新后重试。');
|
|
|
if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择有效的宿主机网络接入。');
|
|
|
return {
|
|
|
network_attachment_id: networkAttachmentId,
|
|
|
address_family: family,
|
|
|
name: value('name').trim(), cidr: value('cidr').trim(), gateway: value('gateway').trim(),
|
|
|
gateway_on_link: value('gateway_on_link') === '1',
|
|
|
dns_servers: formList(value('dns_servers')), reserved_ips: formList(value('reserved_ips')),
|
|
|
allocation_start: family === 6 ? value('allocation_start').trim() : null,
|
|
|
allocation_end: family === 6 ? value('allocation_end').trim() : null,
|
|
|
max_allocations: family === 6 ? maxAllocations : 0,
|
|
|
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', `${networkPoolFamilyLabel(pool.address_family)} · ${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 attachment = document.createElement('select'); attachment.className = 'form-select'; attachment.name = 'network_attachment_id'; attachment.required = true;
|
|
|
fillNetworkPoolAttachmentSelect(attachment, pool.network_attachment_id, pool.attachment);
|
|
|
const attachmentDetail = element('div', 'form-text', networkPoolAttachmentDetail(pool.network_attachment_id, pool.attachment));
|
|
|
attachment.addEventListener('change', () => { attachmentDetail.textContent = networkPoolAttachmentDetail(attachment.value, pool.attachment); });
|
|
|
const name = networkPoolInput('text', 'name', pool.name, { required: true, maxLength: 80 });
|
|
|
const family = networkPoolInput('select', 'address_family', ''); family.replaceChildren(); family.append(new Option('IPv4', '4'), new Option('IPv6', '6')); family.value = String(Number(pool.address_family || 4));
|
|
|
family.disabled = true;
|
|
|
const cidr = networkPoolInput('text', 'cidr', pool.cidr, { required: true, mono: true });
|
|
|
const gateway = networkPoolInput('text', 'gateway', pool.gateway, { required: true, mono: true });
|
|
|
const gatewayOnLink = networkPoolInput('select', 'gateway_on_link', ''); gatewayOnLink.replaceChildren(); gatewayOnLink.append(new Option('网关位于地址池内', '0'), new Option('网关在链路上(on-link)', '1')); gatewayOnLink.value = pool.gateway_on_link === true ? '1' : '0';
|
|
|
const prefix = networkPoolInput('number', 'guest_prefix_length', pool.guest_prefix_length, { required: true, min: Number(pool.address_family) === 6 ? 48 : 24, max: Number(pool.address_family) === 6 ? 120 : 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 });
|
|
|
const allocationStart = networkPoolInput('text', 'allocation_start', pool.allocation_start || '', { mono: true });
|
|
|
const allocationEnd = networkPoolInput('text', 'allocation_end', pool.allocation_end || '', { mono: true });
|
|
|
const maxAllocations = networkPoolInput('number', 'max_allocations', Number(pool.max_allocations || 0), { min: 1, max: 65535 });
|
|
|
for (const [control, suffix] of [[attachment, 'attachment'], [name, 'name'], [family, 'family'], [cidr, 'cidr'], [gateway, 'gateway'], [gatewayOnLink, 'gateway-on-link'], [prefix, 'prefix'], [status, 'state'], [dns, 'dns'], [reserved, 'reserved'], [allocationStart, 'allocation-start'], [allocationEnd, 'allocation-end'], [maxAllocations, 'max-allocations']]) control.id = `host-network-pool-${pool.pool_key}-${suffix}`;
|
|
|
const sparseFields = [networkPoolField('IPv6 分配起始地址', allocationStart), networkPoolField('IPv6 分配结束地址', allocationEnd), networkPoolField('IPv6 最大分配数量', maxAllocations)];
|
|
|
const syncFamily = () => {
|
|
|
const ipv6 = family.value === '6';
|
|
|
prefix.min = ipv6 ? '48' : '24';
|
|
|
prefix.max = ipv6 ? '120' : '30';
|
|
|
for (const field of sparseFields) field.hidden = !ipv6;
|
|
|
for (const control of [allocationStart, allocationEnd, maxAllocations]) {
|
|
|
control.required = ipv6;
|
|
|
control.disabled = !canManage || !ipv6;
|
|
|
}
|
|
|
gatewayOnLink.disabled = !canManage || !ipv6;
|
|
|
if (!ipv6) {
|
|
|
allocationStart.value = '';
|
|
|
allocationEnd.value = '';
|
|
|
maxAllocations.value = '0';
|
|
|
gatewayOnLink.value = '0';
|
|
|
}
|
|
|
};
|
|
|
family.addEventListener('change', syncFamily); syncFamily();
|
|
|
grid.append(networkPoolAttachmentField(attachment, attachmentDetail), networkPoolField('地址池名称', name, true), networkPoolField('地址族', family), networkPoolField('网关方式', gatewayOnLink), networkPoolField('实际公网 CIDR', cidr), networkPoolField('公网网关', gateway), networkPoolField('客户机网络前缀', prefix), networkPoolField('运行状态', status), networkPoolField('DNS(逗号或空格分隔)', dns, true), networkPoolField('保留 / 禁用 IP', reserved, true), ...sparseFields);
|
|
|
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)} · 可分配 ${Number(pool.available_count || 0)}`);
|
|
|
const actions = element('div', 'd-flex justify-content-between align-items-center gap-2 flex-wrap mt-3');
|
|
|
actions.append(metadata);
|
|
|
const actionButtons = element('div', 'd-flex gap-2 flex-wrap');
|
|
|
if (canManage) {
|
|
|
const maintenance = element('a', 'btn btn-light', '发送维护通知');
|
|
|
maintenance.href = `/admin/maintenance-notices?scope_type=public_ip_pool&host_id=${encodeURIComponent(state.networkPoolHostId)}&pool_key=${encodeURIComponent(pool.pool_key)}`;
|
|
|
actionButtons.append(maintenance);
|
|
|
}
|
|
|
const replacementHistoryCount = Number(pool.replacement_history_count || 0);
|
|
|
const hasReplacementHistory = pool.has_replacement_history === true
|
|
|
|| replacementHistoryCount > 0;
|
|
|
const replacement = element('button', 'btn btn-light', pool.active_replacement
|
|
|
? '查看换池任务'
|
|
|
: hasReplacementHistory ? '查看换池记录' : '受控迁移占用地址');
|
|
|
replacement.type = 'button'; replacement.dataset.poolReplacementOpen = pool.pool_key;
|
|
|
replacement.hidden = Number(pool.occupied_count || 0) < 1
|
|
|
&& !pool.active_replacement && !hasReplacementHistory;
|
|
|
replacement.disabled = !canManage
|
|
|
&& !pool.active_replacement && !hasReplacementHistory;
|
|
|
replacement.addEventListener('click', () => loadNetworkPoolReplacement(
|
|
|
state.networkPoolHostId, pool, replacementPanel));
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存此地址池'); save.type = 'submit'; save.disabled = !canManage;
|
|
|
actionButtons.append(replacement, save); actions.append(actionButtons);
|
|
|
form.addEventListener('submit', event => saveHostNetworkPool(event, pool.pool_key));
|
|
|
form.append(expectedRevision, heading, grid);
|
|
|
const runtimeLocked = Number(pool.occupied_count || 0) > 0;
|
|
|
const replacementLocked = pool.replacement_locked === true
|
|
|
|| (pool.active_replacement && typeof pool.active_replacement === 'object');
|
|
|
if (runtimeLocked) {
|
|
|
for (const control of [attachment, family, cidr, gateway, gatewayOnLink, prefix, dns, allocationStart, allocationEnd, maxAllocations]) control.disabled = true;
|
|
|
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池仍有实例或任务占用;网络接入、CIDR、网关、客户机前缀和 DNS 已锁定。仍可编辑未占用的保留 / 禁用 IP,已分配或任务占用的 IP 会被拒绝。'));
|
|
|
}
|
|
|
if (replacementLocked) {
|
|
|
for (const control of [attachment, name, family, cidr, gateway, gatewayOnLink, prefix, status, dns, reserved, allocationStart, allocationEnd, maxAllocations, save]) control.disabled = true;
|
|
|
form.append(element('p', 'alert alert-warning mt-3 mb-0', '该地址池正在执行受控换池,配置保持锁定;请查看批次进度或前往任务中心核对。'));
|
|
|
}
|
|
|
if (!canManage) for (const control of form.querySelectorAll('input,textarea,select,button')) control.disabled = true;
|
|
|
if (!canManage && (pool.active_replacement || hasReplacementHistory)) {
|
|
|
replacement.disabled = false;
|
|
|
}
|
|
|
const replacementPanel = element('section', 'cloud-admin-pool-replacement mt-3');
|
|
|
replacementPanel.dataset.poolReplacementPanel = pool.pool_key;
|
|
|
replacementPanel.hidden = true;
|
|
|
form.append(actions, replacementPanel);
|
|
|
return form;
|
|
|
}
|
|
|
function networkPoolReplacementPath(hostId, sourcePoolKey, batchKey = '') {
|
|
|
const base = `/api/v1/admin/hosts/${encodeURIComponent(hostId)}/network-pools/${encodeURIComponent(sourcePoolKey)}/replacement-batches`;
|
|
|
return batchKey ? `${base}/${encodeURIComponent(batchKey)}` : base;
|
|
|
}
|
|
|
function networkPoolReplacementState(value) {
|
|
|
return ({ queued: '等待中', preparing: '准备中', running: '执行中', finalizing: '正在收敛', succeeded: '已完成', failed: '失败', blocked: '需要核对', unknown: '效果未知', effect_unknown: '效果未知' })[value] || '状态未知';
|
|
|
}
|
|
|
function networkPoolReplacementTaskLink(batch) {
|
|
|
const link = element('a', 'btn btn-light btn-sm', '查看任务中心');
|
|
|
link.href = typeof batch?.job_url === 'string' && batch.job_url.startsWith('/admin/')
|
|
|
? batch.job_url : `/admin/operations?q=${encodeURIComponent(batch?.parent_job_id || batch?.job_id || '')}`;
|
|
|
return link;
|
|
|
}
|
|
|
function networkPoolReplacementAttentionChildIds(batch) {
|
|
|
const stateValue = String(batch?.state || '');
|
|
|
if (!['blocked', 'unknown', 'effect_unknown'].includes(stateValue)) return [];
|
|
|
const items = Array.isArray(batch?.items) ? batch.items : [];
|
|
|
let attention = items.filter(item => ['blocked', 'unknown', 'effect_unknown'].includes(String(item?.state || '')));
|
|
|
// A legacy/partial projection may report only the batch state. Keep every
|
|
|
// unfinished child reachable instead of falling back to the non-recoverable
|
|
|
// local parent job.
|
|
|
if (!attention.length) attention = items.filter(item => String(item?.state || '') !== 'succeeded');
|
|
|
return Array.from(new Set(attention.map(item => String(item?.child_job_id || ''))
|
|
|
.filter(id => /^[1-9][0-9]*$/.test(id))));
|
|
|
}
|
|
|
function networkPoolReplacementChildTaskLink(jobId) {
|
|
|
const link = element('a', 'btn btn-outline-danger btn-sm', `核对子任务 #${jobId}`);
|
|
|
link.href = `/admin/operations?q=${encodeURIComponent(jobId)}`;
|
|
|
return link;
|
|
|
}
|
|
|
function networkPoolReplacementBatchCard(batch, historical = false) {
|
|
|
const card = element('article', `cloud-admin-pool-replacement-batch${historical ? ' is-history' : ''}`);
|
|
|
const heading = element('div', 'cloud-admin-pool-replacement-batch-head');
|
|
|
const copy = element('div');
|
|
|
copy.append(element('strong', '', historical ? '历史换池批次' : '当前换池批次'),
|
|
|
element('small', 'admin-mono', `#${batch?.parent_job_id || batch?.job_id || '—'}`));
|
|
|
const stateValue = String(batch?.state || '');
|
|
|
const badge = element('span', `cloud-admin-pool-replacement-state is-${['succeeded'].includes(stateValue) ? 'success' : ['failed', 'blocked', 'unknown', 'effect_unknown'].includes(stateValue) ? 'danger' : 'warning'}`, networkPoolReplacementState(stateValue));
|
|
|
heading.append(copy, badge);
|
|
|
const progress = batch?.counts && typeof batch.counts === 'object'
|
|
|
? batch.counts
|
|
|
: (batch?.items && typeof batch.items === 'object' && !Array.isArray(batch.items)
|
|
|
? batch.items : batch || {});
|
|
|
const total = Number(progress.total || 0); const succeeded = Number(progress.succeeded || 0);
|
|
|
const failed = Number(progress.failed || 0); const unknown = Number(progress.unknown || 0);
|
|
|
const queued = Number(progress.queued ?? progress.pending ?? 0);
|
|
|
const running = Number(progress.running || 0);
|
|
|
const finished = Number(progress.finished ?? (succeeded + failed + unknown));
|
|
|
const details = element('p', 'mb-0', total > 0
|
|
|
? `实例进度 ${finished} / ${total} · 等待 ${queued} · 执行 ${running} · 成功 ${succeeded} · 失败 ${failed} · 未知 ${unknown}`
|
|
|
: '批次明细正在建立或已归档。');
|
|
|
if (batch?.last_error_code) details.append(document.createTextNode(` · ${batch.last_error_code}`));
|
|
|
const footer = element('div', 'cloud-admin-pool-replacement-batch-actions');
|
|
|
footer.append(networkPoolReplacementTaskLink(batch));
|
|
|
for (const childJobId of networkPoolReplacementAttentionChildIds(batch)) {
|
|
|
footer.append(networkPoolReplacementChildTaskLink(childJobId));
|
|
|
}
|
|
|
card.append(heading, details, footer);
|
|
|
return card;
|
|
|
}
|
|
|
function networkPoolReplacementFacts(source, pool) {
|
|
|
const facts = element('dl', 'cloud-admin-pool-replacement-facts');
|
|
|
const values = [
|
|
|
['源地址池', source?.name || pool?.name || '未记录'],
|
|
|
['线路', source?.line?.name || source?.line_name || pool?.line?.name || '未记录'],
|
|
|
['网络接入', source?.network_selector || pool?.network_selector || '未记录'],
|
|
|
['待迁移实例', Number(source?.assigned_instance_count ?? source?.assigned_count ?? pool?.assigned_instance_count ?? 0)],
|
|
|
];
|
|
|
for (const [label, value] of values) {
|
|
|
const item = element('div'); item.append(element('dt', '', label), element('dd', label === '网络接入' ? 'admin-mono' : '', value)); facts.append(item);
|
|
|
}
|
|
|
return facts;
|
|
|
}
|
|
|
function networkPoolReplacementRequest(payload, targetSelect, confirmed, panel) {
|
|
|
const source = payload?.source_pool || {};
|
|
|
const targetKey = String(targetSelect?.value || '');
|
|
|
const target = (Array.isArray(payload?.target_options) ? payload.target_options : [])
|
|
|
.find(item => String(item?.pool_key || '') === targetKey);
|
|
|
const sourceRevision = Number(source.expected_revision ?? source.revision);
|
|
|
const targetRevision = Number(target?.expected_revision ?? target?.revision);
|
|
|
if (!target || !/^[0-9a-f]{32}$/.test(targetKey)) throw new Error('请选择符合条件的目标地址池。');
|
|
|
if (!Number.isInteger(sourceRevision) || sourceRevision < 1
|
|
|
|| !Number.isInteger(targetRevision) || targetRevision < 1) {
|
|
|
throw new Error('源或目标地址池版本无效,请刷新后重试。');
|
|
|
}
|
|
|
if (confirmed !== true) throw new Error('请确认实例会逐台重启并更换公网 IP。');
|
|
|
if (!/^[0-9a-f]{32}$/.test(String(panel?.dataset?.requestKey || ''))) {
|
|
|
panel.dataset.requestKey = newNetworkPoolRequestKey();
|
|
|
}
|
|
|
return {
|
|
|
target_pool_key: targetKey,
|
|
|
expected_source_revision: sourceRevision,
|
|
|
expected_target_revision: targetRevision,
|
|
|
request_key: panel.dataset.requestKey,
|
|
|
confirm_replacement: true,
|
|
|
};
|
|
|
}
|
|
|
function renderNetworkPoolReplacementPanel(panel, payload, hostId, pool) {
|
|
|
panel.replaceChildren(); panel.hidden = false;
|
|
|
const source = payload?.source_pool && typeof payload.source_pool === 'object'
|
|
|
? payload.source_pool : pool;
|
|
|
const header = element('header', 'cloud-admin-pool-replacement-head');
|
|
|
const heading = element('div'); heading.append(element('h6', 'mb-1', '受控迁移占用地址'),
|
|
|
element('p', 'mb-0', '同一宿主机、同一商业线路内逐台换 IP;每台实例使用独立任务和冻结目标地址。'));
|
|
|
const close = element('button', 'btn btn-light btn-sm', '收起'); close.type = 'button';
|
|
|
close.addEventListener('click', () => { panel.hidden = true; }); header.append(heading, close);
|
|
|
panel.append(header, networkPoolReplacementFacts(source, pool));
|
|
|
|
|
|
const active = payload?.active_batch && typeof payload.active_batch === 'object'
|
|
|
? payload.active_batch : null;
|
|
|
if (active) {
|
|
|
panel.append(networkPoolReplacementBatchCard(active));
|
|
|
if (['failed', 'blocked', 'unknown', 'effect_unknown'].includes(String(active.state || ''))) {
|
|
|
const hasChildRecovery = networkPoolReplacementAttentionChildIds(active).length > 0;
|
|
|
panel.append(element('p', 'alert alert-danger mb-0', hasChildRecovery
|
|
|
? '该批次需要按上方子任务编号逐项核对效果。页面不会自动重试,也不会重新分配目标地址。'
|
|
|
: '该批次需要在任务中心核对效果。页面不会自动重试,也不会重新分配目标地址。'));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
const history = Array.isArray(payload?.history) ? payload.history : [];
|
|
|
const unresolvedHistory = history.some(batch => ['failed', 'blocked', 'unknown', 'effect_unknown'].includes(String(batch?.state || '')));
|
|
|
const targets = Array.isArray(payload?.target_options) ? payload.target_options.filter(target =>
|
|
|
target && target.eligible !== false
|
|
|
&& /^[0-9a-f]{32}$/.test(String(target.pool_key || ''))) : [];
|
|
|
const canStart = !active && targets.length > 0
|
|
|
&& (payload?.can_start === true || (payload?.can_start !== false && !unresolvedHistory));
|
|
|
if (canStart && canManage) {
|
|
|
const controls = element('div', 'cloud-admin-pool-replacement-controls');
|
|
|
const targetLabel = element('label'); targetLabel.append(element('span', 'form-label d-block', '目标地址池'));
|
|
|
const target = document.createElement('select'); target.className = 'form-select'; target.required = true;
|
|
|
target.append(new Option('请选择同线路目标地址池', ''));
|
|
|
for (const option of targets) {
|
|
|
const available = Number(option.available_count || 0);
|
|
|
target.append(new Option(`${option.name || option.cidr || option.pool_key} · ${option.network_selector || '接入未记录'} · 可用 ${available}`, option.pool_key));
|
|
|
}
|
|
|
targetLabel.append(target);
|
|
|
const confirmLabel = element('label', 'cloud-admin-pool-replacement-confirm');
|
|
|
const confirm = document.createElement('input'); confirm.type = 'checkbox';
|
|
|
confirmLabel.append(confirm, document.createTextNode('我确认实例会逐台受控重启、分配新公网 IP;失败或效果未知不会自动重放。'));
|
|
|
const feedback = element('p', 'form-text mb-0'); feedback.dataset.poolReplacementFeedback = '';
|
|
|
const submit = element('button', 'btn btn-primary', '开始受控换池'); submit.type = 'button';
|
|
|
submit.addEventListener('click', () => startNetworkPoolReplacement(
|
|
|
hostId, source, pool, payload, panel, target, confirm, submit, feedback));
|
|
|
controls.append(targetLabel, confirmLabel, feedback, submit); panel.append(controls);
|
|
|
} else if (canStart && !canManage) {
|
|
|
panel.append(element('p', 'alert alert-info mb-0', '当前为只读管理权限;可以查看换池记录,但不能发起新的受控换池。'));
|
|
|
} else if (!active) {
|
|
|
const message = payload?.start_block_reason || (unresolvedHistory
|
|
|
? '最近批次仍有失败或效果未知结果,请先在任务中心完成核对。'
|
|
|
: targets.length ? '当前地址池暂不能开始新的受控换池。' : '当前没有同宿主机、同线路且容量足够的目标地址池。');
|
|
|
panel.append(element('p', 'alert alert-warning mb-0', message));
|
|
|
}
|
|
|
|
|
|
if (history.length) {
|
|
|
const historyBox = element('details', 'cloud-admin-pool-replacement-history');
|
|
|
const historyTitle = element('summary', '', `最近批次(${history.length})`); historyBox.append(historyTitle);
|
|
|
for (const batch of history.slice(0, 5)) historyBox.append(networkPoolReplacementBatchCard(batch, true));
|
|
|
panel.append(historyBox);
|
|
|
}
|
|
|
}
|
|
|
async function loadNetworkPoolReplacement(hostId, pool, panel, batchKey = '') {
|
|
|
if (!hostId || !pool?.pool_key || state.networkPoolReplacementBusy.has(pool.pool_key)) return;
|
|
|
if (!panel.hidden && !batchKey && panel.dataset.loaded === '1') { panel.hidden = true; return; }
|
|
|
const epoch = state.networkPoolEpoch; state.networkPoolReplacementBusy.add(pool.pool_key);
|
|
|
panel.hidden = false; panel.replaceChildren(element('p', 'alert alert-info mb-0', '正在读取受控换池状态…'));
|
|
|
try {
|
|
|
const payload = await api(networkPoolReplacementPath(hostId, pool.pool_key, batchKey));
|
|
|
if (!networkPoolContextCurrent(hostId, epoch)
|
|
|
|| String(panel.dataset.poolReplacementPanel) !== String(pool.pool_key)) return;
|
|
|
let view = payload;
|
|
|
if (batchKey) {
|
|
|
if (String(payload?.batch_key || '') !== String(batchKey)) throw new Error('换池批次状态与请求不一致,请刷新后重试。');
|
|
|
view = { source_pool: pool, target_options: [], active_batch: payload, history: [], can_start: false };
|
|
|
} else if (String(payload?.source_pool?.pool_key || '') !== String(pool.pool_key)) {
|
|
|
throw new Error('换池状态与源地址池不一致,请刷新后重试。');
|
|
|
}
|
|
|
panel.dataset.loaded = '1'; renderNetworkPoolReplacementPanel(panel, view, hostId, pool);
|
|
|
} catch (error) {
|
|
|
if (networkPoolContextCurrent(hostId, epoch)) {
|
|
|
panel.replaceChildren(element('p', 'alert alert-danger mb-0', error.message));
|
|
|
}
|
|
|
} finally { state.networkPoolReplacementBusy.delete(pool.pool_key); }
|
|
|
}
|
|
|
function observeNetworkPoolReplacement(receipt, hostId, source, pool, panel, batchKey) {
|
|
|
const url = taskUrl(receipt); if (!url) return;
|
|
|
const key = `${hostId}:${source.pool_key}`;
|
|
|
const previous = state.networkPoolReplacementObservers.get(key);
|
|
|
if (previous?.active && previous.url === url) return;
|
|
|
if (previous?.active) previous.stop('replaced');
|
|
|
const handle = observeTask(receipt, {
|
|
|
maxDurationMs: 900000,
|
|
|
onUpdate: task => {
|
|
|
if (!task.terminal) hostNetworkPoolNotice(`换池任务 #${task.id} 正在后台逐台处理实例。`);
|
|
|
},
|
|
|
onTerminal: task => {
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
const recoveryNotice = recoveryTaskFailureNotice(task);
|
|
|
hostNetworkPoolNotice(succeeded ? `换池任务 #${task.id} 已完成,正在刷新地址池账本。`
|
|
|
: recoveryNotice || `换池任务 #${task.id} 未正常完成,请按原任务编号核对。`, !succeeded);
|
|
|
delete panel.dataset.loaded;
|
|
|
void loadNetworkPoolReplacement(hostId, pool, panel, batchKey);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'deadline') {
|
|
|
hostNetworkPoolNotice('换池任务观察已到期,正在读取持久化批次状态;不会自动重放任务。', true);
|
|
|
delete panel.dataset.loaded;
|
|
|
void loadNetworkPoolReplacement(hostId, pool, panel, batchKey);
|
|
|
}
|
|
|
},
|
|
|
});
|
|
|
state.networkPoolReplacementObservers.set(key, handle); state.taskObservers.add(handle);
|
|
|
void handle.done.finally(() => {
|
|
|
state.taskObservers.delete(handle);
|
|
|
if (state.networkPoolReplacementObservers.get(key) === handle) state.networkPoolReplacementObservers.delete(key);
|
|
|
});
|
|
|
}
|
|
|
async function startNetworkPoolReplacement(hostId, source, pool, payload, panel, target, confirm, submit, feedback) {
|
|
|
if (!canManage || state.networkPoolReplacementBusy.has(source.pool_key)) return;
|
|
|
let receipt = null;
|
|
|
let body;
|
|
|
try { body = networkPoolReplacementRequest(payload, target, confirm.checked, panel); }
|
|
|
catch (error) { feedback.textContent = error.message; feedback.className = 'text-danger fs-13 mb-0'; return; }
|
|
|
state.networkPoolReplacementBusy.add(source.pool_key); submit.disabled = true; target.disabled = true; confirm.disabled = true;
|
|
|
feedback.textContent = '正在冻结源、目标地址池并创建批量任务,请勿重复提交…'; feedback.className = 'text-muted fs-13 mb-0';
|
|
|
try {
|
|
|
receipt = await acceptedTask(networkPoolReplacementPath(hostId, source.pool_key), { method: 'POST', body });
|
|
|
} catch (error) {
|
|
|
feedback.textContent = error.message; feedback.className = 'text-danger fs-13 mb-0';
|
|
|
if (error.keepMutationLocked === true || error.mutationMayHaveApplied === true) {
|
|
|
feedback.textContent += ' 操作结果无法确认,请勿再次提交;请前往任务中心核对原任务。';
|
|
|
hostNetworkPoolNotice(feedback.textContent, true);
|
|
|
return;
|
|
|
}
|
|
|
submit.disabled = false; target.disabled = false; confirm.disabled = false;
|
|
|
} finally {
|
|
|
state.networkPoolReplacementBusy.delete(source.pool_key);
|
|
|
}
|
|
|
if (!receipt) return;
|
|
|
announceTaskAccepted(receipt, { title: '受控迁移公网地址池' });
|
|
|
feedback.textContent = `换池任务 #${receipt.task_id} 已接收。`;
|
|
|
hostNetworkPoolNotice(`换池任务 #${receipt.task_id} 已接收;实例会由独立子任务并行处理。`);
|
|
|
delete panel.dataset.loaded;
|
|
|
await loadNetworkPoolReplacement(hostId, pool, panel);
|
|
|
observeNetworkPoolReplacement(receipt, hostId, source, pool, panel, '');
|
|
|
}
|
|
|
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 readyAttachments = networkPoolAttachments().filter(attachment => attachment.ready === true);
|
|
|
const add = byId('host-network-pool-add');
|
|
|
if (add) add.disabled = state.networkPoolBusy || !canManage || !payload || readyAttachments.length === 0 || items.length >= Number(payload.maximum || 32);
|
|
|
const submit = byId('host-network-pool-create-submit');
|
|
|
if (submit) submit.disabled = state.networkPoolBusy || !canManage || readyAttachments.length === 0;
|
|
|
}
|
|
|
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 stopNetworkPoolReplacementObservers(reason = 'drawer-close') {
|
|
|
for (const observer of state.networkPoolReplacementObservers.values()) {
|
|
|
if (observer?.active) observer.stop(reason);
|
|
|
}
|
|
|
state.networkPoolReplacementObservers.clear();
|
|
|
}
|
|
|
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 items = Array.isArray(payload?.items) ? payload.items : []; const attachments = networkPoolAttachments();
|
|
|
byId('host-network-pools-title').textContent = `${host.name || `宿主机 #${host.id}`} · 公网地址池`;
|
|
|
const summary = byId('host-network-pools-summary'); summary.replaceChildren();
|
|
|
const cachedHost = state.hosts.find(item => Number(item.id) === Number(hostId));
|
|
|
for (const [label, value] of [['兼容默认网络(旧入口)', hostNetworkLabel(cachedHost?.default_network)], ['可用网络接入', `${attachments.filter(item => item.ready === true).length} / ${attachments.length}`], ['地址池数量', `${items.length} / ${Number(payload?.maximum || 32)}`]]) summary.append(element('dt', '', label), element('dd', label.startsWith('兼容默认网络') ? '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));
|
|
|
fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment'));
|
|
|
byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail('');
|
|
|
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;
|
|
|
stopNetworkPoolReplacementObservers(); 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-family').value = '4'; byId('host-network-pool-new-prefix').value = '28'; byId('host-network-pool-new-gateway-on-link').value = '0'; byId('host-network-pool-new-state').value = 'active'; syncNewNetworkPoolFamily(); form.hidden = false;
|
|
|
fillNetworkPoolAttachmentSelect(byId('host-network-pool-new-attachment'));
|
|
|
const firstReady = networkPoolAttachments().find(attachment => attachment.ready === true);
|
|
|
if (firstReady) byId('host-network-pool-new-attachment').value = String(networkPoolAttachmentId(firstReady));
|
|
|
byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(byId('host-network-pool-new-attachment').value);
|
|
|
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 syncNewNetworkPoolFamily() {
|
|
|
const ipv6 = byId('host-network-pool-new-family').value === '6';
|
|
|
const prefix = byId('host-network-pool-new-prefix'); prefix.min = ipv6 ? '48' : '24'; prefix.max = ipv6 ? '120' : '30'; prefix.value = ipv6 ? '64' : '28';
|
|
|
for (const id of ['host-network-pool-new-allocation-start', 'host-network-pool-new-allocation-end', 'host-network-pool-new-max-allocations']) { const control = byId(id); control.required = ipv6; control.disabled = !canManage || !ipv6; }
|
|
|
const gatewayOnLink = byId('host-network-pool-new-gateway-on-link'); gatewayOnLink.disabled = !canManage || !ipv6;
|
|
|
for (const field of document.querySelectorAll?.('[data-network-pool-ipv6-only]') || []) field.hidden = !ipv6;
|
|
|
if (!ipv6) gatewayOnLink.value = '0';
|
|
|
}
|
|
|
function newNetworkPoolBody(form) {
|
|
|
const family = Number(byId('host-network-pool-new-family').value);
|
|
|
const prefix = Number(byId('host-network-pool-new-prefix').value);
|
|
|
const maxAllocations = Number(byId('host-network-pool-new-max-allocations').value);
|
|
|
const networkAttachmentId = Number(byId('host-network-pool-new-attachment').value);
|
|
|
if (![4, 6].includes(family)) throw new Error('请选择 IPv4 或 IPv6 地址族。');
|
|
|
if (!Number.isInteger(prefix) || (family === 4 ? prefix < 24 || prefix > 30 : prefix < 48 || prefix > 120)) throw new Error(family === 4 ? 'IPv4 前缀必须是 24 至 30 的整数。' : 'IPv6 前缀必须是 48 至 120 的整数。');
|
|
|
if (family === 6 && (!Number.isInteger(maxAllocations) || maxAllocations < 1 || maxAllocations > 65535)) throw new Error('IPv6 最大分配数量必须是 1 至 65535 的整数。');
|
|
|
if (!Number.isInteger(networkAttachmentId) || networkAttachmentId < 1) throw new Error('请选择已验证的宿主机网络接入。');
|
|
|
const requestKey = form.dataset.requestKey || '';
|
|
|
if (!/^[0-9a-f]{32}$/.test(requestKey)) throw new Error('创建请求标识已失效,请取消后重新添加。');
|
|
|
return { network_attachment_id: networkAttachmentId, address_family: family, 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(), gateway_on_link: byId('host-network-pool-new-gateway-on-link').value === '1', dns_servers: formList(byId('host-network-pool-new-dns').value), reserved_ips: formList(byId('host-network-pool-new-reserved').value), allocation_start: family === 6 ? byId('host-network-pool-new-allocation-start').value.trim() : null, allocation_end: family === 6 ? byId('host-network-pool-new-allocation-end').value.trim() : null, max_allocations: family === 6 ? maxAllocations : 0, 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-attachments').addEventListener('click', () => openHostConfigTool('networkAttachments'));
|
|
|
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-membership-create-form').addEventListener('submit', createHostMembership); 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-attachments-close').addEventListener('click', closeHostNetworkAttachments); byId('host-network-attachment-create-form').addEventListener('submit', createHostNetworkAttachment); byId('host-network-attachment-discover').addEventListener('click', discoverHostNetworkAttachments);
|
|
|
const attachmentDrawer = byId('host-network-attachments-drawer'); attachmentDrawer.addEventListener('cancel', event => { event.preventDefault(); closeHostNetworkAttachments(); }); attachmentDrawer.addEventListener('click', event => { if (event.target === attachmentDrawer) closeHostNetworkAttachments(); });
|
|
|
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);
|
|
|
byId('host-network-pool-new-attachment').addEventListener('change', event => { byId('host-network-pool-new-attachment-detail').textContent = networkPoolAttachmentDetail(event.currentTarget.value); });
|
|
|
byId('host-network-pool-new-family').addEventListener('change', syncNewNetworkPoolFamily); syncNewNetworkPoolFamily();
|
|
|
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();
|