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
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:
1 parent
ab25c1f218
commit
e9984f8271
30 files changed
+1005
-20
No files matched your search
+15
-1
@@ -298,6 +298,7 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.metrics.Rejected("duplicate", len(req.Results)-len(fresh))
|
||||
req.Results = fresh
|
||||
ids := make([]uuid.UUID, len(req.Results))
|
||||
for i, r := range req.Results {
|
||||
@@ -308,6 +309,8 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
var (
|
||||
accepted []agentapi.Result
|
||||
changed []uuid.UUID
|
||||
unknown int
|
||||
badTime int
|
||||
)
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
a := agentOf(c)
|
||||
@@ -325,7 +328,12 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
// A checker may only report monitors of its own region, and
|
||||
// timestamps far from now are rejected rather than skewing
|
||||
// history.
|
||||
if !ok || r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)) {
|
||||
switch {
|
||||
case !ok:
|
||||
unknown++
|
||||
continue
|
||||
case r.StartedAt.After(now.Add(time.Minute)) || r.StartedAt.Before(now.Add(-24*time.Hour)):
|
||||
badTime++
|
||||
continue
|
||||
}
|
||||
row := store.InsertCheckResultsParams{
|
||||
@@ -353,6 +361,12 @@ func (s *Server) agentResults(c *gin.Context) {
|
||||
internalError(c, err)
|
||||
return
|
||||
}
|
||||
s.metrics.Rejected("unknown_monitor", unknown)
|
||||
s.metrics.Rejected("bad_time", badTime)
|
||||
label := regionLabel(agentOf(c))
|
||||
for _, r := range accepted {
|
||||
s.metrics.Result(label, r.OK, now.Sub(r.StartedAt))
|
||||
}
|
||||
s.pagesChanged(ctx, changed...)
|
||||
s.evaluateResults(ctx, region, accepted, monitors)
|
||||
s.storeEvidence(ctx, region, instance, accepted, monitors)
|
||||
|
||||
@@ -128,6 +128,7 @@ func (s *Server) transition(ctx context.Context, m store.MonitorsForResultsRow,
|
||||
}
|
||||
}
|
||||
s.log.InfoContext(ctx, "incident "+event, "monitor", m.ID, "incident", inc.ID, "channels", len(channels))
|
||||
s.metrics.Incident(event)
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -167,7 +168,9 @@ func (s *Server) deliverBatch(ctx context.Context) int {
|
||||
return 0
|
||||
}
|
||||
for _, n := range rows {
|
||||
sent := time.Now()
|
||||
sendErr := s.send(ctx, n.ChannelType, n.ChannelConfig, eventOf(n))
|
||||
s.metrics.Notification(n.ChannelType, sendErr, time.Since(sent))
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkNotificationSent(ctx, n.ID)
|
||||
|
||||
@@ -81,7 +81,7 @@ func (s *Server) RunDomainWatch(ctx context.Context) {
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if ok, err := s.rdb.SetNX(ctx, keyDomainWatch, 1, domainWatchEvery-5*time.Second).Result(); err == nil && ok {
|
||||
if err := s.WatchDomains(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("domain_watch", func() error { return s.WatchDomains(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "checking custom domains failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,10 +129,12 @@ func (s *Server) RunHeartbeats(ctx context.Context) {
|
||||
if err != nil || !got {
|
||||
continue
|
||||
}
|
||||
if err := s.CheckHeartbeats(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("heartbeats", func() error { return s.CheckHeartbeats(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking heartbeats failed", "error", err)
|
||||
}
|
||||
if err := s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("alertmanager_monitors", func() error {
|
||||
return s.CheckAlertmanagerMonitors(ctx, nil, time.Now(), false)
|
||||
}); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "checking alertmanager monitors failed", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) {
|
||||
tick := time.NewTicker(time.Hour)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.Housekeep(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("housekeeping", func() error { return s.Housekeep(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "housekeeping failed", "error", err)
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -0,0 +1,187 @@
|
||||
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"}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -534,6 +534,7 @@ func (s *Server) RunScheduler(ctx context.Context) {
|
||||
return
|
||||
case <-dispatch.C:
|
||||
n, err := s.sched.Dispatch(ctx)
|
||||
s.metrics.Dispatched(n)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "dispatch failed", "error", err)
|
||||
}
|
||||
@@ -555,19 +556,22 @@ func (s *Server) reconcile(ctx context.Context) {
|
||||
// Taken before reading the database: monitors upserted later survive.
|
||||
start := time.Now()
|
||||
defer func() { s.log.DebugContext(ctx, "schedule reconciled", "took", time.Since(start)) }()
|
||||
var rows []store.ListEnabledMonitorsForScheduleRow
|
||||
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
|
||||
return err
|
||||
})
|
||||
if err == nil {
|
||||
err = s.metrics.Job("reconcile", func() error {
|
||||
var rows []store.ListEnabledMonitorsForScheduleRow
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
var err error
|
||||
rows, err = q.ListEnabledMonitorsForSchedule(ctx)
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
want := make([]schedule.Monitor, len(rows))
|
||||
for i, r := range rows {
|
||||
want[i] = schedule.Monitor{ID: r.ID, Interval: time.Duration(r.IntervalSeconds) * time.Second, Regions: r.Regions}
|
||||
}
|
||||
err = s.sched.Reconcile(ctx, want, start)
|
||||
}
|
||||
return s.sched.Reconcile(ctx, want, start)
|
||||
})
|
||||
if err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "schedule reconciliation failed", "error", err)
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ func (s *Server) runOrgPurges(ctx context.Context) {
|
||||
tick := time.NewTicker(orgPurgeEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.PurgeDeletedOrgs(ctx); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("org_purge", func() error { return s.PurgeDeletedOrgs(ctx) }); err != nil && ctx.Err() == nil {
|
||||
s.log.ErrorContext(ctx, "purging deleted organizations failed", "error", err)
|
||||
}
|
||||
select {
|
||||
|
||||
@@ -39,7 +39,7 @@ func (s *Server) RunRegionWatch(ctx context.Context) {
|
||||
tick := time.NewTicker(regionWatchEvery)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if err := s.WatchRegions(ctx, time.Now()); err != nil && ctx.Err() == nil {
|
||||
if err := s.metrics.Job("region_watch", func() error { return s.WatchRegions(ctx, time.Now()) }); err != nil && ctx.Err() == nil {
|
||||
s.log.WarnContext(ctx, "watching regions failed", "error", err)
|
||||
}
|
||||
select {
|
||||
|
||||
+13
-1
@@ -18,6 +18,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/evaluate"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/metrics"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/requestid"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/schedule"
|
||||
@@ -72,6 +73,8 @@ type Server struct {
|
||||
publicRegions publicRegionsCache
|
||||
// ogImages keeps the preview image of the public pages.
|
||||
ogImages appImages
|
||||
// metrics counts what the instance does, for Prometheus.
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// Deps are the external resources a Server needs.
|
||||
@@ -81,6 +84,8 @@ type Deps struct {
|
||||
Redis redis.UniversalClient
|
||||
Keys *sealed.Keyring
|
||||
Catalog *i18n.Catalog
|
||||
// Metrics, if nil, are created for the Server alone.
|
||||
Metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
// New returns a Server. It does not register any routes; see Mount.
|
||||
@@ -88,7 +93,12 @@ type Deps struct {
|
||||
func New(cfg config.API, d Deps) *Server {
|
||||
allowPrivate := cfg.SSOAllowPrivate()
|
||||
mail, _ := notify.ParseSMTP(cfg.SMTPURL)
|
||||
return &Server{
|
||||
m := d.Metrics
|
||||
if m == nil {
|
||||
m = metrics.New(string(cfg.Edition))
|
||||
}
|
||||
s := &Server{
|
||||
metrics: m,
|
||||
orgPurges: make(chan struct{}, 1),
|
||||
eval: evaluate.New(d.Redis),
|
||||
smtp: mail,
|
||||
@@ -111,6 +121,8 @@ func New(cfg config.API, d Deps) *Server {
|
||||
support: newVersioned[supportSettings]("support"),
|
||||
pageHome: newVersioned[string]("statuspage-home"),
|
||||
}
|
||||
m.Register(&platformCollector{s: s})
|
||||
return s
|
||||
}
|
||||
|
||||
// EndLongPollsOn makes the checkers' long polls return as soon as ch is
|
||||
|
||||
@@ -25,6 +25,7 @@ import (
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/api"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/metrics"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/migrations"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
|
||||
"git.zb-server.de/ZB-Server/uptimesebi/internal/sealed"
|
||||
@@ -37,6 +38,8 @@ type env struct {
|
||||
dbPool *pgxpool.Pool
|
||||
rdb *redis.Client
|
||||
api *api.Server
|
||||
// metrics are the API's own, as cmd/api serves them.
|
||||
metrics *metrics.Metrics
|
||||
}
|
||||
|
||||
func newEnv(t *testing.T) *env {
|
||||
@@ -104,7 +107,8 @@ func newEnvWith(t *testing.T, adjust func(*config.API)) *env {
|
||||
if adjust != nil {
|
||||
adjust(&cfg)
|
||||
}
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog})
|
||||
e.metrics = metrics.New(string(cfg.Edition))
|
||||
e.api = api.New(cfg, api.Deps{Log: log, DB: tenant.New(pool), Redis: rdb, Keys: keys, Catalog: catalog, Metrics: e.metrics})
|
||||
e.api.Mount(r)
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -314,6 +314,7 @@ func (s *Server) deliverSubscriberBatch(ctx context.Context) int {
|
||||
}
|
||||
for _, n := range rows {
|
||||
sendErr := s.smtp.Send(ctx, s.subscriberMail(n))
|
||||
s.metrics.SubscriberMail(sendErr)
|
||||
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
||||
if sendErr == nil {
|
||||
return q.MarkSubscriberNotificationSent(ctx, n.ID)
|
||||
|
||||
@@ -70,6 +70,9 @@ const (
|
||||
SignupClosed SignupMode = "closed"
|
||||
)
|
||||
|
||||
// MetricsOff switches the metrics listener off.
|
||||
const MetricsOff = "off"
|
||||
|
||||
// API configures cmd/api.
|
||||
type API struct {
|
||||
Common
|
||||
@@ -77,6 +80,11 @@ type API struct {
|
||||
Listen string `env:"UPTIME_API_LISTEN" envDefault:":8080"`
|
||||
SecretKeys string `env:"UPTIME_SECRET_KEYS"`
|
||||
Signup SignupMode `env:"UPTIME_SIGNUP" envDefault:"first-user"`
|
||||
|
||||
// MetricsListen is where Prometheus metrics are served, apart from the
|
||||
// public listener; "off" switches them off.
|
||||
MetricsListen string `env:"UPTIME_API_METRICS_LISTEN" envDefault:":9090"`
|
||||
|
||||
// SignupVerify is "auto", "required" or "off": whether new accounts
|
||||
// confirm their email address before signing in. Auto requires it in
|
||||
// the cloud edition and wherever mail can be sent.
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -332,6 +332,13 @@ func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error)
|
||||
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
|
||||
}
|
||||
|
||||
// Overdue returns how many monitors of region should have been dispatched
|
||||
// more than late ago, as when the region has no live instance.
|
||||
func (s *Scheduler) Overdue(ctx context.Context, region string, late time.Duration) (int64, error) {
|
||||
max := strconv.FormatInt(s.now().Add(-late).UnixMilli(), 10)
|
||||
return s.rdb.ZCount(ctx, keyDue(region), "-inf", max).Result()
|
||||
}
|
||||
|
||||
func parseEntry(s string) (Entry, bool) {
|
||||
id, at, ok := strings.Cut(s, "|")
|
||||
if !ok {
|
||||
|
||||
@@ -239,3 +239,33 @@ func TestReconcileKeepsMonitorsCreatedDuringRead(t *testing.T) {
|
||||
t.Errorf("jobs after Reconcile = %+v, want the freshly created monitor", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverdueCountsRunsLeftBehind(t *testing.T) {
|
||||
s, now := newTest(t)
|
||||
ctx := context.Background()
|
||||
for range 2 {
|
||||
_ = s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil)
|
||||
}
|
||||
overdue := func() int64 {
|
||||
t.Helper()
|
||||
n, err := s.Overdue(ctx, "eu", 10*time.Second)
|
||||
if err != nil {
|
||||
t.Fatalf("Overdue() failed: %v", err)
|
||||
}
|
||||
return n
|
||||
}
|
||||
if n := overdue(); n != 0 {
|
||||
t.Errorf("Overdue() right after scheduling = %d, want 0", n)
|
||||
}
|
||||
// No instance takes the runs.
|
||||
*now = now.Add(11 * time.Second)
|
||||
mustDispatch(t, s)
|
||||
if n := overdue(); n != 2 {
|
||||
t.Errorf("Overdue() without instances = %d, want 2", n)
|
||||
}
|
||||
_ = s.Heartbeat(ctx, "eu", uuid.New())
|
||||
mustDispatch(t, s)
|
||||
if n := overdue(); n != 0 {
|
||||
t.Errorf("Overdue() after dispatch = %d, want 0", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: metrics.sql
|
||||
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const monitorCounts = `-- name: MonitorCounts :many
|
||||
SELECT type, enabled, count(*)::bigint AS monitors
|
||||
FROM monitors
|
||||
GROUP BY type, enabled
|
||||
ORDER BY type, enabled
|
||||
`
|
||||
|
||||
type MonitorCountsRow struct {
|
||||
Type string
|
||||
Enabled bool
|
||||
Monitors int64
|
||||
}
|
||||
|
||||
// System scope. Monitors by type and whether they are enabled.
|
||||
func (q *Queries) MonitorCounts(ctx context.Context) ([]MonitorCountsRow, error) {
|
||||
rows, err := q.db.Query(ctx, monitorCounts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []MonitorCountsRow{}
|
||||
for rows.Next() {
|
||||
var i MonitorCountsRow
|
||||
if err := rows.Scan(&i.Type, &i.Enabled, &i.Monitors); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const platformCounts = `-- name: PlatformCounts :one
|
||||
SELECT
|
||||
(SELECT count(*) FROM orgs)::bigint AS orgs,
|
||||
(SELECT count(*) FROM users)::bigint AS users,
|
||||
(SELECT count(*) FROM status_pages)::bigint AS status_pages,
|
||||
(SELECT count(*) FROM status_page_subscribers WHERE confirmed_at IS NOT NULL)::bigint AS subscribers,
|
||||
(SELECT count(*) FROM incidents WHERE resolved_at IS NULL)::bigint AS open_incidents,
|
||||
(SELECT count(*) FROM notifications WHERE status = 'pending')::bigint AS pending_notifications,
|
||||
(SELECT count(*) FROM subscriber_notifications WHERE status = 'pending')::bigint AS pending_subscriber_notifications
|
||||
`
|
||||
|
||||
type PlatformCountsRow struct {
|
||||
Orgs int64
|
||||
Users int64
|
||||
StatusPages int64
|
||||
Subscribers int64
|
||||
OpenIncidents int64
|
||||
PendingNotifications int64
|
||||
PendingSubscriberNotifications int64
|
||||
}
|
||||
|
||||
// System scope. Platform totals for the operator metrics.
|
||||
func (q *Queries) PlatformCounts(ctx context.Context) (PlatformCountsRow, error) {
|
||||
row := q.db.QueryRow(ctx, platformCounts)
|
||||
var i PlatformCountsRow
|
||||
err := row.Scan(
|
||||
&i.Orgs,
|
||||
&i.Users,
|
||||
&i.StatusPages,
|
||||
&i.Subscribers,
|
||||
&i.OpenIncidents,
|
||||
&i.PendingNotifications,
|
||||
&i.PendingSubscriberNotifications,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -314,6 +314,8 @@ type Querier interface {
|
||||
MemberGrants(ctx context.Context, arg MemberGrantsParams) ([]MemberGrantsRow, error)
|
||||
MonitorAlertGroups(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
|
||||
MonitorAlertRoutes(ctx context.Context, monitorID uuid.UUID) ([]MonitorAlertRoutesRow, error)
|
||||
// System scope. Monitors by type and whether they are enabled.
|
||||
MonitorCounts(ctx context.Context) ([]MonitorCountsRow, error)
|
||||
MonitorRegions(ctx context.Context, monitorID uuid.UUID) ([]uuid.UUID, error)
|
||||
// System scope: monitors to hand to a checker of region, skipping ones that
|
||||
// were disabled, deleted or moved out of the region since dispatch. An
|
||||
@@ -341,6 +343,8 @@ type Querier interface {
|
||||
OrgServesOwnPages(ctx context.Context, orgID *uuid.UUID) (bool, error)
|
||||
// Organizations user owns, with their member and owner counts.
|
||||
OwnedOrgs(ctx context.Context, userID uuid.UUID) ([]OwnedOrgsRow, error)
|
||||
// System scope. Platform totals for the operator metrics.
|
||||
PlatformCounts(ctx context.Context) (PlatformCountsRow, error)
|
||||
// The public updates of incidents shown on a status page, newest first.
|
||||
PublicIncidentUpdates(ctx context.Context, ids []uuid.UUID) ([]PublicIncidentUpdatesRow, error)
|
||||
// Resolved and long silent alerts are history the monitors' results keep.
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
-- name: PlatformCounts :one
|
||||
-- System scope. Platform totals for the operator metrics.
|
||||
SELECT
|
||||
(SELECT count(*) FROM orgs)::bigint AS orgs,
|
||||
(SELECT count(*) FROM users)::bigint AS users,
|
||||
(SELECT count(*) FROM status_pages)::bigint AS status_pages,
|
||||
(SELECT count(*) FROM status_page_subscribers WHERE confirmed_at IS NOT NULL)::bigint AS subscribers,
|
||||
(SELECT count(*) FROM incidents WHERE resolved_at IS NULL)::bigint AS open_incidents,
|
||||
(SELECT count(*) FROM notifications WHERE status = 'pending')::bigint AS pending_notifications,
|
||||
(SELECT count(*) FROM subscriber_notifications WHERE status = 'pending')::bigint AS pending_subscriber_notifications;
|
||||
|
||||
-- name: MonitorCounts :many
|
||||
-- System scope. Monitors by type and whether they are enabled.
|
||||
SELECT type, enabled, count(*)::bigint AS monitors
|
||||
FROM monitors
|
||||
GROUP BY type, enabled
|
||||
ORDER BY type, enabled;
|
||||
Reference in new issue
Block a user