Files
uptimesebi/internal/api/metrics_test.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

91 lines
3.0 KiB
Go

package api_test
import (
"context"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
// scrape returns the value of every series of the API's metrics, keyed by
// name and labels as the text format prints them.
func (e *env) scrape(t *testing.T) map[string]float64 {
t.Helper()
rec := httptest.NewRecorder()
e.metrics.Handler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/metrics", nil))
if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/plain") {
t.Fatalf("metrics answered %d %q", rec.Code, rec.Header().Get("Content-Type"))
}
body, _ := io.ReadAll(rec.Body)
out := map[string]float64{}
for _, line := range strings.Split(string(body), "\n") {
if line == "" || strings.HasPrefix(line, "#") {
continue
}
i := strings.LastIndexByte(line, ' ')
v, err := strconv.ParseFloat(line[i+1:], 64)
if err != nil {
t.Fatalf("bad metric line %q", line)
}
out[line[:i]] = v
}
return out
}
func TestMetrics(t *testing.T) {
e := newEnv(t)
key := uniq("metrics-")
tok, region := e.platformChecker(t, key)
owner := e.browser(t)
owner.signup("o@"+uniq("id")+".test", uniq("id-"))
_, m := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "m", "type": "tcp", "target": "example.com:443", "interval_seconds": 3600, "regions": []string{region},
})
monitor := uuid.MustParse(m["id"].(string))
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
at := time.Now().Truncate(time.Millisecond)
batch := []agentapi.Result{
{MonitorID: monitor, ScheduledAt: at, StartedAt: at, OK: true},
{MonitorID: monitor, ScheduledAt: at.Add(time.Second), StartedAt: at.Add(time.Second), OK: false},
{MonitorID: uuid.New(), ScheduledAt: at, StartedAt: at, OK: true},
}
for range 2 {
if err := client.Report(context.Background(), batch); err != nil {
t.Fatal(err)
}
}
got := e.scrape(t)
for series, want := range map[string]float64{
`uptimesebi_check_results_total{ok="true",region="` + key + `"}`: 1,
`uptimesebi_check_results_total{ok="false",region="` + key + `"}`: 1,
`uptimesebi_check_results_rejected_total{reason="duplicate"}`: 3,
`uptimesebi_check_results_rejected_total{reason="unknown_monitor"}`: 1,
`uptimesebi_checker_instances{region="` + key + `"}`: 0,
`uptimesebi_platform_metrics_error`: 0,
} {
if v, ok := got[series]; !ok || v != want {
t.Errorf("%s = %v (present %v), want %v", series, v, ok, want)
}
}
// Other tests share the database, so totals are at least ours.
for series, least := range map[string]float64{
`uptimesebi_orgs`: 1,
`uptimesebi_users`: 1,
`uptimesebi_monitors{enabled="true",type="tcp"}`: 1,
`uptimesebi_regions{online="false"}`: 1,
} {
if got[series] < least {
t.Errorf("%s = %v, want at least %v", series, got[series], least)
}
}
}