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.
313 lines
19 KiB
JavaScript
313 lines
19 KiB
JavaScript
const root = document.querySelector('[data-admin-host-inventory]');
|
|
const byId = id => document.getElementById(id);
|
|
const filterNames = ['host_id', 'outcome', 'per_page'];
|
|
const columns = ['宿主机 / 来源', '开始 / 结束', '耗时 / 预算', '面板结果', '阶段 / 错误码', '容量生效', '操作'];
|
|
const stageLabels = {
|
|
request: '引擎接收请求', registry_profile: '解析宿主机配置',
|
|
update_lock_wait: '等待全局锁', update_check: '检查在线更新状态',
|
|
iso_gc: '清理 ISO 待删除资源', template_gc: '清理镜像待删除资源',
|
|
profile: '装载宿主机凭据', libvirt_connect: '连接 libvirt', host_info: '读取宿主机资源',
|
|
domain_list: '枚举虚拟机', domain_scan: '扫描虚拟机', storage_scan: '读取存储池',
|
|
public_pool_catalog: '读取公网池目录', public_ip_claims: '读取公网 IP 占用',
|
|
public_ip_scan: '盘点公网 IP', response: '返回响应',
|
|
};
|
|
const traceStates = { running: '进行中', succeeded: '采集成功', failed: '失败', interrupted: '中断 / 未知' };
|
|
const state = { page: null, url: null, request: null, loading: false,
|
|
detailId: null, detailRequest: null, engineRequest: null, closing: false, scroll: null, opener: null };
|
|
|
|
function el(tag, className = '', value) {
|
|
const node = document.createElement(tag); node.className = className;
|
|
if (value !== undefined) node.textContent = String(value);
|
|
return node;
|
|
}
|
|
function text(value, fallback = '未记录') {
|
|
return value === null || value === undefined || String(value).trim() === '' ? fallback : String(value);
|
|
}
|
|
function date(value) {
|
|
if (!value || !Number.isFinite(Number(value))) return '尚未记录';
|
|
const parsed = new Date(Number(value) * 1000);
|
|
if (!Number.isFinite(parsed.getTime())) return '时间无效';
|
|
// Match the server-rendered rows even when the administrator's browser uses
|
|
// another time zone. Elapsed durations still come from each process's clock.
|
|
return parsed.toLocaleString('zh-CN', { hour12: false, timeZone: root?.dataset.timezone || 'UTC' });
|
|
}
|
|
function duration(value) {
|
|
return value === null || value === undefined || !Number.isFinite(Number(value)) ? '未确认' : `${Number(value).toLocaleString('zh-CN')} ms`;
|
|
}
|
|
function applied(attempt) {
|
|
if (attempt.applied === true) return '容量已更新';
|
|
if (attempt.outcome === 'superseded') return '结果已被取代';
|
|
if (attempt.outcome === 'interrupted') return '是否生效待核对';
|
|
return attempt.outcome === 'running' ? '尚未确认' : '容量未更新';
|
|
}
|
|
function stack(primary, ...secondary) {
|
|
const node = el('span', 'admin-checkout-user');
|
|
node.append(primary instanceof Node ? primary : el('strong', '', primary));
|
|
for (const value of secondary.filter(Boolean)) node.append(value instanceof Node ? value : el('span', '', value));
|
|
return node;
|
|
}
|
|
function infoList(entries) {
|
|
const list = el('dl', 'admin-instance-details');
|
|
for (const [label, value] of entries) list.append(el('dt', '', label), el('dd', 'text-break', text(value)));
|
|
return list;
|
|
}
|
|
function notice(message, error = false) {
|
|
const node = byId('inventory-notice'); node.textContent = message;
|
|
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'} mb-3`;
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
}
|
|
function detailNotice(message, error = false) {
|
|
const node = byId('inventory-detail-state'); node.textContent = message; node.hidden = !message;
|
|
node.className = `alert alert-${error ? 'danger' : 'info'}`;
|
|
node.setAttribute('role', error ? 'alert' : 'status');
|
|
}
|
|
async function api(path, controller, timeoutMs = 15000) {
|
|
const timer = setTimeout(() => controller.abort('timeout'), timeoutMs);
|
|
try {
|
|
const response = await fetch(path, { headers: { Accept: 'application/json' },
|
|
credentials: 'same-origin', cache: 'no-store', signal: controller.signal });
|
|
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
|
|
if (response.status === 403) throw new Error('当前账号没有查看权限。');
|
|
let payload;
|
|
try { payload = await response.json(); } catch { throw new Error('服务器响应格式无效,请稍后重试。'); }
|
|
if (!response.ok) throw new Error(typeof payload?.detail === 'string' ? payload.detail : '诊断记录暂不可读取,请稍后重试。');
|
|
return payload;
|
|
} catch (error) {
|
|
if (controller.signal.reason === 'timeout') throw new Error('读取诊断超时;未触发新的盘点。');
|
|
throw error;
|
|
} finally { clearTimeout(timer); }
|
|
}
|
|
function listUrl(input = new URL(location.href)) {
|
|
const url = new URL('/admin/host-inventory', location.origin);
|
|
for (const key of [...filterNames, 'page']) {
|
|
const value = input.searchParams.get(key);
|
|
if (value) url.searchParams.set(key, value);
|
|
}
|
|
return url;
|
|
}
|
|
function readForm(url) {
|
|
const form = byId('inventory-filter');
|
|
for (const key of filterNames) {
|
|
const control = form.elements.namedItem(key);
|
|
const value = url.searchParams.get(key) || ({ outcome: 'all', per_page: '20' })[key] || '';
|
|
if (value && !Array.from(control.options).some(option => option.value === value)) control.add(new Option(value, value));
|
|
control.value = value;
|
|
}
|
|
}
|
|
function formUrl() {
|
|
const url = new URL('/admin/host-inventory', location.origin);
|
|
for (const key of filterNames) {
|
|
const value = byId('inventory-filter').elements.namedItem(key).value;
|
|
if (value) url.searchParams.set(key, value);
|
|
}
|
|
return url;
|
|
}
|
|
function pagination() {
|
|
const page = state.page?.pagination;
|
|
byId('inventory-count').textContent = page ? `共 ${page.total} 条` : '数据未获取';
|
|
byId('inventory-pagination').hidden = !page?.total;
|
|
byId('inventory-page-label').textContent = page ? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 条` : '记录暂不可用';
|
|
byId('inventory-previous').disabled = state.loading || !page || page.page <= 1;
|
|
byId('inventory-next').disabled = state.loading || !page || page.page >= page.total_pages;
|
|
byId('inventory-refresh').disabled = state.loading;
|
|
byId('inventory-body').setAttribute('aria-busy', String(state.loading));
|
|
}
|
|
function renderRows() {
|
|
const body = byId('inventory-body'); body.replaceChildren();
|
|
for (const attempt of state.page.items) {
|
|
const row = el('tr'); const button = el('button', 'btn btn-primary btn-sm', '查看详情');
|
|
button.type = 'button'; button.dataset.inventoryDetail = String(attempt.attempt_id);
|
|
const statusClass = attempt.outcome === 'succeeded' ? 'text-success'
|
|
: (['failed', 'timeout'].includes(attempt.outcome) ? 'text-danger' : (attempt.outcome === 'interrupted' ? 'text-warning' : ''));
|
|
const cells = [
|
|
stack(`${text(attempt.host_name, '宿主机已移除')} · #${attempt.host_id}`, attempt.source_label),
|
|
stack(date(attempt.started_at), attempt.finished_at ? date(attempt.finished_at) : (attempt.outcome === 'running' ? '尚未结束' : '结束时间未确认')),
|
|
stack(`${attempt.duration_is_final === false ? '已记录 ' : ''}${duration(attempt.duration_ms)}`, `每请求 ${duration(attempt.timeout_ms)}`),
|
|
stack(el('strong', statusClass, text(attempt.outcome_label)), attempt.error_message ? el('span', 'text-danger', attempt.error_message) : ''),
|
|
stack(text(attempt.stage_label, '阶段未确认'), text(attempt.error_code, '未记录错误码')),
|
|
applied(attempt), button,
|
|
];
|
|
cells.forEach((value, index) => {
|
|
const cell = el('td'); cell.dataset.label = columns[index];
|
|
cell.append(value instanceof Node ? value : el('span', '', value)); row.append(cell);
|
|
});
|
|
body.append(row);
|
|
}
|
|
if (!state.page.items.length) {
|
|
const row = el('tr'); const cell = el('td', 'text-center text-muted py-4', '没有符合条件的记录;新功能只记录启用后的盘点尝试。');
|
|
cell.colSpan = columns.length; row.append(cell); body.append(row);
|
|
}
|
|
}
|
|
function applyPage(page, replaceRows = true) {
|
|
if (!Array.isArray(page?.items) || !page.pagination || !page.filters || !page.summary) throw new Error('盘点记录格式无效,请重试。');
|
|
state.page = page;
|
|
const url = new URL('/admin/host-inventory', location.origin);
|
|
for (const key of [...filterNames, 'page']) {
|
|
const value = ['page', 'per_page'].includes(key) ? page.pagination[key] : page.filters[key];
|
|
if (value !== null && value !== undefined && value !== '') url.searchParams.set(key, String(value));
|
|
}
|
|
state.url = url;
|
|
const host = byId('inventory-host'); host.replaceChildren(new Option('全部宿主机', ''));
|
|
for (const item of page.hosts || []) host.add(new Option(`${item.name} · #${item.id}`, item.id));
|
|
readForm(url);
|
|
for (const key of ['last_attempt_at', 'last_success_at', 'last_failure_at']) byId(`inventory-summary-${key}`).textContent = date(page.summary[key]);
|
|
byId('inventory-summary-state').textContent = `记录中的进行中:${page.summary.in_progress} 次。`
|
|
+ (page.filters.host_id ? `该宿主机连续失败:${page.summary.consecutive_failures} 次。` : '选择宿主机可查看连续失败次数。');
|
|
if (replaceRows) renderRows();
|
|
pagination();
|
|
}
|
|
async function loadPage(url, historyMode = 'push') {
|
|
state.request?.abort(); const controller = new AbortController(); state.request = controller;
|
|
state.loading = true; pagination(); notice('正在读取数据库记录…');
|
|
try {
|
|
const payload = await api(`/api/v1/admin/host-inventory${url.search}`, controller);
|
|
if (controller.signal.aborted || state.request !== controller) return;
|
|
applyPage(payload);
|
|
if (historyMode === 'push') history.pushState(history.state, '', state.url);
|
|
notice(`已读取 ${payload.pagination.total} 条盘点记录;未执行宿主机扫描。`);
|
|
} catch (error) {
|
|
if (state.request !== controller || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
notice(`${error.message}${state.page ? ' 下方保留上次成功读取的记录。' : ''}`, true);
|
|
} finally {
|
|
if (state.request === controller) { state.request = null; state.loading = false; pagination(); }
|
|
}
|
|
}
|
|
function renderStages(stages, engine = false) {
|
|
const list = el('ul', 'list-unstyled mb-0');
|
|
for (const item of (Array.isArray(stages) ? stages : [])) {
|
|
const label = engine ? (stageLabels[item.stage] || text(item.stage, '阶段未确认')) : text(item.label, item.stage);
|
|
const status = engine ? ` · ${traceStates[item.state] || text(item.state)}` : '';
|
|
list.append(el('li', 'text-break py-1', `${label}${status} · ${duration(item.duration_ms)}`));
|
|
}
|
|
if (!list.children.length) list.append(el('li', 'text-muted', '未记录阶段耗时。'));
|
|
return list;
|
|
}
|
|
function renderDetail(payload) {
|
|
const attempt = payload?.attempt;
|
|
if (!attempt || String(attempt.attempt_id) !== state.detailId) throw new Error('记录与请求不一致,请重新打开。');
|
|
byId('inventory-detail-title').textContent = `${text(attempt.host_name, '宿主机已移除')} · ${text(attempt.outcome_label)}`;
|
|
const body = byId('inventory-detail-body');
|
|
body.replaceChildren(el('h3', 'h6', '面板同步结果'), infoList([
|
|
['尝试编号', attempt.attempt_id], ['宿主机', `${text(attempt.host_name)} · #${attempt.host_id}`],
|
|
['来源', attempt.source_label], ['面板结果', attempt.outcome_label], ['容量是否生效', applied(attempt)],
|
|
['开始时间', date(attempt.started_at)], ['结束时间', attempt.finished_at ? date(attempt.finished_at) : '尚未确认'],
|
|
[attempt.duration_is_final === false ? '已记录耗时(非最终)' : '总耗时', duration(attempt.duration_ms)], ['每个引擎请求预算', duration(attempt.timeout_ms)],
|
|
['面板记录阶段', attempt.stage_label], ['错误码', attempt.error_code],
|
|
['脱敏说明', text(attempt.error_message, '未记录错误')], ['引擎 HTTP 状态', attempt.http_status],
|
|
['面板诊断版本', attempt.panel_version], ['PHP 版本', attempt.php_version], ['同步代际', attempt.generation],
|
|
]), el('h3', 'h6 mt-4', 'PHP 阶段耗时'), renderStages(attempt.stages));
|
|
for (const note of payload.notes || []) body.append(el('p', 'text-muted fs-13 mt-3 mb-0', note));
|
|
byId('inventory-engine').hidden = false;
|
|
byId('inventory-engine-refresh').disabled = false;
|
|
}
|
|
function renderEvidence(payload) {
|
|
if (!payload || payload.attempt_id !== state.detailId || !Array.isArray(payload.traces)) throw new Error('引擎线索与请求不一致。');
|
|
const box = byId('inventory-engine-body'); box.replaceChildren();
|
|
byId('inventory-engine-state').textContent = text(payload.message,
|
|
payload.available ? '已读取引擎记录;不改变面板同步结果。' : '无法取得引擎线索,内部阶段尚未确认。');
|
|
if (!payload.available) {
|
|
if (payload.error_code) box.append(el('p', 'text-muted text-break', `诊断查询错误码:${payload.error_code}`));
|
|
return;
|
|
}
|
|
if (!payload.traces.length) { box.append(el('p', 'text-muted', '没有对应引擎记录:可能尚未接收、未启用记录或已过保留期;不能据此认定宿主机故障。')); return; }
|
|
for (const trace of payload.traces) {
|
|
const section = el('section', 'border-top pt-3 mt-3');
|
|
section.append(el('h4', 'h6', ({ capacity: '容量请求', network: '公网网络请求' })[trace.resource] || '引擎请求'), infoList([
|
|
['引擎结果(独立)', traceStates[trace.state] || text(trace.state)],
|
|
['最后确认阶段', stageLabels[trace.stage] || text(trace.stage, '尚未确认')],
|
|
['引擎开始时间', date(trace.started_at)], ['引擎结束时间', trace.finished_at ? date(trace.finished_at) : '尚未确认'],
|
|
['引擎耗时', duration(trace.duration_ms)], ['引擎 HTTP 状态', trace.http_status],
|
|
['引擎错误码', trace.error_code], ['引擎运行版本', trace.engine_version],
|
|
]), renderStages(trace.stages, true));
|
|
box.append(section);
|
|
}
|
|
box.append(el('p', 'text-muted fs-13 mt-3', '各进程独立计时,不能直接相减面板与引擎的时间。引擎父阶段包含子阶段耗时,不能相加计算总时长。只有阶段开始记录时,不能将该阶段直接认定为故障根因。'));
|
|
}
|
|
async function readEvidence() {
|
|
if (!state.detailId || state.engineRequest || state.closing) return;
|
|
const id = state.detailId; const controller = new AbortController(); state.engineRequest = controller;
|
|
byId('inventory-engine-refresh').disabled = true;
|
|
byId('inventory-engine-state').textContent = '正在读取引擎已有记录,不会扫描宿主机…';
|
|
byId('inventory-engine-body').replaceChildren();
|
|
try {
|
|
const payload = await api(`/api/v1/admin/host-inventory/${id}/engine`, controller, 5000);
|
|
if (controller.signal.aborted || state.detailId !== id || state.engineRequest !== controller) return;
|
|
renderEvidence(payload);
|
|
} catch (error) {
|
|
if (state.detailId !== id || state.engineRequest !== controller || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
byId('inventory-engine-state').textContent = `${error.message} 引擎内部阶段尚未确认。`;
|
|
} finally {
|
|
if (state.engineRequest === controller) { state.engineRequest = null; byId('inventory-engine-refresh').disabled = false; }
|
|
}
|
|
}
|
|
async function openDetail(id, opener) {
|
|
if (!/^[0-9a-f]{32}$/.test(id) || state.closing) return;
|
|
state.detailRequest?.abort(); state.engineRequest?.abort(); state.engineRequest = null;
|
|
state.detailId = id; state.opener = opener;
|
|
const controller = new AbortController(); state.detailRequest = controller;
|
|
byId('inventory-detail-title').textContent = '盘点诊断'; byId('inventory-detail-body').replaceChildren();
|
|
byId('inventory-engine').hidden = true; byId('inventory-engine-body').replaceChildren();
|
|
byId('inventory-engine-state').textContent = '尚未查询。仅读取已存在的线索,不会发起盘点。';
|
|
detailNotice('正在读取数据库记录…');
|
|
if (!byId('inventory-detail').open) {
|
|
state.scroll = { x: window.scrollX, y: window.scrollY };
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
window.VenixDrawerMotion.openDrawerWithMotion(byId('inventory-detail'));
|
|
}
|
|
try {
|
|
const payload = await api(`/api/v1/admin/host-inventory/${id}`, controller);
|
|
if (controller.signal.aborted || state.detailId !== id || state.detailRequest !== controller) return;
|
|
renderDetail(payload); detailNotice('');
|
|
} catch (error) {
|
|
if (state.detailRequest !== controller || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
detailNotice(`${error.message} 请关闭后重试。`, true);
|
|
} finally { if (state.detailRequest === controller) state.detailRequest = null; }
|
|
}
|
|
function closeDetail() {
|
|
if (state.closing || !byId('inventory-detail').open) return;
|
|
state.detailRequest?.abort(); state.engineRequest?.abort();
|
|
state.detailRequest = null; state.engineRequest = null; state.detailId = null; state.closing = true;
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(byId('inventory-detail')).then(closed => {
|
|
state.closing = false; if (!closed) return;
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
if (state.scroll) window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
|
|
state.scroll = null; if (state.opener?.isConnected) state.opener.focus({ preventScroll: true }); state.opener = null;
|
|
});
|
|
}
|
|
|
|
if (root) {
|
|
try {
|
|
const payload = JSON.parse(byId('admin-inventory-bootstrap').textContent);
|
|
if (payload) applyPage(payload, false); else readForm(listUrl());
|
|
} catch { notice('首屏诊断记录无效,请点击刷新记录重试。', true); readForm(listUrl()); }
|
|
byId('inventory-filter').addEventListener('submit', event => { event.preventDefault(); void loadPage(formUrl()); });
|
|
byId('inventory-reset').addEventListener('click', event => {
|
|
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey) return;
|
|
event.preventDefault(); void loadPage(new URL('/admin/host-inventory', location.origin));
|
|
});
|
|
byId('inventory-refresh').addEventListener('click', () => { void loadPage(listUrl(), 'none'); });
|
|
for (const [id, delta] of [['inventory-previous', -1], ['inventory-next', 1]]) byId(id).addEventListener('click', () => {
|
|
if (!state.page || state.loading) return;
|
|
const url = new URL(state.url); url.searchParams.set('page', state.page.pagination.page + delta); void loadPage(url);
|
|
});
|
|
root.addEventListener('click', event => {
|
|
const button = event.target.closest('[data-inventory-detail]');
|
|
if (button) void openDetail(button.dataset.inventoryDetail, button);
|
|
});
|
|
byId('inventory-detail-close').addEventListener('click', closeDetail);
|
|
byId('inventory-engine-refresh').addEventListener('click', () => { void readEvidence(); });
|
|
const dialog = byId('inventory-detail');
|
|
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
|
|
dialog.addEventListener('click', event => {
|
|
if (event.target !== dialog) return;
|
|
const rect = dialog.getBoundingClientRect();
|
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
|
|
});
|
|
window.addEventListener('popstate', () => { closeDetail(); readForm(listUrl()); void loadPage(listUrl(), 'none'); });
|
|
window.addEventListener('pagehide', () => { state.request?.abort(); state.detailRequest?.abort(); state.engineRequest?.abort(); closeDetail(); });
|
|
pagination();
|
|
// Intentionally no initial fetch, timer, visibility refresh or automatic engine query.
|
|
}
|