package api_test import ( "bytes" "context" "encoding/json" "net/http" "strings" "testing" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) func TestAlertmanagerMonitor(t *testing.T) { e := newEnv(t) owner := e.browser(t) owner.signup("o@"+uniq("am")+".test", uniq("am-")) st, body := owner.do("POST", "/api/v1/org/alertmanager/receivers", map[string]any{"name": "prod"}) if st != http.StatusCreated { t.Fatalf("create receiver = %d %v", st, body) } hook := body["url"].(string) token := hook[strings.LastIndex(hook, "/")+1:] st, body = owner.do("POST", "/api/v1/org/monitors", map[string]any{ "name": "Shop errors", "type": "alertmanager", "interval_seconds": 60, "config": map[string]any{"matchers": []map[string]string{ {"label": "alertname", "op": "=", "value": "HighErrorRate"}, {"label": "severity", "op": "=~", "value": "critical|page"}, }}, }) if st != http.StatusCreated { t.Fatalf("create monitor = %d %v", st, body) } monitor := body["id"].(string) send := func(url, auth string, alerts ...map[string]any) int { t.Helper() raw, _ := json.Marshal(map[string]any{"version": "4", "status": "firing", "alerts": alerts}) req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(raw)) req.Header.Set("Content-Type", "application/json") if auth != "" { req.Header.Set("Authorization", "Bearer "+auth) } resp, err := e.srv.Client().Do(req) if err != nil { t.Fatal(err) } _ = resp.Body.Close() return resp.StatusCode } alert := func(fp, status, name, severity, service string) map[string]any { return map[string]any{ "status": status, "fingerprint": fp, "startsAt": time.Now().Add(-time.Minute), "labels": map[string]string{"alertname": name, "severity": severity, "service": service}, "annotations": map[string]string{"summary": "Error rate above 5%"}, } } open := func() bool { _, b := owner.do("GET", "/api/v1/org/incidents", nil) for _, i := range b["incidents"].([]any) { if i.(map[string]any)["resolved_at"] == nil { return true } } return false } if st := send(e.srv.URL+"/am/uam_wrong", "", alert("a1", "firing", "HighErrorRate", "critical", "shop")); st != http.StatusUnauthorized { t.Errorf("wrong token = %d, want 401", st) } if st := send(hook, "", alert("a1", "firing", "HighErrorRate", "critical", "shop"), alert("a2", "firing", "DiskFull", "warning", "db")); st != http.StatusNoContent { t.Fatalf("webhook = %d", st) } if !open() { t.Fatal("a matching firing alert opened no incident") } _, list := owner.do("GET", "/api/v1/org/monitors", nil) if !strings.Contains(mustJSON(list), "1 firing: HighErrorRate: Error rate above 5%") { t.Errorf("result message missing: %s", mustJSON(list)) } // The overview shows which alerts no monitor follows, with a way to add one. _, alerts := owner.do("GET", "/api/v1/org/alertmanager/alerts", nil) var followed, unfollowed int for _, a := range alerts["alerts"].([]any) { if len(a.(map[string]any)["monitors"].([]any)) > 0 { followed++ } else { unfollowed++ } } if followed != 1 || unfollowed != 1 { t.Errorf("alerts followed/unfollowed = %d/%d, want 1/1", followed, unfollowed) } _, _, page := owner.page("/settings/alertmanager") if !strings.Contains(page, "/monitors/new?") || !strings.Contains(page, "DiskFull") { t.Error("the overview does not offer to create a monitor for DiskFull") } _, _, editor := owner.page("/monitors/new?type=alertmanager&name=DiskFull&m=alertname%3DDiskFull&m=service%3Ddb") if !strings.Contains(editor, `value="DiskFull"`) || !strings.Contains(editor, `value="db"`) { t.Error("the editor is not prefilled from the alert") } // Resolved, sent with the token as bearer. if st := send(e.srv.URL+"/am", token, alert("a1", "resolved", "HighErrorRate", "critical", "shop")); st != http.StatusNoContent { t.Fatalf("bearer webhook = %d", st) } if open() { t.Fatal("the resolved alert did not resolve the incident") } // An alert Alertmanager stopped repeating ends after the stale period. send(hook, "", alert("a3", "firing", "HighErrorRate", "page", "shop")) if !open() { t.Fatal("no incident for the second alert") } ctx := context.Background() org := uuid.MustParse(owner.orgID()) if err := e.asSystem(t, func(tx pgx.Tx) error { _, err := tx.Exec(ctx, `UPDATE alertmanager_alerts SET updated_at = now() - interval '25 hours' WHERE org_id = $1 AND fingerprint = 'a3'`, org) return err }); err != nil { t.Fatal(err) } if err := e.api.CheckAlertmanagerMonitors(ctx, &org, time.Now(), true); err != nil { t.Fatal(err) } if open() { t.Error("a stale alert still holds the monitor down") } // Other organizations see none of it. other := e.browser(t) other.signup("x@"+uniq("am")+".test", uniq("amx-")) if _, oa := other.do("GET", "/api/v1/org/alertmanager/alerts", nil); len(oa["alerts"].([]any)) != 0 { t.Error("another organization sees the alerts") } _ = monitor }