Files
uptimesebi/internal/api/metrics.go
T
Sebastian UnterschützandClaude Opus 5.5 2fa439c47d
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m57s
ci / test (pull_request) Successful in 13m1s
ci / build (pull_request) Successful in 19m25s
ci / image (pull_request) In progress
feat(api): count queued runs as overdue; alert rules in the chart
uptimesebi_checks_overdue counted only runs not dispatched yet. Dispatch
hands due runs to an instance's queue and schedules the next run at once,
so a checker too busy to take its work left the metric at 0. It now also
counts queued runs due more than 10 seconds ago.

The chart adds an optional PrometheusRule (api.metrics.prometheusRule):
UptimeSebiRegionBehind fires when a region's checks stay overdue, and
UptimeSebiPlatformMetricsFailing when the platform metrics cannot be read.

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

188 lines
5.9 KiB
Go

package api
import (
"context"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
// Platform metrics are read from the database and Redis when scraped, at
// most once per platformMetricsTTL, so scrapes stay cheap. Every replica
// reports the same platform totals; dashboards take their max().
const (
platformMetricsTTL = 15 * time.Second
// checksLateAfter leaves the runs alone that the next dispatch, every
// second, takes anyway.
checksLateAfter = 10 * time.Second
)
var (
descCheckers = prometheus.NewDesc("uptimesebi_checker_instances",
"Live checker instances per platform region.", []string{"region"}, nil)
descOverdue = prometheus.NewDesc("uptimesebi_checks_overdue",
"Checks of a platform region due for more than 10 seconds and not started: undispatched, as when no checker of the region is live, or waiting in the queue of a checker too busy to take them.", []string{"region"}, nil)
descRegions = prometheus.NewDesc("uptimesebi_regions",
"Platform regions by whether a checker is live.", []string{"online"}, nil)
descOrgs = prometheus.NewDesc("uptimesebi_orgs",
"Organizations on the platform.", nil, nil)
descUsers = prometheus.NewDesc("uptimesebi_users",
"User accounts on the platform.", nil, nil)
descMonitors = prometheus.NewDesc("uptimesebi_monitors",
"Monitors by type and whether they are enabled.", []string{"type", "enabled"}, nil)
descPages = prometheus.NewDesc("uptimesebi_status_pages",
"Status pages on the platform.", nil, nil)
descSubscribers = prometheus.NewDesc("uptimesebi_status_page_subscribers",
"Confirmed subscribers of status pages.", nil, nil)
descOpenIncidents = prometheus.NewDesc("uptimesebi_incidents_open",
"Incidents not resolved yet.", nil, nil)
descPending = prometheus.NewDesc("uptimesebi_notifications_pending",
"Notifications waiting for delivery, by kind: channel or subscriber.", []string{"kind"}, nil)
descScrapeError = prometheus.NewDesc("uptimesebi_platform_metrics_error",
"1 if reading the platform metrics failed on the last attempt.", nil, nil)
)
type platformSnapshot struct {
counts store.PlatformCountsRow
monitors []store.MonitorCountsRow
regions []regionLoad
}
type regionLoad struct {
key string
checkers int64
overdue int64
}
// platformCollector reports the platform's totals, checkers and backlog.
type platformCollector struct {
s *Server
mu sync.Mutex
last platformSnapshot
err error
expires time.Time
}
// Describe implements prometheus.Collector.
func (p *platformCollector) Describe(ch chan<- *prometheus.Desc) {
for _, d := range []*prometheus.Desc{
descCheckers, descOverdue, descRegions, descOrgs, descUsers, descMonitors,
descPages, descSubscribers, descOpenIncidents, descPending, descScrapeError,
} {
ch <- d
}
}
// Collect implements prometheus.Collector. It reads the database and
// Redis at most once per platformMetricsTTL.
func (p *platformCollector) Collect(ch chan<- prometheus.Metric) {
p.mu.Lock()
if time.Now().After(p.expires) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
snap, err := p.s.platformSnapshot(ctx)
cancel()
// A failed read keeps the last good values, flagged.
if err == nil {
p.last = snap
} else {
p.s.log.Warn("reading platform metrics failed", "error", err)
}
p.err, p.expires = err, time.Now().Add(platformMetricsTTL)
}
snap, failed := p.last, p.err != nil
p.mu.Unlock()
gauge := func(d *prometheus.Desc, v int64, labels ...string) {
ch <- prometheus.MustNewConstMetric(d, prometheus.GaugeValue, float64(v), labels...)
}
var online, offline int64
for _, r := range snap.regions {
gauge(descCheckers, r.checkers, r.key)
gauge(descOverdue, r.overdue, r.key)
if r.checkers > 0 {
online++
} else {
offline++
}
}
gauge(descRegions, online, "true")
gauge(descRegions, offline, "false")
c := snap.counts
gauge(descOrgs, c.Orgs)
gauge(descUsers, c.Users)
gauge(descPages, c.StatusPages)
gauge(descSubscribers, c.Subscribers)
gauge(descOpenIncidents, c.OpenIncidents)
gauge(descPending, c.PendingNotifications, "channel")
gauge(descPending, c.PendingSubscriberNotifications, "subscriber")
for _, m := range snap.monitors {
enabled := "false"
if m.Enabled {
enabled = "true"
}
gauge(descMonitors, m.Monitors, m.Type, enabled)
}
var flag int64
if failed {
flag = 1
}
gauge(descScrapeError, flag)
}
func (s *Server) platformSnapshot(ctx context.Context) (platformSnapshot, error) {
var (
snap platformSnapshot
regions []store.Region
)
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
if snap.counts, err = q.PlatformCounts(ctx); err != nil {
return err
}
if snap.monitors, err = q.MonitorCounts(ctx); err != nil {
return err
}
regions, err = q.ListPlatformRegions(ctx)
return err
})
if err != nil {
return snap, err
}
for _, r := range regions {
n, err := s.sched.Instances(ctx, r.ID.String())
if err != nil {
return snap, err
}
late, err := s.sched.Overdue(ctx, r.ID.String(), checksLateAfter)
if err != nil {
return snap, err
}
snap.regions = append(snap.regions, regionLoad{key: r.Key, checkers: n, overdue: late})
}
return snap, nil
}
// regionLabel names a checker's region in metrics: the key of a platform
// region, or "own" for organizations' checkers, whose regions are many and
// not the operator's.
func regionLabel(a store.GetAgentByHashRow) string {
if a.OrgID != nil {
return "own"
}
if a.RegionKey != nil {
return *a.RegionKey
}
return "none"
}
// StreamingRoutes stay open on purpose: the agents' streams and the
// checkers' long polls. Request metrics count them but do not time them.
func StreamingRoutes() []string {
return []string{agentapi.Prefix + agentapi.StreamPath, agentapi.Prefix + "/jobs"}
}