Files
nmon/internal/alert/integration_rules_test.go
Vibe Coder b529423324 Add custom alert rules built from metrics and inventory fields
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
2026-10-24 00:17:48 +00:00

99 lines
3.9 KiB
Go

//go:build integration && linux
package alert
import (
"context"
"fmt"
"testing"
"time"
"github.com/v10networks/nmon/internal/alertrule"
"github.com/v10networks/nmon/internal/metrics"
"github.com/v10networks/nmon/internal/vmsup"
)
// TestIntegrationBuilderTemplatesAgainstRealStore compiles every combination of transform, function and
// aggregate the builder allows for a catalogue of representative metrics and runs each query through the real
// hot store: all must be accepted and, with data present, return readings.
func TestIntegrationBuilderTemplatesAgainstRealStore(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
sup := startHotStore(ctx, t)
end := time.Now().Add(-2 * time.Minute).Truncate(time.Minute)
var ss []metrics.Sample
for i := 0; i <= 30; i++ {
ts := end.Add(-time.Duration(30-i) * time.Minute)
add := func(name string, v float64, kv ...string) { ss = append(ss, metrics.New(name, v, ts, kv...)) }
add("hrProcessorLoad", 96, "device", "cpu1", "component", "1")
add("hrProcessorLoad", 40, "device", "cpu1", "component", "2")
add("hrStorageUsed", 900, "device", "disk1", "component", "/data")
add("hrStorageSize", 1000, "device", "disk1", "component", "/data")
add("ifInErrors", float64(i)*60, "device", "sw1", "iface", "if1")
add("ifHCInOctets", float64(i)*60*1000, "device", "sw1", "iface", "if1")
add("ifOperStatus", 2, "device", "sw1", "iface", "if1")
add("memTotalReal", 1000, "device", "lin1")
add("room_temp", 31, "device", "room1", "push", "1")
}
q := vmsup.NewQueue(vmsup.StoreHot, sup, vmsup.QueueOptions{MaxAge: 72 * time.Hour})
if err := q.Write(ctx, ss); err != nil {
t.Fatal(err)
}
if err := q.Flush(ctx); err != nil {
t.Fatal(err)
}
cat := alertrule.NewCatalogue([]alertrule.MetricInfo{
{Name: "hrProcessorLoad", Type: "gauge", Level: alertrule.LevelComponent, IntervalSeconds: 60},
{Name: "hrStorageUsed", Type: "gauge", Level: alertrule.LevelComponent, Of: "hrStorageSize", IntervalSeconds: 60},
{Name: "hrStorageSize", Type: "gauge", Level: alertrule.LevelComponent, IntervalSeconds: 60},
{Name: "ifInErrors", Type: "counter32", Level: alertrule.LevelInterface, IntervalSeconds: 60},
{Name: "ifHCInOctets", Type: "counter64", Level: alertrule.LevelInterface, IntervalSeconds: 60},
{Name: "ifOperStatus", Type: "status", Level: alertrule.LevelInterface, IntervalSeconds: 60},
{Name: "memTotalReal", Type: "gauge", Level: alertrule.LevelDevice, IntervalSeconds: 60},
{Name: "room_temp", Type: "gauge", Level: alertrule.LevelDevice, Source: alertrule.SourcePush},
})
var specs []alertrule.MetricSpec
for _, m := range cat.List() {
for _, tr := range m.Transforms {
funcs := []string{"last", "avg", "max", "min"}
if tr == alertrule.TransformRate {
funcs = []string{"avg"}
}
aggs := []string{"each"}
if m.Level == alertrule.LevelComponent {
aggs = append(aggs, "max", "min", "avg", "sum")
}
for _, f := range funcs {
for _, a := range aggs {
specs = append(specs, alertrule.MetricSpec{Metric: m.Name, Transform: tr, Func: f, Aggregate: a, Window: "10m", Op: ">=", Threshold: -1e18})
}
}
}
}
// Retry until the asynchronous ingest makes the data searchable.
deadline := time.Now().Add(40 * time.Second)
for _, sp := range specs {
for {
c, err := alertrule.CompileMetric(&sp, cat, time.Minute)
if err != nil {
t.Fatalf("%+v: %v", sp, err)
}
rule := Rule{Name: "t", Severity: SevInfo, Expr: c.Expr, Op: c.Op, Threshold: c.Threshold, Labels: c.Labels, Summary: "s", Description: "d"}
rds, err := Probe(ctx, vmsup.NewQuerier(sup), StoreHot, rule, time.Now())
if err == nil && len(rds) > 0 {
for _, rd := range rds {
if !rd.Breach {
t.Errorf("%s: %+v does not breach threshold -1e18", fmt.Sprint(sp), rd)
}
}
break
}
if time.Now().After(deadline) {
t.Fatalf("%s %+v: no readings (err %v)", c.Expr, sp, err)
}
time.Sleep(time.Second)
}
}
}