From d9891bb050efea7af6625033a40a48b9ab142082 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 01:12:53 +0100 Subject: [PATCH] feat!: let checkers and status page servers reach data only through the api Only cmd/api connects to Postgres and Redis. Agents authenticate with tokens created by 'api agent create' and use /agent/v1: checkers long poll for jobs, which doubles as heartbeat, and report results in batches. Organizations manage monitors through /api/v1/org/monitors. BREAKING CHANGE: cmd/checker and cmd/statuspage no longer read UPTIME_DATABASE_URL or UPTIME_REDIS_*; they need UPTIME_API_URL and UPTIME_AGENT_TOKEN. UPTIME_CHECKER_REGION is replaced by the region bound to the agent token. Closes #10 Closes #11 Closes #12 Closes #13 Closes #49 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- .env.example | 11 +- Makefile | 3 +- cmd/api/admin.go | 129 +++++++++++ cmd/api/main.go | 18 +- cmd/checker/main.go | 40 +++- cmd/statuspage/main.go | 22 +- deploy/dev/postgres-init.sql | 6 + internal/api/agent.go | 250 ++++++++++++++++++++++ internal/api/checker_test.go | 205 ++++++++++++++++++ internal/api/invitations.go | 4 +- internal/api/monitors.go | 376 +++++++++++++++++++++++++++++++++ internal/api/server.go | 13 ++ internal/api/sso_test.go | 4 +- internal/api/tokens.go | 7 +- internal/checker/checker.go | 201 ++++++++++++++++++ internal/config/config.go | 43 +++- internal/config/config_test.go | 14 +- internal/i18n/i18n_test.go | 1 + internal/i18n/locales/de.json | 13 ++ internal/i18n/locales/en.json | 13 ++ internal/platform/agent.go | 29 +++ internal/platform/redis.go | 2 +- internal/platform/run.go | 2 +- 23 files changed, 1361 insertions(+), 45 deletions(-) create mode 100644 cmd/api/admin.go create mode 100644 internal/api/agent.go create mode 100644 internal/api/checker_test.go create mode 100644 internal/api/monitors.go create mode 100644 internal/checker/checker.go create mode 100644 internal/platform/agent.go diff --git a/.env.example b/.env.example index b1b024e..4721dac 100644 --- a/.env.example +++ b/.env.example @@ -1,6 +1,5 @@ UPTIME_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime?sslmode=disable UPTIME_REDIS_URL=redis://localhost:6379/0 -UPTIME_CHECKER_REGION=local # Sentinel instead of a single redis (docker compose --profile sentinel up -d) # UPTIME_REDIS_SENTINEL_MASTER=uptime @@ -13,3 +12,13 @@ UPTIME_PUBLIC_URL=http://localhost:8080 # Lets organizations use IdPs on private networks (e.g. an internal Keycloak). # auto = allowed for UPTIME_EDITION=selfhosted, denied for cloud. UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto + +# Checker and status page reach the API only. Create tokens with: +# api agent create --kind checker --region local --name dev +# api agent create --kind statuspage --name dev +# and set UPTIME_AGENT_TOKEN for each process. +UPTIME_API_URL=http://localhost:8080 + +# Integration tests (make test). The Redis database is flushed by the tests. +UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable +UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 diff --git a/Makefile b/Makefile index 128135b..9a9d618 100644 --- a/Makefile +++ b/Makefile @@ -16,7 +16,8 @@ build: generate web CGO_ENABLED=0 go build -trimpath -ldflags "$(LDFLAGS)" -o bin/ ./cmd/... test: - go test ./... + # Integration tests share one Postgres and Redis database, so packages run one at a time. + go test -p 1 ./... lint: golangci-lint run diff --git a/cmd/api/admin.go b/cmd/api/admin.go new file mode 100644 index 0000000..3b8fc33 --- /dev/null +++ b/cmd/api/admin.go @@ -0,0 +1,129 @@ +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "text/tabwriter" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +const usage = `usage: + api [serve] + api migrate up|down|status + api region add [name] + api agent create --kind checker|statuspage [--region ] --name + api agent list + api agent revoke ` + +// admin runs operator commands. They act across all organizations, hence the +// system scope, and print to stdout for humans and scripts. +func admin(ctx context.Context, cfg config.API, args []string) error { + if err := cfg.Storage.Validate(); err != nil { + return err + } + pool, err := platform.OpenPostgres(ctx, cfg.DatabaseURL) + if err != nil { + return err + } + defer pool.Close() + db := tenant.New(pool) + + switch { + case len(args) >= 3 && args[0] == "region" && args[1] == "add": + name := args[2] + if len(args) > 3 { + name = args[3] + } + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + r, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: args[2], Name: name}) + if err == nil { + fmt.Printf("region %s (%s)\n", r.Key, r.Name) + } + return err + }) + case len(args) >= 2 && args[0] == "agent" && args[1] == "create": + return createAgent(ctx, db, args[2:]) + case len(args) == 2 && args[0] == "agent" && args[1] == "list": + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + agents, err := q.ListAgents(ctx) + if err != nil { + return err + } + w := tabwriter.NewWriter(os.Stdout, 0, 4, 2, ' ', 0) + _, _ = fmt.Fprintln(w, "ID\tKIND\tREGION\tNAME\tTOKEN\tLAST SEEN\tRELEASE") + for _, a := range agents { + seen := "never" + if a.LastSeenAt != nil { + seen = a.LastSeenAt.Format(time.DateTime) + } + _, _ = fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s…\t%s\t%s\n", a.ID, a.Kind, deref(a.Region), a.Name, a.Prefix, seen, deref(a.Release)) + } + return w.Flush() + }) + case len(args) == 3 && args[0] == "agent" && args[1] == "revoke": + id, err := uuid.Parse(args[2]) + if err != nil { + return err + } + return db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + n, err := q.DeleteAgent(ctx, id) + if err == nil && n == 0 { + err = errors.New("agent not found") + } + return err + }) + } + return errors.New(usage) +} + +func createAgent(ctx context.Context, db *tenant.DB, args []string) error { + fs := flag.NewFlagSet("agent create", flag.ContinueOnError) + kind := fs.String("kind", "checker", "checker or statuspage") + region := fs.String("region", "", "region key, required for checkers; created if missing") + name := fs.String("name", "", "display name") + if err := fs.Parse(args); err != nil { + return err + } + if *name == "" || (*kind == "checker") != (*region != "") { + return errors.New(usage) + } + tok := api.AgentTokenPrefix + auth.RandomToken() + params := store.CreateAgentParams{Kind: *kind, Name: *name, TokenHash: api.HashToken(tok), Prefix: tok[:len(api.AgentTokenPrefix)+6]} + if *region != "" { + params.Region = region + } + err := db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + if *region != "" { + if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: *region, Name: ""}); err != nil { + return err + } + } + _, err := q.CreateAgent(ctx, params) + return err + }) + if err != nil { + return err + } + fmt.Println(tok) + return nil +} + +func deref[T any](p *T) T { + var zero T + if p == nil { + return zero + } + return *p +} diff --git a/cmd/api/main.go b/cmd/api/main.go index a7e7ac4..f3b33a1 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -38,11 +38,16 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { ctx, stop := platform.SignalContext() defer stop() - if len(args) > 0 && args[0] == "migrate" { - return migrate(ctx, log, cfg.DatabaseURL, args[1:]) - } - if len(args) > 0 && args[0] != "serve" { - return errors.New("usage: api [serve | migrate up|down|status]") + if len(args) > 0 { + switch args[0] { + case "migrate": + return migrate(ctx, log, cfg.DatabaseURL, args[1:]) + case "agent", "region": + return admin(ctx, cfg, args) + case "serve": + default: + return errors.New(usage) + } } if err := cfg.Validate(); err != nil { @@ -52,7 +57,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { if err != nil { return err } - deps, err := platform.Connect(ctx, cfg.Common, log) + deps, err := platform.Connect(ctx, cfg.Storage, log) if err != nil { return err } @@ -68,6 +73,7 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { health.Register(r) r.StaticFS("/static", web.Static()) srv.Mount(r) + go srv.RunScheduler(ctx) return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout) } diff --git a/cmd/checker/main.go b/cmd/checker/main.go index b813983..7c6959b 100644 --- a/cmd/checker/main.go +++ b/cmd/checker/main.go @@ -1,11 +1,20 @@ -// Command checker executes uptime checks for one region and pulls data from -// external sources. Any number of instances per region may run. +// Command checker executes uptime checks for one region. It talks only to +// the API, never to the database or Redis, so it can run anywhere the API is +// reachable, including customer networks. Any number of instances may share +// a region and token; each check goes to a randomly chosen live instance. package main import ( + "errors" + "fmt" "log/slog" "os" + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" + "git.zb-server.de/ZB-Server/uptimesebi/internal/checker" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" ) @@ -26,19 +35,36 @@ func run(log *slog.Logger, level *slog.LevelVar) error { return err } level.Set(cfg.LogLevel) + if err := cfg.Common.Validate(); err != nil { + return err + } ctx, stop := platform.SignalContext() defer stop() - log = log.With("region", cfg.Region) - deps, err := platform.Connect(ctx, cfg.Common, log) + instance := uuid.New() + client := agentapi.NewClient(cfg.APIURL, cfg.Token, instance, buildinfo.Version) + hello, err := platform.Hello(ctx, client, log) if err != nil { return err } - defer deps.Close() + if hello.Kind != "checker" { + return fmt.Errorf("token belongs to a %s agent, not a checker", hello.Kind) + } + log = log.With("region", hello.Region, "agent", hello.Name, "instance", instance) + log.Info("connected to api") - health := platform.NewHealth(deps.Probes()) + runner := checker.New(client, cfg.Concurrency, log) + health := platform.NewHealth(map[string]platform.Probe{"api": runner.Healthy}) r := platform.NewRouter(log) health.Register(r) - return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout) + serveErr := make(chan error, 1) + go func() { + serveErr <- platform.Serve(ctx, log, platform.NewHTTPServer(cfg.HealthListen, r), health, 0, cfg.ShutdownTimeout) + }() + runErr := runner.Run(ctx, cfg.ShutdownTimeout) + if errors.Is(runErr, agentapi.ErrUnauthorized) { + stop() + } + return errors.Join(runErr, <-serveErr) } diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index c827959..7c74a50 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -1,12 +1,18 @@ // Command statuspage serves public status pages, including on customer -// domains. +// domains. Like the checker it reads data only through the API. package main import ( + "context" + "fmt" "log/slog" "os" "time" + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo" "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/platform" "git.zb-server.de/ZB-Server/uptimesebi/internal/web" @@ -28,16 +34,24 @@ func run(log *slog.Logger, level *slog.LevelVar) error { return err } level.Set(cfg.LogLevel) + if err := cfg.Common.Validate(); err != nil { + return err + } ctx, stop := platform.SignalContext() defer stop() - deps, err := platform.Connect(ctx, cfg.Common, log) + client := agentapi.NewClient(cfg.APIURL, cfg.Token, uuid.New(), buildinfo.Version) + hello, err := platform.Hello(ctx, client, log) if err != nil { return err } - defer deps.Close() + if hello.Kind != "statuspage" { + return fmt.Errorf("token belongs to a %s agent, not a status page server", hello.Kind) + } - health := platform.NewHealth(deps.Probes()) + health := platform.NewHealth(map[string]platform.Probe{ + "api": func(ctx context.Context) error { _, err := client.Hello(ctx); return err }, + }) r := platform.NewRouter(log) health.Register(r) r.StaticFS("/static", web.Static()) diff --git a/deploy/dev/postgres-init.sql b/deploy/dev/postgres-init.sql index 5060fe0..56ebdb6 100644 --- a/deploy/dev/postgres-init.sql +++ b/deploy/dev/postgres-init.sql @@ -5,3 +5,9 @@ CREATE DATABASE uptime OWNER uptime; \connect uptime CREATE EXTENSION IF NOT EXISTS timescaledb; CREATE EXTENSION IF NOT EXISTS citext; + +-- Integration tests run against their own database (UPTIME_TEST_DATABASE_URL). +CREATE DATABASE uptime_test OWNER uptime; +\connect uptime_test +CREATE EXTENSION IF NOT EXISTS timescaledb; +CREATE EXTENSION IF NOT EXISTS citext; diff --git a/internal/api/agent.go b/internal/api/agent.go new file mode 100644 index 0000000..15ca8a1 --- /dev/null +++ b/internal/api/agent.go @@ -0,0 +1,250 @@ +package api + +import ( + "context" + "errors" + "net/http" + "strconv" + "time" + "unicode/utf8" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "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" +) + +// AgentTokenPrefix marks agent tokens, distinct from user API tokens. +const AgentTokenPrefix = "usa_" + +const ( + ctxAgent = "api.agent" + ctxInstance = "api.instance" + maxJobWait = 25 * time.Second + maxJobBatch = 200 +) + +func (s *Server) mountAgentAPI(r gin.IRouter) { + g := r.Group("/agent/v1", s.agentAuth()) + g.GET("/hello", s.agentHello) + checker := g.Group("", requireAgentKind("checker")) + checker.POST("/jobs", s.agentJobs) + checker.POST("/results", s.agentResults) + checker.POST("/release", s.agentRelease) +} + +// agentAuth authenticates the agent token and the protocol version and +// requires an instance ID, which distinguishes processes sharing a token. +func (s *Server) agentAuth() gin.HandlerFunc { + return func(c *gin.Context) { + v, err := strconv.Atoi(c.GetHeader(agentapi.VersionHeader)) + if err != nil || v < agentapi.Version-1 || v > agentapi.Version { + fail(c, http.StatusUpgradeRequired, "agent_protocol_unsupported") + return + } + instance, err := uuid.Parse(c.GetHeader(agentapi.InstanceHeader)) + if err != nil { + fail(c, http.StatusBadRequest, "invalid_input") + return + } + tok := bearerToken(c) + if len(tok) <= len(AgentTokenPrefix) || tok[:len(AgentTokenPrefix)] != AgentTokenPrefix { + fail(c, http.StatusUnauthorized, "unauthenticated") + return + } + ctx := c.Request.Context() + var a store.Agent + release := truncate(c.GetHeader(agentapi.ReleaseHeader), 64) + err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + if a, err = q.GetAgentByHash(ctx, HashToken(tok)); err != nil { + return err + } + return q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release}) + }) + if errors.Is(err, pgx.ErrNoRows) { + fail(c, http.StatusUnauthorized, "unauthenticated") + return + } + if err != nil { + internalError(c, err) + return + } + c.Set(ctxAgent, a) + c.Set(ctxInstance, instance) + c.Next() + } +} + +func requireAgentKind(kind string) gin.HandlerFunc { + return func(c *gin.Context) { + if agentOf(c).Kind != kind { + fail(c, http.StatusForbidden, "forbidden") + return + } + c.Next() + } +} + +func agentOf(c *gin.Context) store.Agent { return c.MustGet(ctxAgent).(store.Agent) } +func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) } +func regionOf(c *gin.Context) string { return deref(agentOf(c).Region) } +func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud } +func (s *Server) allowPrivate(a store.Agent) bool { + // Operator checkers in the cloud share our network; customers must not + // reach it through them. Customer-run checkers and self-hosted + // installations check whatever their operator can reach. + return !s.cloud() || a.OrgID != nil +} + +func (s *Server) agentHello(c *gin.Context) { + a := agentOf(c) + c.JSON(http.StatusOK, agentapi.Hello{ + AgentID: a.ID, Name: a.Name, Kind: a.Kind, Region: deref(a.Region), Protocol: agentapi.Version, + }) +} + +func (s *Server) agentJobs(c *gin.Context) { + var req agentapi.JobsRequest + if !bind(c, &req) { + return + } + ctx := c.Request.Context() + region, instance := regionOf(c), instanceOf(c) + if err := s.sched.Heartbeat(ctx, region, instance); err != nil { + internalError(c, err) + return + } + wait := min(time.Duration(req.WaitMS)*time.Millisecond, maxJobWait) + entries, err := s.sched.Take(ctx, instance, min(req.Max, maxJobBatch), wait) + if err != nil && ctx.Err() == nil { + internalError(c, err) + return + } + jobs, err := s.resolveJobs(ctx, agentOf(c), entries) + if err != nil { + internalError(c, err) + return + } + c.JSON(http.StatusOK, agentapi.JobsResponse{Jobs: jobs}) +} + +// resolveJobs attaches the current monitor settings to dispatched runs. +// Checking is cross-tenant work, hence the system scope. +func (s *Server) resolveJobs(ctx context.Context, a store.Agent, entries []schedule.Entry) ([]agentapi.Job, error) { + jobs := []agentapi.Job{} + if len(entries) == 0 { + return jobs, nil + } + ids := make([]uuid.UUID, len(entries)) + for i, e := range entries { + ids[i] = e.MonitorID + } + var rows []store.Monitor + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + var err error + rows, err = q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: deref(a.Region), Ids: ids}) + return err + }) + if err != nil { + return nil, err + } + byID := make(map[uuid.UUID]store.Monitor, len(rows)) + for _, m := range rows { + byID[m.ID] = m + } + for _, e := range entries { + m, ok := byID[e.MonitorID] + if !ok { + continue + } + jobs = append(jobs, agentapi.Job{ + MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target, + TimeoutMS: int(m.TimeoutMs), Config: m.Config, AllowPrivate: s.allowPrivate(a), + }) + } + return jobs, nil +} + +func (s *Server) agentResults(c *gin.Context) { + var req agentapi.ResultsRequest + if !bind(c, &req) { + return + } + if len(req.Results) > agentapi.MaxResults { + fail(c, http.StatusRequestEntityTooLarge, "invalid_input") + return + } + ctx := c.Request.Context() + region, instance := regionOf(c), instanceOf(c) + ids := make([]uuid.UUID, len(req.Results)) + for i, r := range req.Results { + ids[i] = r.MonitorID + } + now := time.Now() + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { + monitors, err := q.MonitorsForJobs(ctx, store.MonitorsForJobsParams{Region: region, Ids: ids}) + if err != nil { + return err + } + orgOf := make(map[uuid.UUID]uuid.UUID, len(monitors)) + for _, m := range monitors { + orgOf[m.ID] = m.OrgID + } + rows := make([]store.InsertCheckResultsParams, 0, len(req.Results)) + for _, r := range req.Results { + org, ok := orgOf[r.MonitorID] + // A checker may only report monitors of its own region, and + // timestamps far from now are rejected rather than skewing + // history. + if !ok || r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)) { + continue + } + row := store.InsertCheckResultsParams{ + Time: r.StartedAt, OrgID: org, MonitorID: r.MonitorID, Region: region, + CheckerID: instance, Ok: r.OK, LatencyMs: ptr(int32(max(r.LatencyMS, 0))), + } + if r.StatusCode > 0 { + row.StatusCode = ptr(int32(r.StatusCode)) + } + if r.Error != "" { + row.Error = ptr(truncateValid(r.Error, 500)) + } + rows = append(rows, row) + } + if len(rows) == 0 { + return nil + } + _, err = q.InsertCheckResults(ctx, rows) + return err + }) + if err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) +} + +func (s *Server) agentRelease(c *gin.Context) { + if err := s.sched.Release(c.Request.Context(), regionOf(c), instanceOf(c)); err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) +} + +// truncateValid shortens s to n bytes without splitting a UTF-8 sequence. +func truncateValid(s string, n int) string { + if len(s) <= n { + return s + } + for n > 0 && !utf8.RuneStart(s[n]) { + n-- + } + return s[:n] +} diff --git a/internal/api/checker_test.go b/internal/api/checker_test.go new file mode 100644 index 0000000..f9ab00e --- /dev/null +++ b/internal/api/checker_test.go @@ -0,0 +1,205 @@ +package api_test + +import ( + "context" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/auth" + "git.zb-server.de/ZB-Server/uptimesebi/internal/checker" + "git.zb-server.de/ZB-Server/uptimesebi/internal/store" + "git.zb-server.de/ZB-Server/uptimesebi/internal/tenant" +) + +// agentToken creates a checker agent for region directly in the database, +// as "api agent create" would. +func (e *env) agentToken(t *testing.T, region string) string { + t.Helper() + tok := api.AgentTokenPrefix + auth.RandomToken() + ctx := context.Background() + err := tenant.New(e.dbPool).Tx(ctx, tenant.System(), func(q *store.Queries) error { + if _, err := q.UpsertRegion(ctx, store.UpsertRegionParams{Key: region}); err != nil { + return err + } + _, err := q.CreateAgent(ctx, store.CreateAgentParams{ + Kind: "checker", Name: "test-" + region, Region: ®ion, TokenHash: api.HashToken(tok), Prefix: tok[:10], + }) + return err + }) + if err != nil { + t.Fatalf("creating agent: %v", err) + } + return tok +} + +// startChecker runs a checker instance until the returned stop is called. +func (e *env) startChecker(t *testing.T, token string) (uuid.UUID, func()) { + t.Helper() + id := uuid.New() + client := agentapi.NewClient(e.srv.URL, token, id, "test").WithHTTPClient(e.srv.Client()) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + _ = checker.New(client, 8, slog.New(slog.DiscardHandler)).Run(ctx, 5*time.Second) + }() + var once bool + stop := func() { + if once { + return + } + once = true + cancel() + <-done + } + t.Cleanup(stop) + return id, stop +} + +func TestCheckersPerRegion(t *testing.T) { + e := newEnv(t) + ctx, cancel := context.WithCancel(context.Background()) + t.Cleanup(cancel) + go e.api.RunScheduler(ctx) + + target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/down" { + w.WriteHeader(http.StatusInternalServerError) + } + })) + defer target.Close() + + eu, us := uniq("eu-"), uniq("us-") + euTok, usTok := e.agentToken(t, eu), e.agentToken(t, us) + euA, stopA := e.startChecker(t, euTok) + euB, _ := e.startChecker(t, euTok) + usC, _ := e.startChecker(t, usTok) + + owner := e.browser(t) + owner.signup("o@"+uniq("c")+".test", uniq("chk-")) + org := owner.orgID() + + // Instances register on their first poll. + waitFor(t, 5*time.Second, "both eu instances registered", func() bool { + _, body := owner.do("GET", "/api/v1/regions", nil) + for _, r := range body["regions"].([]any) { + r := r.(map[string]any) + if r["key"] == eu && r["instances"] == float64(2) { + return true + } + } + return false + }) + + const n = 30 + for i := range n { + path := "/up" + if i == 0 { + path = "/down" + } + regions := []string{eu} + if i < 3 { + regions = append(regions, us) + } + st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "m", "type": "http", "target": target.URL + path, "interval_seconds": 3600, "regions": regions, + }) + if st != http.StatusCreated { + t.Fatalf("create monitor = %d %v", st, body) + } + } + + count := func(checker uuid.UUID) (total, failed int) { + _ = e.dbPool.QueryRow(context.Background(), + `SELECT count(*), count(*) FILTER (WHERE NOT ok) FROM check_results WHERE org_id = $1 AND checker_id = $2`, + org, checker).Scan(&total, &failed) + return total, failed + } + waitFor(t, 15*time.Second, "all first runs reported", func() bool { + a, _ := count(euA) + b, _ := count(euB) + c, _ := count(usC) + return a+b == n && c == 3 + }) + a, aFailed := count(euA) + b, bFailed := count(euB) + if a < 5 || b < 5 { + t.Errorf("eu instances ran %d and %d checks, want both to get a random share of %d", a, b, n) + } + if aFailed+bFailed != 1 { + t.Errorf("failed eu checks = %d, want 1 (the /down monitor)", aFailed+bFailed) + } + + _, body := owner.do("GET", "/api/v1/org/monitors", nil) + withLatest := 0 + for _, m := range body["monitors"].([]any) { + if len(m.(map[string]any)["latest"].([]any)) > 0 { + withLatest++ + } + } + if withLatest != n { + t.Errorf("monitors with latest results = %d, want %d", withLatest, n) + } + + // Stopping one eu instance leaves the other to take every eu check. + stopA() + st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{ + "name": "after", "type": "tcp", "target": target.Listener.Addr().String(), "interval_seconds": 3600, "regions": []string{eu}, + }) + if st != http.StatusCreated { + t.Fatalf("create monitor = %d %v", st, body) + } + before, _ := count(euB) + waitFor(t, 10*time.Second, "remaining eu instance runs the new monitor", func() bool { + now, _ := count(euB) + return now == before+1 + }) + if after, _ := count(euA); after != a { + t.Errorf("stopped instance ran %d more checks", after-a) + } +} + +func TestAgentAuth(t *testing.T) { + e := newEnv(t) + tok := e.agentToken(t, uniq("x-")) + ctx := context.Background() + if _, err := agentapi.NewClient(e.srv.URL, "usa_wrong", uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx); !errors.Is(err, agentapi.ErrUnauthorized) { + t.Errorf("Hello(wrong token) = %v, want %v", err, agentapi.ErrUnauthorized) + } + h, err := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "t").WithHTTPClient(e.srv.Client()).Hello(ctx) + if err != nil || h.Kind != "checker" { + t.Errorf("Hello() = %+v, %v; want checker", h, err) + } + // User API tokens and sessions do not open the agent API. + owner := e.browser(t) + owner.signup("a@"+uniq("a")+".test", uniq("auth-")) + st, _ := owner.do("GET", "/agent/v1/hello", nil) + if st == http.StatusOK { + t.Error("session opened the agent API") + } +} + +func (b *browser) orgID() string { + b.t.Helper() + _, me := b.do("GET", "/api/v1/me", nil) + return me["active_org"].(string) +} + +func waitFor(t *testing.T, d time.Duration, what string, cond func() bool) { + t.Helper() + deadline := time.Now().Add(d) + for !cond() { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for: %s", what) + } + time.Sleep(100 * time.Millisecond) + } +} diff --git a/internal/api/invitations.go b/internal/api/invitations.go index 1ff42c9..31620d1 100644 --- a/internal/api/invitations.go +++ b/internal/api/invitations.go @@ -65,7 +65,7 @@ func (s *Server) createInvitation(c *gin.Context) { } } _, err = q.CreateInvitation(ctx, store.CreateInvitationParams{ - OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: hashToken(tok), + OrgID: p.Org.ID, Email: email, RoleID: role.ID, TokenHash: HashToken(tok), InvitedBy: &p.UserID, ExpiresAt: time.Now().Add(invitationTTL), }) return err @@ -138,7 +138,7 @@ func (s *Server) deleteInvitation(c *gin.Context) { // findInvitation returns the invitation for tok, or ok=false if it does not // exist, was used or has expired. func (s *Server) findInvitation(ctx context.Context, tok string) (inv store.GetInvitationByHashRow, ok bool, err error) { - hash := hashToken(tok) + hash := HashToken(tok) var org uuid.UUID err = s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { org, err = q.InvitationOrg(ctx, hash) diff --git a/internal/api/monitors.go b/internal/api/monitors.go new file mode 100644 index 0000000..6b8683b --- /dev/null +++ b/internal/api/monitors.go @@ -0,0 +1,376 @@ +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 []string `json:"regions" binding:"required,min=1,max=50"` +} + +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"` + Regions []string `json:"regions"` + Latest []latestView `json:"latest"` +} + +func viewMonitor(m store.Monitor, regions []string) 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, 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.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.Sort(req.Regions) + 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.ListRegions(ctx) + return err + }) + if err != nil { + internalError(c, err) + return false + } + for _, r := range req.Regions { + if !slices.ContainsFunc(known, func(k store.Region) bool { return k.Key == 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][]string{} + for _, r := range regions { + byMonitor[r.MonitorID] = append(byMonitor[r.MonitorID], r.Region) + } + 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, + }) + 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 []string) 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, Region: 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 []string) error { + if !m.Enabled { + return s.sched.Remove(ctx, m.ID, append(regions, previous...)) + } + return s.sched.Upsert(ctx, schedule.Monitor{ + ID: m.ID, Interval: time.Duration(m.IntervalSeconds) * time.Second, Regions: regions, + }, previous) +} + +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 []string + ) + 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, + }) + 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 []string + 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, regions); err != nil { + internalError(c, err) + return + } + c.Status(http.StatusNoContent) +} + +type regionView struct { + Key string `json:"key"` + Name string `json:"name"` + Instances int64 `json:"instances"` +} + +func (s *Server) listRegions(c *gin.Context) { + ctx := c.Request.Context() + var rows []store.Region + err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { + var err error + rows, err = q.ListRegions(ctx) + return err + }) + if err != nil { + internalError(c, err) + return + } + out := make([]regionView, len(rows)) + for i, r := range rows { + n, err := s.sched.Instances(ctx, r.Key) + if err != nil { + internalError(c, err) + return + } + out[i] = regionView{Key: r.Key, Name: r.Name, Instances: n} + } + c.JSON(http.StatusOK, gin.H{"regions": out}) +} + +// 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) + } +} diff --git a/internal/api/server.go b/internal/api/server.go index 47cbd75..e83386a 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -16,6 +16,7 @@ import ( "git.zb-server.de/ZB-Server/uptimesebi/internal/config" "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" + "git.zb-server.de/ZB-Server/uptimesebi/internal/schedule" "git.zb-server.de/ZB-Server/uptimesebi/internal/sealed" "git.zb-server.de/ZB-Server/uptimesebi/internal/sso" "git.zb-server.de/ZB-Server/uptimesebi/internal/store" @@ -36,6 +37,7 @@ type Server struct { limiter *auth.Limiter totp *auth.TOTPVerifier sso *sso.Client + sched *schedule.Scheduler } // Deps are the external resources a Server needs. @@ -61,16 +63,22 @@ func New(cfg config.API, d Deps) *Server { limiter: auth.NewLimiter(d.Redis), totp: auth.NewTOTPVerifier(d.Redis), sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate), + sched: schedule.New(d.Redis), } } // Mount installs session loading, locale resolution and CSRF protection and // registers the JSON API and the console pages below them. func (s *Server) Mount(r gin.IRouter) { + // Agents authenticate with tokens and never carry cookies, so they skip + // the session and CSRF middleware. + s.mountAgentAPI(r) + g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF()) v1 := g.Group("/api/v1") v1.POST("/locale", s.setLocale) + v1.GET("/regions", auth.Require(), s.listRegions) a := v1.Group("/auth") a.POST("/signup", s.signup) @@ -92,6 +100,11 @@ func (s *Server) Mount(r gin.IRouter) { org := v1.Group("/org", s.orgAccess()) org.PUT("/policy", sessionOnly(), can(authz.OrgManage), s.updatePolicy) + org.GET("/monitors", can(authz.MonitorsRead), s.listMonitors) + org.POST("/monitors", can(authz.MonitorsWrite), s.createMonitor) + org.PUT("/monitors/:id", can(authz.MonitorsWrite), s.updateMonitor) + org.DELETE("/monitors/:id", can(authz.MonitorsWrite), s.deleteMonitor) + org.GET("/sso", can(authz.OrgManage), s.listSSOProviders) org.POST("/sso", sessionOnly(), can(authz.OrgManage), s.createSSOProvider) org.PUT("/sso/:id", sessionOnly(), can(authz.OrgManage), s.updateSSOProvider) diff --git a/internal/api/sso_test.go b/internal/api/sso_test.go index 1803ad3..5422510 100644 --- a/internal/api/sso_test.go +++ b/internal/api/sso_test.go @@ -34,6 +34,7 @@ import ( type env struct { srv *httptest.Server dbPool *pgxpool.Pool + api *api.Server } func newEnv(t *testing.T) *env { @@ -89,7 +90,8 @@ func newEnv(t *testing.T) *env { PublicURL: e.srv.URL, SSOPrivateNetworks: "true", } - api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}).Mount(r) + e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog}) + e.api.Mount(r) return e } diff --git a/internal/api/tokens.go b/internal/api/tokens.go index 9b7efa0..6539c9e 100644 --- a/internal/api/tokens.go +++ b/internal/api/tokens.go @@ -21,7 +21,8 @@ import ( // tokenPrefix makes tokens recognizable to secret scanners and to humans. const tokenPrefix = "ust_" -func hashToken(tok string) []byte { +// HashToken returns the stored form of an API or agent token. +func HashToken(tok string) []byte { sum := sha256.Sum256([]byte(tok)) return sum[:] } @@ -38,7 +39,7 @@ func (s *Server) tokenPrincipal(ctx context.Context, tok string) (*principal, in if !strings.HasPrefix(tok, tokenPrefix) { return nil, http.StatusUnauthorized, "unauthenticated", nil } - hash := hashToken(tok) + hash := HashToken(tok) var org uuid.UUID err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error { var err error @@ -163,7 +164,7 @@ func (s *Server) createToken(c *gin.Context) { var err error row, err = q.CreateAPIToken(ctx, store.CreateAPITokenParams{ OrgID: p.Org.ID, UserID: p.UserID, Name: strings.TrimSpace(req.Name), - TokenHash: hashToken(tok), Prefix: tok[:len(tokenPrefix)+6], + TokenHash: HashToken(tok), Prefix: tok[:len(tokenPrefix)+6], Permissions: perms.Strings(), ExpiresAt: expires, }) return err diff --git a/internal/checker/checker.go b/internal/checker/checker.go new file mode 100644 index 0000000..3abf049 --- /dev/null +++ b/internal/checker/checker.go @@ -0,0 +1,201 @@ +// Package checker is the checker agent: it fetches jobs from the API, runs +// them and reports the results. It keeps no state beyond results that are +// waiting to be sent. +package checker + +import ( + "context" + "errors" + "log/slog" + "sync" + "sync/atomic" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" +) + +// API is the part of agentapi.Client the runner uses. +type API interface { + Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) + Report(ctx context.Context, results []agentapi.Result) error + Release(ctx context.Context) error +} + +const ( + pollWait = 20 * time.Second + flushInterval = 2 * time.Second + // maxPending bounds results kept while the API is unreachable. + maxPending = 50_000 +) + +// Runner executes jobs with bounded concurrency. +type Runner struct { + api API + log *slog.Logger + slots chan struct{} + run func(context.Context, check.Spec) check.Outcome + + results chan agentapi.Result + lastPoll atomic.Int64 +} + +// New returns a Runner that runs at most concurrency checks at once. +func New(api API, concurrency int, log *slog.Logger) *Runner { + return &Runner{ + api: api, + log: log, + slots: make(chan struct{}, max(concurrency, 1)), + run: check.Run, + results: make(chan agentapi.Result, 1024), + } +} + +// Healthy reports an error unless the API answered a poll recently. +func (r *Runner) Healthy(context.Context) error { + if time.Since(time.UnixMilli(r.lastPoll.Load())) > 2*pollWait+10*time.Second { + return errors.New("no successful poll recently") + } + return nil +} + +// Run polls and executes jobs until ctx is cancelled, then hands queued jobs +// back, lets running checks finish within drain and sends the last results. +// It returns early only if the API rejects the agent token. +func (r *Runner) Run(ctx context.Context, drain time.Duration) error { + var running sync.WaitGroup + reportDone := make(chan struct{}) + reportCtx, stopReport := context.WithCancel(context.WithoutCancel(ctx)) + go func() { + defer close(reportDone) + r.report(reportCtx) + }() + + err := r.poll(ctx, &running) + + releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + if rerr := r.api.Release(releaseCtx); rerr != nil { + r.log.Warn("release failed; queued jobs move to other instances once this one is considered gone", "error", rerr) + } + cancel() + + waited := make(chan struct{}) + go func() { running.Wait(); close(waited) }() + select { + case <-waited: + case <-time.After(drain): + r.log.Warn("checks still running at shutdown", "drain", drain) + } + stopReport() + <-reportDone + return err +} + +func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { + backoff := time.Second + for ctx.Err() == nil { + free := cap(r.slots) - len(r.slots) + wait := pollWait + if free == 0 { + // Still poll as a heartbeat, but do not take work. + wait = 0 + } + jobs, err := r.api.Jobs(ctx, free, wait) + switch { + case errors.Is(err, agentapi.ErrUnauthorized): + return err + case err != nil: + if ctx.Err() != nil { + return nil + } + r.log.Warn("polling for jobs failed", "error", err, "retry_in", backoff) + sleep(ctx, backoff) + backoff = min(backoff*2, 30*time.Second) + continue + } + backoff = time.Second + r.lastPoll.Store(time.Now().UnixMilli()) + for _, j := range jobs { + r.slots <- struct{}{} + running.Add(1) + go func() { + defer func() { <-r.slots; running.Done() }() + r.results <- r.execute(ctx, j) + }() + } + if free == 0 { + sleep(ctx, time.Second) + } + } + return nil +} + +func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result { + // Checks already started finish even during shutdown; their timeout + // bounds them. + ctx = context.WithoutCancel(ctx) + start := time.Now() + o := r.run(ctx, check.Spec{ + Type: check.Type(j.Type), Target: j.Target, Timeout: time.Duration(j.TimeoutMS) * time.Millisecond, + Config: j.Config, AllowPrivate: j.AllowPrivate, + }) + return agentapi.Result{ + MonitorID: j.MonitorID, ScheduledAt: j.ScheduledAt, StartedAt: start, OK: o.OK, + LatencyMS: int(o.Latency.Milliseconds()), StatusCode: o.StatusCode, Error: o.Error, + } +} + +// report batches results and sends them. Unsent results are retried with +// the next batch; when ctx ends it makes one last attempt. +func (r *Runner) report(ctx context.Context) { + tick := time.NewTicker(flushInterval) + defer tick.Stop() + var pending []agentapi.Result + flush := func(ctx context.Context) { + for len(pending) > 0 { + n := min(len(pending), agentapi.MaxResults) + if err := r.api.Report(ctx, pending[:n]); err != nil { + r.log.Warn("reporting results failed", "error", err, "pending", len(pending)) + return + } + pending = pending[n:] + } + } + for { + select { + case res := <-r.results: + pending = append(pending, res) + if len(pending) > maxPending { + dropped := len(pending) - maxPending + pending = pending[dropped:] + r.log.Warn("dropping old results while the API is unreachable", "dropped", dropped) + } + if len(pending) >= agentapi.MaxResults { + flush(ctx) + } + case <-tick.C: + flush(ctx) + case <-ctx.Done(): + for { + select { + case res := <-r.results: + pending = append(pending, res) + continue + default: + } + break + } + last, cancel := context.WithTimeout(context.Background(), 5*time.Second) + flush(last) + cancel() + return + } + } +} + +func sleep(ctx context.Context, d time.Duration) { + select { + case <-ctx.Done(): + case <-time.After(d): + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 3aead1d..82c03d7 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -24,14 +24,25 @@ const ( // Common holds settings shared by all components. type Common struct { - Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` - LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` - DatabaseURL string `env:"UPTIME_DATABASE_URL"` - RedisURL string `env:"UPTIME_REDIS_URL"` - RedisSentinel Sentinel + Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` + LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` ShutdownTimeout time.Duration `env:"UPTIME_SHUTDOWN_TIMEOUT" envDefault:"20s"` } +// Storage locates Postgres and Redis. Only the API connects to them; every +// other component goes through the API. +type Storage struct { + DatabaseURL string `env:"UPTIME_DATABASE_URL"` + RedisURL string `env:"UPTIME_REDIS_URL"` + RedisSentinel Sentinel +} + +// Agent configures how checkers and status page servers reach the API. +type Agent struct { + APIURL string `env:"UPTIME_API_URL,required,notEmpty"` + Token string `env:"UPTIME_AGENT_TOKEN,required,notEmpty"` +} + // Sentinel switches the redis client to failover mode. UPTIME_REDIS_URL then // only contributes credentials, db and TLS for the master; its host is ignored. type Sentinel struct { @@ -58,6 +69,7 @@ const ( // API configures cmd/api. type API struct { Common + Storage Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"` SecretKeys string `env:"UPTIME_SECRET_KEYS"` Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"` @@ -86,6 +98,9 @@ func (a API) Validate() error { if err := a.Common.Validate(); err != nil { return err } + if err := a.Storage.Validate(); err != nil { + return err + } if a.SecretKeys == "" { return fmt.Errorf("config: UPTIME_SECRET_KEYS is required (format id:base64-32-bytes)") } @@ -108,17 +123,19 @@ func (a API) Validate() error { return nil } -// Checker configures cmd/checker. Region names the location this instance -// checks from and must match the regions assigned to monitors. +// Checker configures cmd/checker. Its region is bound to the agent token. type Checker struct { Common - Region string `env:"UPTIME_CHECKER_REGION,required,notEmpty"` + Agent HealthListen string `env:"UPTIME_CHECKER_HEALTH_LISTEN" envDefault:":8081"` + // Concurrency caps checks running at the same time in one instance. + Concurrency int `env:"UPTIME_CHECKER_CONCURRENCY" envDefault:"64"` } // StatusPage configures cmd/statuspage. type StatusPage struct { Common + Agent Listen string `env:"UPTIME_STATUSPAGE_LISTEN" envDefault:":8082"` } @@ -131,13 +148,17 @@ func Load[T any]() (T, error) { return cfg, nil } -// Validate reports missing or contradictory settings. +// Validate reports an unknown edition. func (c Common) Validate() error { switch c.Edition { case EditionCloud, EditionSelfHosted: - default: - return fmt.Errorf("config: unknown edition %q", c.Edition) + return nil } + return fmt.Errorf("config: unknown edition %q", c.Edition) +} + +// Validate reports missing or contradictory database and Redis settings. +func (c Storage) Validate() error { if c.DatabaseURL == "" { return fmt.Errorf("config: UPTIME_DATABASE_URL is required") } diff --git a/internal/config/config_test.go b/internal/config/config_test.go index c62092a..2ed970c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -2,20 +2,20 @@ package config import "testing" -func TestCommonValidateRedisModes(t *testing.T) { +func TestStorageValidateRedisModes(t *testing.T) { tests := []struct { name string - modify func(*Common) + modify func(*Storage) wantErr bool }{ - {"standalone", func(c *Common) { c.RedisURL = "redis://r" }, false}, - {"no redis", func(*Common) {}, true}, - {"sentinel", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false}, - {"sentinel without addrs", func(c *Common) { c.RedisSentinel = Sentinel{Master: "m"} }, true}, + {"standalone", func(c *Storage) { c.RedisURL = "redis://r" }, false}, + {"no redis", func(*Storage) {}, true}, + {"sentinel", func(c *Storage) { c.RedisSentinel = Sentinel{Master: "m", Addrs: []string{"s:26379"}} }, false}, + {"sentinel without addrs", func(c *Storage) { c.RedisSentinel = Sentinel{Master: "m"} }, true}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := Common{Edition: EditionSelfHosted, DatabaseURL: "postgres://x"} + c := Storage{DatabaseURL: "postgres://x"} tt.modify(&c) if err := c.Validate(); (err != nil) != tt.wantErr { t.Errorf("Validate() = %v, want error: %t", err, tt.wantErr) diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go index 16a932c..c6d3676 100644 --- a/internal/i18n/i18n_test.go +++ b/internal/i18n/i18n_test.go @@ -68,6 +68,7 @@ var usagePatterns = []struct { {re: regexp.MustCompile(`[^(]"(sso_[a-z_]+)"`), prefix: "error.", dir: "api"}, {re: regexp.MustCompile(`return "(invalid_[a-z_]+)"`), prefix: "error."}, {re: regexp.MustCompile(`code = "([a-z_]+)"`), prefix: "error."}, + {re: regexp.MustCompile(`\binvalid\("([a-z_]+)"\)`), prefix: "error."}, {re: regexp.MustCompile(`NoticeID = "([a-z0-9_.]+)"`)}, {re: regexp.MustCompile(`@(?:settingsHeading|sectionHeading)\("([a-z0-9_.]+)"`)}, {re: regexp.MustCompile(`@settingsHeading\("[a-z0-9_.]+", "([a-z0-9_.]+)"`)}, diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index f610030..f4a1e12 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -32,20 +32,33 @@ "console.nav.tokens": "API-Tokens", "console.sso_required_action": "Mit SSO anmelden", "console.totp_missing_action": "Jetzt einrichten", + "error.agent_protocol_unsupported": "Diese Agent-Version wird von der API nicht unterstützt. Bitte den Agent aktualisieren.", "error.already_assigned": "Das Mitglied hat diese Rolle bereits.", "error.already_member": "Diese Person ist bereits Mitglied.", "error.email_taken": "Diese E-Mail-Adresse ist bereits registriert.", "error.forbidden": "Dafür fehlt dir die Berechtigung.", "error.internal": "Interner Fehler.", "error.invalid_code": "Code ungültig.", + "error.invalid_config": "Die Check-Einstellungen sind ungültig.", "error.invalid_credentials": "E-Mail oder Passwort falsch.", "error.invalid_domain": "Eine der Domains ist ungültig.", "error.invalid_email": "Bitte eine gültige E-Mail-Adresse eingeben.", + "error.invalid_expect_status": "Erwartete Statuscodes müssen Codes wie 200 oder Klassen wie 2xx sein.", + "error.invalid_header": "Ein Request-Header ist ungültig.", "error.invalid_input": "Eingaben prüfen.", + "error.invalid_interval": "Das Intervall muss mindestens {{.Min}} Sekunden und höchstens einen Tag betragen.", + "error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.", "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", + "error.invalid_record": "Nicht unterstützter DNS-Record-Typ.", + "error.invalid_region": "Unbekannte Region.", + "error.invalid_resolver": "Der Resolver muss als host:port angegeben werden.", "error.invalid_slug": "Kurzname: 2–63 Zeichen, a–z, 0–9 und Bindestrich.", + "error.invalid_target": "Das Ziel passt nicht zu diesem Check-Typ.", + "error.invalid_timeout": "Der Timeout muss zwischen 100 ms und 60 s liegen und kürzer als das Intervall sein.", + "error.invalid_type": "Unbekannter Check-Typ.", "error.invitation_email_mismatch": "Diese Einladung ging an eine andere E-Mail-Adresse als die, mit der du angemeldet bist.", "error.invitation_invalid": "Diese Einladung ist ungültig, abgelaufen oder wurde bereits verwendet.", + "error.keyword_needs_get": "Keyword-Checks brauchen GET-Anfragen.", "error.mfa_expired": "Anmeldung abgelaufen, bitte erneut anmelden.", "error.no_password": "Konto ohne Passwort.", "error.not_found": "Nicht gefunden.", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index 19b7654..41979f2 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -32,20 +32,33 @@ "console.nav.tokens": "API tokens", "console.sso_required_action": "Sign in with SSO", "console.totp_missing_action": "Set up now", + "error.agent_protocol_unsupported": "This agent version is not supported by the API. Please update the agent.", "error.already_assigned": "The member already has this role.", "error.already_member": "This person is already a member.", "error.email_taken": "This email address is already registered.", "error.forbidden": "You are not allowed to do this.", "error.internal": "Internal error.", "error.invalid_code": "Invalid code.", + "error.invalid_config": "The check settings are not valid.", "error.invalid_credentials": "Wrong email or password.", "error.invalid_domain": "One of the domains is not valid.", "error.invalid_email": "Please enter a valid email address.", + "error.invalid_expect_status": "Expected status codes must be codes like 200 or classes like 2xx.", + "error.invalid_header": "A request header is not valid.", "error.invalid_input": "Please check your input.", + "error.invalid_interval": "The interval must be at least {{.Min}} seconds and at most one day.", + "error.invalid_method": "Only GET and HEAD requests are supported.", "error.invalid_permissions": "Choose at least one permission.", + "error.invalid_record": "Unsupported DNS record type.", + "error.invalid_region": "Unknown region.", + "error.invalid_resolver": "The resolver must be given as host:port.", "error.invalid_slug": "Short name: 2–63 characters, a–z, 0–9 and hyphen.", + "error.invalid_target": "The target is not valid for this check type.", + "error.invalid_timeout": "The timeout must be between 100 ms and 60 s and shorter than the interval.", + "error.invalid_type": "Unknown check type.", "error.invitation_email_mismatch": "This invitation was sent to a different email address than the one you are signed in with.", "error.invitation_invalid": "This invitation is invalid, expired or was already used.", + "error.keyword_needs_get": "Keyword checks need GET requests.", "error.mfa_expired": "Sign-in expired, please start again.", "error.no_password": "This account has no password.", "error.not_found": "Not found.", diff --git a/internal/platform/agent.go b/internal/platform/agent.go new file mode 100644 index 0000000..af5d7d8 --- /dev/null +++ b/internal/platform/agent.go @@ -0,0 +1,29 @@ +package platform + +import ( + "context" + "errors" + "log/slog" + "time" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" +) + +// Hello waits until the API accepts the agent token, retrying while the API +// is unreachable so agents can start before it. A rejected token is fatal. +func Hello(ctx context.Context, c *agentapi.Client, log *slog.Logger) (agentapi.Hello, error) { + backoff := time.Second + for { + h, err := c.Hello(ctx) + if err == nil || errors.Is(err, agentapi.ErrUnauthorized) || ctx.Err() != nil { + return h, err + } + log.Warn("api not reachable yet", "error", err, "retry_in", backoff) + select { + case <-ctx.Done(): + return h, ctx.Err() + case <-time.After(backoff): + } + backoff = min(backoff*2, 30*time.Second) + } +} diff --git a/internal/platform/redis.go b/internal/platform/redis.go index 585704f..414d6a6 100644 --- a/internal/platform/redis.go +++ b/internal/platform/redis.go @@ -11,7 +11,7 @@ import ( // OpenRedis connects to a single server or, when c.RedisSentinel is enabled, // to the current master via sentinel with automatic failover. -func OpenRedis(ctx context.Context, c config.Common) (*redis.Client, error) { +func OpenRedis(ctx context.Context, c config.Storage) (*redis.Client, error) { var rdb *redis.Client if c.RedisSentinel.Enabled() { opts, err := failoverOptions(c.RedisURL, c.RedisSentinel) diff --git a/internal/platform/run.go b/internal/platform/run.go index 3b3a715..843a8e4 100644 --- a/internal/platform/run.go +++ b/internal/platform/run.go @@ -47,7 +47,7 @@ func SignalContext() (context.Context, context.CancelFunc) { // Connect validates c, refuses to start against an outdated schema, and // opens Postgres and Redis. -func Connect(ctx context.Context, c config.Common, log *slog.Logger) (*Deps, error) { +func Connect(ctx context.Context, c config.Storage, log *slog.Logger) (*Deps, error) { if err := c.Validate(); err != nil { return nil, err }