feat(alerting): add monitor alert groups with default routing

This commit is contained in:
Sebastian Unterschütz committed 2026-11-22 18:25:36 +01:00
1 parent 52819e64bb
commit 8544e5a585
26 files changed
+2938 -1473

No files matched your search

+170
View File
@@ -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
}
+154
View File
@@ -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)
}
}
+3 -2
View File
@@ -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
View File
@@ -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",
+3
View File
@@ -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",
+35
View File
@@ -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
View File
@@ -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,
})
}
+14
View File
@@ -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")
}
+44 -2
View File
@@ -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) {
+4
View File
@@ -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)
+16 -1
View File
@@ -18,6 +18,15 @@
"agents.region": "Region",
"agents.revoke_confirm": "Diesen Agent widerrufen? Seine Instanzen hören sofort auf zu arbeiten.",
"agents.token_now": "Kopiere den Token jetzt und setze ihn als UPTIME_AGENT_TOKEN. Er wird nicht erneut angezeigt. Beliebig viele Instanzen können ihn teilen.",
"alert_groups.create": "Gruppe erstellen",
"alert_groups.default": "Standardgruppe",
"alert_groups.delete_confirm": "Diese Alertgruppe löschen? Ihre Monitore benachrichtigen diese Kanäle dann nur noch, wenn eine andere zugeordnete Gruppe sie enthält.",
"alert_groups.intro": "Bündele Benachrichtigungskanäle und ordne die Gruppen Monitoren zu. Neue Monitore und Kanäle werden automatisch der Standardgruppe zugeordnet. Kanäle in mehreren Gruppen erhalten jeden Alert nur einmal.",
"alert_groups.monitor_hint": "Wähle die Gruppen, die Alerts erhalten sollen. Ohne Auswahl werden für diesen Monitor keine Benachrichtigungen verschickt.",
"alert_groups.new": "Neue Alertgruppe",
"alert_groups.no_channels": "Erstelle unten einen Benachrichtigungskanal, um Alerts zu erhalten.",
"alert_groups.save": "Gruppe speichern",
"alert_groups.title": "Alertgruppen",
"alertmanager.config_hint": "Trage sie als Webhook-Empfänger in die alertmanager.yml ein; send_resolved ist nötig, damit Monitore wieder hochgehen.",
"alertmanager.copy_now": "Kopiere die URL jetzt, sie wird nicht erneut angezeigt. Sie enthält ein Geheimnis.",
"alertmanager.create_monitor": "Monitor anlegen",
@@ -43,6 +52,9 @@
"audit.action.agent.create": "Agent erstellt",
"audit.action.agent.delete": "Agent widerrufen",
"audit.action.agent.update": "Agent geändert",
"audit.action.alert_group.create": "Alertgruppe erstellt",
"audit.action.alert_group.delete": "Alertgruppe gelöscht",
"audit.action.alert_group.update": "Alertgruppe geändert",
"audit.action.alertmanager.receiver_create": "Alertmanager-Empfänger angelegt",
"audit.action.alertmanager.receiver_delete": "Alertmanager-Empfänger gelöscht",
"audit.action.auth.login": "Angemeldet",
@@ -259,7 +271,7 @@
"channels.help_splunk": "Der REST-Endpunkt aus der REST-Integration von Splunk On-Call, mit dem Routing-Key am Ende.",
"channels.help_teams": "Nutze die URL eines Teams-Workflows „Bei Empfang einer Webhookanforderung in einem Kanal posten“.",
"channels.help_telegram": "Lege mit @BotFather einen Bot an; die Chat-ID einer Gruppe beginnt mit -100.",
"channels.intro": "Jeder aktive Kanal wird benachrichtigt, wenn ein Monitor in allen seinen Regionen ausfällt und wenn er sich erholt.",
"channels.intro": "Aktivierte Kanäle erhalten Ausfall- und Entwarnungsmeldungen von Monitoren, die ihren Alertgruppen zugeordnet sind.",
"channels.language": "Sprache",
"channels.new_email": "Neuer E-Mail-Kanal",
"channels.new_service": "Weitere Dienste",
@@ -432,6 +444,7 @@
"email.test.body": "Dies ist ein Test. Wenn du ihn lesen kannst, funktioniert der Kanal.",
"email.test.subject": "Testbenachrichtigung von UptimeSebi",
"error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.",
"error.alert_group_not_deletable": "Die Gruppe existiert nicht oder ist die geschützte Standardgruppe.",
"error.all_check_types_disabled": "Lass mindestens einen Check-Typ eingeschaltet.",
"error.already_assigned": "Das Mitglied hat diese Rolle bereits.",
"error.already_member": "Diese Person ist bereits Mitglied.",
@@ -447,10 +460,12 @@
"error.group_cycle": "Eine Gruppe kann nicht in sich selbst oder eine ihrer Untergruppen verschoben werden.",
"error.group_too_deep": "Gruppen lassen sich höchstens acht Ebenen tief verschachteln.",
"error.internal": "Interner Fehler.",
"error.invalid_alert_group": "Eine Alertgruppe existiert nicht in dieser Organisation.",
"error.invalid_assertion_op": "Unbekannter Operator.",
"error.invalid_assertion_path": "Ein Pfad ist ungültig. Nutze durch Punkte getrennte Schlüssel und [n] für Array-Elemente.",
"error.invalid_assertion_value": "Vergleiche mit <, >, ≤ und ≥ brauchen eine Zahl.",
"error.invalid_assertions": "Lege 1 bis 10 Bedingungen an.",
"error.invalid_channel": "Ein Benachrichtigungskanal existiert nicht in dieser Organisation.",
"error.invalid_channel_settings": "Fülle die Pflichtfelder aus; Adressen müssen https-URLs sein.",
"error.invalid_code": "Code ungültig.",
"error.invalid_config": "Die Check-Einstellungen sind ungültig.",
+16 -1
View File
@@ -18,6 +18,15 @@
"agents.region": "Region",
"agents.revoke_confirm": "Revoke this agent? Its instances stop working immediately.",
"agents.token_now": "Copy the token now and set it as UPTIME_AGENT_TOKEN. It will not be shown again. Any number of instances may share it.",
"alert_groups.create": "Create group",
"alert_groups.default": "Default group",
"alert_groups.delete_confirm": "Delete this alert group? Its monitors will no longer notify its channels unless another assigned group includes them.",
"alert_groups.intro": "Bundle notification channels and assign groups to monitors. New monitors and channels are automatically assigned to the default group. Channels shared by several groups receive each alert only once.",
"alert_groups.monitor_hint": "Select the groups that should receive alerts. No selection disables notifications for this monitor.",
"alert_groups.new": "New alert group",
"alert_groups.no_channels": "Create a notification channel below to receive alerts.",
"alert_groups.save": "Save group",
"alert_groups.title": "Alert groups",
"alertmanager.config_hint": "Add it to alertmanager.yml as a webhook receiver; send_resolved is needed so monitors recover.",
"alertmanager.copy_now": "Copy the URL now; it is not shown again. It contains a secret.",
"alertmanager.create_monitor": "Create monitor",
@@ -43,6 +52,9 @@
"audit.action.agent.create": "Agent created",
"audit.action.agent.delete": "Agent revoked",
"audit.action.agent.update": "Agent changed",
"audit.action.alert_group.create": "Alert group created",
"audit.action.alert_group.delete": "Alert group deleted",
"audit.action.alert_group.update": "Alert group changed",
"audit.action.alertmanager.receiver_create": "Alertmanager receiver created",
"audit.action.alertmanager.receiver_delete": "Alertmanager receiver deleted",
"audit.action.auth.login": "Signed in",
@@ -259,7 +271,7 @@
"channels.help_splunk": "The REST endpoint from Splunk On-Call's REST integration, ending in the routing key.",
"channels.help_teams": "Use the URL of a Teams workflow \"Post to a channel when a webhook request is received\".",
"channels.help_telegram": "Create a bot with @BotFather; the chat ID of a group starts with -100.",
"channels.intro": "Every enabled channel is notified when a monitor goes down in all of its regions and when it recovers.",
"channels.intro": "Enabled channels receive outage and recovery alerts from monitors assigned to their alert groups.",
"channels.language": "Language",
"channels.new_email": "New email channel",
"channels.new_service": "Other services",
@@ -432,6 +444,7 @@
"email.test.body": "This is a test. If you can read it, the channel works.",
"email.test.subject": "Test notification from UptimeSebi",
"error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.",
"error.alert_group_not_deletable": "The group does not exist or is the protected default group.",
"error.all_check_types_disabled": "Leave at least one check type on.",
"error.already_assigned": "The member already has this role.",
"error.already_member": "This person is already a member.",
@@ -447,10 +460,12 @@
"error.group_cycle": "A group cannot be placed inside itself or one of its subgroups.",
"error.group_too_deep": "Groups can be nested at most eight levels deep.",
"error.internal": "Internal error.",
"error.invalid_alert_group": "An alert group does not exist in this organization.",
"error.invalid_assertion_op": "Unknown condition operator.",
"error.invalid_assertion_path": "A condition path is invalid. Use keys separated by dots and [n] for array elements.",
"error.invalid_assertion_value": "Comparisons with <, >, ≤ and ≥ need a number.",
"error.invalid_assertions": "Add between 1 and 10 conditions.",
"error.invalid_channel": "A notification channel does not exist in this organization.",
"error.invalid_channel_settings": "Fill in the required fields; addresses must be https URLs.",
"error.invalid_code": "Invalid code.",
"error.invalid_config": "The check settings are not valid.",
+72
View File
@@ -0,0 +1,72 @@
package migrations
import (
"context"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
func TestAlertGroupsBackfill(t *testing.T) {
dsn := os.Getenv("UPTIME_TEST_DATABASE_URL")
if dsn == "" {
t.Skip("UPTIME_TEST_DATABASE_URL not set")
}
ctx := context.Background()
if _, err := Up(ctx, dsn); err != nil {
t.Fatal(err)
}
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
t.Fatal(err)
}
defer func() { _ = conn.Close(ctx) }()
tx, err := conn.Begin(ctx)
if err != nil {
t.Fatal(err)
}
// Exercise both directions inside a transaction; existing test data and
// goose's migration history remain unchanged after rollback.
defer func() { _ = tx.Rollback(ctx) }()
if _, err := tx.Exec(ctx, "SET LOCAL app.scope = 'system'"); err != nil {
t.Fatal(err)
}
raw, err := files.ReadFile("sql/00039_alert_groups.sql")
if err != nil {
t.Fatal(err)
}
up, down, ok := strings.Cut(string(raw), "-- +goose Down")
if !ok {
t.Fatal("missing down migration")
}
if _, err := tx.Exec(ctx, down); err != nil {
t.Fatalf("down: %v", err)
}
orgID := uuid.New()
if _, err := tx.Exec(ctx, `INSERT INTO orgs (id,slug,name) VALUES ($1,$2,'Existing organization')`, orgID, "migration-"+orgID.String()); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, `INSERT INTO monitors (org_id,name,type,target,interval_seconds,timeout_ms) VALUES ($1,'Existing monitor','tcp','example.test:443',60,1000)`, orgID); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, `INSERT INTO notification_channels (org_id,name,type,config) VALUES ($1,'Existing channel','webhook','{}')`, orgID); err != nil {
t.Fatal(err)
}
if _, err := tx.Exec(ctx, up); err != nil {
t.Fatalf("up: %v", err)
}
var groups, monitors, channels int
err = tx.QueryRow(ctx, `SELECT
(SELECT count(*) FROM alert_groups WHERE org_id=$1 AND is_default),
(SELECT count(*) FROM monitor_alert_groups WHERE org_id=$1),
(SELECT count(*) FROM alert_group_channels WHERE org_id=$1)`, orgID).Scan(&groups, &monitors, &channels)
if err != nil {
t.Fatal(err)
}
if groups != 1 || monitors != 1 || channels != 1 {
t.Fatalf("backfilled groups/monitors/channels = %d/%d/%d, want 1/1/1", groups, monitors, channels)
}
}
@@ -0,0 +1,78 @@
-- +goose Up
CREATE TABLE alert_groups (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
name text NOT NULL CHECK (length(name) BETWEEN 1 AND 100),
is_default boolean NOT NULL DEFAULT false,
UNIQUE (id, org_id)
);
CREATE UNIQUE INDEX alert_groups_default_idx ON alert_groups (org_id) WHERE is_default;
ALTER TABLE notification_channels ADD UNIQUE (id, org_id);
CREATE TABLE alert_group_channels (
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
group_id uuid NOT NULL,
channel_id uuid NOT NULL,
PRIMARY KEY (group_id, channel_id),
FOREIGN KEY (group_id, org_id) REFERENCES alert_groups (id, org_id) ON DELETE CASCADE,
FOREIGN KEY (channel_id, org_id) REFERENCES notification_channels (id, org_id) ON DELETE CASCADE
);
CREATE TABLE monitor_alert_groups (
org_id uuid NOT NULL REFERENCES orgs (id) ON DELETE CASCADE,
monitor_id uuid NOT NULL,
group_id uuid NOT NULL,
PRIMARY KEY (monitor_id, group_id),
FOREIGN KEY (monitor_id, org_id) REFERENCES monitors (id, org_id) ON DELETE CASCADE,
FOREIGN KEY (group_id, org_id) REFERENCES alert_groups (id, org_id) ON DELETE CASCADE
);
CREATE INDEX monitor_alert_groups_group_idx ON monitor_alert_groups (group_id);
CREATE INDEX alert_group_channels_channel_idx ON alert_group_channels (channel_id);
INSERT INTO alert_groups (org_id, name, is_default) SELECT id, 'Default', true FROM orgs;
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT c.org_id, g.id, c.id FROM notification_channels c JOIN alert_groups g ON g.org_id = c.org_id AND g.is_default;
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT m.org_id, m.id, g.id FROM monitors m JOIN alert_groups g ON g.org_id = m.org_id AND g.is_default;
-- Defaults apply to every creation path, including CLI and imports.
-- +goose StatementBegin
CREATE FUNCTION alert_groups_defaults() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF TG_TABLE_NAME = 'orgs' THEN
INSERT INTO alert_groups (org_id, name, is_default) VALUES (NEW.id, 'Default', true);
ELSIF TG_TABLE_NAME = 'monitors' THEN
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT NEW.org_id, NEW.id, id FROM alert_groups WHERE org_id = NEW.org_id AND is_default;
ELSE
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT NEW.org_id, id, NEW.id FROM alert_groups WHERE org_id = NEW.org_id AND is_default;
END IF;
RETURN NEW;
END
$$;
-- +goose StatementEnd
CREATE TRIGGER org_alert_group AFTER INSERT ON orgs FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
CREATE TRIGGER monitor_alert_group AFTER INSERT ON monitors FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
CREATE TRIGGER channel_alert_group AFTER INSERT ON notification_channels FOR EACH ROW EXECUTE FUNCTION alert_groups_defaults();
ALTER TABLE alert_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE alert_groups FORCE ROW LEVEL SECURITY;
CREATE POLICY alert_groups_tenant ON alert_groups FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE alert_group_channels ENABLE ROW LEVEL SECURITY;
ALTER TABLE alert_group_channels FORCE ROW LEVEL SECURITY;
CREATE POLICY alert_group_channels_tenant ON alert_group_channels FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
ALTER TABLE monitor_alert_groups ENABLE ROW LEVEL SECURITY;
ALTER TABLE monitor_alert_groups FORCE ROW LEVEL SECURITY;
CREATE POLICY monitor_alert_groups_tenant ON monitor_alert_groups FOR ALL
USING (app_scope_system() OR org_id = app_org_id()) WITH CHECK (app_scope_system() OR org_id = app_org_id());
-- +goose Down
DROP TRIGGER channel_alert_group ON notification_channels;
DROP TRIGGER monitor_alert_group ON monitors;
DROP TRIGGER org_alert_group ON orgs;
DROP FUNCTION alert_groups_defaults();
DROP TABLE monitor_alert_groups;
DROP TABLE alert_group_channels;
DROP TABLE alert_groups;
ALTER TABLE notification_channels DROP CONSTRAINT notification_channels_id_org_id_key;
+240
View File
@@ -0,0 +1,240 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: alert_groups.sql
package store
import (
"context"
"github.com/google/uuid"
)
const addAlertGroupChannel = `-- name: AddAlertGroupChannel :execrows
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT c.org_id, $1, c.id FROM notification_channels c
WHERE c.id = $2 AND c.org_id = $3
ON CONFLICT DO NOTHING
`
type AddAlertGroupChannelParams struct {
GroupID uuid.UUID
ChannelID uuid.UUID
OrgID uuid.UUID
}
func (q *Queries) AddAlertGroupChannel(ctx context.Context, arg AddAlertGroupChannelParams) (int64, error) {
result, err := q.db.Exec(ctx, addAlertGroupChannel, arg.GroupID, arg.ChannelID, arg.OrgID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const addMonitorAlertGroup = `-- name: AddMonitorAlertGroup :execrows
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT g.org_id, $1, g.id FROM alert_groups g
WHERE g.id = $2 AND g.org_id = $3
ON CONFLICT DO NOTHING
`
type AddMonitorAlertGroupParams struct {
MonitorID uuid.UUID
GroupID uuid.UUID
OrgID uuid.UUID
}
func (q *Queries) AddMonitorAlertGroup(ctx context.Context, arg AddMonitorAlertGroupParams) (int64, error) {
result, err := q.db.Exec(ctx, addMonitorAlertGroup, arg.MonitorID, arg.GroupID, arg.OrgID)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const allMonitorAlertGroups = `-- name: AllMonitorAlertGroups :many
SELECT org_id, monitor_id, group_id FROM monitor_alert_groups ORDER BY monitor_id, group_id
`
func (q *Queries) AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error) {
rows, err := q.db.Query(ctx, allMonitorAlertGroups)
if err != nil {
return nil, err
}
defer rows.Close()
items := []MonitorAlertGroup{}
for rows.Next() {
var i MonitorAlertGroup
if err := rows.Scan(&i.OrgID, &i.MonitorID, &i.GroupID); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const createAlertGroup = `-- name: CreateAlertGroup :one
INSERT INTO alert_groups (org_id, name) VALUES ($1, $2) RETURNING id, org_id, name, is_default
`
type CreateAlertGroupParams struct {
OrgID uuid.UUID
Name string
}
func (q *Queries) CreateAlertGroup(ctx context.Context, arg CreateAlertGroupParams) (AlertGroup, error) {
row := q.db.QueryRow(ctx, createAlertGroup, arg.OrgID, arg.Name)
var i AlertGroup
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Name,
&i.IsDefault,
)
return i, err
}
const deleteAlertGroup = `-- name: DeleteAlertGroup :execrows
DELETE FROM alert_groups WHERE id = $1 AND NOT is_default
`
func (q *Queries) DeleteAlertGroup(ctx context.Context, id uuid.UUID) (int64, error) {
result, err := q.db.Exec(ctx, deleteAlertGroup, id)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const deleteAlertGroupChannels = `-- name: DeleteAlertGroupChannels :exec
DELETE FROM alert_group_channels WHERE group_id = $1
`
func (q *Queries) DeleteAlertGroupChannels(ctx context.Context, groupID uuid.UUID) error {
_, err := q.db.Exec(ctx, deleteAlertGroupChannels, groupID)
return err
}
const deleteMonitorAlertGroups = `-- name: DeleteMonitorAlertGroups :exec
DELETE FROM monitor_alert_groups WHERE monitor_id = $1
`
func (q *Queries) DeleteMonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) error {
_, err := q.db.Exec(ctx, deleteMonitorAlertGroups, monitorID)
return err
}
const listAlertGroups = `-- name: ListAlertGroups :many
SELECT g.id, g.org_id, g.name, g.is_default, ARRAY(SELECT c.channel_id FROM alert_group_channels c WHERE c.group_id = g.id ORDER BY c.channel_id)::uuid[] AS channel_ids
FROM alert_groups g ORDER BY g.is_default DESC, g.name, g.id
`
type ListAlertGroupsRow struct {
ID uuid.UUID
OrgID uuid.UUID
Name string
IsDefault bool
ChannelIds []uuid.UUID
}
func (q *Queries) ListAlertGroups(ctx context.Context) ([]ListAlertGroupsRow, error) {
rows, err := q.db.Query(ctx, listAlertGroups)
if err != nil {
return nil, err
}
defer rows.Close()
items := []ListAlertGroupsRow{}
for rows.Next() {
var i ListAlertGroupsRow
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Name,
&i.IsDefault,
&i.ChannelIds,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const monitorAlertGroups = `-- name: MonitorAlertGroups :many
SELECT group_id FROM monitor_alert_groups WHERE monitor_id = $1 ORDER BY group_id
`
func (q *Queries) MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, monitorAlertGroups, monitorID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var group_id uuid.UUID
if err := rows.Scan(&group_id); err != nil {
return nil, err
}
items = append(items, group_id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const monitorChannelIDs = `-- name: MonitorChannelIDs :many
SELECT DISTINCT c.id FROM notification_channels c
JOIN alert_group_channels gc ON gc.channel_id = c.id AND gc.org_id = c.org_id
JOIN monitor_alert_groups mg ON mg.group_id = gc.group_id AND mg.org_id = gc.org_id
WHERE mg.monitor_id = $1 AND c.enabled
`
func (q *Queries) MonitorChannelIDs(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, monitorChannelIDs, monitorID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const updateAlertGroup = `-- name: UpdateAlertGroup :one
UPDATE alert_groups SET name = $2 WHERE id = $1 RETURNING id, org_id, name, is_default
`
type UpdateAlertGroupParams struct {
ID uuid.UUID
Name string
}
func (q *Queries) UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error) {
row := q.db.QueryRow(ctx, updateAlertGroup, arg.ID, arg.Name)
var i AlertGroup
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Name,
&i.IsDefault,
)
return i, err
}
-24
View File
@@ -241,30 +241,6 @@ func (q *Queries) ListChannels(ctx context.Context) ([]NotificationChannel, erro
return items, nil
}
const listEnabledChannelIDs = `-- name: ListEnabledChannelIDs :many
SELECT id FROM notification_channels WHERE org_id = $1 AND enabled
`
func (q *Queries) ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) {
rows, err := q.db.Query(ctx, listEnabledChannelIDs, orgID)
if err != nil {
return nil, err
}
defer rows.Close()
items := []uuid.UUID{}
for rows.Next() {
var id uuid.UUID
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listIncidents = `-- name: ListIncidents :many
SELECT i.id, i.org_id, i.monitor_id, i.started_at, i.resolved_at, i.cause, m.name AS monitor_name
FROM incidents i
+19
View File
@@ -41,6 +41,19 @@ type AgentStorage struct {
Modified time.Time
}
type AlertGroup struct {
ID uuid.UUID
OrgID uuid.UUID
Name string
IsDefault bool
}
type AlertGroupChannel struct {
OrgID uuid.UUID
GroupID uuid.UUID
ChannelID uuid.UUID
}
type AlertmanagerAlert struct {
OrgID uuid.UUID
Fingerprint string
@@ -214,6 +227,12 @@ type Monitor struct {
GroupID *uuid.UUID
}
type MonitorAlertGroup struct {
OrgID uuid.UUID
MonitorID uuid.UUID
GroupID uuid.UUID
}
type MonitorGroup struct {
ID uuid.UUID
OrgID uuid.UUID
+11 -1
View File
@@ -13,8 +13,10 @@ import (
type Querier interface {
APITokenOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
AddAlertGroupChannel(ctx context.Context, arg AddAlertGroupChannelParams) (int64, error)
AddMaintenanceTarget(ctx context.Context, arg AddMaintenanceTargetParams) error
AddMembership(ctx context.Context, arg AddMembershipParams) error
AddMonitorAlertGroup(ctx context.Context, arg AddMonitorAlertGroupParams) (int64, error)
AddMonitorRegion(ctx context.Context, arg AddMonitorRegionParams) error
AddStatusPageMonitor(ctx context.Context, arg AddStatusPageMonitorParams) error
AgentInstancesByID(ctx context.Context, ids []uuid.UUID) ([]AgentInstancesByIDRow, error)
@@ -23,6 +25,7 @@ type Querier interface {
AlertmanagerMonitors(ctx context.Context, orgID *uuid.UUID) ([]AlertmanagerMonitorsRow, error)
// System scope: the receiver a webhook token belongs to.
AlertmanagerReceiverByHash(ctx context.Context, tokenHash []byte) (AlertmanagerReceiverByHashRow, error)
AllMonitorAlertGroups(ctx context.Context) ([]MonitorAlertGroup, error)
AllMonitorRegions(ctx context.Context) ([]AllMonitorRegionsRow, error)
AnyUserExists(ctx context.Context) (bool, error)
// How much one instance checked for the organization in the last hour.
@@ -38,6 +41,7 @@ type Querier interface {
CountUnusedRecoveryCodes(ctx context.Context, userID uuid.UUID) (int64, error)
CreateAPIToken(ctx context.Context, arg CreateAPITokenParams) (ApiToken, error)
CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent, error)
CreateAlertGroup(ctx context.Context, arg CreateAlertGroupParams) (AlertGroup, error)
CreateAlertmanagerReceiver(ctx context.Context, arg CreateAlertmanagerReceiverParams) (CreateAlertmanagerReceiverRow, error)
CreateAssignment(ctx context.Context, arg CreateAssignmentParams) (RoleAssignment, error)
CreateChannel(ctx context.Context, arg CreateChannelParams) (NotificationChannel, error)
@@ -57,6 +61,8 @@ type Querier interface {
DeleteAPIToken(ctx context.Context, id uuid.UUID) (int64, error)
DeleteAccountAudit(ctx context.Context, actorUserID *uuid.UUID) error
DeleteAgent(ctx context.Context, arg DeleteAgentParams) (int64, error)
DeleteAlertGroup(ctx context.Context, id uuid.UUID) (int64, error)
DeleteAlertGroupChannels(ctx context.Context, groupID uuid.UUID) error
DeleteAlertmanagerReceiver(ctx context.Context, id uuid.UUID) (int64, error)
DeleteAssignment(ctx context.Context, id uuid.UUID) (int64, error)
DeleteAssignmentsForResource(ctx context.Context, arg DeleteAssignmentsForResourceParams) error
@@ -67,6 +73,7 @@ type Querier interface {
DeleteLegalDocument(ctx context.Context, arg DeleteLegalDocumentParams) error
DeleteMaintenance(ctx context.Context, id uuid.UUID) (int64, error)
DeleteMonitor(ctx context.Context, id uuid.UUID) (int64, error)
DeleteMonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) error
DeleteMonitorRegions(ctx context.Context, monitorID uuid.UUID) error
DeleteOrg(ctx context.Context, id uuid.UUID) (int64, error)
DeleteOrgStorage(ctx context.Context, orgID uuid.UUID) error
@@ -149,13 +156,13 @@ type Querier interface {
ListAPITokens(ctx context.Context, arg ListAPITokensParams) ([]ListAPITokensRow, error)
// Agents owned by org, or platform agents when org is NULL.
ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error)
ListAlertGroups(ctx context.Context) ([]ListAlertGroupsRow, error)
ListAlertmanagerReceivers(ctx context.Context) ([]ListAlertmanagerReceiversRow, error)
ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error)
// Newest first, paged by time. kind narrows to one kind; the row policy
// already limits what the scope can see.
ListAuditEvents(ctx context.Context, arg ListAuditEventsParams) ([]ListAuditEventsRow, error)
ListChannels(ctx context.Context) ([]NotificationChannel, error)
ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error)
// System scope: every enabled monitor with its regions, for reconciling the
// schedule.
ListEnabledMonitorsForSchedule(ctx context.Context) ([]ListEnabledMonitorsForScheduleRow, error)
@@ -188,6 +195,8 @@ type Querier interface {
MarkNotificationSent(ctx context.Context, id uuid.UUID) error
// Every role a member holds, with the scope it applies to.
MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error)
MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
MonitorChannelIDs(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
MonitorIncidents(ctx context.Context, monitorID uuid.UUID) ([]Incident, error)
MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
// System scope: monitors to hand to a checker of region, skipping ones that
@@ -260,6 +269,7 @@ type Querier interface {
// Writes at most once a minute per instance; agents poll far more often.
TouchAgentInstance(ctx context.Context, arg TouchAgentInstanceParams) error
TouchIdentity(ctx context.Context, arg TouchIdentityParams) error
UpdateAlertGroup(ctx context.Context, arg UpdateAlertGroupParams) (AlertGroup, error)
UpdateChannel(ctx context.Context, arg UpdateChannelParams) (NotificationChannel, error)
UpdateGroup(ctx context.Context, arg UpdateGroupParams) (MonitorGroup, error)
UpdateMaintenance(ctx context.Context, arg UpdateMaintenanceParams) (MaintenanceWindow, error)
+42
View File
@@ -0,0 +1,42 @@
-- name: ListAlertGroups :many
SELECT g.*, ARRAY(SELECT c.channel_id FROM alert_group_channels c WHERE c.group_id = g.id ORDER BY c.channel_id)::uuid[] AS channel_ids
FROM alert_groups g ORDER BY g.is_default DESC, g.name, g.id;
-- name: CreateAlertGroup :one
INSERT INTO alert_groups (org_id, name) VALUES ($1, $2) RETURNING *;
-- name: UpdateAlertGroup :one
UPDATE alert_groups SET name = $2 WHERE id = $1 RETURNING *;
-- name: DeleteAlertGroup :execrows
DELETE FROM alert_groups WHERE id = $1 AND NOT is_default;
-- name: DeleteAlertGroupChannels :exec
DELETE FROM alert_group_channels WHERE group_id = $1;
-- name: AddAlertGroupChannel :execrows
INSERT INTO alert_group_channels (org_id, group_id, channel_id)
SELECT c.org_id, sqlc.arg(group_id), c.id FROM notification_channels c
WHERE c.id = sqlc.arg(channel_id) AND c.org_id = sqlc.arg(org_id)
ON CONFLICT DO NOTHING;
-- name: AllMonitorAlertGroups :many
SELECT * FROM monitor_alert_groups ORDER BY monitor_id, group_id;
-- name: MonitorAlertGroups :many
SELECT group_id FROM monitor_alert_groups WHERE monitor_id = $1 ORDER BY group_id;
-- name: DeleteMonitorAlertGroups :exec
DELETE FROM monitor_alert_groups WHERE monitor_id = $1;
-- name: AddMonitorAlertGroup :execrows
INSERT INTO monitor_alert_groups (org_id, monitor_id, group_id)
SELECT g.org_id, sqlc.arg(monitor_id), g.id FROM alert_groups g
WHERE g.id = sqlc.arg(group_id) AND g.org_id = sqlc.arg(org_id)
ON CONFLICT DO NOTHING;
-- name: MonitorChannelIDs :many
SELECT DISTINCT c.id FROM notification_channels c
JOIN alert_group_channels gc ON gc.channel_id = c.id AND gc.org_id = c.org_id
JOIN monitor_alert_groups mg ON mg.group_id = gc.group_id AND mg.org_id = gc.org_id
WHERE mg.monitor_id = $1 AND c.enabled;
-3
View File
@@ -16,9 +16,6 @@ JOIN monitors m ON m.id = i.monitor_id
ORDER BY i.started_at DESC
LIMIT 200;
-- name: ListEnabledChannelIDs :many
SELECT id FROM notification_channels WHERE org_id = $1 AND enabled;
-- name: EnqueueNotification :exec
INSERT INTO notifications (org_id, channel_id, incident_id, event)
VALUES ($1, $2, $3, $4)
+77
View File
@@ -0,0 +1,77 @@
package web
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
// AlertGroupOption is a selectable group or channel in an alert routing form.
type AlertGroupOption struct {
ID string
Name string
Default bool
Checked bool
}
// AlertGroupRow describes a group and its available notification channels.
type AlertGroupRow struct {
ID string
Name string
Default bool
Channels []AlertGroupOption
}
templ alertGroupOptions(name string, options []AlertGroupOption) {
<input type="hidden" name={ name } data-multi/>
for _, opt := range options {
<label class="mb-2 flex items-center gap-2 text-sm">
<input type="checkbox" name={ name } value={ opt.ID } data-multi checked?={ opt.Checked }/>
<span>{ opt.Name }</span>
if opt.Default {
<span class="text-xs text-muted">{ i18n.T(ctx, "alert_groups.default") }</span>
}
</label>
}
}
templ alertGroupsSettings(v ChannelsView) {
<section class="mb-12">
@sectionHeading("alert_groups.title")
<p class="mb-6 max-w-2xl text-sm text-muted">{ i18n.T(ctx, "alert_groups.intro") }</p>
<div class="grid gap-6 md:grid-cols-2">
for _, g := range v.AlertGroups {
<form data-api={ "/org/alert-groups/" + g.ID } data-method="put" data-next="/settings/channels" class="border border-rule p-4">
@formError()
if g.Default {
<p class="mb-3 text-xs text-muted">{ i18n.T(ctx, "alert_groups.default") }</p>
}
<fieldset disabled?={ !v.CanWrite }>
@valueField(i18n.T(ctx, "sso.field.name"), "name", g.Name, "", true)
@alertGroupOptions("channel_ids", g.Channels)
if len(g.Channels) == 0 {
<p class="mb-4 text-sm text-muted">{ i18n.T(ctx, "alert_groups.no_channels") }</p>
}
if v.CanWrite {
@submit(i18n.T(ctx, "alert_groups.save"))
}
</fieldset>
if v.CanWrite && !g.Default {
<button type="button" data-delete={ "/org/alert-groups/" + g.ID } data-confirm={ i18n.T(ctx, "alert_groups.delete_confirm") } class="mt-3 text-sm text-muted hover:text-down">{ i18n.T(ctx, "regions.delete") }</button>
}
</form>
}
if v.CanWrite {
<form data-api="/org/alert-groups" data-next="/settings/channels" class="border border-rule p-4">
@sectionHeading("alert_groups.new")
@formError()
@valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true)
<input type="hidden" name="channel_ids" data-multi/>
for _, ch := range v.Channels {
<label class="mb-2 flex items-center gap-2 text-sm">
<input type="checkbox" name="channel_ids" value={ ch.ID } data-multi/>
<span>{ ch.Name }</span>
</label>
}
@submit(i18n.T(ctx, "alert_groups.create"))
</form>
}
</div>
</section>
}
+400
View File
@@ -0,0 +1,400 @@
// Code generated by templ - DO NOT EDIT.
// templ: version: v0.3.1118
package web
//lint:file-ignore SA4006 This context is only used if a nested component is present.
import "github.com/a-h/templ"
import templruntime "github.com/a-h/templ/runtime"
import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
// AlertGroupOption is a selectable group or channel in an alert routing form.
type AlertGroupOption struct {
ID string
Name string
Default bool
Checked bool
}
// AlertGroupRow describes a group and its available notification channels.
type AlertGroupRow struct {
ID string
Name string
Default bool
Channels []AlertGroupOption
}
func alertGroupOptions(name string, options []AlertGroupOption) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "<input type=\"hidden\" name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var2 string
templ_7745c5c3_Var2, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 22, Col: 33}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 2, "\" data-multi> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, opt := range options {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "<label class=\"mb-2 flex items-center gap-2 text-sm\"><input type=\"checkbox\" name=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var3 string
templ_7745c5c3_Var3, templ_7745c5c3_Err = templruntime.NewAttributeExpression(name).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 25, Col: 37}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var3)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var4 string
templ_7745c5c3_Var4, templ_7745c5c3_Err = templruntime.NewAttributeExpression(opt.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 25, Col: 54}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var4)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "\" data-multi")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if opt.Checked {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, " checked")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 7, "> <span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var5 string
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(opt.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 26, Col: 19}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 8, "</span> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if opt.Default {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 9, "<span class=\"text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var6 string
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.default"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 28, Col: 74}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 10, "</span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 11, "</label>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
return nil
})
}
func alertGroupsSettings(v ChannelsView) templ.Component {
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
return templ_7745c5c3_CtxErr
}
templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W)
if !templ_7745c5c3_IsBuffer {
defer func() {
templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer)
if templ_7745c5c3_Err == nil {
templ_7745c5c3_Err = templ_7745c5c3_BufErr
}
}()
}
ctx = templ.InitializeContext(ctx)
ctx = templ.ClearChildren(ctx)
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 12, "<section class=\"mb-12\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = sectionHeading("alert_groups.title").Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 13, "<p class=\"mb-6 max-w-2xl text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var8 string
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.intro"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 37, Col: 82}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 14, "</p><div class=\"grid gap-6 md:grid-cols-2\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, g := range v.AlertGroups {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "<form data-api=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var9 string
templ_7745c5c3_Var9, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/org/alert-groups/" + g.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 40, Col: 48}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var9)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 16, "\" data-method=\"put\" data-next=\"/settings/channels\" class=\"border border-rule p-4\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if g.Default {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 17, "<p class=\"mb-3 text-xs text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var10 string
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.default"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 43, Col: 78}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 18, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "<fieldset")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if !v.CanWrite {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 20, " disabled")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 21, ">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", g.Name, "", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = alertGroupOptions("channel_ids", g.Channels).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if len(g.Channels) == 0 {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 22, "<p class=\"mb-4 text-sm text-muted\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var11 string
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "alert_groups.no_channels"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 49, Col: 83}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 23, "</p>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if v.CanWrite {
templ_7745c5c3_Err = submit(i18n.T(ctx, "alert_groups.save")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</fieldset>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
if v.CanWrite && !g.Default {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 25, "<button type=\"button\" data-delete=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var12 string
templ_7745c5c3_Var12, templ_7745c5c3_Err = templruntime.NewAttributeExpression("/org/alert-groups/" + g.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 56, Col: 69}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var12)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "\" data-confirm=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var13 string
templ_7745c5c3_Var13, templ_7745c5c3_Err = templruntime.NewAttributeExpression(i18n.T(ctx, "alert_groups.delete_confirm")).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 56, Col: 129}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var13)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 27, "\" class=\"mt-3 text-sm text-muted hover:text-down\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var14 string
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "regions.delete"))
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 56, Col: 211}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</button>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 29, "</form>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
if v.CanWrite {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 30, "<form data-api=\"/org/alert-groups\" data-next=\"/settings/channels\" class=\"border border-rule p-4\">")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = sectionHeading("alert_groups.new").Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = formError().Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = valueField(i18n.T(ctx, "sso.field.name"), "name", "", "", true).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 31, "<input type=\"hidden\" name=\"channel_ids\" data-multi> ")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
for _, ch := range v.Channels {
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 32, "<label class=\"mb-2 flex items-center gap-2 text-sm\"><input type=\"checkbox\" name=\"channel_ids\" value=\"")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var15 string
templ_7745c5c3_Var15, templ_7745c5c3_Err = templruntime.NewAttributeExpression(ch.ID).Resolve(ctx)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 68, Col: 62}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var15)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 33, "\" data-multi> <span>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
var templ_7745c5c3_Var16 string
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(ch.Name)
if templ_7745c5c3_Err != nil {
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/alert_groups.templ`, Line: 69, Col: 22}
}
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 34, "</span></label>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = submit(i18n.T(ctx, "alert_groups.create")).Render(ctx, templ_7745c5c3_Buffer)
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 35, "</form>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
}
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 36, "</div></section>")
if templ_7745c5c3_Err != nil {
return templ_7745c5c3_Err
}
return nil
})
}
var _ = templruntime.GeneratedTemplate
+8
View File
@@ -450,6 +450,7 @@ type RegionOption struct {
// MonitorForm is the data of the monitor editor; ID is empty for new ones.
type MonitorForm struct {
AlertGroups []AlertGroupOption
ID string
Name string
Type string
@@ -611,6 +612,11 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
<div>
@formError()
@valueField(i18n.T(ctx, "sso.field.name"), "name", f.Name, "", true)
<fieldset class="mb-6">
<legend class="mb-2 text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "alert_groups.title") }</legend>
@alertGroupOptions("alert_group_ids", f.AlertGroups)
<p class="mt-2 text-xs text-muted">{ i18n.T(ctx, "alert_groups.monitor_hint") }</p>
</fieldset>
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "groups.group") }</span>
@groupSelect("group_id", f.Groups, f.GroupID, f.TopLevel)
@@ -875,6 +881,7 @@ type ChannelRow struct {
// ChannelsView is the data of the notification channels page.
type ChannelsView struct {
AlertGroups []AlertGroupRow
Channels []ChannelRow
EmailAvailable bool
CanWrite bool
@@ -885,6 +892,7 @@ type ChannelsView struct {
templ ChannelsPage(p Page, me Me, v ChannelsView) {
@consoleShell(p, me) {
@settingsHeading("channels.title", "channels.intro")
@alertGroupsSettings(v)
if len(v.Channels) > 0 {
<ul class="mb-12 divide-y divide-rule border-y border-rule text-sm">
for _, ch := range v.Channels {
File diff suppressed because it is too large. Load diff
+13
View File
@@ -13,6 +13,10 @@ X-Empty:
</fieldset>
<fieldset data-type="http" disabled hidden><select name="config.method"><option value="HEAD" selected>HEAD</option></select></fieldset>
<fieldset data-hide-for="heartbeat"><input type="checkbox" name="regions" value="r1" data-multi checked></fieldset>
<input type="hidden" name="alert_group_ids" data-multi>
<input type="checkbox" name="alert_group_ids" value="default" data-multi checked>
<input type="checkbox" name="alert_group_ids" value="ops" data-multi>
<input type="hidden" name="channel_ids" data-multi>
<button type="submit">save</button>
</form>
<form data-api="/org/agents/a1" data-method="patch" data-autosave id="auto">
@@ -42,6 +46,15 @@ window.axios = { create: () => ({ interceptors: { request: { use() {} } }, reque
check("numbered names build arrays", body.config.assertions, [{ path: "status", op: "==" }, { path: "queue.depth", op: "<" }]);
check("header lines become an object", body.config.headers, { Authorization: "Bearer a:b", "X-Empty": "" });
check("regions sent", body.regions, ["r1"]);
check("default alert group selected", body.alert_group_ids, ["default"]);
check("empty channel list stays an array", body.channel_ids, []);
form.querySelector('[name="alert_group_ids"][value="default"]').checked = false;
body = await submit();
check("cleared alert groups sent explicitly", body.alert_group_ids, []);
form.querySelector('[name="alert_group_ids"][value="ops"]').checked = true;
body = await submit();
check("custom alert group selected", body.alert_group_ids, ["ops"]);
const sel = form.querySelector("[data-type-select]");
sel.value = "heartbeat";