Files
uptimesebi/internal/api/monitors.go
Sebastian UnterschützandClaude Opus 5.5 d7c5cd711e
ci / image (pull_request) Successful in 3m18s
ci / build (pull_request) Successful in 8m38s
ci / test (pull_request) Successful in 12m6s
ci / lint (pull_request) Successful in 15m0s
feat: page long and truncated lists
Lists that were cut off by a fixed LIMIT, or could grow without bound,
are paged by keyset: the cursor holds the sort key and an ID, so pages
neither skip nor repeat items as others are added. The audit logs had a
timestamp-only cursor that could skip entries with equal times.

The API returns at most 100 items per list (limit takes up to 500) with
next_cursor and prev_cursor, passed back as after and before. The
console shows Newer/Older (or Previous/Next) links and To the start,
without JavaScript.

Paged: incidents (optionally of one monitor), a monitor's results and
evidence, a checker's results, the audit logs, members, maintenance
windows, firing Alertmanager alerts, the monitors API and the admin
lists of status pages and organizations, which move to their own admin
pages. A monitor's page shows its latest incidents and results and links
to all of them. The dashboard caps every group at 50 of its own monitors
with a link to a paged view of the group, and gains a search by name or
target. Lists filtered by permission after reading may show fewer items
on a page.

Closes #116

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:40:25 +01:00

616 lines
18 KiB
Go

