Files
uptimesebi/internal/api/monitors.go
Sebastian UnterschützandClaude Opus 5.5 22f0740056 feat(api): organization-owned regions, checkers and status page servers
Organizations create regions and agents for themselves under Regions &
checkers; an org checker only receives its org's monitors. Platform admins
manage shared regions and agents in the admin panel or with the CLI,
which gains 'api admin grant|revoke'. The first user of a self-hosted
installation becomes a platform admin. Region lists show the org's own
regions first.

Closes #52
Refs #29

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

365 lines
11 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/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 string `json:"target" binding:"required,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:"required,min=1,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"`
}
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"`
Regions []uuid.UUID `json:"regions"`
Latest []latestView `json:"latest"`
}
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, 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.
func (s *Server) validateMonitor(c *gin.Context, req *monitorRequest) bool {
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
}
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
}
func (s *Server) listMonitors(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
var 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,
})
}
out = make([]monitorView, len(monitors))
for i, m := range monitors {
out[i] = viewMonitor(m, byMonitor[m.ID])
if l := latestBy[m.ID]; l != nil {
out[i].Latest = l
}
}
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) || !s.validateMonitor(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
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),
})
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, 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) || !s.validateMonitor(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
var (
m store.Monitor
previous []uuid.UUID
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
if previous, err = q.MonitorRegions(ctx, id); err != nil {
return err
}
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),
})
if err != nil {
return err
}
return setRegions(ctx, q, m, req.Regions)
})
if errors.Is(err, pgx.ErrNoRows) {
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, 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()
var (
regions []uuid.UUID
n int64
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
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:
if _, err := s.sched.Dispatch(ctx); err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "dispatch failed", "error", err)
}
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
}
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)
}
if err != nil && ctx.Err() == nil {
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
}
}