From e776143ee02e1222388b361345d8f0bdcd76d1fe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 29 Nov 2026 14:15:48 +0100 Subject: [PATCH 1/2] fix(checker): take work as soon as a slot frees With every slot busy, the poll loop paused a fixed second before asking for work again, so a checker took at most one batch of its slots per second, whatever its machine could do. Under load, runs piled up in the checker's queue and started late. The loop now waits for the first freed slot, at most fullHeartbeat (5s), so a checker whose slots stay busy still polls as a heartbeat. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/checker/checker.go | 44 ++++++++++++-- internal/checker/slots_test.go | 108 +++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 4 deletions(-) create mode 100644 internal/checker/slots_test.go diff --git a/internal/checker/checker.go b/internal/checker/checker.go index 0380a7b..5db9533 100644 --- a/internal/checker/checker.go +++ b/internal/checker/checker.go @@ -30,6 +30,9 @@ const ( // quickPoll is a long poll answered empty faster than any wait would. quickPoll = 200 * time.Millisecond flushInterval = 2 * time.Second + // fullHeartbeat is how often a checker with every slot busy still polls, + // so the API keeps it live; well below schedule.StaleAfter. + fullHeartbeat = 5 * time.Second // maxPending bounds results kept while the API is unreachable. maxPending = 50_000 ) @@ -39,6 +42,8 @@ type Runner struct { api API log *slog.Logger slots chan struct{} + // freed is signalled when a slot is freed, for a poll waiting for one. + freed chan struct{} run func(context.Context, check.Spec) check.Outcome results chan agentapi.Result @@ -80,6 +85,7 @@ func New(api API, concurrency int, log *slog.Logger) *Runner { api: api, log: log, slots: make(chan struct{}, max(concurrency, 1)), + freed: make(chan struct{}, 1), run: check.Run, results: make(chan agentapi.Result, 1024), @@ -170,19 +176,49 @@ func (r *Runner) poll(ctx context.Context, running *sync.WaitGroup) error { r.slots <- struct{}{} running.Add(1) go func() { - defer func() { <-r.slots; running.Done() }() + defer func() { r.release(); running.Done() }() r.results <- r.execute(ctx, j) }() } - // A long poll answered empty at once, as by an instance shutting - // down, is not repeated at once either. - if free == 0 || (len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll) { + switch { + case free == 0: + // Take work again as soon as a check finishes, not after a + // fixed pause, which would cap throughput at slots per pause. + r.waitForSlot(ctx, fullHeartbeat) + case len(jobs) == 0 && wait > 0 && time.Since(asked) < quickPoll: + // A long poll answered empty at once, as by an instance + // shutting down, is not repeated at once either. sleep(ctx, time.Second) } } return nil } +// release frees a slot and wakes a poll waiting for one. +func (r *Runner) release() { + <-r.slots + select { + case r.freed <- struct{}{}: + default: + } +} + +// waitForSlot returns once a slot is free, ctx is done or at most after +// d. +func (r *Runner) waitForSlot(ctx context.Context, d time.Duration) { + t := time.NewTimer(d) + defer t.Stop() + for len(r.slots) == cap(r.slots) { + select { + case <-r.freed: + case <-ctx.Done(): + return + case <-t.C: + return + } + } +} + func (r *Runner) execute(ctx context.Context, j agentapi.Job) agentapi.Result { // Checks already started finish even during shutdown; their timeout // bounds them. diff --git a/internal/checker/slots_test.go b/internal/checker/slots_test.go new file mode 100644 index 0000000..7127ba6 --- /dev/null +++ b/internal/checker/slots_test.go @@ -0,0 +1,108 @@ +package checker + +import ( + "context" + "log/slog" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi" + "git.zb-server.de/ZB-Server/uptimesebi/internal/check" +) + +// backlogAPI hands out queued jobs as fast as the checker asks for them. +type backlogAPI struct { + mu sync.Mutex + queued int + polls int + reported atomic.Int64 +} + +func (b *backlogAPI) Jobs(ctx context.Context, max int, wait time.Duration) ([]agentapi.Job, error) { + b.mu.Lock() + b.polls++ + n := min(max, b.queued) + b.queued -= n + b.mu.Unlock() + if n == 0 { + select { + case <-time.After(min(wait, 50*time.Millisecond)): + case <-ctx.Done(): + } + return nil, nil + } + jobs := make([]agentapi.Job, n) + for i := range jobs { + jobs[i] = agentapi.Job{MonitorID: uuid.New(), Type: "tcp", Target: "x:1"} + } + return jobs, nil +} + +func (b *backlogAPI) Report(_ context.Context, rs []agentapi.Result) error { + b.reported.Add(int64(len(rs))) + return nil +} + +func (b *backlogAPI) Release(context.Context) error { return nil } + +// TestFullCheckerTakesWorkAsSlotsFree runs a backlog through a single slot. +// A checker pausing a second whenever its slots are full would need about a +// second per job. +func TestFullCheckerTakesWorkAsSlotsFree(t *testing.T) { + const jobs = 10 + api := &backlogAPI{queued: jobs} + r := New(api, 1, slog.New(slog.DiscardHandler)) + var ran atomic.Int64 + r.run = func(context.Context, check.Spec) check.Outcome { + time.Sleep(5 * time.Millisecond) + ran.Add(1) + return check.Outcome{OK: true} + } + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- r.Run(ctx, time.Second) }() + + start := time.Now() + for ran.Load() < jobs && time.Since(start) < 5*time.Second { + time.Sleep(5 * time.Millisecond) + } + took := time.Since(start) + cancel() + if err := <-done; err != nil { + t.Errorf("Run() = %v", err) + } + if n := ran.Load(); n != jobs { + t.Fatalf("ran %d checks in %v, want %d", n, took, jobs) + } + if took > 2*time.Second { + t.Errorf("%d checks through one slot took %v, want well under a second each", jobs, took) + } + if n := api.reported.Load(); n != jobs { + t.Errorf("reported %d results, want %d", n, jobs) + } +} + +// TestWaitForSlotKeepsPolling bounds the wait, so a checker whose slots +// stay busy still polls as a heartbeat. +func TestWaitForSlotKeepsPolling(t *testing.T) { + r := New(nil, 1, slog.New(slog.DiscardHandler)) + r.slots <- struct{}{} + start := time.Now() + r.waitForSlot(context.Background(), 50*time.Millisecond) + if took := time.Since(start); took < 50*time.Millisecond || took > time.Second { + t.Errorf("waitForSlot() with every slot busy returned after %v, want the bound of 50ms", took) + } + go func() { + time.Sleep(20 * time.Millisecond) + r.release() + }() + start = time.Now() + r.waitForSlot(context.Background(), 5*time.Second) + if took := time.Since(start); took > time.Second { + t.Errorf("waitForSlot() returned %v after a slot was freed, want at once", took) + } +} -- 2.54.1 From 2fa439c47dbc09301a184e1e02beddb78a213615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 29 Nov 2026 14:15:49 +0100 Subject: [PATCH 2/2] feat(api): count queued runs as overdue; alert rules in the chart uptimesebi_checks_overdue counted only runs not dispatched yet. Dispatch hands due runs to an instance's queue and schedules the next run at once, so a checker too busy to take its work left the metric at 0. It now also counts queued runs due more than 10 seconds ago. The chart adds an optional PrometheusRule (api.metrics.prometheusRule): UptimeSebiRegionBehind fires when a region's checks stay overdue, and UptimeSebiPlatformMetricsFailing when the platform metrics cannot be read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- README.md | 2 +- .../uptimesebi/templates/prometheusrule.yaml | 39 +++++++++++++++++++ deploy/helm/uptimesebi/values.yaml | 11 ++++++ internal/api/metrics.go | 2 +- internal/schedule/schedule.go | 26 +++++++++++-- internal/schedule/schedule_test.go | 12 +++++- 6 files changed, 84 insertions(+), 8 deletions(-) create mode 100644 deploy/helm/uptimesebi/templates/prometheusrule.yaml diff --git a/README.md b/README.md index 740c958..a6f8141 100644 --- a/README.md +++ b/README.md @@ -152,7 +152,7 @@ helm install uptime uptimesebi/uptimesebi -n uptime --create-namespace \ --set ingress.enabled=true --set ingress.tls.enabled=true ``` -The API pods serve metrics on port 9090 (`api.metrics`); `--set api.metrics.serviceMonitor.enabled=true` adds a ServiceMonitor for the Prometheus Operator. Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too. +The API pods serve metrics on port 9090 (`api.metrics`); `--set api.metrics.serviceMonitor.enabled=true` adds a ServiceMonitor for the Prometheus Operator, and `api.metrics.prometheusRule.enabled=true` alert rules for a region whose checks fall behind. Every setting can come from an existing secret instead (`existingSecret`); [`values.yaml`](deploy/helm/uptimesebi/values.yaml) explains them all. Migrations run as a hook before each install and upgrade. To try it out without a database and Redis of your own, `--set database.bundled.enabled=true --set redis.bundled.enabled=true` adds a single TimescaleDB and Redis, without backups or high availability. Pods run unprivileged with a read-only root filesystem; the API pods need amd64 nodes, checkers and status page servers run on ARM too. Run as many API, checker and status page instances as you need; they share no local state. The supported setups are: diff --git a/deploy/helm/uptimesebi/templates/prometheusrule.yaml b/deploy/helm/uptimesebi/templates/prometheusrule.yaml new file mode 100644 index 0000000..54a24da --- /dev/null +++ b/deploy/helm/uptimesebi/templates/prometheusrule.yaml @@ -0,0 +1,39 @@ +{{- if and .Values.api.metrics.enabled .Values.api.metrics.prometheusRule.enabled }} +{{- $rule := .Values.api.metrics.prometheusRule }} +apiVersion: monitoring.coreos.com/v1 +kind: PrometheusRule +metadata: + name: {{ include "uptimesebi.fullname" . }}-api + labels: + {{- include "uptimesebi.labels" . | nindent 4 }} + app.kubernetes.io/component: api + {{- with $rule.labels }} + {{- toYaml . | nindent 4 }} + {{- end }} +spec: + groups: + - name: uptimesebi + rules: + # Every replica reports the same platform values, hence max(). + - alert: UptimeSebiRegionBehind + expr: max by (region) (uptimesebi_checks_overdue) > 0 + for: {{ $rule.regionBehindFor }} + labels: + severity: {{ $rule.severity }} + annotations: + summary: "Region {{ "{{ $labels.region }}" }} falls behind its checks" + description: >- + {{ "{{ $value }}" }} checks of region {{ "{{ $labels.region }}" }} are more than + 10 seconds overdue: no checker of the region is live, or its + checkers cannot take the work in time. + - alert: UptimeSebiPlatformMetricsFailing + expr: max(uptimesebi_platform_metrics_error) > 0 + for: 10m + labels: + severity: {{ $rule.severity }} + annotations: + summary: UptimeSebi cannot read its platform metrics + description: >- + The API fails to read the database or Redis for its platform + metrics, so UptimeSebiRegionBehind sees stale values. +{{- end }} diff --git a/deploy/helm/uptimesebi/values.yaml b/deploy/helm/uptimesebi/values.yaml index 6fc9453..12e84ac 100644 --- a/deploy/helm/uptimesebi/values.yaml +++ b/deploy/helm/uptimesebi/values.yaml @@ -137,6 +137,17 @@ api: interval: 30s # Extra labels, for a Prometheus that selects ServiceMonitors by label. labels: {} + # Alert rules for the Prometheus Operator: a region whose checks fall + # behind, and platform metrics that cannot be read. Needs the + # ServiceMonitor or another scrape of the metrics. + prometheusRule: + enabled: false + # How long checks must stay overdue before the alert fires. + regionBehindFor: 5m + severity: warning + # Extra labels, for a Prometheus that selects rules by label, like + # release: with kube-prometheus-stack. + labels: {} # The API image is built for amd64 only; checkers and status page servers # run on arm64 and 32-bit ARM too. Also used by the migration job. nodeSelector: diff --git a/internal/api/metrics.go b/internal/api/metrics.go index 5f299f3..08a6d66 100644 --- a/internal/api/metrics.go +++ b/internal/api/metrics.go @@ -26,7 +26,7 @@ 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) + "Checks of a platform region due for more than 10 seconds and not started: undispatched, as when no checker of the region is live, or waiting in the queue of a checker too busy to take them.", []string{"region"}, nil) descRegions = prometheus.NewDesc("uptimesebi_regions", "Platform regions by whether a checker is live.", []string{"online"}, nil) descOrgs = prometheus.NewDesc("uptimesebi_orgs", diff --git a/internal/schedule/schedule.go b/internal/schedule/schedule.go index f70391c..75ef083 100644 --- a/internal/schedule/schedule.go +++ b/internal/schedule/schedule.go @@ -332,11 +332,29 @@ 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. +// overdueScript counts the runs of a region due before a cutoff: those not +// dispatched yet and those waiting in an instance's queue. +// +// KEYS: due set, instance set. +// ARGV: cutoff ms, job queue prefix. +var overdueScript = redis.NewScript(` +local cutoff = tonumber(ARGV[1]) +local n = redis.call('ZCOUNT', KEYS[1], '-inf', cutoff) +for _, inst in ipairs(redis.call('ZRANGE', KEYS[2], 0, -1)) do + for _, job in ipairs(redis.call('LRANGE', ARGV[2] .. inst, 0, -1)) do + local at = tonumber(string.sub(job, string.find(job, '|', 1, true) + 1)) + if at ~= nil and at <= cutoff then n = n + 1 end + end +end +return n +`) + +// Overdue returns how many runs of region were due more than late ago and +// have not started: runs not dispatched, as when the region has no live +// instance, and runs left in the queue of an instance too busy to take them. 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() + return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)}, + s.now().Add(-late).UnixMilli(), jobsPrefix).Int64() } func parseEntry(s string) (Entry, bool) { diff --git a/internal/schedule/schedule_test.go b/internal/schedule/schedule_test.go index aa8e654..062606c 100644 --- a/internal/schedule/schedule_test.go +++ b/internal/schedule/schedule_test.go @@ -263,9 +263,17 @@ func TestOverdueCountsRunsLeftBehind(t *testing.T) { if n := overdue(); n != 2 { t.Errorf("Overdue() without instances = %d, want 2", n) } - _ = s.Heartbeat(ctx, "eu", uuid.New()) + busy := uuid.New() + _ = s.Heartbeat(ctx, "eu", busy) mustDispatch(t, s) + // The queued runs were due 11 seconds ago and are still waiting. + if n := overdue(); n != 2 { + t.Errorf("Overdue() with the runs left in a queue = %d, want 2", n) + } + if _, err := s.Take(ctx, busy, 10, 0); err != nil { + t.Fatal(err) + } if n := overdue(); n != 0 { - t.Errorf("Overdue() after dispatch = %d, want 0", n) + t.Errorf("Overdue() after the instance took the runs = %d, want 0", n) } } -- 2.54.1