The predefined rules are too constraining: an ISP cannot say "CPU over 80% on servers for 15 minutes" or "uplink without a description", and every new need meant editing config.yaml. Admins now build their own rules; the shipped ones stay as read-only built-in macros with their names unchanged, so v1.1 policies and alert history keep working. Custom rules live in a new alert_rules table (migration 13) and are builder-only. A metric rule names a catalogue metric (every pollable profile metric plus push-ingested names) with a transform (value, rate, percent_of), window, function, aggregate, comparison and threshold; the pure internal/alertrule package compiles it to MetricsQL from fixed templates, so no user text reaches a query. An inventory rule ANDs one to five conditions over whitelisted device or port fields and is evaluated in Go over store rows. The evaluator takes its rule set from a function each cycle, so edits apply live, and both kinds use the existing state machine, policies, suppression and notifications. Comparisons now cover > >= < <= == != everywhere. utilisation is not offered: port speed is not a stored series. config.yaml rules still work but are deprecated. API (additive): rule list gains id/kind/editable/spec/expr, plus get, create, update, delete, catalogue, test (viewer, read-only) and copy of a built-in (cpu_high, ups_on_battery, printer_supply_empty) to a custom rule. Deleting or renaming a rule that a policy names is a 409. The UI gets an Alert rules tab with a builder dialog, a test button and the generated query, and the policy dialog lists custom rules. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01T4PdJUPrakM8fHvN8jYv2x
126 lines
8.2 KiB
TypeScript
126 lines
8.2 KiB
TypeScript
// Stateful mock of the alert rule endpoints: a few built-ins, the builder catalogue, custom rule CRUD, test and
|
|
// copy. PolicyStore owns one and tells it how many policies name a rule.
|
|
import type { components } from '../../src/api/schema.d.ts'
|
|
import type { Reply } from './groups.ts'
|
|
|
|
type S = components['schemas']
|
|
|
|
const BUILTINS: S['AlertRuleInfo'][] = [
|
|
{ id: 'interface_down', name: 'interface_down', kind: 'builtin', editable: false, enabled: true, level: 'interface', op: '>', threshold: 0, severity: 'warning', for: '2m0s', policy_count: 0, copyable: false, expr: '(ifOperStatus == bool 2) * on(device, iface) (ifAdminStatus == bool 1)' },
|
|
{ id: 'interface_errors', name: 'interface_errors', kind: 'builtin', editable: false, enabled: true, level: 'interface', op: '>', threshold: 0.1, severity: 'warning', for: '0s', policy_count: 0, copyable: false, expr: '100 * rate(ifInErrors[5m])' },
|
|
{ id: 'cpu_high', name: 'cpu_high', kind: 'builtin', editable: false, enabled: true, level: 'device', op: '>', threshold: 90, severity: 'warning', for: '10m0s', policy_count: 0, copyable: true, expr: 'avg by (device) (last_over_time(hrProcessorLoad[15m]))' },
|
|
{ id: 'device_down', name: 'device_down', kind: 'builtin', editable: false, enabled: true, level: 'device', threshold: null, severity: 'critical', for: null, policy_count: 0, copyable: false },
|
|
{ id: 'device_warning', name: 'device_warning', kind: 'builtin', editable: false, enabled: true, level: 'device', threshold: null, severity: 'warning', for: null, policy_count: 0, copyable: false },
|
|
{ id: 'system', name: 'system', kind: 'builtin', editable: false, enabled: true, level: 'system', threshold: null, severity: 'warning', for: null, policy_count: 0, copyable: false },
|
|
]
|
|
|
|
const FIELDS: S['InventoryField'][] = [
|
|
{ name: 'last_seen_age', label: 'Time since last seen', entity: 'device', type: 'duration', ops: ['older_than', 'newer_than'] },
|
|
{ name: 'site', label: 'Site', entity: 'device', type: 'string', ops: ['equals', 'not_equals', 'matches', 'empty', 'not_empty'] },
|
|
{ name: 'if_speed_mbps', label: 'Port speed (Mb/s)', entity: 'interface', type: 'number', ops: ['>', '>=', '<', '<=', '==', '!='] },
|
|
{ name: 'oper_status', label: 'Oper status', entity: 'interface', type: 'number', ops: ['>', '>=', '<', '<=', '==', '!='], enum: { '1': 'up', '2': 'down' } },
|
|
{ name: 'if_alias', label: 'Port alias', entity: 'interface', type: 'string', ops: ['equals', 'not_equals', 'matches', 'empty', 'not_empty'] },
|
|
{ name: 'unreliable', label: 'Counters unreliable', entity: 'interface', type: 'bool', ops: ['is_true', 'is_false'] },
|
|
]
|
|
|
|
const METRICS: S['MetricInfo'][] = [
|
|
{ name: 'hrProcessorLoad', label: 'CPU load', unit: 'percent', type: 'gauge', category: 'health', level: 'component', source: 'profile', interval_seconds: 300, transforms: ['value'] },
|
|
{ name: 'hrStorageUsed', label: 'Storage used', unit: 'count', type: 'gauge', category: 'health', of: 'hrStorageSize', level: 'component', source: 'profile', interval_seconds: 300, transforms: ['value', 'percent_of'] },
|
|
{ name: 'ifHCInOctets', label: 'In octets', unit: 'octets', type: 'counter64', level: 'interface', source: 'profile', interval_seconds: 60, transforms: ['rate'] },
|
|
{ name: 'ifOperStatus', label: 'Oper status', unit: 'enum', type: 'status', level: 'interface', source: 'profile', interval_seconds: 60, transforms: ['value'], enum: { '1': 'up', '2': 'down' } },
|
|
{ name: 'room_temp', label: 'room_temp', unit: '', type: 'gauge', level: 'device', source: 'push', transforms: ['value'] },
|
|
]
|
|
|
|
const problem = (status: number, detail: string): Reply => ({ status, body: { type: 'about:blank', title: 'Error', status, detail } })
|
|
|
|
export class RuleStore {
|
|
private readonly rows: S['AlertRuleInfo'][] = []
|
|
private seq = 0
|
|
/** How many policies name a rule; set by the PolicyStore. */
|
|
countPolicies: (rule: string) => number = () => 0
|
|
readonly calls: { method: string; path: string; body: unknown }[] = []
|
|
|
|
levelOf(rule: string): string | undefined {
|
|
return [...BUILTINS, ...this.rows].find((r) => r.name === rule)?.level
|
|
}
|
|
|
|
private all(): S['AlertRuleInfo'][] {
|
|
return [...BUILTINS, ...[...this.rows].sort((a, b) => a.name.localeCompare(b.name))].map((r) => ({ ...r, policy_count: this.countPolicies(r.name) }))
|
|
}
|
|
|
|
private levelFor(b: S['AlertRuleBody']): 'device' | 'interface' {
|
|
if (b.kind === 'metric') return METRICS.find((x) => x.name === b.spec.metric?.metric)?.level === 'interface' ? 'interface' : 'device'
|
|
const ports = FIELDS.filter((f) => f.entity === 'interface').map((f) => f.name)
|
|
return b.spec.inventory?.conditions.some((c) => ports.includes(c.field)) ? 'interface' : 'device'
|
|
}
|
|
|
|
private info(id: string, b: S['AlertRuleBody'], keep?: S['AlertRuleInfo']): S['AlertRuleInfo'] {
|
|
const m = b.spec.metric
|
|
const level = this.levelFor(b)
|
|
return {
|
|
id, name: b.name, kind: b.kind, editable: true, enabled: b.enabled ?? keep?.enabled ?? true, level, op: m?.op ?? '>', threshold: m?.threshold ?? 0,
|
|
severity: b.severity, for: b.for ?? '0s', summary: b.summary, spec: b.spec, expr: m ? `last_over_time(${m.metric}[${m.window ?? '10m'}])` : undefined, policy_count: 0, copyable: false,
|
|
}
|
|
}
|
|
|
|
/** Dispatches /alert-rules*; undefined when `p` is none of them. */
|
|
route(method: string, p: string, body: () => unknown): Reply | undefined {
|
|
if (!p.startsWith('/alert-rules')) return undefined
|
|
if (method !== 'GET') this.calls.push({ method, path: p, body: method === 'DELETE' ? null : body() })
|
|
if (p === '/alert-rules') return method === 'GET' ? { status: 200, body: { items: this.all() } } : this.create(body() as S['AlertRuleBody'])
|
|
if (p === '/alert-rules/catalogue') return { status: 200, body: { metrics: METRICS, fields: FIELDS, ops: ['>', '>=', '<', '<=', '==', '!='], window: { default_seconds: 300, max_seconds: 86400 } } }
|
|
if (p === '/alert-rules/test') return this.test(body() as S['AlertRuleBody'])
|
|
const copy = /^\/alert-rules\/([^/]+)\/copy$/.exec(p)
|
|
if (copy) return this.copy(decodeURIComponent(copy[1] as string))
|
|
const one = /^\/alert-rules\/([^/]+)$/.exec(p)
|
|
return one ? this.one(method, decodeURIComponent(one[1] as string), body) : undefined
|
|
}
|
|
|
|
private test(b: S['AlertRuleBody']): Reply {
|
|
const m = b.spec.metric
|
|
if (m && !METRICS.some((x) => x.name === m.metric)) return problem(422, `metric "${m.metric}" is not in the catalogue`)
|
|
const expr = m ? `last_over_time(${m.metric}[${m.window ?? '10m'}])` : ''
|
|
return {
|
|
status: 200,
|
|
body: { expr, level: 'device', entities: 12, breaching: 2, samples: [{ device: 'sw1-x', value: 91, breach: true }, { device: 'sw2-x', value: 95, breach: true }, { device: 'sw3-x', value: 12, breach: false }] },
|
|
}
|
|
}
|
|
|
|
private create(b: S['AlertRuleBody']): Reply {
|
|
if ([...BUILTINS, ...this.rows].some((r) => r.name === b.name)) return problem(409, `rule name "${b.name}" is taken`)
|
|
const v = this.info(`01K9RUL${String(++this.seq).padStart(19, '0')}`, b)
|
|
this.rows.push(v)
|
|
return { status: 201, body: v }
|
|
}
|
|
|
|
private copy(name: string): Reply {
|
|
if (name !== 'cpu_high') return problem(422, `${name} cannot be copied to the builder: it joins two metrics`)
|
|
return this.create({
|
|
name: 'cpu_high_custom', kind: 'metric', severity: 'warning', for: '10m0s',
|
|
spec: { metric: { metric: 'hrProcessorLoad', window: '15m', func: 'last', aggregate: 'avg', op: '>', threshold: 90 } },
|
|
})
|
|
}
|
|
|
|
private one(method: string, id: string, body: () => unknown): Reply {
|
|
const i = this.rows.findIndex((r) => r.id === id)
|
|
const cur = this.rows[i]
|
|
if (!cur) {
|
|
const builtin = BUILTINS.find((r) => r.id === id)
|
|
if (builtin && method === 'GET') return { status: 200, body: builtin }
|
|
return builtin ? problem(409, `rule "${id}" is builtin and cannot be changed`) : problem(404, 'not found')
|
|
}
|
|
if (method === 'DELETE') {
|
|
const n = this.countPolicies(cur.name)
|
|
if (n > 0) return problem(409, `alert policies still bind rule "${cur.name}"`)
|
|
this.rows.splice(i, 1)
|
|
return { status: 204, body: null }
|
|
}
|
|
if (method === 'PUT') {
|
|
const v = this.info(id, body() as S['AlertRuleBody'], cur)
|
|
this.rows[i] = v
|
|
return { status: 200, body: v }
|
|
}
|
|
return { status: 200, body: cur }
|
|
}
|
|
}
|