Files
uptimesebi/internal/metrics/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

213 lines
8.2 KiB
Go

// 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"
}