You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/agent-settings.js

136 lines
7.5 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

const root = document.querySelector('[data-cloud-agent-settings]');
const byId = id => document.getElementById(id);
const canManage = root?.dataset.canManage === '1';
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', agents: [], selected: null, busy: false };
function notice(message, error = false) {
const box = byId('agent-settings-status');
box.textContent = message;
box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`;
}
async function api(path, options = {}) {
const headers = { Accept: 'application/json' };
let body;
if (options.body !== undefined) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(options.body);
}
if (options.method && options.method !== 'GET') headers['X-Admin-CSRF-Token'] = state.csrf;
const response = await fetch(path, {
method: options.method || 'GET', headers, body,
credentials: 'same-origin', cache: 'no-store', redirect: 'error',
});
let payload = {};
try { payload = await response.json(); } catch {}
if (!response.ok) throw new Error(payload.error || payload.detail || 'Agent API 请求失败。');
return payload;
}
function text(tag, className, value) {
const node = document.createElement(tag); node.className = className; node.textContent = value; return node;
}
function selectedAgent() {
return state.agents.find(agent => String(agent.host_id) === String(state.selected)) || null;
}
function renderList() {
const list = byId('agent-settings-list'); list.replaceChildren();
if (!state.agents.length) { list.append(text('p', 'text-muted', '请先添加计算节点。')); return; }
for (const agent of state.agents) {
const button = text('button', 'cloud-admin-host-item', agent.host_name || `宿主机 #${agent.host_id}`);
button.type = 'button'; button.dataset.active = String(agent.host_id) === String(state.selected) ? '1' : '0';
button.append(text('small', '', `${agent.region || '地区未设置'} · Agent ID ${agent.agent_id || agent.host_id}`));
button.addEventListener('click', () => { state.selected = String(agent.host_id); renderList(); fill(agent); });
list.append(button);
}
}
function renderHealth(agent) {
const health = byId('agent-settings-health'); health.replaceChildren();
const rows = [
['配置版本', String(agent.revision || 0)],
['就绪状态', agent.ready === true ? '已通过当前版本测试' : '未就绪,不参与调度'],
['密钥状态', agent.secret_configured ? '已安全保存' : '未配置'],
['最近测试', agent.last_test_status === 'healthy' ? '正常' : agent.last_test_status === 'unhealthy' ? '失败' : '尚未测试'],
['Agent 版本', agent.last_agent_version || '--'],
['错误代码', agent.last_error_code || '--'],
];
for (const [label, value] of rows) { health.append(text('dt', '', label), text('dd', '', value)); }
}
function fill(agent) {
byId('agent-settings-host-id').value = agent?.host_id || '';
byId('agent-settings-revision').value = String(agent?.revision || 0);
byId('agent-settings-title').textContent = agent ? `Agent 上行连接 · ${agent.host_name}` : '选择计算节点';
byId('agent-settings-agent-id').value = agent?.agent_id || agent?.host_id || '';
byId('agent-settings-secret').value = '';
byId('agent-settings-secret').placeholder = agent?.secret_configured ? '已配置,留空保留现有密钥' : '首次配置必须填写至少 32 位密钥';
byId('agent-settings-enabled').checked = agent?.enabled === true;
byId('agent-settings-secret-help').textContent = agent?.secret_configured ? '已配置密钥;留空保存不会覆盖。密钥永不回显。' : '尚未配置密钥;首次保存必须填写。';
byId('agent-settings-save').disabled = !canManage || !agent || state.busy;
byId('agent-settings-test').disabled = !canManage || !agent?.enabled || !agent?.secret_configured || state.busy;
renderHealth(agent || {});
}
async function load() {
notice('正在读取 Agent API 配置…');
const session = await api('/api/v1/session');
if (!session.admin) throw new Error('需要管理员权限。');
state.csrf = session.csrf_token || state.csrf;
if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
const payload = await api('/api/v1/admin/agents');
state.agents = Array.isArray(payload.agents) ? payload.agents : [];
if (!selectedAgent() && state.agents.length) state.selected = String(state.agents[0].host_id);
renderList(); fill(selectedAgent());
notice(canManage ? '请选择计算节点配置 Agent API。' : '当前管理员仅可查看 Agent API 配置与状态。');
}
async function save(event) {
event.preventDefault(); if (!canManage || state.busy) return;
const hostId = byId('agent-settings-host-id').value; if (!hostId) return;
const body = {
enabled: byId('agent-settings-enabled').checked,
api_secret: byId('agent-settings-secret').value,
expected_revision: Number(byId('agent-settings-revision').value),
};
if (!Number.isSafeInteger(body.expected_revision) || body.expected_revision < 0) return notice('配置版本无效,请刷新页面。', true);
if (body.api_secret && (body.api_secret.length < 32 || body.api_secret.length > 256 || /\s/.test(body.api_secret))) return notice('API 密钥需为 32 至 256 位无空格字符。', true);
state.busy = true; fill(selectedAgent()); notice('正在保存 Agent API 配置…');
try {
const saved = await api(`/api/v1/admin/agents/${encodeURIComponent(hostId)}`, { method: 'PUT', body });
const index = state.agents.findIndex(agent => String(agent.host_id) === String(hostId));
if (index >= 0) state.agents[index] = saved;
byId('agent-settings-secret').value = ''; renderList(); fill(saved);
notice(saved.enabled
? 'Agent API 配置已加密保存;请测试当前版本,通过前不参与调度。'
: 'Agent API 配置已加密保存,当前为停用状态。');
} catch (error) { notice(error.message, true); }
finally { state.busy = false; fill(selectedAgent()); }
}
async function testConnection() {
if (!canManage || state.busy) return;
const agent = selectedAgent(); if (!agent) return;
state.busy = true; fill(agent); notice('正在通过上行 WSS 验证 Agent 连接…');
try {
const tested = await api(`/api/v1/admin/agents/${encodeURIComponent(agent.host_id)}/test`, { method: 'POST', body: { expected_revision: agent.revision } });
const index = state.agents.findIndex(item => item.host_id === agent.host_id); if (index >= 0) state.agents[index] = tested;
renderList(); fill(tested);
const capabilityCount = Number(tested.capabilities?.required_feature_count || 0);
const firmware = tested.capabilities?.uefi === true && tested.capabilities?.secure_boot === false
? ',UEFI 已启用且安全启动已关闭' : '';
notice(`Agent 连接正常,当前配置版本已就绪${tested.health?.version ? `,Agent 版本 ${tested.health.version}` : ''}${capabilityCount > 0 ? `,${capabilityCount} 项必要能力已验证` : ''}${firmware}。`);
} catch (error) {
try { const refreshed = await api(`/api/v1/admin/agents/${encodeURIComponent(agent.host_id)}`); const index = state.agents.findIndex(item => item.host_id === agent.host_id); if (index >= 0) state.agents[index] = refreshed; fill(refreshed); } catch {}
notice(error.message, true);
} finally { state.busy = false; fill(selectedAgent()); }
}
if (root) {
byId('agent-settings-form').addEventListener('submit', save);
byId('agent-settings-test').addEventListener('click', testConnection);
void load().catch(error => notice(error.message, true));
}