Files
uptimesebi/internal/api/agent.go
T
Sebastian UnterschützandClaude Opus 5.5 538c43b563
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m29s
ci / test (pull_request) Successful in 12m55s
ci / build (pull_request) Successful in 16m45s
ci / image (pull_request) Successful in 5m41s
feat(agents): talk to the API over a WebSocket and push page changes
Checkers and status page servers keep one WebSocket open to the API at
/agent/v1/stream and send their requests over it. The API answers them
through the agent API as if they had come over HTTP, each authenticated
again, so the protocol stays the same and a revoked token ends the
stream. While the stream is down agents fall back to plain HTTP, and an
API without it is asked again every five minutes.

Over the stream the API tells status page servers which of their pages
changed, so they fetch them at once instead of on their next refresh:
when a region of a monitor changes between up and down, an incident
opens or resolves, or anything of the organization is edited. Changes
are announced through Redis to every API instance and sent at most every
five seconds per stream. A page that changes while it is fetched is
fetched once more.

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

423 lines
13 KiB
Go

package api
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"unicode/utf8"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
agentdeploy "git.zb-server.de/ZB-Server/uptimesebi/deploy/agent"
"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/check"
"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"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// AgentTokenPrefix marks agent tokens, distinct from user API tokens.
const AgentTokenPrefix = "usa_"
const (
ctxAgent = "api.agent"
ctxInstance = "api.instance"
maxJobWait = 25 * time.Second
// drainingPollHold is how long a draining instance still holds a poll.
drainingPollHold = time.Second
maxJobBatch = 200
)
func (s *Server) mountAgentAPI(r gin.IRouter) {
g := r.Group(agentapi.Prefix, s.agentAuth())
g.GET("/hello", s.agentHello)
g.GET("/update", s.agentUpdate)
g.GET(agentapi.StreamPath, s.agentStream)
sp := g.Group("", requireAgentKind("statuspage"))
sp.GET("/pages", s.agentPage)
sp.GET("/pages/index", s.agentPageIndex)
sp.GET("/storage", s.storageGet)
sp.PUT("/storage", s.storagePut)
sp.DELETE("/storage", s.storageDelete)
sp.GET("/storage/stat", s.storageStat)
sp.GET("/storage/list", s.storageList)
sp.POST("/storage/lock", s.storageLock)
sp.DELETE("/storage/lock", s.storageUnlock)
sp.POST("/certificates", s.agentCertificate)
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.GetAgentByHashRow
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
}
// The launcher of a self-updating agent asks for updates with
// an instance of its own; only the agent itself is a sign of life.
if strings.HasSuffix(c.FullPath(), "/agent/v1/update") {
return nil
}
if err := q.TouchAgent(ctx, store.TouchAgentParams{ID: a.ID, Release: &release}); err != nil {
return err
}
return q.TouchAgentInstance(ctx, store.TouchAgentInstanceParams{ID: instance, AgentID: a.ID, OrgID: a.OrgID, 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.GetAgentByHashRow {
return c.MustGet(ctxAgent).(store.GetAgentByHashRow)
}
func instanceOf(c *gin.Context) uuid.UUID { return c.MustGet(ctxInstance).(uuid.UUID) }
// regionOf returns the agent's region ID in the string form used for the
// schedule and check results.
func regionOf(c *gin.Context) string {
if id := agentOf(c).RegionID; id != nil {
return id.String()
}
return ""
}
func (s *Server) cloud() bool { return s.cfg.Edition == config.EditionCloud }
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.RegionKey), RegionID: a.RegionID,
RegionName: deref(a.RegionName), OrgOwned: a.OrgID != nil, Protocol: agentapi.Version,
})
}
// agentUpdate names the release self-updating agents run: the platform's
// own, so agents never get ahead of the API. Unreleased builds ("dev")
// are not followed.
func (s *Server) agentUpdate(c *gin.Context) {
u := agentapi.Update{Version: buildinfo.Version}
if buildinfo.Version != "dev" {
u.Image = s.cfg.AgentImage + "-" + agentOf(c).Kind + ":" + strings.TrimPrefix(buildinfo.Version, "v")
}
c.JSON(http.StatusOK, u)
}
// installView is what the console shows to install a new agent.
func (s *Server) installView() web.InstallView {
v := web.InstallView{
ScriptURL: strings.TrimSuffix(s.cfg.PublicURL, "/") + "/install.sh",
APIURL: strings.TrimSuffix(s.cfg.PublicURL, "/"),
Image: s.cfg.AgentImage,
Channel: agentdeploy.Channel(buildinfo.Version),
Compose: map[string]string{},
}
if buildinfo.Version != "dev" {
v.Release = buildinfo.Version
}
for _, kind := range []string{"checker", "statuspage"} {
if c, err := agentdeploy.Compose(kind); err == nil {
v.Compose[kind] = string(c)
}
}
return v
}
// installScript serves the script that installs a checker or status page
// server with Docker Compose, pointed at this platform.
func (s *Server) installScript(c *gin.Context) {
script, err := agentdeploy.Script(agentdeploy.Install{
APIURL: s.cfg.PublicURL, Image: s.cfg.AgentImage, Tag: agentdeploy.Channel(buildinfo.Version),
})
if err != nil {
internalError(c, err)
return
}
c.Header("Cache-Control", "no-store")
c.Data(http.StatusOK, "text/x-shellscript; charset=utf-8", script)
}
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)
// A draining instance ends long polls within a second or so, empty, so
// the shutdown is not held up and the checker's next poll reaches
// another instance. It still holds them that second, so checkers that
// poll again at once do not spin against it.
pollCtx, stop := context.WithCancel(ctx)
defer stop()
if s.draining != nil {
go func() {
select {
case <-s.draining:
select {
case <-time.After(drainingPollHold):
case <-pollCtx.Done():
}
stop()
case <-pollCtx.Done():
}
}()
}
entries, err := s.sched.Take(pollCtx, instance, min(req.Max, maxJobBatch), wait)
if err != nil && pollCtx.Err() == nil {
internalError(c, err)
return
}
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries)
if err != nil {
internalError(c, err)
return
}
s.trackRunning(ctx, instance, jobs, orgs)
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.
// It also returns each monitor's organization.
func (s *Server) resolveJobs(ctx context.Context, a store.GetAgentByHashRow, entries []schedule.Entry) ([]agentapi.Job, map[uuid.UUID]uuid.UUID, error) {
jobs := []agentapi.Job{}
orgs := map[uuid.UUID]uuid.UUID{}
if len(entries) == 0 {
return jobs, orgs, 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{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
return err
})
if err != nil {
return nil, nil, err
}
allowPrivate := s.allowPrivate(ctx, a)
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
}
cfg, err := s.openMonitorConfig(check.Type(m.Type), m.Config)
if err != nil {
s.log.ErrorContext(ctx, "opening monitor secrets failed", "monitor", m.ID, "error", err)
continue
}
jobs = append(jobs, agentapi.Job{
MonitorID: m.ID, ScheduledAt: e.ScheduledAt, Type: m.Type, Target: m.Target,
TimeoutMS: int(m.TimeoutMs), Config: cfg, AllowPrivate: allowPrivate,
})
orgs[m.ID] = m.OrgID
}
return jobs, orgs, 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)
fresh, seen, err := s.claimResults(ctx, instance, req.Results)
if err != nil {
internalError(c, err)
return
}
req.Results = fresh
ids := make([]uuid.UUID, len(req.Results))
for i, r := range req.Results {
ids[i] = r.MonitorID
}
now := time.Now()
monitors := map[uuid.UUID]store.MonitorsForResultsRow{}
var (
accepted []agentapi.Result
changed []uuid.UUID
)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
a := agentOf(c)
rows, err := q.MonitorsForResults(ctx, store.MonitorsForResultsParams{RegionID: deref(a.RegionID), Ids: ids, AgentOrg: a.OrgID})
if err != nil {
return err
}
for _, m := range rows {
monitors[m.ID] = m
}
params := make([]store.InsertCheckResultsParams, 0, len(req.Results))
for _, r := range req.Results {
m, ok := monitors[r.MonitorID]
org := m.OrgID
// 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))
}
params = append(params, row)
accepted = append(accepted, r)
}
if len(params) == 0 {
return nil
}
changed, err = insertResults(ctx, q, params)
return err
})
if err != nil {
// Unclaimed, the checker's retry is stored instead.
s.unclaimResults(context.WithoutCancel(ctx), seen)
internalError(c, err)
return
}
s.pagesChanged(ctx, changed...)
s.evaluateResults(ctx, region, accepted, monitors)
s.storeEvidence(ctx, region, instance, accepted, monitors)
s.finishRunning(ctx, instance, accepted)
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]
}
// resultClaimTTL covers the retries of a checker that lost the answer to a
// report, which happen within minutes.
const resultClaimTTL = 2 * time.Hour
// claimResults drops results already received. A checker that does not get
// the answer to a report, say because the connection broke while the API was
// still working, sends the batch again; without this, the retry would be
// stored twice. A run is identified by instance, monitor and schedule time.
// It returns the new results and the claim keys to release if storing fails.
func (s *Server) claimResults(ctx context.Context, instance uuid.UUID, results []agentapi.Result) ([]agentapi.Result, []string, error) {
if len(results) == 0 {
return results, nil, nil
}
keys := make([]string, len(results))
cmds := make([]*redis.BoolCmd, len(results))
_, err := s.rdb.Pipelined(ctx, func(p redis.Pipeliner) error {
for i, r := range results {
keys[i] = "result:" + instance.String() + ":" + r.MonitorID.String() + ":" + strconv.FormatInt(r.ScheduledAt.UnixMilli(), 10)
cmds[i] = p.SetNX(ctx, keys[i], 1, resultClaimTTL)
}
return nil
})
if err != nil {
return nil, nil, err
}
fresh := results[:0:0]
var claimed []string
for i, r := range results {
if cmds[i].Val() {
fresh = append(fresh, r)
claimed = append(claimed, keys[i])
}
}
return fresh, claimed, nil
}
func (s *Server) unclaimResults(ctx context.Context, keys []string) {
if len(keys) == 0 {
return
}
if err := s.rdb.Del(ctx, keys...).Err(); err != nil {
s.log.WarnContext(ctx, "releasing result claims failed", "error", err)
}
}