| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845 |
- // app.js — Main Workbench State & Console / Queue / BMC Synchronization
- (() => {
- const $ = id => document.getElementById(id);
- const escape = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
- function redact(value) {
- if (Array.isArray(value)) return value.map(redact);
- if (!value || typeof value !== 'object') return value;
- return Object.fromEntries(Object.entries(value).map(([key,item]) => [key,/^(password|token|api_token|secret)$/i.test(key) ? '已隐藏' : redact(item)]));
- }
- let stationId = 'S1', stationUserChosen = false, stations = [], polling = false, repollPending = false, selectionRevision = 0, connected = false;
- let sysInfoCache = null, sysInfoFetchedAt = 0, dirtyPollTimer = null;
- const logs = new Map(), pending = new Map(), diagnostics = new Map();
- let queueItems = [], queuePolling = false, eventPolling = false, auditItems = [], auditPolling = false;
- const eventViews = new Map(), bmcPending = new Map();
- const fanStateByStation = new Map(), fanQueryInFlight = new Set();
- let diagnosticError = '';
- const terminalStates = new Set(['succeeded', 'failed', 'interrupted']);
- const queueLabels = {queued:'排队', dispatching:'分派中', running:'执行', succeeded:'成功', failed:'失败', interrupted:'中断'};
- const operationLabels = {
- WriteSol:'发送控制台',
- WriteDiagnosticSol:'发送 BIOS 控制台',
- SetDiagnosticSol:'连接管理',
- StationPower:'主板电源',
- QueryBmc:'读取 BMC 信息',
- ConfigureConnections:'配置设备连接',
- ConfigurePxe:'配置 PXE',
- GetN540Config:'读取 N540 串口服务器',
- ConfigureN540:'配置 N540 纯净透传',
- SaveFirmwareSettings:'保存 ICT 配置',
- ApplyUipParameters:'下发 ICT 参数',
- ContinueUip:'ICT 发送 exit 继续',
- SkipAmt:'退出当前 AMT 菜单',
- ListUefiFiles:'读取 UEFI 目录',
- StartMt:'启动 MT 程序',
- SaveBootPlan:'保存启动计划',
- ControlBootPlan:'启动计划控制',
- SaveAmtSettings:'保存 AMT 配置',
- ApplyAmtSettings:'应用 AMT 配置',
- StartAmt:'提交 AMT 测试启动',
- ExecuteAmtCommand:'执行 AMT 菜单命令',
- SaveProfile:'保存测试 Profile',
- DeleteProfile:'删除测试 Profile',
- LoadProfileToWorkspace:'加载 Profile 到工作区',
- SubmitTaskBatch:'提交多计划测试队列',
- ControlTaskBatch:'控制多计划测试队列',
- ConfirmDimmReplacement:'确认更换异常内存条',
- SetStageIntent:'预设阶段控制状态',
- ApplyErrorPreset:'应用零加压拉偏预设',
- ClearTerminalView:'锚定清空控制台窗口',
- };
- const actionLabels = {
- open:'连接 BIOS 控制台',
- close:'断开 BIOS 控制台',
- reconnect:'重连 BIOS 控制台',
- host_on:'主板开机',
- host_off:'主板关机',
- host_reset:'主板复位',
- host_cycle:'主板关开循环',
- bmc_warm_reset:'BMC 热重启(恢复默认温控)',
- fan_low_speed_on:'开启风扇降速模式',
- fan_low_speed_off:'关闭风扇降速(恢复默认温控)',
- };
- const phases = [['boot', '启动'], ['uip', 'ICT 配置'], ['training', 'Training'], ['rmt', 'RMT 执行'], ['amt', 'AMT / AMEMDIAG'], ['post', 'POST / DXE / BDS'], ['uefi', 'UEFI'], ['mt', 'MT']];
- const phaseNames = new Map([...phases, ['amemdiag', 'AMEMDIAG控制台']]);
- const labels = {
- powered_off:'已断电', post:'POST / DXE / BDS', amemdiag:'AMEMDIAG 控制台',
- idle:'空闲', rmt:'RMT', amt:'AMT / AMEMDIAG测试', uefi_ready:'UEFI', mt:'MT',
- online:'在线', offline:'离线', on:'开', off:'关', unknown:'未知',
- pending:'待判定', pass:'通过', fail:'失败', failed:'失败', skipped:'跳过',
- completed:'已完成', stopped:'已停止', running:'运行中', connecting:'连接中',
- closed:'未连接', disabled:'未启用', enabled:'已启用', error:'连接异常',
- valid:'有效', unavailable:'无读数',
- };
- const label = value => labels[value] || value || '未知';
- const diag = () => diagnostics.get(stationId) || {};
- function transportLabel(snapshot = diag()) {
- const value = snapshot.transport || '';
- if (value === 'local_serial') return '物理串口 · /dev/ttyUSB0';
- if (value.startsWith('local_serial:')) return '物理串口 · ' + value.slice('local_serial:'.length);
- if (value === 'tcp_serial') return 'N540 TCP Server · ' + (snapshot.session_rx_bytes ? `RX ${snapshot.session_rx_bytes}B` : 'TCP 透传');
- if (value.startsWith('tcp_serial:')) return 'N540 TCP · ' + value.slice('tcp_serial:'.length);
- if (value.startsWith('tcp_serial_server:')) return 'N540 TCPC 监听 · ' + value.slice('tcp_serial_server:'.length);
- if (value === 'ipmi_sol' || value.startsWith('ipmi_sol:')) return 'IPMI SOL';
- if (value === 'ssh_console') return 'SSH BIOS 控制台';
- if (value.startsWith('ssh_console:')) return `SSH BIOS · ${value.slice('ssh_console:'.length)}`;
- return value || '等待链路信息';
- }
- function capabilities(s = current()) {
- return window.stlFirmware?.capabilities(s?.station_id) || {
- console: !!s?.bmc_address,
- bmc_power: !!s?.bmc_address,
- bmc_query: !!s?.bmc_address,
- };
- }
- function consoleContext() {
- const d = diag();
- return {
- kind: 'diagnostic',
- key: d.session_id ? `diag:${stationId}:${d.session_id}` : '',
- session_id: d.session_id || '',
- exists: !!d.session_id,
- writable: connected && (d.state === 'online' || !!current()?.console_online),
- };
- }
- function runLog(key) {
- if (!logs.has(key)) logs.set(key, {offset:0, text:'', decoder:new TextDecoder()});
- return logs.get(key);
- }
- function visibleLog() {
- const c = consoleContext();
- return c.key ? runLog(c.key) : null;
- }
- function terminalText(text) {
- return String(text || '')
- .replace(/\x1b\][^\x07]*(?:\x07|\x1b\\)/g, '')
- .replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
- .replace(/\x1b[()][A-Z0-9]/g, '')
- .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, '')
- .replace(/\r(?!\n)/g, '\n');
- }
- const stamp = () => new Date().toLocaleTimeString();
- const id = () => `web-${Date.now()}-${Math.random().toString(36).slice(2)}`;
- const current = () => stations.find(s => s.station_id === stationId);
- const decode = value => Uint8Array.from(atob(value || ''), c => c.charCodeAt(0));
- function encode(bytes) {
- let text = '';
- for (let i = 0; i < bytes.length; i += 8192) text += String.fromCharCode(...bytes.subarray(i, i + 8192));
- return btoa(text);
- }
- function status(text, error = false) {
- $('action-status').textContent = terminalText(text);
- $('action-status').classList.toggle('error', error);
- }
- function enable(button, allowed) {
- const el = $(button);
- if (el) el.disabled = !allowed || el.dataset.busy === '1';
- }
- function time(ms) { return Number(ms) > 0 ? new Date(Number(ms)).toLocaleString() : '未知'; }
- function formatElapsed(ms) {
- const n = Math.max(0, Math.floor(Number(ms || 0) / 1000));
- const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60;
- return [h, m, s].map(v => String(v).padStart(2, '0')).join(':');
- }
- function callApi(method, payload = {}, timeoutMs) {
- return window.stlTransport.call(method, payload, timeoutMs);
- }
- async function command(method, request, cmdLabel) {
- const commandStation = request.station_id || stationId;
- const args = {...request};
- delete args.station_id; delete args.command_id; delete args.operator;
- const commandId = id(), tracked = {label:cmdLabel, station:commandStation, state:'submitting', updated:0};
- pending.set(commandId, tracked);
- let result;
- try {
- result = await callApi('EnqueueCommand', {
- command_id: commandId,
- station_id: commandStation,
- method,
- arguments: args,
- operator: 'operator',
- });
- } catch (error) {
- if (tracked.result) result = tracked.result;
- else {
- if (['DISCONNECTED','REQUEST_TIMEOUT','SEND_FAILED'].includes(error.code)) {
- tracked.state = 'submission_unknown';
- throw Object.assign(
- new Error(`${cmdLabel}:提交结果待核对 · ${commandId}。重连后将按此编号查询,不会自动重复执行。${error.message}`),
- {code:error.code, command_id:commandId}
- );
- } else pending.delete(commandId);
- throw error;
- }
- }
- Object.assign(tracked, {state:result.state, updated:result.updated_unix_ms, result});
- if (method === 'QueryBmc') bmcPending.set(commandStation, result.command_id);
- if (!$('command-station-filter').value || $('command-station-filter').value === commandStation) {
- queueItems = [result, ...queueItems.filter(item => item.command_id !== result.command_id)].slice(0, 100);
- renderQueue();
- }
- showCommand(result, cmdLabel);
- receiveBmcResult(result);
- return result;
- }
- function showCommand(result, cmdLabel) {
- const meanings = {queued:'已排队', dispatching:'正在分派', running:'执行中', succeeded:'执行成功', failed:'执行失败', interrupted:'已中断'};
- status(`${cmdLabel}:${meanings[result.state] || result.state}${result.detail ? ' — ' + result.detail : ''}`, ['failed', 'interrupted'].includes(result.state));
- if (terminalStates.has(result.state)) pending.delete(result.command_id);
- }
- function operation(item) {
- return actionLabels[item.arguments?.action] || operationLabels[item.method] || item.method || '未知操作';
- }
- function renderQueue() {
- const selectedState = $('command-state-filter').value;
- const items = [...queueItems].sort((a,b) => Number(b.sequence) - Number(a.sequence));
- const counts = {queued:0, running:0, succeeded:0, failed:0, interrupted:0};
- for (const item of items) {
- const state = item.state === 'dispatching' ? 'running' : item.state;
- if (state in counts) counts[state]++;
- }
- $('command-queue-counts').innerHTML = Object.entries(counts).map(([state,count]) => `<span class="queue-count">${queueLabels[state]}<strong>${count}</strong></span>`).join('');
- $('command-queue-size').textContent = String(items.length);
- const open = new Set([...document.querySelectorAll('#commands-tbody details[open]')].map(node => node.dataset.command));
- const visible = items.filter(item => !selectedState || item.state === selectedState || (selectedState === 'running' && item.state === 'dispatching'));
- $('commands-tbody').innerHTML = visible.map(item => {
- const result = JSON.stringify(redact({arguments:item.arguments || {}, result:item.result || {}, ...(item.error_code ? {error_code:item.error_code} : {})}), null, 2);
- const summary = item.detail || queueLabels[item.state] || item.state;
- return `<tr data-command-id="${escape(item.command_id)}" data-command-state="${escape(item.state)}"><td>${time(item.created_unix_ms)}</td><td>${escape(item.station_id)}</td><td><span class="queue-operation">${escape(operation(item))}</span><span class="queue-method">${escape(item.method)}</span></td><td>${escape(item.operator || 'operator')}</td><td><span class="queue-state queue-state-${escape(item.state)}">${escape(queueLabels[item.state] || item.state)}</span></td><td><details class="queue-result" data-command="${escape(item.command_id)}" ${open.has(item.command_id) ? 'open' : ''}><summary>${escape(summary)}</summary><div class="queue-result-meta">${escape(item.command_id)} · 更新 ${time(item.updated_unix_ms)}</div><pre>${escape(result)}</pre></details></td></tr>`;
- }).join('') || '<tr><td colspan="6">当前筛选下没有命令记录</td></tr>';
- }
- function applyFanResultText(targetStationId, text) {
- try {
- const parsed = JSON.parse(text || '{}');
- if (parsed && (typeof parsed.enabled === 'boolean' || parsed.fan_mode_restored === 'auto')) {
- const enabled = parsed.fan_mode_restored === 'auto' ? false : !!parsed.enabled;
- fanStateByStation.set(targetStationId, {
- enabled,
- mode: enabled ? 'low_speed' : 'auto',
- raw_mode: parsed.raw_mode || (enabled ? '01' : '00'),
- label: parsed.label || (enabled ? '降速静音模式 (系统30% / 电源1%)' : '服务器默认自动温控 (Auto)'),
- fans: Array.isArray(parsed.fans) ? parsed.fans : [],
- });
- if (targetStationId === stationId) renderFanControl(current());
- }
- } catch (_) {}
- }
- function renderFanControl(s = current()) {
- const caps = capabilities(s), available = connected && !!s && !!caps.bmc_query && s.bmc_state === 'online';
- const st = s ? fanStateByStation.get(s.station_id) : null;
- const chk = $('chk-fan-low-speed');
- if (chk) {
- chk.disabled = !available || chk.dataset.busy === '1';
- if (st && chk.dataset.busy !== '1') chk.checked = !!st.enabled;
- }
- enable('btn-fan-refresh', connected && !!s && !!caps.bmc_query);
- enable('btn-bmc-warm-reset', connected && !!s && !!caps.bmc_query);
- const badge = $('fan-mode-badge'), summary = $('fan-rpm-summary');
- if (!badge || !summary) return;
- if (!s || !caps.bmc_query) {
- badge.textContent = 'BMC 未启用';
- badge.className = 'badge';
- summary.textContent = '';
- return;
- }
- if (!st) {
- badge.textContent = s.bmc_state === 'online' ? '待读取风扇模式' : `BMC ${label(s.bmc_state)}`;
- badge.className = 'badge';
- summary.textContent = '';
- return;
- }
- badge.textContent = `当前: ${st.label}`;
- badge.className = 'badge ' + (st.enabled ? 'error' : 'connected');
- summary.textContent = st.fans?.length ? st.fans.slice(0, 6).join(' · ') : (st.raw_mode ? `原始模式字节: ${st.raw_mode}` : '');
- }
- async function refreshFanMode(targetStationId = stationId, silent = true) {
- const s = stations.find(x => x.station_id === targetStationId);
- if (!connected || !s || !capabilities(s).bmc_query || fanQueryInFlight.has(targetStationId) || s.bmc_state !== 'online') return;
- fanQueryInFlight.add(targetStationId);
- try {
- const cmd = await command('QueryBmc', {station_id: targetStationId, query: 'fan_mode'}, '查询风扇温控模式');
- if (cmd?.result?.text) applyFanResultText(targetStationId, cmd.result.text);
- } catch (error) {
- if (!silent) status(`风扇状态读取失败:${error.message}`, true);
- } finally {
- fanQueryInFlight.delete(targetStationId);
- if (targetStationId === stationId) renderFanControl(current());
- }
- }
- function receiveBmcResult(item) {
- if (item.method === 'QueryBmc' && terminalStates.has(item.state) && item.state === 'succeeded' && item.result?.text) {
- if (['fan_mode','fan_low_speed_on','fan_low_speed_off','bmc_warm_reset'].includes(item.arguments?.query || item.result?.query)) {
- applyFanResultText(item.station_id, item.result.text);
- }
- }
- if (item.method !== 'QueryBmc' || bmcPending.get(item.station_id) !== item.command_id || !terminalStates.has(item.state)) return;
- bmcPending.delete(item.station_id);
- if (stationId !== item.station_id) return;
- $('bmc-query-output').textContent = item.state === 'succeeded' ? item.result?.text || '设备未返回文本' : `查询失败:${item.detail || item.error_code || item.state}`;
- $('bmc-query-time').textContent = time(item.result?.observed_unix_ms || item.updated_unix_ms);
- }
- async function pollQueue() {
- if (queuePolling) return;
- queuePolling = true;
- const filter = $('command-station-filter').value;
- try {
- const snapshot = await callApi('GetQueue', {station_id:filter, limit:100});
- const fetched = snapshot.items || [], byId = new Map(fetched.map(item => [item.command_id,item]));
- for (const [key, tracked] of [...pending]) {
- let item = byId.get(key);
- if (!item) {
- try { item = await callApi('GetQueueItem', {command_id:key}); }
- catch (error) {
- if (error.code === 'NOT_FOUND' && ['submitting','submission_unknown'].includes(tracked.state)) continue;
- throw error;
- }
- }
- tracked.result = item;
- if (item.state !== tracked.state || item.updated_unix_ms !== tracked.updated) {
- tracked.state = item.state; tracked.updated = item.updated_unix_ms;
- showCommand(item, `${tracked.station} ${tracked.label}`);
- }
- receiveBmcResult(item);
- }
- if (filter !== $('command-station-filter').value) return;
- queueItems = fetched; renderQueue();
- $('command-queue-updated').textContent = `已同步 ${stamp()} · 等待 ${Number(snapshot.pending_count || 0)} / 执行 ${Number(snapshot.running_count || 0)}`;
- $('command-queue-error').classList.add('hidden');
- } catch (error) {
- $('command-queue-error').textContent = `队列读取失败,保留上次记录:${error.message}`;
- $('command-queue-error').classList.remove('hidden');
- } finally { queuePolling = false; }
- }
- function deviceEventView() {
- const filter = $('device-event-station-filter').value;
- if (!eventViews.has(filter)) eventViews.set(filter, {events:[], cursor:0, initialized:false, hasMore:false, updated:''});
- return eventViews.get(filter);
- }
- function renderDeviceEvents() {
- const view = deviceEventView(), selectedLevel = $('device-event-level-filter').value;
- const open = new Set([...document.querySelectorAll('#device-events-tbody details[open]')].map(node => node.dataset.event));
- const events = view.events.filter(event => !selectedLevel || (selectedLevel === 'warning' ? ['warning','warn'].includes(event.severity) : selectedLevel === 'error' ? ['error','critical','fatal'].includes(event.severity) : event.severity === selectedLevel)).slice().reverse();
- const severity = {info:'信息', warning:'警告', warn:'警告', error:'错误', critical:'严重', fatal:'严重'};
- $('device-events-tbody').innerHTML = events.map(event => {
- const payload = event.payload || {}, phase = event.phase ? phaseNames.get(event.phase) || label(event.phase) : '—';
- const detail = JSON.stringify(redact({sequence:event.sequence, ...(event.command_id ? {command_id:event.command_id} : {}), payload}), null, 2);
- return `<tr data-event-sequence="${escape(event.sequence)}"><td>${time(event.observed_unix_ms)}</td><td>${escape(event.station_id)}</td><td><span class="event-source">现场诊断</span><span class="event-phase">${escape(phase)}</span></td><td><span class="event-level event-level-${escape(event.severity)}">${escape(severity[event.severity] || event.severity || '信息')}</span></td><td>${escape(event.kind)}</td><td><details class="queue-result" data-event="${escape(event.sequence)}" ${open.has(String(event.sequence)) ? 'open' : ''}><summary>${escape(event.message || event.kind)}</summary><pre>${escape(detail)}</pre></details></td></tr>`;
- }).join('') || '<tr><td colspan="6">当前筛选下没有设备事件</td></tr>';
- $('device-event-cursor').textContent = `本页读取位置:${view.cursor} · 保留 ${view.events.length} 条`;
- $('device-events-updated').textContent = view.updated ? `已同步 ${view.updated}` : '等待设备事件';
- }
- async function pollDeviceEvents() {
- if (eventPolling) return;
- eventPolling = true;
- const filter = $('device-event-station-filter').value, view = deviceEventView();
- try {
- const result = await callApi('ReadEventQueue', {station_id:filter, after_sequence:view.cursor, limit:100});
- view.initialized = true;
- const next = Number(result.next_after_sequence || view.cursor);
- const existing = new Set(view.events.map(event => String(event.sequence)));
- view.events = view.events.concat((result.events || []).filter(event => !existing.has(String(event.sequence)))).sort((a,b) => Number(a.sequence) - Number(b.sequence)).slice(-200);
- view.hasMore = !!result.has_more; view.updated = stamp();
- view.cursor = next;
- if (filter === $('device-event-station-filter').value) {
- renderDeviceEvents(); $('device-events-error').classList.add('hidden');
- }
- } catch (error) {
- $('device-events-error').textContent = `设备事件读取失败,保留上次记录:${error.message}`;
- $('device-events-error').classList.remove('hidden');
- } finally { eventPolling = false; }
- }
- function renderAuditLogs() {
- if (!$('audit-logs-tbody')) return;
- const catLabels = {
- profile_library:'Profile 配置库',
- task_batch:'多计划测试队列',
- ict_settings:'ICT 参数保存',
- ict_dispatch:'ICT 固件下发',
- amt_settings:'AMT 参数保存',
- amt_dispatch:'AMT 固件下发',
- pxe_mt86:'PXE 与 mt86.cfg',
- boot_plan:'启动计划',
- thermal_mcu:'高温罩温控',
- connections:'连接设置',
- dimm_replacement:'停机换条确认',
- stage_intent:'阶段预设覆盖',
- error_preset:'时序拉偏预设',
- start_test:'测试启动',
- power:'电源控制',
- };
- const open = new Set([...document.querySelectorAll('#audit-logs-tbody details[open]')].map(n => n.dataset.seq));
- $('audit-logs-tbody').innerHTML = auditItems.map(item => {
- const seq = String(item.sequence || '');
- const detailJson = JSON.stringify(redact(item.details || {}), null, 2);
- return `<tr>
- <td><code>#${escape(seq)}</code></td>
- <td>${time(item.timestamp_unix_ms)}</td>
- <td><strong>${escape(item.station_id || '-')}</strong></td>
- <td>${escape(item.operator || 'operator')}</td>
- <td><span class="badge">${escape(catLabels[item.category] || item.category || '-')}</span></td>
- <td><code>${escape(item.action || '-')}</code></td>
- <td><details class="queue-result" data-seq="${escape(seq)}" ${open.has(seq) ? 'open' : ''}><summary>${escape(item.summary || '-')}</summary><pre>${escape(detailJson)}</pre></details></td>
- </tr>`;
- }).join('') || '<tr><td colspan="7">当前筛选条件下暂无变更审计记录</td></tr>';
- }
- async function pollAuditLogs() {
- if (auditPolling || !$('audit-logs-tbody')) return;
- auditPolling = true;
- const stFilter = $('audit-station-filter')?.value || '';
- const catFilter = $('audit-category-filter')?.value || '';
- try {
- const res = await callApi('ReadAuditLogs', {station_id: stFilter, category: catFilter, limit: 100});
- auditItems = res.items || [];
- renderAuditLogs();
- if ($('audit-logs-updated')) $('audit-logs-updated').textContent = `已同步 ${stamp()} · 累计序号 #${res.latest_sequence || 0}`;
- } catch (_) {
- } finally { auditPolling = false; }
- }
- async function action(button, task) {
- const element = $(button);
- if (!element || element.dataset.busy === '1') return;
- element.dataset.busy = '1'; element.disabled = true;
- try { await task(); } catch (error) { status(error.message, true); }
- finally { element.dataset.busy = ''; element.disabled = false; renderDetail(); await poll(); }
- }
- function bind(button, task) { if ($(button)) $(button).onclick = () => action(button, task); }
- function renderCards() {
- window.stlNavigation.updateStations(stations, stationId);
- $('stations-grid').innerHTML = stations.map(s => {
- const stage = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
- const state = stage?.main?.label || '阶段待观测';
- const caps = window.stlFirmware.capabilities(s.station_id);
- const unavailable = !!caps && !caps.console && !caps.bmc_query;
- const shortName = (s.name || s.station_id).replace(/\s*\(.+\)$/, '');
- const d = diagnostics.get(s.station_id);
- const consoleOnline = !!(s.console_online ?? (d?.state === 'online'));
- const nodeOnline = consoleOnline || s.bmc_state === 'online';
- const kind = (unavailable || !nodeOnline) ? 'offline' : 'idle';
- const bmcBadge = s.bmc_state === 'online' ? 'BMC 在线' : (s.bmc_address ? `BMC ${label(s.bmc_state || 'offline')}` : '仅串口模式');
- return `<div class="station-card ${s.station_id === stationId ? 'active' : ''}" data-id="${escape(s.station_id)}" role="button" tabindex="0" aria-pressed="${s.station_id === stationId}">
- <div class="station-card-header"><div><span class="station-name">${escape(s.station_id)} · ${escape(shortName)}</span><div class="station-subtitle">${escape(d?.transport ? transportLabel(d) : s.bmc_address ? 'BMC ' + s.bmc_address : '未配置连接')}</div></div><span class="station-status-tag tag-${s.awaiting_dimm_replacement ? 'error' : kind}">${escape(unavailable ? '未配置' : s.awaiting_dimm_replacement ? '待换条' : !nodeOnline ? '离线' : label(state))}</span></div>
- <div class="station-info-row"><span>主板电源</span><span>${escape(label(s.server_power))} · ${escape(bmcBadge)}</span></div>
- <div class="station-info-row"><span>测试用时</span><span>${escape(formatElapsed(s.elapsed_ms || 0))}</span></div>
- <div class="station-card-footer"><span><i class="status-dot ${consoleOnline ? 'online' : ''}"></i>控制台 ${escape(consoleOnline ? '在线 (活动)' : label(d?.state || 'closed'))}</span><span>${escape(s.firmware_family || '硬件工位')}</span></div>
- </div>`;
- }).join('');
- document.querySelectorAll('.station-card').forEach(card => {
- card.onclick = () => selectStation(card.dataset.id);
- card.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); selectStation(card.dataset.id); } };
- });
- }
- function renderDimms(s) { window.stlDimms?.render(window.stlFirmware.snapshot(s.station_id) || {}); }
- function renderBoot(s, d) {
- const control = window.stlFirmware.snapshot(s.station_id) || {};
- window.stlStages.render(control, {station:s, diagnostic:d});
- }
- function renderDiagnostic(s) {
- const d = diag(), caps = capabilities(s), available = connected && !!s, consoleReady = available && !!caps.console;
- enable('btn-diag-open', consoleReady && !['online','connecting'].includes(d.state));
- enable('btn-diag-reconnect', consoleReady && d.state !== 'connecting');
- enable('btn-diag-close', available && ['online','connecting','error'].includes(d.state));
- for (const act of ['on','off','reset','cycle']) {
- enable(`btn-host-${act}`, available && !!caps.bmc_power);
- if ($(`btn-host-${act}`)) $(`btn-host-${act}`).title = caps.bmc_power ? '' : '未启用 BMC IPMI';
- }
- enable('btn-refresh-station', connected);
- enable('btn-query-bmc', available && !!caps.bmc_query && !bmcPending.has(stationId));
- const consoleOnline = !!(s?.console_online ?? (d.state === 'online'));
- $('diagnostic-state').textContent = diagnosticError ? '读取失败' : (consoleOnline ? '控制台在线' : label(d.state || 'closed'));
- $('diagnostic-state').classList.toggle('connected', consoleOnline);
- $('diagnostic-state').classList.toggle('error', !!diagnosticError || d.state === 'error');
- renderBoot(s, d);
- }
- function renderDetail() {
- const s = current(), context = consoleContext();
- enable('btn-send-sol', context.writable);
- enable('btn-send-enter', context.writable);
- $('sol-input-cmd').disabled = !context.writable;
- document.querySelectorAll('[data-sol-key]').forEach(button => { button.disabled = !context.writable || button.dataset.busy === '1'; });
- enable('btn-download-sol', connected && context.exists);
- if (!s) { renderDiagnostic({}); renderDimms({}); return; }
- $('detail-station-tag').textContent = `${s.station_id} · ${s.name || '工位'}`;
- if ($('detail-elapsed')) {
- const ended = Number(s.ended_unix_ms) > 0;
- const activeTiming = Number(s.started_unix_ms) > 0 && !ended;
- $('detail-elapsed').textContent = (ended ? '本批耗时 ' : '测试用时 ') + formatElapsed(s.elapsed_ms || 0);
- $('detail-elapsed').classList.toggle('connected', activeTiming);
- }
- const stageProgress = window.stlFirmware.snapshot(s.station_id)?.firmware?.stage_progress;
- $('detail-phase-tag').textContent = (stageProgress?.live === false ? '最后观测:' : '本轮进度:') + (stageProgress?.main?.label || '等待阶段数据');
- const executionState = window.stlFirmware.snapshot(stationId)?.boot_execution?.state;
- const consoleOnline = !!(s.console_online ?? (diag().state === 'online'));
- $('console-lock-badge').textContent = !consoleOnline && diag().state !== 'online' ? '未连接' : executionState === 'paused' ? '计划已暂停 · 人工接管' : executionState === 'waiting_user' ? '人工节点 · 可输入' : executionState === 'running' ? '自动计划执行中' : '手动调试';
- $('sol-state-badge').textContent = consoleOnline ? '控制台在线' : label(diag().state || 'closed');
- $('sol-state-badge').classList.toggle('connected', consoleOnline);
- $('console-context').textContent = `现场诊断 · ${transportLabel()} · ${diag().session_id || '点击「连接串口」建立会话'}`;
- renderDiagnostic(s); renderFanControl(s); renderDimms(s); window.stlFirmware.render();
- if (connected && s && s.bmc_state === 'online' && !fanStateByStation.has(s.station_id) && !fanQueryInFlight.has(s.station_id)) {
- refreshFanMode(s.station_id, true);
- }
- }
- function renderLog() {
- const context = consoleContext(), state = visibleLog();
- if (!state?.text) {
- $('sol-terminal').textContent = context.exists ? '等待串口输出…' : '连接串口后在此显示主板 BIOS 实时输出。连接成功不会自动发送回车。';
- $('sol-terminal').dataset.renderedOffset = '0';
- return;
- }
- const curOff = String(state.offset || 0);
- if ($('sol-terminal').dataset.renderedOffset === curOff && $('sol-terminal').dataset.renderedLen === String(state.text.length)) {
- return;
- }
- $('sol-terminal').dataset.renderedOffset = curOff;
- $('sol-terminal').dataset.renderedLen = String(state.text.length);
- $('sol-terminal').textContent = state.text;
- if ($('chk-autoscroll').checked) $('sol-terminal').scrollTop = $('sol-terminal').scrollHeight;
- }
- let uartPumpActive = false;
- async function pumpCleanUart(waitMs = 0) {
- if (uartPumpActive || !connected) return;
- const selectedStation = stationId, revision = selectionRevision;
- const snapshot = diagnostics.get(selectedStation);
- if (!snapshot?.session_id) return;
- uartPumpActive = true;
- try {
- const key = `diag:${selectedStation}:${snapshot.session_id}`, state = runLog(key);
- const reqWait = waitMs;
- const chunk = await callApi('ReadCleanedUart', {
- station_id: selectedStation,
- offset: state.offset,
- max_bytes: 65536,
- wait_ms: reqWait,
- }, Math.max(12000, reqWait + 8000));
- if (selectedStation !== stationId || revision !== selectionRevision) return;
- const clearOff = Number(chunk.last_clear_screen_offset || 0);
- if (clearOff > (state.clearAnchor || 0)) {
- state.text = '';
- state.clearAnchor = clearOff;
- }
- if (chunk.text) {
- state.text = (chunk.jumped_to_tail ? chunk.text : state.text + chunk.text).slice(-48000);
- }
- const nextOff = Number(chunk.next_offset ?? state.offset);
- if (nextOff > state.offset || chunk.jumped_to_tail) state.offset = nextOff;
- renderLog();
- } catch (_) {
- } finally {
- uartPumpActive = false;
- }
- }
- async function startLiveTailLoop() {
- while (true) {
- if (connected && diag().session_id && !uartPumpActive) {
- await pumpCleanUart(1000);
- await new Promise(r => setTimeout(r, 40));
- } else {
- await new Promise(r => setTimeout(r, 350));
- }
- }
- }
- async function pollDiagnostic() {
- const selectedStation = stationId, revision = selectionRevision;
- try {
- const snapshot = await callApi('GetDiagnostic', {station_id:selectedStation});
- if (selectedStation !== stationId || revision !== selectionRevision) return;
- diagnostics.set(selectedStation, snapshot); diagnosticError = '';
- if (snapshot.session_id && !uartPumpActive) {
- await pumpCleanUart(0);
- }
- } catch (error) {
- if (selectedStation === stationId) diagnosticError = `诊断状态读取失败:${error.message}`;
- }
- renderDetail(); renderLog();
- }
- async function selectStation(next, byUser = true) {
- if (byUser) stationUserChosen = true;
- stationId = next; diagnosticError = ''; selectionRevision++;
- $('bmc-query-output').textContent = '点击查询显示 BMC 返回结果。'; $('bmc-query-time').textContent = '';
- renderCards(); renderDetail(); renderLog();
- await poll();
- }
- async function poll() {
- if (polling) {
- repollPending = true;
- return;
- }
- polling = true;
- try {
- const needSysInfo = !sysInfoCache || (Date.now() - sysInfoFetchedAt >= 30000);
- const [info, list] = await Promise.all([
- needSysInfo ? callApi('GetSystemInfo') : Promise.resolve(sysInfoCache),
- callApi('ListStations'),
- ]);
- if (needSysInfo && info) {
- sysInfoCache = info;
- sysInfoFetchedAt = Date.now();
- }
- if (!connected) status('已连接后端;选择工位操作。');
- connected = true;
- $('refresh-indicator').classList.remove('offline');
- $('sys-version').textContent = info.version || '未知';
- $('sys-commit').textContent = info.commit ? info.commit.slice(0, 7) : '未知';
- $('sys-mode').textContent = info.mode === 'hardware' ? '硬件实机' : (info.mode || '未知');
- $('sys-heartbeat').textContent = stamp();
- $('refresh-indicator').textContent = 'WebSocket 已连接';
- stations = list.stations || [];
- if (!current() && stations.length) stationId = stations[0].station_id;
- if (!stationUserChosen && stations.length) {
- const cur = current();
- const curOnline = !!(cur && (cur.console_online || cur.bmc_state === 'online'));
- if (!curOnline) {
- const live = stations.find(s => s.console_online || s.bmc_state === 'online');
- if (live) stationId = live.station_id;
- }
- }
- renderCards(); renderDetail();
- await Promise.all([pollQueue(), pollDeviceEvents(), pollAuditLogs(), pollDiagnostic(), window.stlFirmware.refresh()]);
- renderDetail();
- } catch (error) {
- connected = false;
- sysInfoFetchedAt = 0;
- $('refresh-indicator').textContent = '连接失败 · 显示上次数据';
- $('refresh-indicator').classList.add('offline');
- status(`后端连接失败:${error.message}`, true);
- renderDetail();
- } finally {
- polling = false;
- if (repollPending) {
- repollPending = false;
- setTimeout(() => void poll(), 40);
- }
- }
- }
- async function sendBytes(bytes, description = '发送控制台') {
- const context = consoleContext();
- if (!context.writable) throw new Error('当前控制台不可写:请先连接 BIOS 串口');
- const data = encode(new TextEncoder().encode(bytes));
- await command('WriteDiagnosticSol', {station_id:stationId, session_id:context.session_id, data}, description);
- }
- async function sendSol(empty = false) {
- const text = $('sol-input-cmd').value;
- if (!empty && !text) throw new Error('请输入命令;如需空回车请使用右侧按钮');
- await sendBytes((empty ? '' : text) + (empty || $('chk-append-enter').checked ? '\r' : ''));
- if (!empty) $('sol-input-cmd').value = '';
- }
- bind('btn-send-sol', () => sendSol());
- bind('btn-send-enter', () => sendSol(true));
- $('sol-input-cmd').onkeydown = event => {
- if (event.key === 'Enter' && !event.isComposing) {
- event.preventDefault();
- $($('sol-input-cmd').value === '' ? 'btn-send-enter' : 'btn-send-sol').click();
- }
- };
- const keys = {space:' ', escape:'\x1b', tab:'\t', up:'\x1b[A', down:'\x1b[B', right:'\x1b[C', left:'\x1b[D', ctrlc:'\x03', backspace:'\x08', f2:'\x1bOQ', f11:'\x1b[23~', delete:'\x1b[3~'};
- document.querySelectorAll('[data-sol-key]').forEach(button => {
- button.onclick = async () => {
- if (button.dataset.busy === '1') return;
- button.dataset.busy = '1'; button.disabled = true;
- try { await sendBytes(keys[button.dataset.solKey], `发送 ${button.textContent}`); } catch (e) { status(e.message, true); }
- finally { button.dataset.busy = ''; renderDetail(); await poll(); }
- };
- });
- $('btn-clear-sol').onclick = async () => {
- const log = visibleLog();
- if (log) {
- log.text = '';
- $('sol-terminal').dataset.renderedOffset = '';
- }
- renderLog();
- if (connected) {
- try {
- const res = await command('ClearTerminalView', {station_id: stationId}, '锚定清空控制台窗口');
- const cleanOff = Number(res?.result?.clean_offset || 0);
- if (log && cleanOff > 0) {
- log.text = '';
- log.offset = cleanOff;
- log.clearAnchor = cleanOff;
- $('sol-terminal').dataset.renderedOffset = '';
- renderLog();
- }
- } catch (e) {
- status(`清空锚点同步失败:${e.message}`, true);
- }
- }
- };
- bind('btn-refresh-station', async () => { await poll(); status('已刷新工位状态。'); });
- bind('btn-fan-refresh', async () => { await refreshFanMode(stationId, false); });
- $('chk-fan-low-speed').onchange = async () => {
- const chk = $('chk-fan-low-speed'), wantLowSpeed = chk.checked;
- chk.dataset.busy = '1'; chk.disabled = true;
- try {
- const q = wantLowSpeed ? 'fan_low_speed_on' : 'fan_low_speed_off';
- const labelText = wantLowSpeed ? '开启风扇降低转速 (30%/1%)' : '关闭风扇降低转速并恢复服务器默认温控';
- await command('QueryBmc', {station_id: stationId, query: q}, labelText);
- } catch (error) {
- chk.checked = !wantLowSpeed;
- status(error.message, true);
- } finally {
- chk.dataset.busy = '';
- renderFanControl(current());
- await poll();
- }
- };
- bind('btn-bmc-warm-reset', async () => {
- await command('QueryBmc', {station_id: stationId, query: 'bmc_warm_reset'}, 'BMC 热重启 (恢复默认温控)');
- });
- bind('btn-query-bmc', async () => {
- const selectedStation = stationId, query = $('bmc-query-kind').value;
- $('bmc-query-output').textContent = '查询已提交,等待后端返回…';
- $('bmc-query-time').textContent = '';
- try {
- await command('QueryBmc', {station_id:selectedStation, query}, '读取 BMC 信息');
- } catch (error) {
- if (stationId === selectedStation) $('bmc-query-output').textContent = `查询失败:${error.message}`;
- throw error;
- }
- });
- for (const [button, actionName, description] of [['btn-diag-open','open','连接 BIOS 控制台'],['btn-diag-close','close','断开 BIOS 控制台'],['btn-diag-reconnect','reconnect','重连 BIOS 控制台']]) {
- bind(button, async () => {
- await command('SetDiagnosticSol', {station_id:stationId, action:actionName}, description);
- });
- }
- for (const [suffix, actionName, description] of [['on','host_on','主板开机'],['off','host_off','主板关机'],['reset','host_reset','主板复位'],['cycle','host_cycle','主板关开循环']]) {
- bind(`btn-host-${suffix}`, async () => {
- await command('StationPower', {station_id:stationId, action:actionName}, description);
- });
- }
- bind('btn-refresh-commands', pollQueue);
- bind('btn-refresh-device-events', pollDeviceEvents);
- bind('btn-refresh-audits', pollAuditLogs);
- if ($('btn-web-logout')) {
- $('btn-web-logout').onclick = async () => {
- try {
- await fetch('/api/auth/logout', { method: 'POST', credentials: 'same-origin' });
- } finally {
- window.location.reload();
- }
- };
- }
- if ($('audit-station-filter')) $('audit-station-filter').onchange = pollAuditLogs;
- if ($('audit-category-filter')) $('audit-category-filter').onchange = pollAuditLogs;
- $('command-station-filter').onchange = () => { queueItems = []; renderQueue(); pollQueue(); };
- $('command-state-filter').onchange = renderQueue;
- $('device-event-station-filter').onchange = () => { renderDeviceEvents(); pollDeviceEvents(); };
- $('device-event-level-filter').onchange = renderDeviceEvents;
- function saveFile(name, data, type = 'application/octet-stream') {
- const url = URL.createObjectURL(new Blob([data], {type}));
- const anchor = document.createElement('a'); anchor.href = url; anchor.download = name; anchor.click();
- setTimeout(() => URL.revokeObjectURL(url), 10000);
- }
- async function readFile(method, request) {
- const chunks = []; let offset = 0;
- while (true) {
- const part = await callApi(method, {...request, offset, max_bytes: 262144});
- chunks.push(decode(part.data));
- const next = Number(part.next_offset);
- if (part.eof) break;
- if (!(next > Number(offset))) throw new Error('下载未推进,请重试');
- offset = next;
- }
- return new Blob(chunks);
- }
- bind('btn-download-sol', async () => {
- const context = consoleContext();
- saveFile(`${context.session_id || stationId}-sol.bin`, await readFile('ReadDiagnosticSol', {station_id:stationId, session_id:context.session_id}));
- status('原始控制台日志已下载');
- });
- const services = {
- callApi, command, bind, status, time, formatElapsed, terminalText,
- useLiveConsole: () => { renderDetail(); },
- stationId: () => stationId,
- station: current,
- diagnostic: diag,
- consoleContext,
- connected: () => connected,
- };
- window.stlFirmware.init(services);
- window.stlBootPlan.init(services);
- window.stlAmt.init(services);
- window.stlDimms.init(services);
- window.stlStages.init(services);
- window.addEventListener('stl:station-select', event => selectStation(event.detail.stationId));
- window.addEventListener('stl:transport-state', event => {
- const transport = event.detail, ready = transport.state === 'open';
- const stateLabels = {idle:'等待连接',connecting:'连接中',open:'已连接',disconnected:'已断开 · 重连中',closed:'已断开'};
- $('transport-state').textContent = 'WebSocket · ' + (stateLabels[transport.state] || transport.state);
- $('transport-state').dataset.state = transport.state;
- $('transport-state').classList.toggle('connected', ready);
- $('transport-state').classList.toggle('error', ['disconnected','closed'].includes(transport.state));
- if (ready) {
- if (transport.generation > 1) {
- sysInfoFetchedAt = 0;
- poll();
- }
- } else {
- connected = false;
- $('refresh-indicator').textContent = '连接未就绪 · 显示上次数据';
- $('refresh-indicator').classList.add('offline');
- renderDetail();
- }
- });
- window.addEventListener('stl:server-event', event => {
- const ev = event.detail?.event;
- if (ev === 'task_complete') {
- if (dirtyPollTimer) { clearTimeout(dirtyPollTimer); dirtyPollTimer = null; }
- void poll();
- } else if (ev === 'station_dirty') {
- if (!dirtyPollTimer) {
- dirtyPollTimer = setTimeout(() => {
- dirtyPollTimer = null;
- void poll();
- }, 500);
- }
- }
- });
- window.addEventListener('load', async () => {
- renderDetail();
- await poll();
- setInterval(poll, 10000);
- void startLiveTailLoop();
- });
- })();
|