From 98bdb3c28241c015dfd6ba4c8b506f4f99614d66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 15:59:56 +0100 Subject: [PATCH] feat(check): alertmanager monitors with Prometheus label matchers Refs #91 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/check/alertmanager.go | 99 +++++++++++++++++++++++++++++ internal/check/alertmanager_test.go | 48 ++++++++++++++ internal/check/check.go | 13 ++-- 3 files changed, 155 insertions(+), 5 deletions(-) create mode 100644 internal/check/alertmanager.go create mode 100644 internal/check/alertmanager_test.go diff --git a/internal/check/alertmanager.go b/internal/check/alertmanager.go new file mode 100644 index 0000000..1a23cd2 --- /dev/null +++ b/internal/check/alertmanager.go @@ -0,0 +1,99 @@ +package check + +import ( + "context" + "encoding/json" + "regexp" + "slices" +) + +// AlertmanagerConfig configures a monitor fed by Alertmanager: it is down +// while an alert matching every matcher fires. +type AlertmanagerConfig struct { + Matchers []Matcher `json:"matchers"` + // StaleHours ends a firing alert that Alertmanager has not repeated for + // this long, so a lost "resolved" message cannot keep a monitor down + // forever. It must exceed Alertmanager's repeat_interval (4h by default). + StaleHours int `json:"stale_hours"` +} + +// Matcher compares one label the way Prometheus and Alertmanager do: +// = and != compare text, =~ and !~ match a fully anchored regular +// expression. A missing label counts as empty. +type Matcher struct { + Label string `json:"label"` + Op string `json:"op"` + Value string `json:"value"` +} + +// DefaultStaleHours applies when no stale period is set. +const DefaultStaleHours = 24 + +var ( + labelName = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`) + matcherOps = []string{"=", "!=", "=~", "!~"} +) + +type alertmanagerCheck struct{} + +func (alertmanagerCheck) validate(_ string, config json.RawMessage) (json.RawMessage, error) { + c, err := decode[AlertmanagerConfig](config) + if err != nil { + return nil, err + } + // Forms send empty rows for unused matcher slots. + c.Matchers = slices.DeleteFunc(c.Matchers, func(m Matcher) bool { return m.Label == "" }) + if len(c.Matchers) == 0 || len(c.Matchers) > 20 { + return nil, invalid("invalid_matchers") + } + for _, m := range c.Matchers { + if !labelName.MatchString(m.Label) || !slices.Contains(matcherOps, m.Op) || len(m.Value) > 500 { + return nil, invalid("invalid_matchers") + } + if _, err := m.compile(); err != nil { + return nil, invalid("invalid_matchers") + } + } + if c.StaleHours == 0 { + c.StaleHours = DefaultStaleHours + } + if c.StaleHours < 1 || c.StaleHours > 24*30 { + return nil, invalid("invalid_stale_hours") + } + return encode(c), nil +} + +func (alertmanagerCheck) run(context.Context, Spec) Outcome { + return Outcome{Error: "alertmanager monitors are not run by checkers"} +} + +func (m Matcher) compile() (*regexp.Regexp, error) { + if m.Op != "=~" && m.Op != "!~" { + return nil, nil + } + return regexp.Compile("^(?:" + m.Value + ")$") +} + +// Matches reports whether labels satisfy every matcher of c. +func (c AlertmanagerConfig) Matches(labels map[string]string) bool { + for _, m := range c.Matchers { + v := labels[m.Label] + var ok bool + switch m.Op { + case "=": + ok = v == m.Value + case "!=": + ok = v != m.Value + default: + re, err := m.compile() + if err != nil { + return false + } + ok = re.MatchString(v) == (m.Op == "=~") + } + if !ok { + return false + } + } + return true +} diff --git a/internal/check/alertmanager_test.go b/internal/check/alertmanager_test.go new file mode 100644 index 0000000..1db8397 --- /dev/null +++ b/internal/check/alertmanager_test.go @@ -0,0 +1,48 @@ +package check + +import ( + "encoding/json" + "testing" +) + +func TestAlertmanagerMatchers(t *testing.T) { + c := AlertmanagerConfig{Matchers: []Matcher{ + {Label: "service", Op: "=", Value: "shop"}, + {Label: "severity", Op: "=~", Value: "critical|page"}, + {Label: "env", Op: "!=", Value: "staging"}, + {Label: "team", Op: "!~", Value: "infra.*"}, + }} + for _, tc := range []struct { + labels map[string]string + want bool + }{ + {map[string]string{"service": "shop", "severity": "critical"}, true}, + {map[string]string{"service": "shop", "severity": "page", "env": "prod", "team": "web"}, true}, + {map[string]string{"service": "shop", "severity": "warning"}, false}, + {map[string]string{"service": "shop", "severity": "critical-ish"}, false}, // anchored + {map[string]string{"service": "shop", "severity": "critical", "env": "staging"}, false}, + {map[string]string{"service": "shop", "severity": "critical", "team": "infra-db"}, false}, + {map[string]string{"severity": "critical"}, false}, + } { + if got := c.Matches(tc.labels); got != tc.want { + t.Errorf("Matches(%v) = %t, want %t", tc.labels, got, tc.want) + } + } +} + +func TestAlertmanagerValidate(t *testing.T) { + cfg, err := Validate(Alertmanager, "", json.RawMessage(`{"matchers":[{"label":"alertname","op":"=","value":"Down"},{"label":"","op":"=","value":""}]}`)) + if err != nil { + t.Fatal(err) + } + var c AlertmanagerConfig + _ = json.Unmarshal(cfg, &c) + if len(c.Matchers) != 1 || c.StaleHours != DefaultStaleHours { + t.Errorf("normalized = %+v", c) + } + for _, bad := range []string{`{"matchers":[]}`, `{"matchers":[{"label":"1x","op":"=","value":"a"}]}`, `{"matchers":[{"label":"a","op":"=~","value":"("}]}`, `{"matchers":[{"label":"a","op":"~","value":"a"}]}`} { + if _, err := Validate(Alertmanager, "", json.RawMessage(bad)); err == nil { + t.Errorf("Validate(%s) accepted", bad) + } + } +} diff --git a/internal/check/check.go b/internal/check/check.go index 7e2440a..d34c349 100644 --- a/internal/check/check.go +++ b/internal/check/check.go @@ -29,13 +29,15 @@ const ( // Heartbeat monitors are pinged by the monitored job; no checker runs // them. Heartbeat Type = "heartbeat" + // Alertmanager monitors follow alerts that Alertmanager sends us. + Alertmanager Type = "alertmanager" ) // Types lists every check type. -var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Heartbeat} +var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Heartbeat, Alertmanager} // Passive reports whether t is reported to us rather than run by checkers. -func Passive(t Type) bool { return t == Heartbeat } +func Passive(t Type) bool { return t == Heartbeat || t == Alertmanager } // Spec is everything needed to run one check. type Spec struct { @@ -93,9 +95,10 @@ var impls = map[Type]impl{ DNS: dnsCheck{}, TLS: tlsCheck{}, - JSON: jsonCheck{}, - Prometheus: prometheusCheck{}, - Heartbeat: heartbeatCheck{}, + JSON: jsonCheck{}, + Prometheus: prometheusCheck{}, + Heartbeat: heartbeatCheck{}, + Alertmanager: alertmanagerCheck{}, } // Validate checks target and config for type t and returns the normalized