feat(alerting): add monitor alert groups with default routing
This commit is contained in:
1 parent
52819e64bb
commit
8544e5a585
26 files changed
+2938
-1473
No files matched your search
@@ -0,0 +1,170 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
||||
)
|
||||
|
||||
type alertGroupRequest struct {
|
||||
Name string `json:"name" binding:"required,max=100"`
|
||||
ChannelIDs []uuid.UUID `json:"channel_ids" binding:"max=200"`
|
||||
}
|
||||
|
||||
type alertGroupView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
ChannelIDs []uuid.UUID `json:"channel_ids"`
|
||||
}
|
||||
|
||||
var errInvalidAlertGroup = errors.New("api: invalid alert group")
|
||||
var errInvalidChannel = errors.New("api: invalid notification channel")
|
||||
|
||||
func (s *Server) listAlertGroups(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
out := []alertGroupView{}
|
||||
err := s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
rows, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, row := range rows {
|
||||
out = append(out, alertGroupView{ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, ChannelIDs: row.ChannelIds})
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{"alert_groups": out})
|
||||
}
|
||||
|
||||
func (s *Server) saveAlertGroup(c *gin.Context) {
|
||||
var req alertGroupRequest
|
||||
if !bind(c, &req) {
|
||||
return
|
||||
}
|
||||
req.Name = strings.TrimSpace(req.Name)
|
||||
if req.Name == "" {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_input")
|
||||
return
|
||||
}
|
||||
var id uuid.UUID
|
||||
if c.Param("id") != "" {
|
||||
var err error
|
||||
id, err = uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
p := current(c)
|
||||
var row store.AlertGroup
|
||||
// Stable ordering also avoids deadlocks when concurrent edits share channels.
|
||||
slices.SortFunc(req.ChannelIDs, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
|
||||
req.ChannelIDs = slices.Compact(req.ChannelIDs)
|
||||
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
var err error
|
||||
if c.Param("id") == "" {
|
||||
row, err = q.CreateAlertGroup(ctx, store.CreateAlertGroupParams{OrgID: p.Org.ID, Name: req.Name})
|
||||
} else {
|
||||
row, err = q.UpdateAlertGroup(ctx, store.UpdateAlertGroupParams{ID: id, Name: req.Name})
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := q.DeleteAlertGroupChannels(ctx, row.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, ch := range req.ChannelIDs {
|
||||
n, err := q.AddAlertGroupChannel(ctx, store.AddAlertGroupChannelParams{OrgID: p.Org.ID, GroupID: row.ID, ChannelID: ch})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errInvalidChannel
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errInvalidChannel) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_channel")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
status := http.StatusOK
|
||||
if c.Param("id") == "" {
|
||||
status = http.StatusCreated
|
||||
}
|
||||
if req.ChannelIDs == nil {
|
||||
req.ChannelIDs = []uuid.UUID{}
|
||||
}
|
||||
c.JSON(status, alertGroupView{ID: row.ID, Name: row.Name, IsDefault: row.IsDefault, ChannelIDs: req.ChannelIDs})
|
||||
}
|
||||
|
||||
func (s *Server) deleteAlertGroup(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
fail(c, http.StatusNotFound, "not_found")
|
||||
return
|
||||
}
|
||||
ctx := c.Request.Context()
|
||||
var n int64
|
||||
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
|
||||
n, err = q.DeleteAlertGroup(ctx, id)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
fail(c, http.StatusNotFound, "alert_group_not_deletable")
|
||||
return
|
||||
}
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// setMonitorAlertGroups preserves assignments when ids is omitted. On creation,
|
||||
// the database assigns the default group; an explicit empty list opts out.
|
||||
func setMonitorAlertGroups(ctx context.Context, q *store.Queries, m store.Monitor, ids []uuid.UUID) error {
|
||||
if ids == nil {
|
||||
return nil
|
||||
}
|
||||
if err := q.DeleteMonitorAlertGroups(ctx, m.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
continue
|
||||
}
|
||||
seen[id] = true
|
||||
n, err := q.AddMonitorAlertGroup(ctx, store.AddMonitorAlertGroupParams{OrgID: m.OrgID, MonitorID: m.ID, GroupID: id})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n != 1 {
|
||||
return errInvalidAlertGroup
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAlertGroups(t *testing.T) {
|
||||
e := newEnv(t)
|
||||
owner := e.browser(t)
|
||||
owner.signup("o@"+uniq("ag")+".test", uniq("ag-"))
|
||||
groups := func(b *browser) []any {
|
||||
t.Helper()
|
||||
st, body := b.do("GET", "/api/v1/org/alert-groups", nil)
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("list groups = %d %v", st, body)
|
||||
}
|
||||
return body["alert_groups"].([]any)
|
||||
}
|
||||
initial := groups(owner)
|
||||
if len(initial) != 1 || initial[0].(map[string]any)["is_default"] != true {
|
||||
t.Fatalf("initial groups = %v", initial)
|
||||
}
|
||||
defaultID := initial[0].(map[string]any)["id"].(string)
|
||||
channel := func(b *browser, name string, enabled bool) string {
|
||||
t.Helper()
|
||||
st, body := b.do("POST", "/api/v1/org/channels", map[string]any{"name": name, "type": "webhook", "url": "https://example.test/hook", "enabled": enabled})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create channel = %d %v", st, body)
|
||||
}
|
||||
return body["channel"].(map[string]any)["id"].(string)
|
||||
}
|
||||
selected := channel(owner, "Selected", true)
|
||||
unselected := channel(owner, "Unselected", true)
|
||||
disabled := channel(owner, "Disabled", false)
|
||||
if got := groups(owner)[0].(map[string]any)["channel_ids"].([]any); len(got) != 3 {
|
||||
t.Fatalf("default channels = %v", got)
|
||||
}
|
||||
group := func(name string, channels []string) string {
|
||||
t.Helper()
|
||||
st, body := owner.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": name, "channel_ids": channels})
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create group = %d %v", st, body)
|
||||
}
|
||||
return body["id"].(string)
|
||||
}
|
||||
a := group("Operations", []string{selected, selected, disabled})
|
||||
b := group("Escalation", []string{selected})
|
||||
monitor := map[string]any{"name": "Backup", "type": "heartbeat", "interval_seconds": 3600}
|
||||
st, body := owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
if st != http.StatusCreated {
|
||||
t.Fatalf("create monitor = %d %v", st, body)
|
||||
}
|
||||
id := body["id"].(string)
|
||||
token := body["target"].(string)
|
||||
if got := body["alert_group_ids"].([]any); len(got) != 1 || got[0] != defaultID {
|
||||
t.Fatalf("default monitor assignments = %v", got)
|
||||
}
|
||||
st, _, html := owner.page("/monitors/" + id + "/edit")
|
||||
if st != http.StatusOK || !strings.Contains(html, `name="alert_group_ids"`) || !strings.Contains(html, "Operations") {
|
||||
t.Fatalf("monitor editor = %d, lacks alert groups", st)
|
||||
}
|
||||
st, _, html = owner.page("/settings/channels")
|
||||
if st != http.StatusOK || !strings.Contains(html, "/org/alert-groups/"+a) {
|
||||
t.Fatalf("settings = %d, lacks alert group editor", st)
|
||||
}
|
||||
monitor["alert_group_ids"] = []string{a, b, a}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("assign groups = %d %v", st, body)
|
||||
}
|
||||
delete(monitor, "alert_group_ids")
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("preserve assignments = %d %v", st, body)
|
||||
}
|
||||
// Exercise actual incident transitions and their outbox, including recovery.
|
||||
for _, suffix := range []string{"/fail", ""} {
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+suffix, "text/plain", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("heartbeat %q = %d", suffix, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
count := func(ch string) int {
|
||||
return e.count(t, `SELECT count(*) FROM notifications n JOIN incidents i ON i.id=n.incident_id WHERE i.monitor_id=$1 AND n.channel_id=$2`, id, ch)
|
||||
}
|
||||
if count(selected) != 2 || count(unselected) != 0 || count(disabled) != 0 {
|
||||
t.Fatalf("deliveries selected/unselected/disabled = %d/%d/%d", count(selected), count(unselected), count(disabled))
|
||||
}
|
||||
|
||||
other := e.browser(t)
|
||||
other.signup("x@"+uniq("ag")+".test", uniq("agx-"))
|
||||
foreignGroup := groups(other)[0].(map[string]any)["id"].(string)
|
||||
foreignChannel := channel(other, "Foreign", true)
|
||||
monitor["alert_group_ids"] = []string{foreignGroup}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
expect(t, "foreign monitor assignment", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
expect(t, "foreign assignment on creation", st, body, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Changed", "channel_ids": []string{foreignChannel}})
|
||||
expect(t, "foreign channel assignment", st, body, http.StatusUnprocessableEntity, "invalid_channel")
|
||||
st, body = other.do("PUT", "/api/v1/org/alert-groups/"+a, map[string]any{"name": "Stolen"})
|
||||
expect(t, "foreign group update", st, body, http.StatusNotFound, "not_found")
|
||||
for _, g := range groups(owner) {
|
||||
g := g.(map[string]any)
|
||||
if g["id"] == a && (g["name"] != "Operations" || len(g["channel_ids"].([]any)) != 2) {
|
||||
t.Fatalf("failed update changed group: %v", g)
|
||||
}
|
||||
}
|
||||
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
monitors := body["monitors"].([]any)
|
||||
if len(monitors) != 1 || len(monitors[0].(map[string]any)["alert_group_ids"].([]any)) != 2 {
|
||||
t.Fatalf("failed assignment changed monitors: %v", monitors)
|
||||
}
|
||||
viewer := e.joinVia(t, owner.invite("v@"+uniq("ag")+".test", owner.roleID("viewer")))
|
||||
st, body = viewer.do("POST", "/api/v1/org/alert-groups", map[string]any{"name": "Forbidden"})
|
||||
expect(t, "viewer creates group", st, body, http.StatusForbidden, "forbidden")
|
||||
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+defaultID, nil)
|
||||
expect(t, "protected default", st, body, http.StatusNotFound, "alert_group_not_deletable")
|
||||
st, body = owner.do("PUT", "/api/v1/org/alert-groups/"+defaultID, map[string]any{"name": "Standard", "channel_ids": []string{selected}})
|
||||
if st != http.StatusOK || body["is_default"] != true {
|
||||
t.Fatalf("edit default = %d %v", st, body)
|
||||
}
|
||||
st, body = owner.do("DELETE", "/api/v1/org/alert-groups/"+a, nil)
|
||||
expect(t, "delete custom group", st, body, http.StatusNoContent, "")
|
||||
_, body = owner.do("GET", "/api/v1/org/monitors", nil)
|
||||
assigned := body["monitors"].([]any)[0].(map[string]any)["alert_group_ids"].([]any)
|
||||
if !slices.Equal(assigned, []any{b}) {
|
||||
t.Fatalf("assignments after group deletion = %v", assigned)
|
||||
}
|
||||
monitor["alert_group_ids"] = []string{}
|
||||
st, body = owner.do("PUT", "/api/v1/org/monitors/"+id, monitor)
|
||||
if st != http.StatusOK || len(body["alert_group_ids"].([]any)) != 0 {
|
||||
t.Fatalf("clear assignments = %d %v", st, body)
|
||||
}
|
||||
resp, err := e.srv.Client().Post(e.srv.URL+"/hb/"+token+"/fail", "text/plain", strings.NewReader(""))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || count(selected) != 2 {
|
||||
t.Fatalf("unassigned monitor queued notifications, status=%d count=%d", resp.StatusCode, count(selected))
|
||||
}
|
||||
st, body = owner.do("POST", "/api/v1/org/monitors", monitor)
|
||||
if st != http.StatusCreated || len(body["alert_group_ids"].([]any)) != 0 {
|
||||
t.Fatalf("explicit empty creation = %d %v", st, body)
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,8 @@ func (s *Server) evaluateResults(ctx context.Context, region string, results []a
|
||||
}
|
||||
|
||||
// transition opens or resolves the monitor's incident and queues a
|
||||
// notification for every enabled channel of the org, in one transaction.
|
||||
// notification for every enabled channel assigned to the monitor, in one
|
||||
// transaction.
|
||||
func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow, t evaluate.Transition, at time.Time) error {
|
||||
return s.db.Tx(ctx, tenant.Org(m.OrgID, uuid.Nil), func(q *store.Queries) error {
|
||||
var (
|
||||
@@ -96,7 +97,7 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
channels, err := q.ListEnabledChannelIDs(ctx, m.OrgID)
|
||||
channels, err := q.MonitorChannelIDs(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
+12
-3
@@ -57,10 +57,11 @@ var endpoints = []endpoint{
|
||||
description: "Only monitors the caller may read; header values and heartbeat tokens only for those who may change the monitor.",
|
||||
perm: "monitors.read", resp: obj{"monitors": []monitorView{}}},
|
||||
{method: "POST", path: "/api/v1/org/monitors", tag: "Monitors", summary: "Create a monitor",
|
||||
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`.",
|
||||
description: "`type` is one of http, json, prometheus, tcp, tls, dns, icmp, postgres, mysql, mssql, mongodb, redis, mqtt, kafka, rabbitmq, grpc, smtp, radius, snmp, steam, minecraft, docker, heartbeat or alertmanager (GET /api/v1/org/check-types lists those offered); `config` depends on it (see HTTPConfig, JSONConfig, PrometheusConfig, DNSConfig, TLSConfig, DBConfig, BrokerConfig, GRPCConfig, SMTPConfig, RADIUSConfig, SNMPConfig, GameConfig, DockerConfig, HeartbeatConfig, AlertmanagerConfig). Passwords, RADIUS secrets and SNMP communities are stored encrypted and never returned: `secrets_set` names those set, and an update that leaves one empty keeps it. Heartbeat and alertmanager monitors take neither target nor regions; heartbeats return their `ping_url`. Omit `alert_group_ids` to assign the default alert group; an empty array disables notifications.",
|
||||
perm: "monitors.write", req: monitorRequest{}, status: http.StatusCreated, resp: monitorView{}},
|
||||
{method: "PUT", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Change a monitor", perm: "monitors.write",
|
||||
req: monitorRequest{}, resp: monitorView{}},
|
||||
description: "Omitting alert_group_ids preserves existing assignments; an empty array removes all alert groups.",
|
||||
req: monitorRequest{}, resp: monitorView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/monitors/:id", tag: "Monitors", summary: "Delete a monitor and its history", perm: "monitors.write",
|
||||
status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/monitors/:id/evidence", tag: "Monitors", summary: "What checkers saw: captured responses",
|
||||
@@ -123,10 +124,18 @@ var endpoints = []endpoint{
|
||||
media: "text/html"},
|
||||
|
||||
// Alerting
|
||||
{method: "GET", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "List alert groups and their channels", perm: "notifications.read",
|
||||
resp: obj{"alert_groups": []alertGroupView{}}},
|
||||
{method: "POST", path: "/api/v1/org/alert-groups", tag: "Alerting", summary: "Create an alert group", perm: "notifications.write",
|
||||
req: alertGroupRequest{}, status: http.StatusCreated, resp: alertGroupView{}},
|
||||
{method: "PUT", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Rename an alert group and replace its channels", perm: "notifications.write",
|
||||
req: alertGroupRequest{}, resp: alertGroupView{}},
|
||||
{method: "DELETE", path: "/api/v1/org/alert-groups/:id", tag: "Alerting", summary: "Delete an alert group", perm: "notifications.write",
|
||||
description: "The default group cannot be deleted. Deleting other groups removes their monitor assignments; no fallback group is assigned.", status: http.StatusNoContent},
|
||||
{method: "GET", path: "/api/v1/org/channels", tag: "Alerting", summary: "List notification channels", perm: "notifications.read",
|
||||
resp: obj{"channels": []channelView{}, "email_available": false}},
|
||||
{method: "POST", path: "/api/v1/org/channels", tag: "Alerting", summary: "Create a channel",
|
||||
description: "`type` is webhook (`url`), email (`to`, `locale`) or one of slack, discord, teams, googlechat, mattermost, rocketchat, telegram, matrix, ntfy, gotify, pushover, pushbullet, signal, pagerduty, opsgenie, apprise with their `settings`. Secret settings are stored encrypted and never returned; on update, leaving one empty keeps it. Webhook channels return their signing secret once.",
|
||||
description: "`type` is webhook (`url`), email (`to`, `locale`) or one of slack, discord, teams, googlechat, mattermost, rocketchat, telegram, matrix, ntfy, gotify, pushover, pushbullet, signal, pagerduty, opsgenie, apprise with their `settings`. Secret settings are stored encrypted and never returned; on update, leaving one empty keeps it. Webhook channels return their signing secret once. New channels join the default alert group.",
|
||||
perm: "notifications.write",
|
||||
req: channelRequest{}, status: http.StatusCreated, resp: obj{"channel": channelView{}, "signing_secret": ""}},
|
||||
{method: "PUT", path: "/api/v1/org/channels/:id", tag: "Alerting", summary: "Change a channel", perm: "notifications.write",
|
||||
|
||||
@@ -26,6 +26,9 @@ import (
|
||||
// empty name marks a route deliberately not audited. A test fails for
|
||||
// routes missing here, so new endpoints cannot slip past the log.
|
||||
var auditActions = map[string]string{
|
||||
"POST /api/v1/org/alert-groups": "alert_group.create",
|
||||
"PUT /api/v1/org/alert-groups/:id": "alert_group.update",
|
||||
"DELETE /api/v1/org/alert-groups/:id": "alert_group.delete",
|
||||
"POST /api/v1/locale": "",
|
||||
"POST /api/v1/markdown/preview": "",
|
||||
"POST /api/v1/auth/signup": "account.signup",
|
||||
|
||||
@@ -533,6 +533,24 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
|
||||
if regions, err = q.ListVisibleRegions(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
groups, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var selected []uuid.UUID
|
||||
if idParam != "" {
|
||||
id, err := uuid.Parse(idParam)
|
||||
if err != nil {
|
||||
return pgx.ErrNoRows
|
||||
}
|
||||
selected, err = q.MonitorAlertGroups(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, g := range groups {
|
||||
f.AlertGroups = append(f.AlertGroups, web.AlertGroupOption{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault, Checked: slices.Contains(selected, g.ID) || (idParam == "" && g.IsDefault)})
|
||||
}
|
||||
if idParam == "" {
|
||||
return nil
|
||||
}
|
||||
@@ -747,6 +765,23 @@ func (s *Server) channelsView(c *gin.Context, p *principal, page web.Page, me we
|
||||
}
|
||||
v.Channels = append(v.Channels, web.ChannelRow{ID: r.ID.String(), Name: r.Name, Type: r.Type, Target: target, Enabled: r.Enabled})
|
||||
}
|
||||
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
||||
groups, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, g := range groups {
|
||||
row := web.AlertGroupRow{ID: g.ID.String(), Name: g.Name, Default: g.IsDefault}
|
||||
for _, ch := range rows {
|
||||
row.Channels = append(row.Channels, web.AlertGroupOption{ID: ch.ID.String(), Name: ch.Name, Checked: slices.Contains(g.ChannelIds, ch.ID)})
|
||||
}
|
||||
v.AlertGroups = append(v.AlertGroups, row)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return web.ChannelsPage(page, me, v), nil
|
||||
}
|
||||
|
||||
|
||||
+20
-1
@@ -208,6 +208,7 @@ func (s *Server) sendExport(c *gin.Context, format, name, title string, x any) {
|
||||
}
|
||||
|
||||
type orgExport struct {
|
||||
AlertGroups []alertGroupView `json:"alert_groups"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Organization exportOrg `json:"organization"`
|
||||
Members []exportMember `json:"members"`
|
||||
@@ -255,6 +256,7 @@ type exportGroup struct {
|
||||
}
|
||||
|
||||
type exportMonitor struct {
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
@@ -391,6 +393,22 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
x.Groups = append(x.Groups, exportGroup{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
||||
}
|
||||
|
||||
alertGroups, err := q.ListAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
x.AlertGroups = []alertGroupView{}
|
||||
for _, g := range alertGroups {
|
||||
x.AlertGroups = append(x.AlertGroups, alertGroupView{ID: g.ID, Name: g.Name, IsDefault: g.IsDefault, ChannelIDs: g.ChannelIds})
|
||||
}
|
||||
alertAssignments, err := q.AllMonitorAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
alertGroupsByMonitor := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, a := range alertAssignments {
|
||||
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regionRows, err := q.AllMonitorRegions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -408,7 +426,8 @@ func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, e
|
||||
x.Monitors = append(x.Monitors, exportMonitor{
|
||||
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
||||
TimeoutMS: m.TimeoutMs, Confirmations: m.Confirmations, Enabled: m.Enabled, GroupID: m.GroupID,
|
||||
Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt,
|
||||
AlertGroupIDs: orEmpty(alertGroupsByMonitor[m.ID]),
|
||||
Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,20 @@ func TestExports(t *testing.T) {
|
||||
if st != http.StatusOK {
|
||||
t.Fatalf("org export = %d", st)
|
||||
}
|
||||
var org map[string]any
|
||||
if err := json.Unmarshal(raw, &org); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
groups := org["alert_groups"].([]any)
|
||||
monitors := org["monitors"].([]any)
|
||||
if len(groups) != 1 || len(monitors) != 1 {
|
||||
t.Fatalf("export groups/monitors = %v/%v", groups, monitors)
|
||||
}
|
||||
group := groups[0].(map[string]any)
|
||||
assigned := monitors[0].(map[string]any)["alert_group_ids"].([]any)
|
||||
if group["is_default"] != true || len(group["channel_ids"].([]any)) != 1 || len(assigned) != 1 || assigned[0] != group["id"] {
|
||||
t.Fatalf("export lost alert routing: group=%v assignments=%v", group, assigned)
|
||||
}
|
||||
if !bytes.Contains(raw, []byte(`"Shop"`)) || !bytes.Contains(raw, []byte(`"Hook"`)) {
|
||||
t.Errorf("org export lacks monitor or channel")
|
||||
}
|
||||
|
||||
@@ -36,6 +36,9 @@ type monitorRequest struct {
|
||||
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
|
||||
// GroupID places the monitor in a group; nil keeps it at the top level.
|
||||
GroupID *uuid.UUID `json:"group_id"`
|
||||
// AlertGroupIDs defaults on creation and preserves assignments on update
|
||||
// when omitted. An explicit empty list disables notifications.
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids" binding:"max=100"`
|
||||
}
|
||||
|
||||
type latestView struct {
|
||||
@@ -48,6 +51,7 @@ type latestView struct {
|
||||
}
|
||||
|
||||
type monitorView struct {
|
||||
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
@@ -192,6 +196,14 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
assignments, err := q.AllMonitorAlertGroups(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
alertGroups := map[uuid.UUID][]uuid.UUID{}
|
||||
for _, a := range assignments {
|
||||
alertGroups[a.MonitorID] = append(alertGroups[a.MonitorID], a.GroupID)
|
||||
}
|
||||
regions, err := q.AllMonitorRegions(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -215,6 +227,10 @@ func (s *Server) listMonitors(c *gin.Context) {
|
||||
continue
|
||||
}
|
||||
v := viewMonitor(m, byMonitor[m.ID])
|
||||
v.AlertGroupIDs = alertGroups[m.ID]
|
||||
if v.AlertGroupIDs == nil {
|
||||
v.AlertGroupIDs = []uuid.UUID{}
|
||||
}
|
||||
if !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) {
|
||||
v = redactMonitor(v)
|
||||
}
|
||||
@@ -266,8 +282,19 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setRegions(ctx, q, m, req.Regions)
|
||||
})
|
||||
if errors.Is(err, errInvalidAlertGroup) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
internalError(c, err)
|
||||
return
|
||||
@@ -276,7 +303,9 @@ func (s *Server) createMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusCreated, s.withPingURL(viewMonitor(m, req.Regions)))
|
||||
v := viewMonitor(m, req.Regions)
|
||||
v.AlertGroupIDs = req.AlertGroupIDs
|
||||
c.JSON(http.StatusCreated, s.withPingURL(v))
|
||||
}
|
||||
|
||||
func setRegions(ctx context.Context, q *store.Queries, m store.Monitor, regions []uuid.UUID) error {
|
||||
@@ -372,8 +401,19 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := setMonitorAlertGroups(ctx, q, m, req.AlertGroupIDs); err != nil {
|
||||
return err
|
||||
}
|
||||
req.AlertGroupIDs, err = q.MonitorAlertGroups(ctx, m.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return setRegions(ctx, q, m, req.Regions)
|
||||
})
|
||||
if errors.Is(err, errInvalidAlertGroup) {
|
||||
fail(c, http.StatusUnprocessableEntity, "invalid_alert_group")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errCheckTypeDisabled) {
|
||||
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
|
||||
return
|
||||
@@ -390,7 +430,9 @@ func (s *Server) updateMonitor(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, s.withPingURL(viewMonitor(m, req.Regions)))
|
||||
v := viewMonitor(m, req.Regions)
|
||||
v.AlertGroupIDs = req.AlertGroupIDs
|
||||
c.JSON(http.StatusOK, s.withPingURL(v))
|
||||
}
|
||||
|
||||
func (s *Server) deleteMonitor(c *gin.Context) {
|
||||
|
||||
@@ -190,6 +190,10 @@ func (s *Server) Mount(r gin.IRouter) {
|
||||
org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents)
|
||||
org.GET("/audit", can(authz.AuditRead), s.listOrgAudit)
|
||||
|
||||
org.GET("/alert-groups", can(authz.NotificationsRead), s.listAlertGroups)
|
||||
org.POST("/alert-groups", can(authz.NotificationsWrite), s.saveAlertGroup)
|
||||
org.PUT("/alert-groups/:id", can(authz.NotificationsWrite), s.saveAlertGroup)
|
||||
org.DELETE("/alert-groups/:id", can(authz.NotificationsWrite), s.deleteAlertGroup)
|
||||
org.GET("/channels", can(authz.NotificationsRead), s.listChannels)
|
||||
org.POST("/channels", can(authz.NotificationsWrite), s.createChannel)
|
||||
org.PUT("/channels/:id", can(authz.NotificationsWrite), s.updateChannel)
|
||||
|
||||
Reference in new issue
Block a user