feat(api): Prometheus metrics for operators
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

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
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-29 11:56:46 +01:00
1 parent ab25c1f218
commit e9984f8271
30 files changed
+1005 -20

No files matched your search

+212
View File
@@ -0,0 +1,212 @@
// Package metrics holds the Prometheus metrics of the API for operators:
// requests, the checker pipeline, notifications, background jobs and the
// connection pools. Every Metrics has a registry of its own, so tests and
// replicas never share state.
package metrics
import (
"net/http"
"strconv"
"time"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"git.zb-server.de/ZB-Server/uptimesebi/internal/buildinfo"
)
const namespace = "uptimesebi"
// Metrics are the instruments the API updates as it works.
type Metrics struct {
reg *prometheus.Registry
requests *prometheus.CounterVec
duration *prometheus.HistogramVec
inFlight prometheus.Gauge
dispatched prometheus.Counter
results *prometheus.CounterVec
rejected *prometheus.CounterVec
resultDelay prometheus.Histogram
notifications *prometheus.CounterVec
notifyDuration *prometheus.HistogramVec
subscriberMail *prometheus.CounterVec
incidents *prometheus.CounterVec
jobRuns *prometheus.CounterVec
jobDuration *prometheus.HistogramVec
jobSuccess *prometheus.GaugeVec
}
// New returns Metrics with the Go runtime, process and build metrics
// registered. edition labels the build info.
func New(edition string) *Metrics {
reg := prometheus.NewRegistry()
m := &Metrics{
reg: reg,
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "http_requests_total",
Help: "HTTP requests by method, route and status code. Requests no route matches have the route \"unmatched\".",
}, []string{"method", "route", "code"}),
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace, Name: "http_request_duration_seconds",
Help: "Time to answer HTTP requests, without long polls and event streams.",
Buckets: []float64{0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10},
}, []string{"method", "route"}),
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: namespace, Name: "http_requests_in_flight",
Help: "HTTP requests being answered, long polls and event streams included.",
}),
dispatched: prometheus.NewCounter(prometheus.CounterOpts{
Namespace: namespace, Name: "checks_dispatched_total",
Help: "Checks this instance moved from the schedule to the checkers' queues.",
}),
results: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "check_results_total",
Help: "Check results stored, by region (\"own\" for organizations' own checkers) and outcome.",
}, []string{"region", "ok"}),
rejected: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "check_results_rejected_total",
Help: "Check results not stored: duplicate (a retried report), unknown_monitor (not checked in the region) or bad_time (timestamp out of range).",
}, []string{"reason"}),
resultDelay: prometheus.NewHistogram(prometheus.HistogramOpts{
Namespace: namespace, Name: "check_result_delay_seconds",
Help: "Time from the start of a check to its result reaching the API.",
Buckets: []float64{0.5, 1, 2.5, 5, 10, 30, 60, 120, 300},
}),
notifications: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "notifications_total",
Help: "Notification delivery attempts by channel type and result.",
}, []string{"channel_type", "result"}),
notifyDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace, Name: "notification_send_duration_seconds",
Help: "Time to deliver a notification, by channel type.",
Buckets: []float64{0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30},
}, []string{"channel_type"}),
subscriberMail: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "subscriber_notifications_total",
Help: "Mails to status page subscribers by result.",
}, []string{"result"}),
incidents: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "incidents_total",
Help: "Incidents this instance opened or resolved.",
}, []string{"event"}),
jobRuns: prometheus.NewCounterVec(prometheus.CounterOpts{
Namespace: namespace, Name: "job_runs_total",
Help: "Runs of background jobs by result, ok or failed.",
}, []string{"job", "result"}),
jobDuration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
Namespace: namespace, Name: "job_duration_seconds",
Help: "Duration of background job runs.",
Buckets: []float64{0.01, 0.05, 0.1, 0.5, 1, 5, 10, 30, 60, 300},
}, []string{"job"}),
jobSuccess: prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace, Name: "job_last_success_timestamp_seconds",
Help: "Unix time of the last successful run of a background job on this instance.",
}, []string{"job"}),
}
build := prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: namespace, Name: "build_info",
Help: "Always 1; the labels name the running release.",
}, []string{"version", "commit", "edition"})
build.WithLabelValues(buildinfo.Version, buildinfo.Commit, edition).Set(1)
reg.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
build,
m.requests, m.duration, m.inFlight,
m.dispatched, m.results, m.rejected, m.resultDelay,
m.notifications, m.notifyDuration, m.subscriberMail,
m.incidents,
m.jobRuns, m.jobDuration, m.jobSuccess,
)
return m
}
// Register adds collectors, such as those reading the database when
// scraped.
func (m *Metrics) Register(cs ...prometheus.Collector) { m.reg.MustRegister(cs...) }
// Handler serves the metrics in the Prometheus text format.
func (m *Metrics) Handler() http.Handler {
return promhttp.HandlerFor(m.reg, promhttp.HandlerOpts{Registry: m.reg})
}
// Gatherer exposes the registry to tests.
func (m *Metrics) Gatherer() prometheus.Gatherer { return m.reg }
// HTTP counts and times the requests of r. Routes listed in streaming are
// counted but not timed, since they stay open on purpose.
func (m *Metrics) HTTP(streaming ...string) gin.HandlerFunc {
skip := map[string]bool{}
for _, r := range streaming {
skip[r] = true
}
return func(c *gin.Context) {
start := time.Now()
m.inFlight.Inc()
defer m.inFlight.Dec()
c.Next()
route := c.FullPath()
if route == "" {
route = "unmatched"
}
m.requests.WithLabelValues(c.Request.Method, route, strconv.Itoa(c.Writer.Status())).Inc()
if !skip[route] {
m.duration.WithLabelValues(c.Request.Method, route).Observe(time.Since(start).Seconds())
}
}
}
// Dispatched counts checks moved to the checkers' queues.
func (m *Metrics) Dispatched(n int) { m.dispatched.Add(float64(n)) }
// Result counts a stored check result and how long it took to arrive.
func (m *Metrics) Result(region string, ok bool, delay time.Duration) {
m.results.WithLabelValues(region, strconv.FormatBool(ok)).Inc()
m.resultDelay.Observe(max(delay, 0).Seconds())
}
// Rejected counts n check results not stored for reason.
func (m *Metrics) Rejected(reason string, n int) {
if n > 0 {
m.rejected.WithLabelValues(reason).Add(float64(n))
}
}
// Notification counts a delivery attempt to a channel of type typ.
func (m *Metrics) Notification(typ string, err error, took time.Duration) {
m.notifications.WithLabelValues(typ, result(err)).Inc()
m.notifyDuration.WithLabelValues(typ).Observe(took.Seconds())
}
// SubscriberMail counts a mail to a status page subscriber.
func (m *Metrics) SubscriberMail(err error) { m.subscriberMail.WithLabelValues(result(err)).Inc() }
// Incident counts an incident event, "opened" or "resolved".
func (m *Metrics) Incident(event string) { m.incidents.WithLabelValues(event).Inc() }
// Job runs one round of the background job name and records its outcome.
// It returns run's error.
func (m *Metrics) Job(name string, run func() error) error {
start := time.Now()
err := run()
outcome := "ok"
if err != nil {
outcome = "failed"
}
m.jobRuns.WithLabelValues(name, outcome).Inc()
m.jobDuration.WithLabelValues(name).Observe(time.Since(start).Seconds())
if err == nil {
m.jobSuccess.WithLabelValues(name).SetToCurrentTime()
}
return err
}
func result(err error) string {
if err != nil {
return "failed"
}
return "sent"
}
+134
View File
@@ -0,0 +1,134 @@
package metrics
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/redis/go-redis/v9"
)
func TestHTTPCountsRoutesAndTimesShortRequests(t *testing.T) {
gin.SetMode(gin.TestMode)
m := New("selfhosted")
r := gin.New()
r.Use(m.HTTP("/stream"))
r.GET("/items/:id", func(c *gin.Context) { c.Status(http.StatusTeapot) })
r.GET("/stream", func(c *gin.Context) { c.Status(http.StatusOK) })
for _, path := range []string{"/items/1", "/items/2", "/stream", "/nowhere"} {
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, path, nil))
}
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "/items/:id", "418")); got != 2 {
t.Errorf("requests for the route = %v, want 2", got)
}
if got := testutil.ToFloat64(m.requests.WithLabelValues("GET", "unmatched", "404")); got != 1 {
t.Errorf("unmatched requests = %v, want 1", got)
}
// The stream is counted, not timed.
if got := testutil.CollectAndCount(m.duration); got != 2 {
t.Errorf("timed series = %d, want 2: the route and unmatched paths, not the stream", got)
}
if got := testutil.ToFloat64(m.inFlight); got != 0 {
t.Errorf("in flight after the requests = %v, want 0", got)
}
}
func TestJobRecordsOutcome(t *testing.T) {
m := New("cloud")
boom := errors.New("boom")
if err := m.Job("housekeeping", func() error { return nil }); err != nil {
t.Fatalf("Job() = %v, want nil", err)
}
if err := m.Job("housekeeping", func() error { return boom }); !errors.Is(err, boom) {
t.Fatalf("Job() = %v, want the run's error", err)
}
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "ok")); got != 1 {
t.Errorf("ok runs = %v, want 1", got)
}
if got := testutil.ToFloat64(m.jobRuns.WithLabelValues("housekeeping", "failed")); got != 1 {
t.Errorf("failed runs = %v, want 1", got)
}
if got := testutil.ToFloat64(m.jobSuccess.WithLabelValues("housekeeping")); got < float64(time.Now().Add(-time.Minute).Unix()) {
t.Errorf("last success = %v, want about now", got)
}
}
func TestCountersAndHandler(t *testing.T) {
m := New("cloud")
m.Dispatched(3)
m.Result("fsn", true, 2*time.Second)
m.Result("fsn", false, -time.Second)
m.Rejected("duplicate", 2)
m.Rejected("bad_time", 0)
m.Notification("slack", nil, time.Second)
m.Notification("slack", errors.New("x"), time.Second)
m.SubscriberMail(nil)
m.Incident("opened")
for name, c := range map[string]struct {
got, want float64
}{
"dispatched": {testutil.ToFloat64(m.dispatched), 3},
"ok results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "true")), 1},
"failed results": {testutil.ToFloat64(m.results.WithLabelValues("fsn", "false")), 1},
"duplicates": {testutil.ToFloat64(m.rejected.WithLabelValues("duplicate")), 2},
"sent": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "sent")), 1},
"failed": {testutil.ToFloat64(m.notifications.WithLabelValues("slack", "failed")), 1},
"subscriber": {testutil.ToFloat64(m.subscriberMail.WithLabelValues("sent")), 1},
"incidents": {testutil.ToFloat64(m.incidents.WithLabelValues("opened")), 1},
} {
if c.got != c.want {
t.Errorf("%s = %v, want %v", name, c.got, c.want)
}
}
if got := testutil.CollectAndCount(m.rejected); got != 1 {
t.Errorf("rejection series = %d, want 1: zero rejections add none", got)
}
rec := httptest.NewRecorder()
m.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
body, _ := io.ReadAll(rec.Body)
for _, want := range []string{`uptimesebi_build_info{commit="none",edition="cloud",version="dev"} 1`, "go_goroutines", "uptimesebi_checks_dispatched_total 3"} {
if !strings.Contains(string(body), want) {
t.Errorf("metrics lack %q", want)
}
}
}
func TestPoolCollectors(t *testing.T) {
// Neither pool connects before it is used.
pool, err := pgxpool.New(context.Background(), "postgres://u@127.0.0.1:1/db")
if err != nil {
t.Fatal(err)
}
defer pool.Close()
rdb := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
defer func() { _ = rdb.Close() }()
m := New("cloud")
m.Register(DBPool(pool), RedisPool(rdb))
for _, c := range []prometheus.Collector{DBPool(pool), RedisPool(rdb)} {
if problems, err := testutil.CollectAndLint(c); err != nil || len(problems) > 0 {
t.Errorf("pool metrics lint: %v %v", problems, err)
}
}
if got := testutil.CollectAndCount(DBPool(pool)); got != 7 {
t.Errorf("DB pool series = %d, want 7", got)
}
if got := testutil.CollectAndCount(RedisPool(rdb)); got != 6 {
t.Errorf("Redis pool series = %d, want 6", got)
}
if _, err := m.Gatherer().Gather(); err != nil {
t.Errorf("Gather() = %v", err)
}
}
+81
View File
@@ -0,0 +1,81 @@
package metrics
import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/prometheus/client_golang/prometheus"
"github.com/redis/go-redis/v9"
)
// DBPool reports the state of a Postgres connection pool when scraped.
func DBPool(pool *pgxpool.Pool) prometheus.Collector { return dbPool{pool} }
type dbPool struct{ pool *pgxpool.Pool }
var (
dbConns = prometheus.NewDesc(namespace+"_db_pool_connections",
"Connections of the Postgres pool by state.", []string{"state"}, nil)
dbMax = prometheus.NewDesc(namespace+"_db_pool_max_connections",
"Size limit of the Postgres pool.", nil, nil)
dbAcquires = prometheus.NewDesc(namespace+"_db_pool_acquires_total",
"Connections taken from the Postgres pool.", nil, nil)
dbEmptyAcquires = prometheus.NewDesc(namespace+"_db_pool_empty_acquires_total",
"Acquires that had to wait for or open a connection because none was idle.", nil, nil)
dbAcquireWait = prometheus.NewDesc(namespace+"_db_pool_acquire_seconds_total",
"Total time spent acquiring Postgres connections.", nil, nil)
)
// Describe implements prometheus.Collector.
func (dbPool) Describe(ch chan<- *prometheus.Desc) {
for _, d := range []*prometheus.Desc{dbConns, dbMax, dbAcquires, dbEmptyAcquires, dbAcquireWait} {
ch <- d
}
}
// Collect implements prometheus.Collector.
func (p dbPool) Collect(ch chan<- prometheus.Metric) {
s := p.pool.Stat()
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.AcquiredConns()), "acquired")
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.IdleConns()), "idle")
ch <- prometheus.MustNewConstMetric(dbConns, prometheus.GaugeValue, float64(s.ConstructingConns()), "constructing")
ch <- prometheus.MustNewConstMetric(dbMax, prometheus.GaugeValue, float64(s.MaxConns()))
ch <- prometheus.MustNewConstMetric(dbAcquires, prometheus.CounterValue, float64(s.AcquireCount()))
ch <- prometheus.MustNewConstMetric(dbEmptyAcquires, prometheus.CounterValue, float64(s.EmptyAcquireCount()))
ch <- prometheus.MustNewConstMetric(dbAcquireWait, prometheus.CounterValue, s.AcquireDuration().Seconds())
}
// RedisPool reports the state of a Redis client's connection pool when
// scraped.
func RedisPool(rdb redis.UniversalClient) prometheus.Collector { return redisPool{rdb} }
type redisPool struct{ rdb redis.UniversalClient }
var (
redisConns = prometheus.NewDesc(namespace+"_redis_pool_connections",
"Connections of the Redis pool by state.", []string{"state"}, nil)
redisHits = prometheus.NewDesc(namespace+"_redis_pool_hits_total",
"Times an idle Redis connection was reused.", nil, nil)
redisMisses = prometheus.NewDesc(namespace+"_redis_pool_misses_total",
"Times no idle Redis connection was available.", nil, nil)
redisTimeouts = prometheus.NewDesc(namespace+"_redis_pool_timeouts_total",
"Times waiting for a Redis connection timed out.", nil, nil)
redisStale = prometheus.NewDesc(namespace+"_redis_pool_stale_total",
"Stale Redis connections the pool closed.", nil, nil)
)
// Describe implements prometheus.Collector.
func (redisPool) Describe(ch chan<- *prometheus.Desc) {
for _, d := range []*prometheus.Desc{redisConns, redisHits, redisMisses, redisTimeouts, redisStale} {
ch <- d
}
}
// Collect implements prometheus.Collector.
func (p redisPool) Collect(ch chan<- prometheus.Metric) {
s := p.rdb.PoolStats()
ch <- prometheus.MustNewConstMetric(redisConns, prometheus.GaugeValue, float64(s.TotalConns), "total")
ch <- prometheus.MustNewConstMetric(redisConns, prometheus.GaugeValue, float64(s.IdleConns), "idle")
ch <- prometheus.MustNewConstMetric(redisHits, prometheus.CounterValue, float64(s.Hits))
ch <- prometheus.MustNewConstMetric(redisMisses, prometheus.CounterValue, float64(s.Misses))
ch <- prometheus.MustNewConstMetric(redisTimeouts, prometheus.CounterValue, float64(s.Timeouts))
ch <- prometheus.MustNewConstMetric(redisStale, prometheus.CounterValue, float64(s.StaleConns))
}