ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m10s
ci / test (pull_request) Successful in 12m19s
ci / build (pull_request) Successful in 18m13s
ci / image (pull_request) Successful in 5m20s
Every console page that shows monitor status (monitors, incidents, monitor details, evidence) went through one loader that read, for all of the organization's monitors: - the newest result per monitor and region, by scanning a day of raw results; - the bars of the selected range, from raw results for ranges up to 24h, though only one page of monitors is shown; - when each monitor first reported, scanning two days of results. With 3000 monitors that took about a second, growing with the number of results. Now: - latest_results keeps the newest result per monitor and region, updated as results are stored (migration 00055 fills it from the last day); - bars are loaded only for the monitors a page shows; - first data is loaded per monitor on its page, and the monitor list asks only for the organization's earliest data, by index; - monitor, region and incident queries name the organization, so their indexes are used instead of row security filtering whole tables. Public status pages also read only their own monitors' latest results and hourly buckets instead of the whole organization's. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
160 lines
5.1 KiB
Go
160 lines
5.1 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 {
|
|
return s.recordPassive(ctx, heartbeatRegion, id, org, interval, confirmations, ok, msg, at)
|
|
}
|
|
|
|
// recordPassive stores a result reported to us instead of by a checker,
|
|
// under the pseudo-region of its kind, and evaluates it.
|
|
func (s *Server) recordPassive(ctx context.Context, region string, 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: region, Ok: ok}
|
|
if msg != "" {
|
|
row.Error = ptr(truncateValid(msg, 500))
|
|
}
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
return insertResults(ctx, q, []store.InsertCheckResultsParams{row})
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.evaluateResults(ctx, region,
|
|
[]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{region},
|
|
}})
|
|
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)
|
|
}
|
|
if err := s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false); err != nil && ctx.Err() == nil {
|
|
s.log.ErrorContext(ctx, "checking alertmanager monitors 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
|
|
}
|