487 lines
20 KiB
TypeScript
487 lines
20 KiB
TypeScript
import { apiFetch } from '../api.js';
|
|
import { confirmDialog } from '../dialogs.js';
|
|
import {
|
|
el,
|
|
extractErrorMessage,
|
|
fmtTime,
|
|
isAiEnabled,
|
|
type ClientState,
|
|
} from '../state.js';
|
|
import type { MultiplexWsClient } from '../ws-client.js';
|
|
|
|
interface AlertChannelItem {
|
|
id: string;
|
|
name: string;
|
|
type: 'discord' | 'telegram' | 'ntfy' | 'generic';
|
|
url?: string;
|
|
secretRef: string;
|
|
chatId?: string;
|
|
topic?: string;
|
|
enabled: boolean;
|
|
}
|
|
|
|
interface AlertRuleItem {
|
|
id: string;
|
|
name: string;
|
|
kind: 'metric' | 'disk' | 'offline' | 'probe' | 'system' | 'security-event';
|
|
severity: 'warn' | 'critical';
|
|
target: { serverId?: string; tags?: string[]; all?: boolean };
|
|
forConsecutivePolls: number;
|
|
cooldownSec: number;
|
|
channelIds: string[];
|
|
remediationWorkflowId?: string;
|
|
enabled: boolean;
|
|
metric?: string;
|
|
operator?: string;
|
|
threshold?: number;
|
|
mountPoint?: string;
|
|
thresholdPct?: number;
|
|
offlineSec?: number;
|
|
probeId?: string;
|
|
systemId?: string;
|
|
item?: string;
|
|
events?: string[];
|
|
}
|
|
|
|
interface MaintenanceWindowItem {
|
|
id: string;
|
|
name: string;
|
|
cron: string;
|
|
timezone: string;
|
|
durationMinutes: number;
|
|
target: { serverId?: string; tags?: string[]; all?: boolean };
|
|
enabled: boolean;
|
|
}
|
|
|
|
interface AlertsPayload {
|
|
alertsConfig: {
|
|
version: 1;
|
|
channels: AlertChannelItem[];
|
|
rules: AlertRuleItem[];
|
|
maintenanceWindows: MaintenanceWindowItem[];
|
|
};
|
|
activeCount: number;
|
|
activeEvents: Array<{
|
|
id: string;
|
|
ruleId: string;
|
|
serverId: string | null;
|
|
state: string;
|
|
severity: string;
|
|
message: string;
|
|
webhookStatus: string | null;
|
|
triggeredAt: number;
|
|
}>;
|
|
recentEvents: Array<{
|
|
id: string;
|
|
ruleId: string;
|
|
serverId: string | null;
|
|
state: string;
|
|
severity: string;
|
|
message: string;
|
|
webhookStatus: string | null;
|
|
triggeredAt: number;
|
|
resolvedAt: number | null;
|
|
}>;
|
|
silences: Array<{
|
|
id: string;
|
|
scopeType: string;
|
|
targetId: string;
|
|
reason: string | null;
|
|
expiresAt: number;
|
|
}>;
|
|
activeMaintenanceWindowIds: string[];
|
|
}
|
|
|
|
export async function renderAlertsView(
|
|
root: HTMLElement,
|
|
state: ClientState,
|
|
wsClient: MultiplexWsClient,
|
|
): Promise<void> {
|
|
root.replaceChildren();
|
|
const [data, credsRes] = await Promise.all([
|
|
apiFetch<AlertsPayload>('/api/alerts'),
|
|
apiFetch<{ credentials: Array<{ id: string; type: string }> }>('/api/vault/credentials').catch(() => ({
|
|
credentials: [],
|
|
})),
|
|
]);
|
|
|
|
state.activeAlertCount = data.activeCount;
|
|
const cfg = data.alertsConfig;
|
|
|
|
const refreshBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Refresh');
|
|
refreshBtn.addEventListener('click', () => {
|
|
void renderAlertsView(root, state, wsClient);
|
|
});
|
|
const aiHelpBtn = isAiEnabled(state)
|
|
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Setup Helper]')
|
|
: null;
|
|
if (aiHelpBtn) {
|
|
aiHelpBtn.addEventListener('click', async () => {
|
|
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
|
await openAiAssistantDrawer({
|
|
state,
|
|
wsClient,
|
|
surface: 'setup',
|
|
title: 'AI Alert Rules & Channels Helper',
|
|
contextText: JSON.stringify(cfg, null, 2),
|
|
targetPath: 'alerts.json',
|
|
defaultDraftKind: 'alerts',
|
|
onApplied: () => renderAlertsView(root, state, wsClient),
|
|
});
|
|
});
|
|
}
|
|
|
|
root.append(
|
|
el(
|
|
'section',
|
|
{ class: 'panel row-between' },
|
|
el('div', {}, el('h1', {}, `Alerting & Webhooks (${data.activeCount} firing)`), el('p', { class: 'muted' }, `${cfg.rules.length} rules, ${cfg.channels.length} channels, ${cfg.maintenanceWindows.length} maintenance windows, ${data.silences.length} active silences.`)),
|
|
el('div', { class: 'row' }, ...(aiHelpBtn ? [aiHelpBtn] : []), refreshBtn),
|
|
),
|
|
);
|
|
|
|
// 1. Firing Incidents + Quick Snooze
|
|
const firingPanel = el('section', { class: 'panel panel-region' });
|
|
firingPanel.append(el('h2', {}, `Active Firing Alerts (${data.activeEvents.length})`));
|
|
if (data.activeEvents.length === 0) {
|
|
firingPanel.append(el('p', { class: 'ok-text' }, 'All monitored rules are currently healthy.'));
|
|
} else {
|
|
for (const evt of data.activeEvents) {
|
|
const snoozeButtons = (
|
|
[
|
|
['Snooze 30m', 'rule', evt.ruleId, 30],
|
|
['Mute Server 2h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 120],
|
|
['Mute 12h', evt.serverId ? 'server' : 'rule', evt.serverId ?? evt.ruleId, 720],
|
|
] as const
|
|
).map(([label, scopeType, targetId, durationMinutes]) => {
|
|
const b = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, label);
|
|
b.addEventListener('click', async () => {
|
|
await apiFetch('/api/alerts/silences', {
|
|
method: 'POST',
|
|
body: { scopeType, targetId, durationMinutes, reason: `Quick snooze from ${evt.id}` },
|
|
});
|
|
await renderAlertsView(root, state, wsClient);
|
|
});
|
|
return b;
|
|
});
|
|
const diagBtn = isAiEnabled(state)
|
|
? el('button', { type: 'button', class: 'btn btn-sm' }, '[AI Diagnose]')
|
|
: null;
|
|
if (diagBtn) {
|
|
diagBtn.addEventListener('click', async () => {
|
|
const { openAiAssistantDrawer } = await import('./ai-drawer.js');
|
|
await openAiAssistantDrawer({
|
|
state,
|
|
wsClient,
|
|
surface: 'logs',
|
|
title: `AI Alert Debugger (${evt.ruleId})`,
|
|
contextText: `Alert ${evt.id} (${evt.severity})\nRule: ${evt.ruleId}\nServer: ${evt.serverId ?? 'hub'}\nMessage: ${evt.message}\nWebhook: ${evt.webhookStatus ?? 'none'}`,
|
|
serverId: evt.serverId ?? undefined,
|
|
});
|
|
});
|
|
}
|
|
firingPanel.append(
|
|
el(
|
|
'div',
|
|
{ class: 'alert-box' },
|
|
el('div', { class: 'row-between' }, el('strong', { class: evt.severity === 'critical' ? 'err-text' : 'warn-text' }, `[${evt.severity.toUpperCase()}] ${evt.ruleId}${evt.serverId ? ` @ ${evt.serverId}` : ''}`), el('div', { class: 'row' }, ...snoozeButtons, ...(diagBtn ? [diagBtn] : []))),
|
|
el('div', { class: 'mono' }, evt.message),
|
|
el('div', { class: 'mono muted' }, `Fired: ${fmtTime(evt.triggeredAt)} | Webhook: ${evt.webhookStatus ?? 'none'}`),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
root.append(firingPanel);
|
|
|
|
// 2. Silences & Maintenance Windows
|
|
const silPanel = el('section', { class: 'panel panel-region' });
|
|
silPanel.append(el('h2', {}, 'Active Silences / Snoozes'));
|
|
const silScope = el(
|
|
'select',
|
|
{ class: 'input-sm' },
|
|
el('option', { value: 'server' }, 'server'),
|
|
el('option', { value: 'rule' }, 'rule'),
|
|
el('option', { value: 'tag' }, 'tag'),
|
|
el('option', { value: 'all' }, 'all'),
|
|
);
|
|
const silTarget = el('input', { class: 'input-sm', placeholder: 'Target ID (or * for all)' });
|
|
const silDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 43200, value: '120' });
|
|
const silReason = el('input', { class: 'input-sm', placeholder: 'Reason (optional)' });
|
|
const silForm = el(
|
|
'form',
|
|
{ class: 'row', style: 'margin-bottom:8px' },
|
|
silScope,
|
|
silTarget,
|
|
silDur,
|
|
silReason,
|
|
el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, 'Add Silence'),
|
|
);
|
|
silForm.addEventListener('submit', async (ev) => {
|
|
ev.preventDefault();
|
|
await apiFetch('/api/alerts/silences', {
|
|
method: 'POST',
|
|
body: {
|
|
scopeType: silScope.value,
|
|
targetId: silScope.value === 'all' ? '*' : silTarget.value.trim(),
|
|
durationMinutes: Number(silDur.value || 60),
|
|
reason: silReason.value.trim() || undefined,
|
|
},
|
|
});
|
|
await renderAlertsView(root, state, wsClient);
|
|
});
|
|
silPanel.append(silForm);
|
|
|
|
for (const s of data.silences) {
|
|
const unmuteBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Remove');
|
|
unmuteBtn.addEventListener('click', async () => {
|
|
await apiFetch(`/api/alerts/silences/${encodeURIComponent(s.id)}`, { method: 'DELETE' });
|
|
await renderAlertsView(root, state, wsClient);
|
|
});
|
|
silPanel.append(
|
|
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `[${s.scopeType}:${s.targetId}] expires ${fmtTime(s.expiresAt)}${s.reason ? ` — ${s.reason}` : ''}`), unmuteBtn),
|
|
);
|
|
}
|
|
|
|
// Maintenance windows inside same card
|
|
silPanel.append(el('h2', { style: 'margin-top:12px' }, `Scheduled Maintenance Windows (${cfg.maintenanceWindows.length})`));
|
|
const saveConfig = async (nextCfg: AlertsPayload['alertsConfig']) => {
|
|
await apiFetch('/api/alerts/config', { method: 'PUT', body: nextCfg });
|
|
await renderAlertsView(root, state, wsClient);
|
|
};
|
|
|
|
for (const w of cfg.maintenanceWindows) {
|
|
const active = data.activeMaintenanceWindowIds.includes(w.id);
|
|
const rmWin = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
|
rmWin.addEventListener('click', () => {
|
|
void saveConfig({
|
|
...cfg,
|
|
maintenanceWindows: cfg.maintenanceWindows.filter((x) => x.id !== w.id),
|
|
});
|
|
});
|
|
silPanel.append(
|
|
el('div', { class: 'row-between panel' }, el('span', { class: 'mono' }, `${w.name} (${w.id}) | cron "${w.cron}" ${w.timezone} (${w.durationMinutes}m) ${active ? '[ACTIVE NOW]' : ''}`), rmWin),
|
|
);
|
|
}
|
|
const mwId = el('input', { class: 'input-sm', placeholder: 'nightly-maint', required: true });
|
|
const mwName = el('input', { class: 'input-sm', placeholder: 'Nightly Updates', required: true });
|
|
const mwCron = el('input', { class: 'input-sm', value: '0 3 * * *', required: true });
|
|
const mwDur = el('input', { class: 'input-sm', type: 'number', min: 1, max: 1440, value: '60', required: true });
|
|
const mwForm = el('form', { class: 'row', style: 'margin-top:6px' }, mwId, mwName, mwCron, mwDur, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Window'));
|
|
mwForm.addEventListener('submit', (ev) => {
|
|
ev.preventDefault();
|
|
void saveConfig({
|
|
...cfg,
|
|
maintenanceWindows: [
|
|
...cfg.maintenanceWindows,
|
|
{
|
|
id: mwId.value.trim(),
|
|
name: mwName.value.trim(),
|
|
cron: mwCron.value.trim(),
|
|
timezone: 'UTC',
|
|
durationMinutes: Number(mwDur.value || 60),
|
|
target: { all: true },
|
|
enabled: true,
|
|
},
|
|
],
|
|
});
|
|
});
|
|
silPanel.append(mwForm);
|
|
root.append(silPanel);
|
|
|
|
// 3. Notification Channels & Test Alert
|
|
const chanPanel = el('section', { class: 'panel panel-region' });
|
|
chanPanel.append(el('h2', {}, `Webhook Channels (${cfg.channels.length})`));
|
|
const chanStatusMsg = el('p', { class: 'form-msg' });
|
|
const cTbl = el('table');
|
|
cTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'ID'), el('th', {}, 'Type'), el('th', {}, 'Endpoint / Ref'), el('th', {}, 'Actions'))));
|
|
const cBody = el('tbody');
|
|
for (const ch of cfg.channels) {
|
|
const testBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Send Test Alert');
|
|
testBtn.addEventListener('click', async () => {
|
|
chanStatusMsg.textContent = `Sending test alert to "${ch.id}"...`;
|
|
try {
|
|
const res = await apiFetch<{ ok: boolean; statusCode?: number; error?: string }>(
|
|
`/api/alerts/channels/${encodeURIComponent(ch.id)}/test`,
|
|
{ method: 'POST' },
|
|
);
|
|
chanStatusMsg.className = res.ok ? 'form-msg ok-text' : 'form-msg err-text';
|
|
chanStatusMsg.textContent = res.ok
|
|
? `Test alert delivered to "${ch.id}" (HTTP ${String(res.statusCode ?? 200)}).`
|
|
: `Test alert failed for "${ch.id}": ${res.error ?? `HTTP ${String(res.statusCode)}`}`;
|
|
} catch (err) {
|
|
chanStatusMsg.className = 'form-msg err-text';
|
|
chanStatusMsg.textContent = extractErrorMessage(err);
|
|
}
|
|
});
|
|
const delCh = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
|
delCh.addEventListener('click', async () => {
|
|
const ok = await confirmDialog('dialog-confirm', `Delete alert channel "${ch.id}"?`);
|
|
if (!ok) return;
|
|
await saveConfig({ ...cfg, channels: cfg.channels.filter((x) => x.id !== ch.id) });
|
|
});
|
|
cBody.append(
|
|
el('tr', {}, el('td', { class: 'mono' }, `${ch.id} (${ch.name})`), el('td', {}, el('span', { class: 'badge' }, ch.type)), el('td', { class: 'mono' }, `${ch.url ?? ch.topic ?? ch.chatId ?? '—'} [vault:${ch.secretRef}]`), el('td', {}, el('div', { class: 'row' }, testBtn, delCh))),
|
|
);
|
|
}
|
|
cTbl.append(cBody);
|
|
|
|
const chId = el('input', { placeholder: 'ops-webhook', required: true });
|
|
const chName = el('input', { placeholder: 'Ops Webhook', required: true });
|
|
const chType = el('select', {}, el('option', { value: 'generic' }, 'generic'), el('option', { value: 'discord' }, 'discord'), el('option', { value: 'telegram' }, 'telegram'), el('option', { value: 'ntfy' }, 'ntfy'));
|
|
const chUrl = el('input', { placeholder: 'Webhook / base URL (optional for ntfy.sh or Telegram)' });
|
|
const chExtra = el('input', { placeholder: 'Telegram chatId OR ntfy topic (optional)' });
|
|
const chRef = el('select', {});
|
|
const webhookCreds = credsRes.credentials.filter((cr) => cr.type === 'webhook-secret');
|
|
for (const cr of webhookCreds) {
|
|
chRef.append(el('option', { value: cr.id }, `${cr.id} (${cr.type})`));
|
|
}
|
|
if (webhookCreds.length === 0) {
|
|
chRef.append(el('option', { value: 'webhook-main' }, 'webhook-main (add webhook-secret in Vault)'));
|
|
}
|
|
const chForm = el(
|
|
'form',
|
|
{ class: 'stack', style: 'margin-top:8px' },
|
|
el('div', { class: 'grid-3' }, chId, chName, chType),
|
|
el('div', { class: 'grid-3' }, chUrl, chExtra, chRef),
|
|
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm mutating-action' }, '+ Add Webhook Channel')),
|
|
);
|
|
chForm.addEventListener('submit', async (ev) => {
|
|
ev.preventDefault();
|
|
chanStatusMsg.textContent = '';
|
|
try {
|
|
await saveConfig({
|
|
...cfg,
|
|
channels: [
|
|
...cfg.channels,
|
|
{
|
|
id: chId.value.trim(),
|
|
name: chName.value.trim(),
|
|
type: chType.value as AlertChannelItem['type'],
|
|
url: chUrl.value.trim() || undefined,
|
|
secretRef: chRef.value.trim(),
|
|
chatId: chType.value === 'telegram' ? chExtra.value.trim() || undefined : undefined,
|
|
topic: chType.value === 'ntfy' ? chExtra.value.trim() || undefined : undefined,
|
|
enabled: true,
|
|
},
|
|
],
|
|
});
|
|
} catch (err) {
|
|
chanStatusMsg.className = 'form-msg err-text';
|
|
chanStatusMsg.textContent = extractErrorMessage(err);
|
|
}
|
|
});
|
|
chanPanel.append(el('div', { class: 'table-wrap' }, cTbl), chanStatusMsg, chForm);
|
|
root.append(chanPanel);
|
|
|
|
// 4. Alert Rules
|
|
const rulesPanel = el('section', { class: 'panel panel-region' });
|
|
rulesPanel.append(el('h2', {}, `Alert Rules (${cfg.rules.length})`));
|
|
const rMsg = el('p', { class: 'form-msg err-text' });
|
|
for (const r of cfg.rules) {
|
|
const condText =
|
|
r.kind === 'metric'
|
|
? `${r.metric} ${r.operator} ${r.threshold}`
|
|
: r.kind === 'disk'
|
|
? `disk ${r.mountPoint ?? '*'} >= ${r.thresholdPct}%`
|
|
: r.kind === 'offline'
|
|
? `offline >= ${r.offlineSec}s`
|
|
: r.kind === 'probe'
|
|
? `probe ${r.probeId ?? '*'}`
|
|
: r.kind === 'security-event'
|
|
? `security-event [${r.events?.join(', ') ?? ''}]`
|
|
: `system ${r.systemId}/${r.item ?? '*'}`;
|
|
const toggleBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, r.enabled ? 'Disable' : 'Enable');
|
|
toggleBtn.addEventListener('click', () => {
|
|
void saveConfig({
|
|
...cfg,
|
|
rules: cfg.rules.map((x) => (x.id === r.id ? { ...x, enabled: !x.enabled } : x)),
|
|
});
|
|
});
|
|
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
|
|
delBtn.addEventListener('click', () => {
|
|
void saveConfig({ ...cfg, rules: cfg.rules.filter((x) => x.id !== r.id) });
|
|
});
|
|
rulesPanel.append(
|
|
el('div', { class: 'row-between panel' }, el('div', {}, el('strong', {}, `${r.name} (${r.id})`), el('div', { class: 'mono muted' }, `${condText} | for=${r.forConsecutivePolls} | cooldown=${r.cooldownSec}s | channels=[${r.channelIds.join(',')}]${r.remediationWorkflowId ? ` | fix=${r.remediationWorkflowId}` : ''}`)), el('div', { class: 'row' }, toggleBtn, delBtn)),
|
|
);
|
|
}
|
|
|
|
const ruleId = el('input', { placeholder: 'high-cpu', required: true });
|
|
const ruleName = el('input', { placeholder: 'High CPU Usage', required: true });
|
|
const ruleKind = el('select', {}, el('option', { value: 'metric' }, 'metric'), el('option', { value: 'disk' }, 'disk'), el('option', { value: 'offline' }, 'offline'), el('option', { value: 'probe' }, 'probe'), el('option', { value: 'system' }, 'system'), el('option', { value: 'security-event' }, 'security-event'));
|
|
const ruleSev = el('select', {}, el('option', { value: 'warn' }, 'warn'), el('option', { value: 'critical' }, 'critical'));
|
|
const ruleParam1 = el('input', { placeholder: 'metric/mount/probe/system or events csv (auth.lockout,ssh.host_key_mismatch,vault.panic_lock)' });
|
|
const ruleThresh = el('input', { type: 'number', value: '85', placeholder: 'Threshold / Offline sec' });
|
|
const rulePolls = el('input', { type: 'number', min: 1, value: '3', placeholder: 'forConsecutivePolls' });
|
|
const ruleChans = el('input', { placeholder: 'channelIds comma-sep (optional)' });
|
|
const ruleRemWf = el('input', { placeholder: 'remediationWorkflowId (optional)' });
|
|
const ruleForm = el(
|
|
'form',
|
|
{ class: 'stack', style: 'margin-top:8px' },
|
|
el('div', { class: 'grid-3' }, ruleId, ruleName, ruleKind),
|
|
el('div', { class: 'grid-3' }, ruleSev, ruleParam1, ruleThresh),
|
|
el('div', { class: 'grid-3' }, rulePolls, ruleChans, ruleRemWf),
|
|
rMsg,
|
|
el('div', {}, el('button', { type: 'submit', class: 'btn btn-sm btn-primary mutating-action' }, '+ Add Alert Rule')),
|
|
);
|
|
ruleForm.addEventListener('submit', async (ev) => {
|
|
ev.preventDefault();
|
|
rMsg.textContent = '';
|
|
const base = {
|
|
id: ruleId.value.trim(),
|
|
name: ruleName.value.trim(),
|
|
severity: ruleSev.value as 'warn' | 'critical',
|
|
target: { all: true },
|
|
forConsecutivePolls: Number(rulePolls.value || 3),
|
|
cooldownSec: 300,
|
|
channelIds: ruleChans.value.split(',').map((c) => c.trim()).filter(Boolean),
|
|
remediationWorkflowId: ruleRemWf.value.trim() || undefined,
|
|
enabled: true,
|
|
};
|
|
let nextRule: AlertRuleItem;
|
|
if (ruleKind.value === 'disk') {
|
|
nextRule = { ...base, kind: 'disk', mountPoint: ruleParam1.value.trim() || undefined, thresholdPct: Number(ruleThresh.value || 90) };
|
|
} else if (ruleKind.value === 'offline') {
|
|
nextRule = { ...base, kind: 'offline', offlineSec: Number(ruleThresh.value || 60) };
|
|
} else if (ruleKind.value === 'probe') {
|
|
nextRule = { ...base, kind: 'probe', probeId: ruleParam1.value.trim() || undefined };
|
|
} else if (ruleKind.value === 'system') {
|
|
nextRule = { ...base, kind: 'system', systemId: ruleParam1.value.trim() || 'docker-compose' };
|
|
} else if (ruleKind.value === 'security-event') {
|
|
const events = ruleParam1.value
|
|
.split(',')
|
|
.map((e) => e.trim())
|
|
.filter(Boolean);
|
|
nextRule = {
|
|
...base,
|
|
kind: 'security-event',
|
|
forConsecutivePolls: 1,
|
|
events: events.length > 0 ? events : ['auth.lockout', 'ssh.host_key_mismatch', 'vault.panic_lock'],
|
|
};
|
|
} else {
|
|
nextRule = { ...base, kind: 'metric', metric: (ruleParam1.value.trim() || 'cpuPct') as 'cpuPct', operator: 'gt', threshold: Number(ruleThresh.value || 85) };
|
|
}
|
|
try {
|
|
await saveConfig({ ...cfg, rules: [...cfg.rules, nextRule] });
|
|
} catch (err) {
|
|
rMsg.textContent = extractErrorMessage(err);
|
|
}
|
|
});
|
|
rulesPanel.append(ruleForm);
|
|
root.append(rulesPanel);
|
|
|
|
// 5. Recent History
|
|
const histPanel = el('section', { class: 'panel panel-region' });
|
|
histPanel.append(el('h2', {}, `Recent Alert Events (${data.recentEvents.length})`));
|
|
const hTbl = el('table');
|
|
hTbl.append(el('thead', {}, el('tr', {}, el('th', {}, 'Rule'), el('th', {}, 'Server'), el('th', {}, 'State'), el('th', {}, 'Message'), el('th', {}, 'Time'))));
|
|
const hBody = el('tbody');
|
|
for (const e of data.recentEvents) {
|
|
hBody.append(
|
|
el('tr', {}, el('td', { class: 'mono' }, e.ruleId), el('td', { class: 'mono' }, e.serverId ?? '—'), el('td', {}, el('span', { class: e.state === 'firing' ? 'badge badge-err' : 'badge badge-ok' }, `[${e.state.toUpperCase()}]`)), el('td', { class: 'mono' }, e.message), el('td', { class: 'mono' }, fmtTime(e.triggeredAt))),
|
|
);
|
|
}
|
|
hTbl.append(hBody);
|
|
histPanel.append(el('div', { class: 'table-wrap' }, hTbl));
|
|
root.append(histPanel);
|
|
}
|