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"` // GroupID places the monitor in a group; nil keeps it at the top level. GroupID *uuid.UUID `json:"group_id"` } 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 { 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"` } // withPingURL adds the ping URL of heartbeat monitors. func (s *Server) withPingURL(v monitorView) monitorView { if check.Passive(check.Type(v.Type)) && v.Target != "" { v.PingURL = s.pingURL(v.Target) } return v } func viewMonitor(m store.Monitor, regions []uuid.UUID) monitorView { return monitorView{ ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds, TimeoutMS: m.TimeoutMs, Config: m.Config, Enabled: m.Enabled, Confirmations: m.Confirmations, GroupID: m.GroupID, Regions: regions, Latest: []latestView{}, } } // 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 } 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) { p := current(c) ctx := c.Request.Context() 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.ListMonitors(ctx) if err != nil { return err } 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]) if check.Passive(check.Type(m.Type)) && !canInGroup(p, authz.MonitorsWrite, t, m.GroupID) { // Whoever knows the ping URL can report the job healthy. v.Target = "" } 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}) } 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 check.Passive(check.Type(req.Type)) { req.Target = newPingToken() } var m store.Monitor err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error { 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 } return setRegions(ctx, q, m, req.Regions) }) if err != nil { internalError(c, err) return } if err := s.syncSchedule(ctx, m, req.Regions, nil); err != nil { internalError(c, err) return } c.JSON(http.StatusCreated, s.withPingURL(viewMonitor(m, req.Regions))) } 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 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 = newPingToken() } } 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 } return setRegions(ctx, q, m, req.Regions) }) 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 } c.JSON(http.StatusOK, s.withPingURL(viewMonitor(m, req.Regions))) } 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) } }