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/admin-system-logs.js

416 lines
22 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-admin-system-logs]');
const config = window.__VENIX_SYSTEM_LOGS__ || {apiUrl: '/api/v1/admin/system-logs', timezone: 'UTC'};
const byId = id => document.getElementById(id);
const LIST_TIMEOUT_MS = 15000;
const DETAIL_TIMEOUT_MS = 8000;
const state = {
page: null,
request: null,
cursor: null,
loading: false,
detailRequest: null,
detailSerial: 0,
detailOpener: null,
detailScroll: null,
detailClosing: false,
};
const priorityLabels = {0: '紧急', 1: '警报', 2: '严重', 3: '错误', 4: '警告', 5: '通知', 6: '信息', 7: '调试'};
function text(value, fallback = '未记录') {
return value === null || value === undefined || String(value).trim() === '' ? fallback : String(value);
}
function timestamp(value) {
if (value === null || value === undefined || value === '') return null;
const numeric = Number(value);
const date = Number.isFinite(numeric)
? new Date(numeric < 100000000000 ? numeric * 1000 : numeric)
: new Date(String(value));
return Number.isFinite(date.getTime()) ? date : null;
}
function date(value) {
const parsed = timestamp(value);
if (!parsed) return '时间未记录';
return parsed.toLocaleString('zh-CN', {hour12: false, timeZone: root?.dataset.timezone || config.timezone || 'UTC'});
}
function level(item) {
const raw = item.level ?? item.priority_label ?? item.priority ?? item.PRIORITY;
if (typeof raw === 'number' || /^\d+$/.test(String(raw))) return priorityLabels[Number(raw)] || `级别 ${raw}`;
const value = text(raw, 'info').toLowerCase();
return ({emerg: '紧急', alert: '警报', crit: '严重', critical: '严重', err: '错误', error: '错误', warning: '警告', warn: '警告', notice: '通知', info: '信息', debug: '调试'})[value] || text(raw, '信息');
}
function levelClass(item) {
const raw = String(item.priority ?? item.PRIORITY ?? item.level ?? item.priority_label ?? '').toLowerCase();
if (['0', '1', '2', '3', 'emerg', 'alert', 'crit', 'critical', 'err', 'error'].includes(raw)) return 'text-danger';
if (['4', 'warning', 'warn'].includes(raw)) return 'text-warning';
return 'text-muted';
}
function normalizeItem(item) {
const source = item && typeof item === 'object' ? item : {};
return {
timestamp: source.timestamp ?? source.time ?? source.at ?? source.__REALTIME_TIMESTAMP ?? source._SOURCE_REALTIME_TIMESTAMP ?? source.realtime_timestamp,
unit: source.unit ?? source.service ?? source.source ?? source._SYSTEMD_UNIT ?? source.syslog_identifier ?? '系统',
priority: source.priority ?? source.PRIORITY ?? source.level,
level: source.level ?? source.priority_label ?? source.priority ?? source.PRIORITY,
message: source.message ?? source.MESSAGE ?? source.msg ?? source.text ?? '',
pid: source.pid ?? source._PID ?? '',
process: source.process ?? source._COMM ?? source.syslog_identifier ?? '',
hostname: source.hostname ?? source._HOSTNAME ?? '',
cursor: source.cursor ?? source.__CURSOR ?? null,
message_truncated: Boolean(source.message_truncated),
message_redacted: Boolean(source.message_redacted),
};
}
function normalizePayload(payload) {
const candidate = payload && payload.data && typeof payload.data === 'object' ? payload.data : payload;
if (!candidate || typeof candidate !== 'object') throw new Error('日志响应格式无效,请稍后重试。');
const rawItems = Array.isArray(candidate.items) ? candidate.items : (Array.isArray(candidate.rows) ? candidate.rows : []);
const items = rawItems.map(normalizeItem);
const summary = candidate.summary && typeof candidate.summary === 'object' ? candidate.summary : {};
return {
items,
units: Array.isArray(candidate.units) ? candidate.units.map(String) : [],
summary: {
total: Number(summary.total ?? candidate.total ?? items.length) || 0,
error_count: Number(summary.error_count ?? summary.errors ?? candidate.error_count ?? 0) || 0,
warning_count: Number(summary.warning_count ?? summary.warnings ?? candidate.warning_count ?? 0) || 0,
latest_at: summary.latest_at ?? (items[0]?.timestamp ?? null),
},
filters: candidate.filters || {},
pagination: {
...(candidate.pagination || {}),
next_cursor: candidate.pagination?.next_cursor ?? candidate.pagination?.nextCursor ?? candidate.next_cursor ?? null,
has_more: Boolean(candidate.pagination?.has_more ?? candidate.pagination?.hasMore ?? candidate.has_more ?? false),
},
};
}
function notice(message, error = false) {
const node = byId('system-logs-notice');
if (!node) return;
node.textContent = message;
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
function filterForm() { return byId('system-logs-filter'); }
function queryUrl(cursor = null) {
const url = new URL(config.apiUrl, window.location.origin);
const form = filterForm();
['unit', 'priority', 'query', 'since', 'until', 'limit'].forEach(name => {
const value = form?.elements.namedItem(name)?.value?.trim();
if (value) url.searchParams.set(name, value);
});
if (cursor) url.searchParams.set('cursor', cursor);
return url;
}
function setBusy(value) {
state.loading = value;
byId('system-logs-refresh').disabled = value;
byId('system-logs-older').disabled = value || !state.page?.pagination?.has_more;
byId('system-logs-newer').disabled = value;
const submit = filterForm()?.querySelector('button[type="submit"]');
if (submit) submit.disabled = value;
const cancel = byId('system-logs-cancel');
if (cancel) { cancel.hidden = !value; cancel.disabled = !value; }
byId('system-logs-body').setAttribute('aria-busy', String(value));
}
function renderSummary(page) {
byId('system-logs-total').textContent = page.summary.total.toLocaleString('zh-CN');
byId('system-logs-errors').textContent = page.summary.error_count.toLocaleString('zh-CN');
byId('system-logs-warnings').textContent = page.summary.warning_count.toLocaleString('zh-CN');
byId('system-logs-latest').textContent = page.summary.latest_at ? date(page.summary.latest_at) : '尚无记录';
byId('system-logs-count').textContent = `共 ${page.summary.total.toLocaleString('zh-CN')} 条`;
byId('system-logs-page-label').textContent = page.pagination.has_more ? '当前窗口 · 可继续加载' : '当前窗口 · 已到末尾';
}
function renderUnits(page) {
const select = byId('system-logs-unit');
if (!select || !Array.isArray(page.units) || !page.units.length) return;
const selected = select.value;
const values = [...new Set(page.units.map(String).filter(Boolean))].sort();
select.replaceChildren(new Option('全部服务', ''));
values.forEach(unit => select.add(new Option(unit, unit)));
if (values.includes(selected)) select.value = selected;
}
function renderRows(page) {
const body = byId('system-logs-body');
body.replaceChildren();
if (!page.items.length) {
const row = document.createElement('tr');
const cell = document.createElement('td'); cell.colSpan = 4; cell.className = 'text-center text-muted py-4'; cell.textContent = '没有符合条件的日志';
row.append(cell); body.append(row); return;
}
page.items.forEach(item => {
const row = document.createElement('tr'); row.tabIndex = 0; row.setAttribute('role', 'button'); row.className = 'system-logs-row';
row.setAttribute('aria-controls', 'system-logs-detail'); row.setAttribute('aria-haspopup', 'dialog');
row.setAttribute('aria-label', `查看 ${text(item.unit, '系统')} 日志详情`);
const values = [date(item.timestamp), text(item.unit, '系统'), level(item), text(item.message, '消息未记录')];
values.forEach((value, index) => {
const cell = document.createElement('td'); cell.dataset.label = ['时间', '服务', '级别', '消息'][index];
if (index === 2) { const badge = document.createElement('span'); badge.className = `system-logs-level ${levelClass(item)}`; badge.textContent = value; cell.append(badge); }
else if (index === 3) { const message = document.createElement('span'); message.className = 'system-logs-message'; message.textContent = value; cell.append(message); }
else cell.textContent = value;
row.append(cell);
});
const open = () => openDetail(item, row);
row.addEventListener('click', open);
row.addEventListener('keydown', event => { if (event.key === 'Enter' || event.key === ' ' || event.key === 'Spacebar') { event.preventDefault(); open(); } });
body.append(row);
});
}
function render(page) {
renderUnits(page); renderSummary(page); renderRows(page);
byId('system-logs-older').disabled = state.loading || !page.pagination.has_more;
}
function invalidateDetail() {
state.detailSerial += 1;
state.detailRequest?.abort('replaced'); state.detailRequest = null;
}
function openDetailDrawer(dialog, opener) {
if (!dialog) return false;
state.detailOpener = opener || state.detailOpener;
if (!dialog.open) {
state.detailScroll = {x: window.scrollX || 0, y: window.scrollY || 0};
document.body?.style?.setProperty('--admin-instance-scroll-top', `${-state.detailScroll.y}px`);
document.documentElement?.classList?.add('admin-instance-detail-open');
}
const motion = window.VenixDrawerMotion?.openDrawerWithMotion;
if (typeof motion === 'function') {
try {
if (motion(dialog) !== false) return true;
} catch (error) {
// Fall back to the native dialog API if the shared optional asset is unavailable.
}
}
if (!dialog.open) {
if (typeof dialog.showModal === 'function') dialog.showModal();
else dialog.setAttribute('open', 'open');
}
dialog.classList?.add('is-drawer-visible');
return true;
}
function finishDetailClose(closed) {
state.detailClosing = false;
if (!closed) return;
document.documentElement?.classList?.remove('admin-instance-detail-open');
document.body?.style?.removeProperty('--admin-instance-scroll-top');
if (state.detailScroll && typeof window.scrollTo === 'function') {
window.scrollTo({left: state.detailScroll.x, top: state.detailScroll.y, behavior: 'auto'});
}
state.detailScroll = null;
const opener = state.detailOpener;
state.detailOpener = null;
if (opener?.isConnected && typeof opener.focus === 'function') opener.focus({preventScroll: true});
}
async function load(cursor = null, replace = true) {
closeDetail();
state.request?.abort();
const controller = new AbortController();
let timedOut = false;
const timer = window.setTimeout(() => { timedOut = true; controller.abort('timeout'); }, LIST_TIMEOUT_MS);
state.request = controller; setBusy(true);
notice('正在读取 journal 日志…');
try {
const response = await fetch(queryUrl(cursor), {headers: {Accept: 'application/json'}, credentials: 'same-origin', cache: 'no-store', signal: controller.signal});
if (state.request !== controller || controller.signal.aborted) return;
let payload; try { payload = await response.json(); } catch { throw new Error('服务器响应格式无效,请稍后重试。'); }
if (state.request !== controller || controller.signal.aborted) return;
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
if (response.status === 403) throw new Error('当前账号没有读取系统日志的权限。');
if (!response.ok) throw new Error(typeof payload?.detail === 'string' ? payload.detail : '系统日志暂不可读取,请稍后重试。');
const page = normalizePayload(payload);
if (replace || !state.page) state.page = page;
else {
const items = [...state.page.items, ...page.items];
const errorCount = items.filter(item => Number(item.priority) <= 3).length;
const warningCount = items.filter(item => Number(item.priority) === 4).length;
state.page = {...page, items, summary: {...page.summary, total: items.length, error_count: errorCount, warning_count: warningCount, latest_at: state.page.summary.latest_at || page.summary.latest_at}};
}
state.cursor = page.pagination.next_cursor || null;
render(state.page);
notice(`已读取 ${state.page.items.length} 条日志;仅读取 journal,不会执行宿主机操作。`);
} catch (error) {
if (state.request !== controller) return;
if (controller.signal.aborted && !timedOut) {
notice('已停止读取系统日志。');
return;
}
notice(timedOut ? '读取系统日志超时,请缩小时间范围后重试。'
: (error.message || '系统日志暂不可读取,请稍后重试。'), true);
if (!state.page) { state.page = normalizePayload({items: [], summary: {}}); render(state.page); }
} finally {
window.clearTimeout(timer);
if (state.request === controller) { state.request = null; setBusy(false); }
}
}
function detailUrl(item) {
const url = new URL(`${config.apiUrl}/detail`, window.location.origin);
url.searchParams.set('cursor', item.cursor);
url.searchParams.set('unit', item.unit);
url.searchParams.set('timestamp', item.timestamp);
return url;
}
function normalizeDetail(payload) {
const source = payload?.item && typeof payload.item === 'object' ? payload.item : payload;
if (!source || typeof source !== 'object' || typeof source.cursor !== 'string') {
throw new Error('日志详情格式无效,请刷新列表后重试。');
}
return {...normalizeItem(source), monotonic_timestamp: source.monotonic_timestamp ?? '',
fields: source.fields && typeof source.fields === 'object' && !Array.isArray(source.fields) ? source.fields : {},
omitted_fields: Array.isArray(source.omitted_fields) ? source.omitted_fields.map(String) : [],
truncated_fields: Array.isArray(source.truncated_fields) ? source.truncated_fields.map(String) : [],
message_redacted: Boolean(source.message_redacted),
redacted_fields: Array.isArray(source.redacted_fields) ? source.redacted_fields.map(String) : []};
}
function renderDetail(item) {
const dialog = byId('system-logs-detail');
byId('system-logs-detail-title').textContent = `${text(item.unit, '系统')} · ${level(item)}`;
const meta = byId('system-logs-detail-meta'); meta.replaceChildren();
[['时间', date(item.timestamp)], ['单调时钟', text(item.monotonic_timestamp, '未记录')], ['服务', text(item.unit)], ['级别', level(item)], ['进程', text(item.process, '未记录')], ['PID', text(item.pid, '未记录')], ['宿主机', text(item.hostname, '未记录')], ['游标', text(item.cursor, '未记录')]].forEach(([label, value]) => {
const dt = document.createElement('dt'); dt.textContent = label; const dd = document.createElement('dd'); dd.className = 'text-break'; dd.textContent = value; meta.append(dt, dd);
});
const fields = byId('system-logs-detail-fields'); fields.replaceChildren();
Object.entries(item.fields).forEach(([name, value]) => {
const dt = document.createElement('dt'); dt.textContent = name;
const dd = document.createElement('dd'); dd.className = 'text-break'; dd.textContent = text(value, '');
fields.append(dt, dd);
});
const stateNode = byId('system-logs-detail-state');
const notices = [];
if (item.message_truncated) notices.push('消息已达到详情长度上限。');
if (item.message_redacted) notices.push('消息中的明显凭据已隐藏。');
const omittedFields = Array.isArray(item.omitted_fields) ? item.omitted_fields : [];
const truncatedFields = Array.isArray(item.truncated_fields) ? item.truncated_fields : [];
const redactedFields = Array.isArray(item.redacted_fields) ? item.redacted_fields : [];
if (omittedFields.length) notices.push(`已省略 ${omittedFields.length} 个敏感运行时字段。`);
if (truncatedFields.length) notices.push(`${truncatedFields.length} 个字段已截断。`);
if (redactedFields.length) notices.push(`${redactedFields.length} 个字段的明显凭据已隐藏。`);
stateNode.textContent = notices.join(' ');
stateNode.hidden = notices.length === 0;
stateNode.className = 'alert alert-warning mb-3';
byId('system-logs-detail-message').textContent = text(item.message, '消息未记录');
}
async function openDetail(item, opener = null) {
const dialog = byId('system-logs-detail');
if (state.detailClosing) return;
invalidateDetail();
const serial = state.detailSerial;
state.detailOpener = opener || state.detailOpener;
renderDetail({...item, fields: {}, omitted_fields: [], truncated_fields: [], redacted_fields: []});
byId('system-logs-detail-state').hidden = false;
byId('system-logs-detail-state').className = 'alert alert-info mb-3';
byId('system-logs-detail-state').textContent = '正在读取该日志的完整信息…';
openDetailDrawer(dialog, opener);
if (!item.cursor || !item.unit || !item.timestamp) {
byId('system-logs-detail-state').className = 'alert alert-warning mb-3';
byId('system-logs-detail-state').textContent = '该日志缺少精确定位信息,请刷新列表后重试。';
return;
}
const controller = new AbortController(); state.detailRequest = controller;
let timedOut = false;
const timer = window.setTimeout(() => { timedOut = true; controller.abort('timeout'); }, DETAIL_TIMEOUT_MS);
try {
const response = await fetch(detailUrl(item), {headers: {Accept: 'application/json'}, credentials: 'same-origin', cache: 'no-store', signal: controller.signal});
if (state.detailRequest !== controller || controller.signal.aborted || state.detailSerial !== serial) return;
let payload; try { payload = await response.json(); } catch { throw new Error('服务器响应格式无效,请稍后重试。'); }
if (state.detailRequest !== controller || controller.signal.aborted || state.detailSerial !== serial) return;
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
if (response.status === 403) throw new Error('当前账号没有查看系统日志的权限。');
if (response.status === 404) throw new Error('日志已轮转或不存在,请刷新列表后重试。');
if (!response.ok) throw new Error(typeof payload?.detail === 'string' ? payload.detail : '日志详情暂不可读取,请稍后重试。');
const detailItem = normalizeDetail(payload);
if (detailItem.cursor !== item.cursor) {
throw new Error('服务器返回的日志游标不匹配,请刷新列表后重试。');
}
renderDetail(detailItem);
} catch (error) {
if (state.detailRequest !== controller || state.detailSerial !== serial) return;
if (controller.signal.aborted && !timedOut) return;
const stateNode = byId('system-logs-detail-state');
stateNode.hidden = false; stateNode.className = 'alert alert-danger mb-3';
stateNode.textContent = timedOut ? '读取日志详情超时,请关闭后重试。' : (error.message || '日志详情暂不可读取,请稍后重试。');
} finally {
window.clearTimeout(timer);
if (state.detailRequest === controller) state.detailRequest = null;
}
}
function applyUrlToForm() {
const url = new URL(window.location.href); const form = filterForm();
['unit', 'priority', 'query', 'since', 'until', 'limit'].forEach(name => {
const control = form?.elements.namedItem(name); if (control && url.searchParams.has(name)) control.value = url.searchParams.get(name);
});
}
filterForm()?.addEventListener('submit', event => {
event.preventDefault(); if (state.loading) return; const url = new URL(window.location.href);
['unit', 'priority', 'query', 'since', 'until', 'limit'].forEach(name => { const value = filterForm().elements.namedItem(name)?.value?.trim(); if (value) url.searchParams.set(name, value); else url.searchParams.delete(name); });
history.pushState(history.state, '', url); state.page = null; state.cursor = null; load();
});
byId('system-logs-refresh')?.addEventListener('click', () => load());
byId('system-logs-newer')?.addEventListener('click', () => load());
byId('system-logs-older')?.addEventListener('click', () => { if (state.cursor) load(state.cursor, false); });
byId('system-logs-cancel')?.addEventListener('click', () => state.request?.abort('cancelled'));
function closeDetail() {
const dialog = byId('system-logs-detail');
invalidateDetail();
if (state.detailClosing) return;
if (!dialog?.open) {
finishDetailClose(true);
return;
}
state.detailClosing = true;
const motion = window.VenixDrawerMotion?.closeDrawerWithMotion;
if (typeof motion === 'function') {
try {
void Promise.resolve(motion(dialog))
.then(closed => finishDetailClose(closed !== false))
.catch(() => {
dialog.classList?.remove('is-drawer-visible');
if (typeof dialog.close === 'function') dialog.close();
else dialog.removeAttribute('open');
finishDetailClose(true);
});
return;
} catch (error) {
// Fall through to the native close path if the optional motion asset fails.
}
}
dialog.classList?.remove('is-drawer-visible');
if (typeof dialog.close === 'function') dialog.close();
else dialog.removeAttribute('open');
finishDetailClose(true);
}
byId('system-logs-detail-close')?.addEventListener('click', closeDetail);
byId('system-logs-detail')?.addEventListener('click', event => { if (event.target === byId('system-logs-detail')) closeDetail(); });
byId('system-logs-detail')?.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
window.addEventListener('pagehide', () => { state.request?.abort('pagehide'); invalidateDetail(); });
window.addEventListener('popstate', () => { applyUrlToForm(); state.page = null; state.cursor = null; load(); });
applyUrlToForm();
let hasBootstrap = false;
try {
const bootstrap = JSON.parse(document.getElementById('admin-system-logs-bootstrap')?.textContent || 'null');
if (bootstrap) { state.page = normalizePayload(bootstrap); state.cursor = state.page.pagination.next_cursor || null; render(state.page); hasBootstrap = true; }
} catch (error) { /* Fetch below will report the usable error. */ }
if (!hasBootstrap) load();