package api
import (
"context"
"encoding/json"
"errors"
"net/http"
"slices"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/authz"
"git.zb-server.de/ZB-Server/uptimesebi/internal/check"
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
type monitorRequest struct {
Name string `json:"name" binding:"required,max=200"`
Type string `json:"type" binding:"required"`
// Target is ignored for heartbeat monitors, whose target is their
// generated ping token.
Target string `json:"target" binding:"max=2000"`
IntervalSeconds int `json:"interval_seconds" binding:"required"`
TimeoutMS int `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
Enabled *bool `json:"enabled"`
Regions []uuid.UUID `json:"regions" binding:"max=50"`
// Confirmations is how many failures in a row make a region count as
// down; 0 keeps the default of 2.
Confirmations int `json:"confirmations" binding:"min=0,max=10"`
// platform marks the platform regions among those visible, filled by
// validateMonitor.
platform map[uuid.UUID]bool
// 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 {
Region string `json:"region"`
Time time.Time `json:"time"`
OK bool `json:"ok"`
LatencyMS *int32 `json:"latency_ms"`
StatusCode *int32 `json:"status_code,omitempty"`
Error *string `json:"error,omitempty"`
}
type monitorView struct {
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Target string `json:"target"`
IntervalSeconds int32 `json:"interval_seconds"`
TimeoutMS int32 `json:"timeout_ms"`
Config json.RawMessage `json:"config"`
Enabled bool `json:"enabled"`
Confirmations int32 `json:"confirmations"`
GroupID *uuid.UUID `json:"group_id"`
Regions []uuid.UUID `json:"regions"`
Latest []latestView `json:"latest"`
// PingURL is where heartbeat monitors are pinged.
PingURL string `json:"ping_url,omitempty"`
// SecretsSet names secret settings that are set; their values are
// never returned.
SecretsSet []string `json:"secrets_set,omitempty"`
}
// withPingURL adds the ping URL of heartbeat monitors.
func (s *Server) withPingURL(v monitorView) monitorView {
if check.Type(v.Type) == check.Heartbeat && v.Target != "" {
v.PingURL = s.pingURL(v.Target)
}
return v
}
func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView {
cfg, secrets := publicMonitorConfig(m.Config)
return monitorView{
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
TimeoutMS: m.TimeoutMs, Config: cfg, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{},
SecretsSet: secrets,
}
}
// minInterval is stricter in the cloud, where checks run on shared capacity.
func (s *Server) minInterval() int {
if s.cloud() {
return 30
}
return 10
}
// validateMonitor normalizes req and writes an error response if it is not
// acceptable, including when the principal may not write monitors in the
// requested group.
func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest, t groupTree) bool {
if req.GroupID != nil {
if _, ok := t.byID[*req.GroupID]; !ok {
fail(c, http.StatusUnprocessableEntity, "invalid_group")
return false
}
}
if !canInGroup(current(c), authz.MonitorsWrite, t, req.GroupID) {
fail(c, http.StatusForbidden, "forbidden")
return false
}
req.Name = strings.TrimSpace(req.Name)
req.Target = strings.TrimSpace(req.Target)
if req.Name == "" {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return false
}
if req.IntervalSeconds < s.minInterval() || req.IntervalSeconds > 86400 {
fail(c, http.StatusUnprocessableEntity, "invalid_interval", "Min", s.minInterval())
return false
}
heartbeat := check.Passive(check.Type(req.Type))
if heartbeat {
// Pings arrive from one place, so one late ping is an outage, and
// there is neither a target nor a timeout to check against.
req.Target, req.Regions = "", nil
if req.Confirmations == 0 {
req.Confirmations = 1
}
if req.TimeoutMS == 0 {
req.TimeoutMS = 1000
}
} else if len(req.Regions) == 0 {
fail(c, http.StatusUnprocessableEntity, "invalid_region")
return false
}
if req.Confirmations == 0 {
req.Confirmations = 2
}
if req.TimeoutMS == 0 {
req.TimeoutMS = min(10000, req.IntervalSeconds*1000/2)
}
if req.TimeoutMS < 100 || req.TimeoutMS > 60000 || req.TimeoutMS >= req.IntervalSeconds*1000 {
fail(c, http.StatusUnprocessableEntity, "invalid_timeout")
return false
}
cfg, err := check.Validate(check.Type(req.Type), req.Target, req.Config)
var inv check.ErrInvalid
if errors.As(err, &inv) {
fail(c, http.StatusUnprocessableEntity, inv.Code)
return false
}
if err != nil {
internalError(c, err)
return false
}
req.Config = cfg
slices.SortFunc(req.Regions, func(a, b uuid.UUID) int { return strings.Compare(a.String(), b.String()) })
req.Regions = slices.Compact(req.Regions)
ctx := c.Request.Context()
var known []store.Region
err = s.db.Tx(ctx, current(c).scope(), func(q *store.Queries) error {
var err error
known, err = q.ListVisibleRegions(ctx)
return err
})
if err != nil {
internalError(c, err)
return false
}
req.platform = map[uuid.UUID]bool{}
for _, k := range known {
req.platform[k.ID] = k.OrgID == nil
}
for _, r := range req.Regions {
// Row-level security limits known to the org's own and the
// platform regions.
if !slices.ContainsFunc(known, func(k store.Region) bool { return k.ID == r }) {
fail(c, http.StatusUnprocessableEntity, "invalid_region")
return false
}
}
return true
}
// listMonitors returns the monitors the principal may read, org-wide or
// through a group assignment.
func (s *Server) listMonitors(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
p := current(c)
ctx := c.Request.Context()
var info pageInfo
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
out := []monitorView{}
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
monitors, err := q.ListMonitorsPage(ctx, store.ListMonitorsPageParams{
AfterS: pg.afterS(), AfterID: pg.afterID(), BeforeS: pg.beforeS(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
if err != nil {
return err
}
// Paged before filtering by permission: a page may hold fewer.
monitors, info = paginate(pg, monitors, func(m store.Monitor) cursor { return cursor{S: m.Name, ID: m.ID} })
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
}
latest, err := q.LatestResults(ctx, p.Org.ID)
if err != nil {
return err
}
byMonitor := map[uuid.UUID][]uuid.UUID{}
for _, r := range regions {
byMonitor[r.MonitorID] = append(byMonitor[r.MonitorID], r.RegionID)
}
latestBy := map[uuid.UUID][]latestView{}
for _, l := range latest {
latestBy[l.MonitorID] = append(latestBy[l.MonitorID], latestView{
Region: l.Region, Time: l.Time, OK: l.Ok, LatencyMS: l.LatencyMs, StatusCode: l.StatusCode, Error: l.Error,
})
}
for _, m := range monitors {
if !canInGroup(p, authz.MonitorsRead, t, m.GroupID) {
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)
}
v = s.withPingURL(v)
if l := latestBy[m.ID]; l != nil {
v.Latest = l
}
out = append(out, v)
}
return nil
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"monitors": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func (s *Server) createMonitor(c *gin.Context) {
var req monitorRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
if !s.validateMonitor(c, &req, t) {
return
}
if !s.offered(ctx, p.Org, req.Type) {
fail(c, http.StatusUnprocessableEntity, "check_type_disabled")
return
}
req.Target = passiveTarget(check.Type(req.Type), req.Target)
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
limits := s.orgLimits(ctx, p.Org)
if err := checkRegions(limits, req.Regions, nil, req.platform); failLimit(c, err) {
return
}
var m store.Monitor
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
if err := reserve(ctx, q, p.Org.ID, limits.Monitors, "monitor_limit", q.CountMonitors); err != nil {
return err
}
var err error
m, err = q.CreateMonitor(ctx, store.CreateMonitorParams{
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Target: req.Target,
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
GroupID: req.GroupID,
})
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 failLimit(c, err) {
return
}
if err != nil {
internalError(c, err)
return
}
if err := s.syncSchedule(ctx, m, req.Regions, nil); err != nil {
internalError(c, err)
return
}
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 {
if err := q.DeleteMonitorRegions(ctx, m.ID); err != nil {
return err
}
for _, r := range regions {
if err := q.AddMonitorRegion(ctx, store.AddMonitorRegionParams{MonitorID: m.ID, OrgID: m.OrgID, RegionID: r}); err != nil {
return err
}
}
return nil
}
// syncSchedule applies a committed monitor change to the scheduler. Should it
// fail, the periodic reconciliation repairs the schedule.
func (s *Server) syncSchedule(ctx context.Context, m store.Monitor, regions, previous []uuid.UUID) error {
if !m.Enabled {
return s.sched.Remove(ctx, m.ID, idStrings(append(regions, previous...)))
}
return s.sched.Upsert(ctx, schedule.Monitor{
ID: m.ID, Interval: time.Duration(m.IntervalSeconds) * time.Second, Regions: idStrings(regions),
}, idStrings(previous))
}
func idStrings(ids []uuid.UUID) []string {
out := make([]string, len(ids))
for i, id := range ids {
out[i] = id.String()
}
return out
}
func (s *Server) updateMonitor(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req monitorRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
if !s.validateMonitor(c, &req, t) {
return
}
var (
m store.Monitor
previous []uuid.UUID
denied bool
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
old, err := q.GetMonitor(ctx, id)
if err != nil {
return err
}
// Moving out of a group needs write access where it was, too.
if !canInGroup(p, authz.MonitorsWrite, t, old.GroupID) {
denied = true
return nil
}
if previous, err = q.MonitorRegions(ctx, id); err != nil {
return err
}
if old.Type != req.Type && !s.offered(ctx, p.Org, req.Type) {
return errCheckTypeDisabled
}
if err := checkRegions(s.orgLimits(ctx, p.Org), req.Regions, previous, req.platform); err != nil {
return err
}
if old.Type == req.Type {
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, old.Config)
} else {
req.Config = s.sealMonitorConfig(check.Type(req.Type), req.Config, nil)
}
if check.Passive(check.Type(req.Type)) {
// The ping URL stays the same across edits.
req.Target = old.Target
if old.Type != req.Type {
req.Target = passiveTarget(check.Type(req.Type), "")
}
}
m, err = q.UpdateMonitor(ctx, store.UpdateMonitorParams{
ID: id, Name: req.Name, Type: req.Type, Target: req.Target,
IntervalSeconds: int32(req.IntervalSeconds), TimeoutMs: int32(req.TimeoutMS),
Config: req.Config, Enabled: req.Enabled == nil || *req.Enabled, Confirmations: int32(req.Confirmations),
GroupID: req.GroupID,
})
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
}
if failLimit(c, err) {
return
}
if errors.Is(err, pgx.ErrNoRows) || (err == nil && denied) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
if err := s.syncSchedule(ctx, m, req.Regions, previous); err != nil {
internalError(c, err)
return
}
v := viewMonitor(m, req.Regions)
v.AlertGroupIDs = req.AlertGroupIDs
c.JSON(http.StatusOK, s.withPingURL(v))
}
func (s *Server) deleteMonitor(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
p := current(c)
ctx := c.Request.Context()
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
internalError(c, err)
return
}
var (
regions []uuid.UUID
n int64
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
old, err := q.GetMonitor(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if !canInGroup(p, authz.MonitorsWrite, t, old.GroupID) {
return nil
}
if regions, err = q.MonitorRegions(ctx, id); err != nil {
return err
}
n, err = q.DeleteMonitor(ctx, id)
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
if err := s.sched.Remove(ctx, id, idStrings(regions)); err != nil {
internalError(c, err)
return
}
_ = s.eval.Forget(ctx, id)
c.Status(http.StatusNoContent)
}
// RunScheduler dispatches due checks and periodically reconciles the
// schedule with the database until ctx ends. Every API replica runs it;
// dispatch is atomic in Redis and reconciliation is idempotent.
func (s *Server) RunScheduler(ctx context.Context) {
dispatch := time.NewTicker(time.Second)
defer dispatch.Stop()
reconcile := time.NewTicker(time.Minute)
defer reconcile.Stop()
s.reconcile(ctx)
for {
select {
case <-ctx.Done():
return
case <-dispatch.C:
n, err := s.sched.Dispatch(ctx)
if err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "dispatch failed", "error", err)
}
if n > 0 {
s.log.DebugContext(ctx, "dispatched checks", "count", n)
}
case <-reconcile.C:
s.reconcile(ctx)
}
}
}
func (s *Server) reconcile(ctx context.Context) {
// One replica per minute is enough.
ok, err := s.rdb.SetNX(ctx, "sched:reconcile-lock", "1", 55*time.Second).Result()
if err != nil || !ok {
return
}
// Taken before reading the database: monitors upserted later survive.
start := time.Now()
defer func() { s.log.DebugContext(ctx, "schedule reconciled", "took", time.Since(start)) }()
var rows []store.ListEnabledMonitorsForScheduleRow
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
return err
})
if err == nil {
want := make([]schedule.Monitor, len(rows))
for i, r := range rows {
want[i] = schedule.Monitor{ID: r.ID, Interval: time.Duration(r.IntervalSeconds) * time.Second, Regions: r.Regions}
}
err = s.sched.Reconcile(ctx, want, start)
}
if err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
}
}
// redactMonitor hides what only editors may see: the ping token of a
// heartbeat, which can report the job healthy, and request header values,
// which typically carry credentials.
func redactMonitor(v monitorView) monitorView {
if check.Passive(check.Type(v.Type)) {
v.Target = ""
}
var cfg map[string]any
if json.Unmarshal(v.Config, &cfg) != nil {
return v
}
if h, ok := cfg["headers"].(map[string]any); ok {
for k := range h {
h[k] = "redacted"
}
v.Config, _ = json.Marshal(cfg)
}
return v
}
// passiveTarget fills the target of monitors that are reported to us:
// heartbeats get their secret ping token; alertmanager monitors, matched by
// labels, a fixed placeholder.
func passiveTarget(t check.Type, target string) string {
switch t {
case check.Heartbeat:
return newPingToken()
case check.Alertmanager:
return alertmanagerRegion
}
return target
}
// passiveRegion is the pseudo-region results of passive monitors carry.
func passiveRegion(t check.Type) string {
if t == check.Alertmanager {
return alertmanagerRegion
}
return heartbeatRegion
}
var errCheckTypeDisabled = errors.New("api: check type switched off")