Files
uptimesebi/internal/api/metrics.go
T
Sebastian UnterschützandClaude Opus 5.5 e9984f8271
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 10m23s
ci / test (pull_request) Successful in 12m59s
ci / build (pull_request) Canceled after 7m17s
ci / image (pull_request) Canceled after 0s
feat(api): Prometheus metrics for operators
The API serves Prometheus metrics on a listener of its own
(UPTIME_API_METRICS_LISTEN, default :9090, "off" disables it), so the
public ingress never exposes them:

- requests by route and status, with durations except for long polls
  and agent streams
- dispatched checks, stored and rejected results per region, how late
  results arrive, live checkers and overdue checks per platform region
- notification and subscriber mail deliveries, incidents opened and
  resolved
- runs, duration and last success of the background jobs
- platform totals (orgs, users, monitors by type, status pages,
  subscribers, open incidents, pending notifications), read at most
  every 15 seconds when scraped
- the Postgres and Redis connection pools, Go runtime and build info

The Helm chart exposes the port on the API service and can add a
ServiceMonitor for the Prometheus Operator.

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

188 lines
5.8 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, as when no checker of the region is live.", []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"}
}