Files
Sebastian UnterschützandClaude Opus 5.5 5a76702dba feat: heartbeat monitors pinged by cron jobs and scripts
A heartbeat monitor has a secret ping URL instead of a target and
regions. Jobs call it with GET, HEAD or POST after each run, or /fail
with an optional message. When no ping arrives within the interval plus
a grace period, a failure is recorded and evaluated like a checker
result, so confirmations, maintenance and notifications apply. One API
replica at a time checks deadlines. The URL is shown only to members who
may edit the monitor, since it can report the job healthy.

Closes #27

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

152 lines
4.6 KiB
Go

package api
import (
"context"
"errors"
"io"
"net/http"
"strings"
"time"
"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/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// heartbeatRegion is the region heartbeat results are filed under: pings
// arrive from wherever the job runs, not from a checker region.
const heartbeatRegion = "heartbeat"
// newPingToken returns the secret that makes up a ping URL.
func newPingToken() string { return auth.RandomToken() }
func (s *Server) pingURL(token string) string {
return strings.TrimSuffix(s.cfg.PublicURL, "/") + "/hb/" + token
}
func (s *Server) mountHeartbeats(r gin.IRouter) {
methods := []string{http.MethodGet, http.MethodHead, http.MethodPost}
r.Match(methods, "/hb/:token", s.ping)
r.Match(methods, "/hb/:token/fail", s.ping)
}
// ping records a heartbeat. Jobs call it with curl or wget, so it takes
// GET, HEAD and POST, needs no headers and answers in plain text. A path
// ending in /fail reports a failure; a message may come as ?msg= or as the
// POST body.
func (s *Server) ping(c *gin.Context) {
token := c.Param("token")
ctx := c.Request.Context()
if !s.limit(c, "ping:"+token, 60, time.Minute) {
return
}
var m store.HeartbeatMonitorRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
m, err = q.HeartbeatMonitor(ctx, token)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
c.String(http.StatusNotFound, "unknown heartbeat\n")
return
}
if err != nil {
internalError(c, err)
return
}
if !m.Enabled {
c.String(http.StatusOK, "OK (paused)\n")
return
}
ok := !strings.HasSuffix(c.FullPath(), "/fail")
msg := c.Query("msg")
if msg == "" && c.Request.Method == http.MethodPost {
body, _ := io.ReadAll(io.LimitReader(c.Request.Body, 2000))
msg = strings.TrimSpace(string(body))
}
if !ok && msg == "" {
msg = "reported failure"
}
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds, m.Confirmations, ok, msg, time.Now()); err != nil {
internalError(c, err)
return
}
c.String(http.StatusOK, "OK\n")
}
// recordHeartbeat stores a ping or a missed deadline and evaluates it like
// a checker result.
func (s *Server) recordHeartbeat(ctx context.Context, id, org uuid.UUID, interval, confirmations int32, ok bool, msg string, at time.Time) error {
row := store.InsertCheckResultsParams{Time: at, OrgID: org, MonitorID: id, Region: heartbeatRegion, Ok: ok}
if msg != "" {
row.Error = ptr(truncateValid(msg, 500))
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
_, err := q.InsertCheckResults(ctx, []store.InsertCheckResultsParams{row})
return err
})
if err != nil {
return err
}
s.evaluateResults(ctx, heartbeatRegion,
[]agentapi.Result{{MonitorID: id, ScheduledAt: at, StartedAt: at, OK: ok}},
map[uuid.UUID]store.MonitorsForResultsRow{id: {
ID: id, OrgID: org, IntervalSeconds: interval, Confirmations: confirmations, Regions: []string{heartbeatRegion},
}})
return nil
}
// missedPing is the error recorded for an overdue heartbeat.
const missedPing = "no ping received in time"
// RunHeartbeats records a failure for every heartbeat monitor whose ping is
// overdue, until ctx ends. Every replica runs it; a short Redis lock lets
// one of them do each round.
func (s *Server) RunHeartbeats(ctx context.Context) {
tick := time.NewTicker(10 * time.Second)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
}
got, err := s.rdb.SetNX(ctx, "lock:heartbeats", 1, 9*time.Second).Result()
if err != nil || !got {
continue
}
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
}
}
}
// CheckHeartbeats records missed deadlines as of now. A recorded failure
// restarts the wait, so a silent job fails once per interval plus grace.
func (s *Server) CheckHeartbeats(ctx context.Context, now time.Time) error {
var due []store.HeartbeatsDueRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
due, err = q.HeartbeatsDue(ctx)
return err
})
if err != nil {
return err
}
for _, m := range due {
deadline := m.WaitingSince.Add(time.Duration(m.IntervalSeconds+m.GraceSeconds) * time.Second)
if now.Before(deadline) {
continue
}
if err := s.recordHeartbeat(ctx, m.ID, m.OrgID, m.IntervalSeconds+m.GraceSeconds, m.Confirmations, false, missedPing, now); err != nil {
return err
}
}
return nil
}