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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
1 parent
56862dce84
commit
d9891bb050
23 files changed
+1361
-45
No files matched your search
@@ -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]
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user