package api import ( "context" "encoding/json" "errors" "fmt" "net/http" "net/url" "slices" "sort" "strings" "time" "github.com/a-h/templ" "github.com/gin-gonic/gin" "github.com/google/uuid" "github.com/jackc/pgx/v5" "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" "git.zb-server.de/ZB-Server/uptimesebi/internal/authz" "git.zb-server.de/ZB-Server/uptimesebi/internal/check" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" ) // Alertmanager feeds monitors: it sends its alerts to a receiver URL of an // organization, and a monitor of type alertmanager is down while an alert // matching its label matchers fires. const ( alertmanagerRegion = "alertmanager" // receiverTokenPrefix tells receiver tokens apart from API tokens. receiverTokenPrefix = "uam_" // maxAlertmanagerBody bounds one webhook; Alertmanager batches alerts // per group, and its default limit is far lower. maxAlertmanagerBody = 4 << 20 // keepAlerts outlasts the longest stale period a monitor may set. keepAlerts = 31 * 24 * time.Hour ) // alertmanagerWebhook is Alertmanager's webhook payload (version 4). type alertmanagerWebhook struct { Version string `json:"version"` Status string `json:"status"` Alerts []struct { Status string `json:"status"` Labels map[string]string `json:"labels"` Annotations map[string]string `json:"annotations"` StartsAt time.Time `json:"startsAt"` GeneratorURL string `json:"generatorURL"` Fingerprint string `json:"fingerprint"` } `json:"alerts"` } func (s *Server) mountAlertmanager(r gin.IRouter) { r.POST("/am", s.alertmanagerWebhook) r.POST("/am/:token", s.alertmanagerWebhook) } // alertmanagerWebhook takes the receiver token from the path or, as // Alertmanager's http_config can send it, as a bearer token. func (s *Server) alertmanagerWebhook(c *gin.Context) { tok := c.Param("token") if tok == "" { tok = bearerToken(c) } if !strings.HasPrefix(tok, receiverTokenPrefix) { fail(c, http.StatusUnauthorized, "unauthenticated") return } ctx := c.Request.Context() if !s.limit(c, "am:"+tok[:min(len(tok), 16)], 600, time.Minute) { return } var payload alertmanagerWebhook if err := json.NewDecoder(http.MaxBytesReader(c.Writer, c.Request.Body, maxAlertmanagerBody)).Decode(&payload); err != nil { fail(c, http.StatusBadRequest, "invalid_input") return } var receiver store.AlertmanagerReceiverByHashRow err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error if receiver, err = q.AlertmanagerReceiverByHash(ctx, HashToken(tok)); err != nil { return err } for _, a := range payload.Alerts { if a.Fingerprint == "" || len(a.Fingerprint) > 200 || (a.Status != "firing" && a.Status != "resolved") { continue } labels, _ := json.Marshal(nonNil(a.Labels)) annotations, _ := json.Marshal(nonNil(a.Annotations)) if err := q.UpsertAlertmanagerAlert(ctx, store.UpsertAlertmanagerAlertParams{ OrgID: receiver.OrgID, Fingerprint: a.Fingerprint, ReceiverID: receiver.ID, Status: a.Status, Labels: labels, Annotations: annotations, StartsAt: a.StartsAt, GeneratorUrl: truncate(a.GeneratorURL, 2000), }); err != nil { return err } } return nil }) if errors.Is(err, pgx.ErrNoRows) { fail(c, http.StatusUnauthorized, "unauthenticated") return } if err != nil { internalError(c, err) return } // State changes show at once; unchanged monitors wait for their interval. if err := s.CheckAlertmanagerMonitors(ctx, &receiver.OrgID, time.Now(), true); err != nil { s.log.ErrorContext(ctx, "evaluating alertmanager monitors failed", "error", err) } c.Status(http.StatusNoContent) } func nonNil(m map[string]string) map[string]string { if m == nil { return map[string]string{} } return m } // firingAlert is an alert of the overview and of monitor evaluation. type firingAlert struct { Fingerprint string `json:"fingerprint"` Labels map[string]string `json:"labels"` Annotations map[string]string `json:"annotations"` StartsAt time.Time `json:"starts_at"` UpdatedAt time.Time `json:"updated_at"` GeneratorURL string `json:"generator_url,omitempty"` } func loadFiringAlerts(ctx context.Context, q *store.Queries, org uuid.UUID, since time.Time) ([]firingAlert, error) { rows, err := q.FiringAlerts(ctx, store.FiringAlertsParams{OrgID: org, UpdatedAt: since}) out := make([]firingAlert, 0, len(rows)) for _, r := range rows { a := firingAlert{Fingerprint: r.Fingerprint, StartsAt: r.StartsAt, UpdatedAt: r.UpdatedAt, GeneratorURL: r.GeneratorUrl} _ = json.Unmarshal(r.Labels, &a.Labels) _ = json.Unmarshal(r.Annotations, &a.Annotations) out = append(out, a) } return out, err } // alertSummary names an alert for result messages: alertname, the summary // annotation if any. func alertSummary(a firingAlert) string { name := a.Labels["alertname"] if name == "" { name = a.Fingerprint } if sum := a.Annotations["summary"]; sum != "" { return name + ": " + sum } return name } // CheckAlertmanagerMonitors records the state of alertmanager monitors, of // org or of all organizations. On a webhook (changed) it records monitors // whose state differs from their last result; otherwise it records those // whose interval has passed, so charts and the SLA have results to show. func (s *Server) CheckAlertmanagerMonitors(ctx context.Context, org *uuid.UUID, now time.Time, changed bool) error { var ( monitors []store.AlertmanagerMonitorsRow alerts = map[uuid.UUID][]firingAlert{} latest = map[uuid.UUID]store.LatestResultForMonitorRow{} ) err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error if monitors, err = q.AlertmanagerMonitors(ctx, org); err != nil { return err } for _, m := range monitors { if _, ok := alerts[m.OrgID]; !ok { // Alerts older than the longest stale period are filtered // per monitor below. if alerts[m.OrgID], err = loadFiringAlerts(ctx, q, m.OrgID, now.Add(-30*24*time.Hour)); err != nil { return err } } if changed { r, err := q.LatestResultForMonitor(ctx, store.LatestResultForMonitorParams{OrgID: m.OrgID, MonitorID: m.ID}) if err != nil && !errors.Is(err, pgx.ErrNoRows) { return err } if err == nil { latest[m.ID] = r } } } return nil }) if err != nil { return err } for _, m := range monitors { var cfg check.AlertmanagerConfig _ = json.Unmarshal(m.Config, &cfg) stale := now.Add(-time.Duration(max(cfg.StaleHours, 1)) * time.Hour) var matching []string for _, a := range alerts[m.OrgID] { if a.UpdatedAt.After(stale) && cfg.Matches(a.Labels) { matching = append(matching, alertSummary(a)) } } ok := len(matching) == 0 msg := "" if !ok { sort.Strings(matching) msg = fmt.Sprintf("%d firing: %s", len(matching), strings.Join(matching, "; ")) } if changed { last, seen := latest[m.ID] if seen && last.Ok == ok && last.Error == msg { continue } } else if now.Sub(m.LastResult) < time.Duration(m.IntervalSeconds)*time.Second { continue } if err := s.recordPassive(ctx, alertmanagerRegion, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, now); err != nil { return err } } return nil } type receiverView struct { ID uuid.UUID `json:"id"` Name string `json:"name"` Prefix string `json:"prefix"` CreatedAt time.Time `json:"created_at"` LastReceivedAt *time.Time `json:"last_received_at"` } type receiverRequest struct { Name string `json:"name" binding:"required,max=100"` } func (s *Server) listReceivers(c *gin.Context) { p := current(c) ctx := c.Request.Context() var rows []store.ListAlertmanagerReceiversRow err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error rows, err = q.ListAlertmanagerReceivers(ctx) return err }) if err != nil { internalError(c, err) return } out := make([]receiverView, len(rows)) for i, r := range rows { out[i] = receiverView{ID: r.ID, Name: r.Name, Prefix: r.Prefix, CreatedAt: r.CreatedAt, LastReceivedAt: r.LastReceivedAt} } c.JSON(http.StatusOK, gin.H{"receivers": out}) } // createReceiver returns the webhook URL once; only its hash is kept. func (s *Server) createReceiver(c *gin.Context) { var req receiverRequest if !bind(c, &req) { return } p := current(c) ctx := c.Request.Context() tok := receiverTokenPrefix + auth.RandomToken() var row store.CreateAlertmanagerReceiverRow err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error row, err = q.CreateAlertmanagerReceiver(ctx, store.CreateAlertmanagerReceiverParams{ OrgID: p.Org.ID, Name: strings.TrimSpace(req.Name), TokenHash: HashToken(tok), Prefix: tok[:len(receiverTokenPrefix)+6], }) return err }) if err != nil { internalError(c, err) return } c.JSON(http.StatusCreated, gin.H{ "receiver": receiverView{ID: row.ID, Name: row.Name, Prefix: row.Prefix, CreatedAt: row.CreatedAt}, "url": s.alertmanagerURL(tok), }) } func (s *Server) alertmanagerURL(tok string) string { return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/am/" + tok } func (s *Server) deleteReceiver(c *gin.Context) { id, err := uuid.Parse(c.Param("id")) if err != nil { fail(c, http.StatusNotFound, "not_found") return } p := current(c) ctx := c.Request.Context() var n int64 err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error n, err = q.DeleteAlertmanagerReceiver(ctx, id) return err }) if err != nil { internalError(c, err) return } if n == 0 { fail(c, http.StatusNotFound, "not_found") return } c.Status(http.StatusNoContent) } // alertView is a firing alert with the monitors that follow it. type alertView struct { firingAlert Monitors []alertMonitorRef `json:"monitors"` } type alertMonitorRef struct { ID uuid.UUID `json:"id"` Name string `json:"name"` } // firingAlertViews lists the organization's firing alerts and which // monitors they hold down, so alerts no monitor follows stand out. func (s *Server) firingAlertViews(ctx context.Context, p *principal) ([]alertView, error) { now := time.Now() var ( alerts []firingAlert monitors []store.AlertmanagerMonitorsRow ) err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error if alerts, err = loadFiringAlerts(ctx, q, p.Org.ID, now.Add(-time.Duration(check.DefaultStaleHours)*time.Hour)); err != nil { return err } monitors, err = q.AlertmanagerMonitors(ctx, &p.Org.ID) return err }) if err != nil { return nil, err } out := make([]alertView, len(alerts)) for i, a := range alerts { out[i] = alertView{firingAlert: a, Monitors: []alertMonitorRef{}} for _, m := range monitors { var cfg check.AlertmanagerConfig _ = json.Unmarshal(m.Config, &cfg) if cfg.Matches(a.Labels) { out[i].Monitors = append(out[i].Monitors, alertMonitorRef{ID: m.ID, Name: m.Name}) } } } return out, nil } func (s *Server) listFiringAlerts(c *gin.Context) { out, err := s.firingAlertViews(c.Request.Context(), current(c)) if err != nil { internalError(c, err) return } c.JSON(http.StatusOK, gin.H{"alerts": out}) } // suggestedMatchers proposes matchers for a monitor following a: its // alertname and the labels that usually tell services apart. func suggestedMatchers(a firingAlert) []check.Matcher { var out []check.Matcher for _, l := range []string{"alertname", "service", "job", "namespace", "instance"} { if v, ok := a.Labels[l]; ok && v != "" { out = append(out, check.Matcher{Label: l, Op: "=", Value: v}) } if len(out) == 3 { break } } return slices.Clip(out) } func (s *Server) alertmanagerPage(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { ctx := c.Request.Context() alerts, err := s.firingAlertViews(ctx, p) if err != nil { return nil, err } v := web.AlertmanagerView{CanManage: p.Grants.Can(authz.OrgManage)} for _, a := range alerts { row := web.AlertRow{ Name: a.Labels["alertname"], Summary: a.Annotations["summary"], Since: a.StartsAt.Local().Format("2006-01-02 15:04"), Labels: sortedLabels(a.Labels), } if row.Name == "" { row.Name = a.Fingerprint } for _, m := range a.Monitors { row.Monitors = append(row.Monitors, web.CheckerLink{URL: "/monitors/" + m.ID.String(), Label: m.Name}) } q := url.Values{"type": {string(check.Alertmanager)}, "name": {row.Name}} for _, m := range suggestedMatchers(a.firingAlert) { q.Add("m", m.Label+"="+m.Value) } row.CreateURL = "/monitors/new?" + q.Encode() v.Alerts = append(v.Alerts, row) } if v.CanManage { var rows []store.ListAlertmanagerReceiversRow err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { var err error rows, err = q.ListAlertmanagerReceivers(ctx) return err }) if err != nil { return nil, err } for _, r := range rows { row := web.ReceiverRow{ID: r.ID.String(), Name: r.Name, Prefix: r.Prefix, Created: r.CreatedAt.Local().Format("2006-01-02"), LastSeen: "–"} if r.LastReceivedAt != nil { row.LastSeen = r.LastReceivedAt.Local().Format("2006-01-02 15:04") } v.Receivers = append(v.Receivers, row) } } return web.AlertmanagerPage(page, me, v), nil } func sortedLabels(labels map[string]string) [][2]string { keys := make([]string, 0, len(labels)) for k := range labels { keys = append(keys, k) } slices.Sort(keys) out := make([][2]string, len(keys)) for i, k := range keys { out[i] = [2]string{k, labels[k]} } return out }