Compare commits

...
14 Commits
Author SHA1 Message Date
Sebi 71219d8031 Merge pull request 'fix(evidence): spread periodic evidence and store a report's in one go' (#176) from fix/evidence-burst into main
ci / build (push) Successful in 18m1s
ci / lint (push) Successful in 6m45s
ci / test (push) Successful in 13m58s
ci / image (push) Successful in 5m24s
release / release (push) Successful in 37m59s
2026-11-29 17:18:02 +00:00
Sebastian UnterschützandClaude Opus 5.5 e26194d260 fix(evidence): spread periodic evidence and store a report's in one go
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 13m0s
ci / test (pull_request) Successful in 13m56s
ci / build (pull_request) Successful in 19m56s
ci / image (pull_request) Successful in 5m50s
Checkers send evidence of healthy checks every 10 minutes, first with
the first result after they start. When checkers restart together, as
after a self-update, every monitor's evidence came in the same minute,
every 10 minutes. The API stored each in a transaction of its own while
the checker waited, reports took up to 36 seconds, the checkers' slots
filled and runs piled up: the overdue waves seen in prod.

Evidence sent for another reason than the period now puts the next
periodic one at a random point of the period, and the API writes all of
a report's evidence in one transaction, with one query each for the
successes to replace and the failures last kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 18:16:05 +01:00
Sebi 61a50ee6f0 Merge pull request 'fix(agent): apply agent settings as they are when jobs are handed out' (#175) from fix/agent-settings-after-poll into main
ci / build (push) Successful in 17m58s
ci / lint (push) Successful in 10m42s
ci / test (push) Successful in 18m29s
release / release (push) Successful in 40m13s
ci / image (push) Successful in 5m24s
2026-11-29 15:40:03 +00:00
Sebastian UnterschützandClaude Opus 5.5 4246e37384 fix(agent): apply agent settings as they are when jobs are handed out
ci / image (push) Skipped
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (push) Skipped
ci / build (pull_request) Successful in 10m26s
ci / lint (pull_request) Successful in 10m46s
ci / test (pull_request) Successful in 8m51s
ci / image (pull_request) Successful in 5m8s
The jobs endpoint read the agent, and with it allow_private, before its
long poll of up to 20 seconds, so jobs handed out afterwards could carry
a setting changed in the meantime and the change only applied a poll
later. It now reads the agent again when the poll returns jobs.

TestCheckerNetwork also waits for two runs at most: the next run after a
monitor's first one is on its phase now, up to one and a half intervals
later.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:37:08 +01:00
Sebi 9d1d6a2544 Merge pull request 'feat(schedule): spread monitor runs evenly over their interval' (#174) from feat/schedule-phase into main
ci / lint (push) Successful in 12m50s
ci / test (push) Successful in 13m53s
ci / build (push) Successful in 20m40s
ci / image (push) Successful in 4m21s
release / release (push) Successful in 42m44s
2026-11-29 15:07:46 +00:00
Sebastian UnterschützandClaude Opus 5.5 050c9dd0a1 feat(schedule): spread monitor runs evenly over their interval
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m40s
ci / test (pull_request) Failing after 13m52s
ci / build (pull_request) Skipped
ci / image (pull_request) Skipped
A monitor's next run was its last due time plus the interval, so monitors
created together, by an import or a test, stayed due in the same second
for good, and late runs all gathered at the dispatch time. In prod, regions
fell behind in waves every interval although the checkers kept up on
average.

Each monitor now has a fixed phase within its interval, from its ID.
After the first run, still right away, it runs on its phase; late runs
snap to their next slot. Reconcile adds lost monitors on their phase, so
rebuilding a schedule causes no burst either. Monitors scheduled before
phases existed keep the old rule until reconciliation adds their phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 16:06:40 +01:00
Sebi 6d4842f4a3 Merge pull request 'fix(checker): take work as soon as a slot frees; alert on overdue checks' (#173) from fix/checker-slot-wait into main
ci / test (push) Successful in 13m12s
ci / lint (push) Successful in 6m46s
ci / build (push) Successful in 17m58s
release / release (push) Successful in 37m25s
ci / image (push) Successful in 6m0s
2026-11-29 13:34:43 +00:00
Sebastian UnterschützandClaude Opus 5.5 2fa439c47d feat(api): count queued runs as overdue; alert rules in the chart
ci / test (push) Skipped
ci / lint (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m57s
ci / test (pull_request) Successful in 13m1s
ci / build (pull_request) Successful in 19m25s
ci / image (pull_request) Successful in 6m9s
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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 14:15:49 +01:00
Sebastian UnterschützandClaude Opus 5.5 e776143ee0 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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 14:15:48 +01:00
Sebi 6aabf9a364 Merge pull request 'feat(api): Prometheus metrics; fix(monitors): region limit in the form' (#172) from feat/api-metrics into main
ci / test (push) Successful in 13m27s
ci / build (push) Successful in 20m8s
release / release (push) Successful in 37m51s
ci / lint (push) Successful in 11m38s
ci / image (push) Successful in 5m42s
2026-11-29 11:21:07 +00:00
Sebastian UnterschützandClaude Opus 5.5 3a7bed5a3e fix(monitors): stop selecting more regions than the limit allows
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / test (pull_request) Successful in 13m28s
ci / lint (pull_request) Successful in 6m31s
ci / build (pull_request) Successful in 10m23s
ci / image (pull_request) Successful in 5m51s
The monitor form let users tick any number of regions and only the save
failed with the region limit. The form now knows the organization's
regions-per-monitor limit: it says how many regions a monitor may use,
counts the ticked ones, and once the limit is reached locks the other
regions that count towards it, in the list and on the map, until one is
unticked. Own regions stay free unless they count. The server still
enforces the limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 12:17:08 +01:00
Sebastian UnterschützandClaude Opus 5.5 e9984f8271 feat(api): Prometheus metrics for operators
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (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
2026-11-29 11:56:46 +01:00
Sebi ab25c1f218 Merge pull request 'fix(regions): keep map labels of nearby regions apart' (#171) from fix/region-map-overlap into main
ci / image (push) Successful in 5m12s
ci / lint (push) Successful in 10m23s
ci / test (push) Successful in 15m11s
ci / build (push) Successful in 16m49s
release / release (push) Successful in 37m59s
2026-11-29 10:09:56 +00:00
Sebastian UnterschützandClaude Opus 5.5 401a361422 fix(regions): keep map labels of nearby regions apart
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 11m19s
ci / test (pull_request) Successful in 13m11s
ci / build (pull_request) Successful in 18m31s
ci / image (pull_request) Successful in 5m52s
Regions a few kilometres apart drew their labels on top of each other.
As on the landing page, a label now runs to the right of its point, or
to the left where the right side would cover another pin or leave the
map; a pin with room on neither side shows only its dot and reveals its
name on hover. Placement reruns while zooming and panning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-29 11:06:42 +01:00
49 changed files with 3164 additions and 1281 deletions

No files matched your search

+3
View File
@@ -24,6 +24,9 @@ UPTIME_SSO_ALLOW_PRIVATE_NETWORKS=auto
# Outgoing mail, for email channels and sign-up confirmation.
# UPTIME_SMTP_URL=smtp://user:pass@mail.example.com:587?from=uptime@example.com
# Prometheus metrics of the API, on a listener apart from the console's;
# "off" switches them off.
# UPTIME_API_METRICS_LISTEN=:9090
# Checker and status page reach the API only. Create tokens with:
# api agent create --kind checker --region local --name dev
# api agent create --kind statuspage --name dev
+2 -1
View File
@@ -125,6 +125,7 @@ All settings are environment variables; [`.env.example`](.env.example) lists the
- `UPTIME_SIGNUP` (`first-user`, `open`, `closed`) decides who may sign up. New accounts confirm their email address before signing in (`UPTIME_SIGNUP_VERIFY`: always in the cloud edition, self-hosted when `UPTIME_SMTP_URL` is set); one account per mailbox, and at most `UPTIME_SIGNUPS_PER_IP` (default 2) a day per client address.
- `UPTIME_TRUSTED_PROXIES` must name your reverse proxy, or client addresses in the audit log and rate limits will be the proxy's.
- `UPTIME_RETENTION_*` set how long results, aggregates, audit entries and captured responses are kept.
- `UPTIME_API_METRICS_LISTEN` (default `:9090`, `off` to disable) serves Prometheus metrics at `/metrics`, apart from the public listener: requests by route, dispatched checks and stored results per region, live checkers and overdue checks per region, notification deliveries, background job runs, platform totals and the database and Redis pools. Platform totals are the same on every API instance; aggregate them with `max()`. Keep the port off the internet.
### Docker Compose
@@ -151,7 +152,7 @@ helm install uptime uptimesebi/uptimesebi -n uptime --create-namespace \
--set ingress.enabled=true --set ingress.tls.enabled=true
```
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:
+28 -1
View File
@@ -6,6 +6,7 @@ import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"time"
@@ -15,6 +16,7 @@ import (
"git.zb-server.de/ZB-Server/uptimesebi/internal/config"
"git.zb-server.de/ZB-Server/uptimesebi/internal/datapolicy"
"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/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/platform"
@@ -80,12 +82,15 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
if err != nil {
return err
}
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog})
m := metrics.New(string(cfg.Edition))
m.Register(metrics.DBPool(deps.DB), metrics.RedisPool(deps.Redis))
srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog, Metrics: m})
health := platform.NewHealth(deps.Probes())
r := platform.NewRouter(log)
if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil {
return err
}
r.Use(m.HTTP(api.StreamingRoutes()...))
health.Register(r)
r.StaticFS("/static", web.Static())
srv.Mount(r)
@@ -97,9 +102,31 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error {
go srv.RunDomainWatch(ctx)
go srv.RunHeartbeats(ctx)
if cfg.MetricsListen != config.MetricsOff {
go serveMetrics(ctx, log, cfg.MetricsListen, m)
}
return platform.Serve(ctx, log, platform.NewHTTPServer(cfg.Listen, r), health, 5*time.Second, cfg.ShutdownTimeout)
}
// serveMetrics serves /metrics on addr, apart from the public listener,
// until ctx ends. Failing to listen is logged but does not stop the API.
func serveMetrics(ctx context.Context, log *slog.Logger, addr string, m *metrics.Metrics) {
mux := http.NewServeMux()
mux.Handle("GET /metrics", m.Handler())
srv := platform.NewHTTPServer(addr, mux)
go func() {
<-ctx.Done()
sctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = srv.Shutdown(sctx)
}()
log.Info("metrics listening", "addr", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Error("serving metrics failed", "addr", addr, "error", err)
}
}
func migrate(ctx context.Context, log *slog.Logger, cfg config.API, args []string) error {
dsn := cfg.DatabaseURL
if dsn == "" {
+11
View File
@@ -63,9 +63,15 @@ spec:
args: [serve]
env:
{{- include "uptimesebi.platformEnv" (list . $secret) | nindent 12 }}
- name: UPTIME_API_METRICS_LISTEN
value: {{ if .Values.api.metrics.enabled }}{{ printf ":%v" .Values.api.metrics.port | quote }}{{ else }}"off"{{ end }}
ports:
- name: http
containerPort: 8080
{{- if .Values.api.metrics.enabled }}
- name: metrics
containerPort: {{ .Values.api.metrics.port }}
{{- end }}
startupProbe:
httpGet: {path: /healthz, port: http}
periodSeconds: 2
@@ -113,6 +119,11 @@ spec:
- name: http
port: {{ .Values.api.service.port }}
targetPort: http
{{- if .Values.api.metrics.enabled }}
- name: metrics
port: {{ .Values.api.metrics.port }}
targetPort: metrics
{{- end }}
{{- if and .Values.api.podDisruptionBudget.enabled (gt (int .Values.api.replicas) 1) }}
---
apiVersion: policy/v1
@@ -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 }}
@@ -0,0 +1,20 @@
{{- if and .Values.api.metrics.enabled .Values.api.metrics.serviceMonitor.enabled }}
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: {{ include "uptimesebi.fullname" . }}-api
labels:
{{- include "uptimesebi.labels" . | nindent 4 }}
app.kubernetes.io/component: api
{{- with .Values.api.metrics.serviceMonitor.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
selector:
matchLabels:
{{- include "uptimesebi.selector" (list . "api") | nindent 6 }}
endpoints:
- port: metrics
path: /metrics
interval: {{ .Values.api.metrics.serviceMonitor.interval }}
{{- end }}
+22
View File
@@ -126,6 +126,28 @@ api:
service:
type: ClusterIP
port: 8080
# Prometheus metrics on a port of their own, which the ingress never
# exposes.
metrics:
enabled: true
port: 9090
# A ServiceMonitor for the Prometheus Operator (kube-prometheus-stack).
serviceMonitor:
enabled: false
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: <name> 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:
+7
View File
@@ -23,6 +23,7 @@ require (
github.com/nicksnyder/go-i18n/v2 v2.7.0
github.com/pquerna/otp v1.5.0
github.com/pressly/goose/v3 v3.30.1
github.com/prometheus/client_golang v1.25.0
github.com/rabbitmq/amqp091-go v1.17.0
github.com/redis/go-redis/v9 v9.23.0
github.com/twmb/franz-go v1.22.3
@@ -46,6 +47,7 @@ require (
github.com/ImVexed/fasturl v0.0.0-20230304231329-4e41488060f3 // indirect
github.com/a-h/parse v0.0.42 // indirect
github.com/andybalholm/brotli v1.3.0 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc // indirect
github.com/btcsuite/btcd/btcec/v2 v2.3.4 // indirect
github.com/btcsuite/btcd/btcutil v1.1.5 // indirect
@@ -80,6 +82,7 @@ require (
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.20.4 // indirect
github.com/klauspost/cpuid/v2 v2.4.0 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/leodido/go-urn v1.5.0 // indirect
github.com/libdns/libdns v1.1.1 // indirect
github.com/mailru/easyjson v0.9.0 // indirect
@@ -90,11 +93,15 @@ require (
github.com/miekg/dns v1.1.73 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/natefinch/atomic v1.0.1 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/opencontainers/image-spec v1.1.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
github.com/pierrec/lz4/v4 v4.1.33 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.72.0 // indirect
github.com/prometheus/procfs v0.23.0 // indirect
github.com/puzpuzpuz/xsync/v3 v3.5.1 // indirect
github.com/quic-go/qpack v0.6.0 // indirect
github.com/quic-go/quic-go v0.59.0 // indirect
+14
View File
@@ -25,6 +25,8 @@ github.com/a-h/templ v0.3.1118/go.mod h1:ttKggixbDULrwkJzfEO5fa4IPGTKiRt3qP09zjP
github.com/aead/siphash v1.0.1/go.mod h1:Nywa3cDsYNNK3gaciGTWPwHt0wlpNV15vwmswBAUSII=
github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY=
github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc h1:biVzkmvwrH8WK8raXaxBx6fRVTlJILwEwQGL1I/ByEI=
github.com/boombuler/barcode v1.0.1-0.20190219062509-6c824513bacc/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
@@ -216,6 +218,8 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/natefinch/atomic v1.0.1 h1:ZPYKxkqQOx3KZ+RsbnP/YsgvxWQPGxjC0oBt2AhwV0A=
github.com/natefinch/atomic v1.0.1/go.mod h1:N/D/ELrljoqDyT3rZrsUmtsuzvHkeB/wWjHV22AZRbM=
github.com/nbd-wtf/go-nostr v0.52.3 h1:Xd87pXfJEJRXHpM+fLjQQln8dBNNaoPA10V7BbyP4KI=
@@ -248,6 +252,14 @@ github.com/pquerna/otp v1.5.0 h1:NMMR+WrmaqXU4EzdGJEE1aUUI0AMRzsp96fFFWNPwxs=
github.com/pquerna/otp v1.5.0/go.mod h1:dkJfzwRKNiegxyNb54X/3fLwhCynbMspSyWKnvi1AEg=
github.com/pressly/goose/v3 v3.30.1 h1:KO28meBdbAUIdMbTP7bl9dp1FYZGXcYWb2O7miT09lE=
github.com/pressly/goose/v3 v3.30.1/go.mod h1:CHGwuG2acDerUaXwz2i5T18VSauXpYDiL4WxzDvcOIM=
github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0=
github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk=
github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo=
github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM=
github.com/prometheus/common v0.72.0 h1:tAYsE+sPJxIncDAobm4H5aQjmox9ZxEIIqPbiffa8G4=
github.com/prometheus/common v0.72.0/go.mod h1:77NWqAQ2tXT7BIK40qjJdw5Acrsrg1TlHAnsQi3i6mk=
github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH/o4=
github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk=
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8=
@@ -334,6 +346,8 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
go.uber.org/zap/exp v0.3.0 h1:6JYzdifzYkGmTdRR59oYH+Ng7k49H9qVpWwNSsGJj3U=
go.uber.org/zap/exp v0.3.0/go.mod h1:5I384qq7XGxYyByIhHm6jg5CHkGY0nsTfbDLgDDlgJQ=
go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI=
+34 -2
View File
@@ -227,7 +227,25 @@ func (s *Server) agentJobs(c *gin.Context) {
internalError(c, err)
return
}
jobs, orgs, err := s.resolveJobs(ctx, agentOf(c), entries)
agent := agentOf(c)
if len(entries) > 0 {
// The long poll may have waited for a while: settings such as
// allow_private apply to the jobs as they are now.
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
agent, err = q.GetAgentByHash(ctx, HashToken(bearerToken(c)))
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
if err != nil {
internalError(c, err)
return
}
}
jobs, orgs, err := s.resolveJobs(ctx, agent, entries)
if err != nil {
internalError(c, err)
return
@@ -298,6 +316,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 +327,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 +346,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 +379,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)
+3
View File
@@ -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)
+3 -1
View File
@@ -85,7 +85,9 @@ func TestCheckerNetwork(t *testing.T) {
}
waitResult := func(id string, ok bool, what string) {
t.Helper()
waitFor(t, 20*time.Second, what, func() bool {
// Two runs at most: the one already handed out, then the next on
// the monitor's phase, up to one and a half intervals later.
waitFor(t, 30*time.Second, what, func() bool {
got, msg, seen := latestOf(owner, id)
return seen && got == ok && (ok || strings.Contains(msg, "non-public"))
})
+2
View File
@@ -941,6 +941,8 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
checked := slices.Contains(assigned, r.ID) || (idParam == "" && i == 0)
f.Regions = append(f.Regions, web.RegionOption{ID: r.ID.String(), Name: r.Name, Own: r.OrgID != nil, Checked: checked, Live: live, Lat: r.Latitude, Lon: r.Longitude})
}
limits := s.orgLimits(ctx, p.Org)
f.RegionLimit, f.OwnRegionsCount = limits.RegionsPerMonitor, limits.OwnRegionsCount
t, err := s.loadGroupTree(ctx, p.scope())
if err != nil {
return nil, err
+1 -1
View File
@@ -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)
}
}
+75 -28
View File
@@ -37,9 +37,15 @@ const (
// storeEvidence keeps the evidence of accepted results: per monitor and
// region the latest success, and failures unless an identical one was kept
// within failureEvidenceEvery. Evidence is an aid; failures are logged and
// never fail the report.
// within failureEvidenceEvery. All of a report's evidence is written in one
// transaction, so a report full of it stays quick and the checker can go
// on. Evidence is an aid; failures are logged and never fail the report.
func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.UUID, results []agentapi.Result, monitors map[uuid.UUID]store.MonitorsForResultsRow) {
var (
successes = map[uuid.UUID]agentapi.Result{}
failures []agentapi.Result
failed []uuid.UUID
)
for _, r := range results {
m, ok := monitors[r.MonitorID]
if len(r.Evidence) == 0 || !ok {
@@ -49,34 +55,75 @@ func (s *Server) storeEvidence(ctx context.Context, region string, checker uuid.
s.log.WarnContext(ctx, "dropping malformed evidence", "monitor", m.ID, "bytes", len(r.Evidence))
continue
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if r.OK {
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{MonitorID: m.ID, Region: region}); err != nil {
return err
}
} else {
last, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{MonitorID: m.ID, Region: region})
if err == nil && last.Error == r.Error && r.StartedAt.Sub(last.Time) < failureEvidenceEvery {
return nil
}
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
return err
}
if r.OK {
// Only the latest success is kept anyway.
if prev, seen := successes[r.MonitorID]; !seen || r.StartedAt.After(prev.StartedAt) {
successes[r.MonitorID] = r
}
row := store.InsertEvidenceParams{
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
return q.InsertEvidence(ctx, row)
})
if err != nil {
s.log.WarnContext(ctx, "storing evidence failed", "monitor", m.ID, "error", err)
continue
}
failures = append(failures, r)
if !slices.Contains(failed, r.MonitorID) {
failed = append(failed, r.MonitorID)
}
}
if len(successes) == 0 && len(failures) == 0 {
return
}
slices.SortFunc(failures, func(a, b agentapi.Result) int { return a.StartedAt.Compare(b.StartedAt) })
insert := func(q *store.Queries, r agentapi.Result) error {
m := monitors[r.MonitorID]
row := store.InsertEvidenceParams{
OrgID: m.OrgID, MonitorID: m.ID, Region: region, CheckerID: checker, Time: r.StartedAt, Ok: r.OK, Evidence: r.Evidence,
}
if r.StatusCode > 0 {
row.StatusCode = ptr(int32(r.StatusCode))
}
if r.Error != "" {
row.Error = ptr(truncateValid(r.Error, 500))
}
return q.InsertEvidence(ctx, row)
}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
if len(successes) > 0 {
ids := make([]uuid.UUID, 0, len(successes))
for id := range successes {
ids = append(ids, id)
}
if err := q.DeleteSuccessEvidence(ctx, store.DeleteSuccessEvidenceParams{Region: region, MonitorIds: ids}); err != nil {
return err
}
for _, r := range successes {
if err := insert(q, r); err != nil {
return err
}
}
}
if len(failures) == 0 {
return nil
}
rows, err := q.LastFailureEvidence(ctx, store.LastFailureEvidenceParams{Region: region, MonitorIds: failed})
if err != nil {
return err
}
last := make(map[uuid.UUID]store.LastFailureEvidenceRow, len(rows))
for _, l := range rows {
last[l.MonitorID] = l
}
for _, r := range failures {
kept := truncateValid(r.Error, 500)
if l, ok := last[r.MonitorID]; ok && l.Error == kept && r.StartedAt.Sub(l.Time) < failureEvidenceEvery {
continue
}
if err := insert(q, r); err != nil {
return err
}
last[r.MonitorID] = store.LastFailureEvidenceRow{MonitorID: r.MonitorID, Time: r.StartedAt, Error: kept}
}
return nil
})
if err != nil {
s.log.WarnContext(ctx, "storing evidence failed", "results", len(successes)+len(failures), "error", err)
}
}
+64
View File
@@ -2,12 +2,17 @@ package api_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
)
func TestEvidence(t *testing.T) {
@@ -103,3 +108,62 @@ func TestEvidence(t *testing.T) {
t.Error("the monitor page links evidence for a viewer")
}
}
// TestEvidenceBatch stores a report with evidence of several monitors and
// runs at once, as a checker sends after a backlog.
func TestEvidenceBatch(t *testing.T) {
e := newEnv(t)
tok, region := e.platformChecker(t, uniq("ev-batch-"))
owner := e.browser(t)
owner.signup("o@"+uniq("evb")+".test", uniq("evb-"))
monitor := func() uuid.UUID {
_, 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},
})
return uuid.MustParse(m["id"].(string))
}
up, down := monitor(), monitor()
client := agentapi.NewClient(e.srv.URL, tok, uuid.New(), "test").WithHTTPClient(e.srv.Client())
ev := json.RawMessage(`{"steps":[]}`)
at := time.Now().Add(-time.Minute).Truncate(time.Millisecond)
run := func(m uuid.UUID, after time.Duration, ok bool, msg string) agentapi.Result {
return agentapi.Result{MonitorID: m, ScheduledAt: at.Add(after), StartedAt: at.Add(after), OK: ok, Error: msg, Evidence: ev}
}
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 0, true, ""),
run(up, time.Second, true, ""),
run(down, 0, false, "boom"),
run(down, time.Second, false, "boom"),
run(down, 2*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
// The latest success only; failures unless the same one was just kept.
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(time.Second)); n != 1 {
t.Errorf("success evidence of the latest run = %d rows, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows = %d, want 2: boom once, then other", n)
}
// The next report replaces the success and thins out the failure
// already kept.
if err := client.Report(context.Background(), []agentapi.Result{
run(up, 5*time.Second, true, ""),
run(down, 10*time.Second, false, "other"),
}); err != nil {
t.Fatal(err)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND ok AND time = $2`, up, at.Add(5*time.Second)); n != 1 {
t.Errorf("success evidence after the next report: latest run kept %d times, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1`, up); n != 1 {
t.Errorf("success evidence rows after the next report = %d, want 1", n)
}
if n := e.count(t, `SELECT count(*) FROM check_evidence WHERE monitor_id = $1 AND NOT ok`, down); n != 2 {
t.Errorf("failure evidence rows after the next report = %d, want still 2", n)
}
}
+4 -2
View File
@@ -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)
}
}
+1 -1
View File
@@ -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 {
+16
View File
@@ -52,6 +52,22 @@ func TestLimits(t *testing.T) {
})
}
// The monitor form locks regions beyond the limit; own ones do not count.
_, _, html := owner.page("/monitors/new")
if !strings.Contains(html, `data-region-limit="1"`) {
t.Error("monitor form lacks the region limit")
}
for id, counted := range map[string]bool{p1: true, o1: false} {
i := strings.Index(html, `value="`+id+`"`)
if i < 0 {
t.Fatalf("monitor form lacks region %s", id)
}
tag := html[i : i+strings.Index(html[i:], ">")]
if strings.Contains(tag, "data-counted") != counted {
t.Errorf("region %s counted = %v, want %v", id, !counted, counted)
}
}
// Monitors, passive ones included.
if st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "hb", "type": "heartbeat", "interval_seconds": 3600}); st != http.StatusCreated {
t.Fatalf("heartbeat = %d %v", st, body)
+187
View File
@@ -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 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",
"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"}
}
+90
View File
@@ -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)
}
}
}
+13 -9
View File
@@ -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)
}
+1 -1
View File
@@ -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 {
+1 -1
View File
@@ -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
View File
@@ -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
+5 -1
View File
@@ -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
}
+1
View File
@@ -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)
+56 -6
View File
@@ -8,6 +8,7 @@ import (
"encoding/json"
"errors"
"log/slog"
"math/rand/v2"
"sync"
"sync/atomic"
"time"
@@ -30,6 +31,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 +43,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
@@ -46,6 +52,8 @@ type Runner struct {
evidenceMu sync.Mutex
evidence map[uuid.UUID]evidenceState
// jitter returns a random duration in [0, d), replaced in tests.
jitter func(d time.Duration) time.Duration
}
// evidenceState remembers what was last sent for a monitor.
@@ -61,13 +69,23 @@ const evidenceEvery = 10 * time.Minute
// shouldSendEvidence decides whether a result carries its evidence: every
// failure, every change between success and failure, and otherwise every
// evidenceEvery. Most results thus stay small.
//
// Evidence sent for another reason than the period, like the first result
// after a start, puts the next periodic one at a random point of the
// period. Otherwise every monitor would send its evidence in the same
// minute every period after a restart, and the API would have to store all
// of it at once.
func (r *Runner) shouldSendEvidence(monitor uuid.UUID, ok bool, now time.Time) bool {
r.evidenceMu.Lock()
defer r.evidenceMu.Unlock()
last, seen := r.evidence[monitor]
send := !ok || !seen || last.ok != ok || now.Sub(last.sent) >= evidenceEvery
if send {
periodic := seen && last.ok == ok && now.Sub(last.sent) >= evidenceEvery
send := !ok || !seen || last.ok != ok || periodic
switch {
case periodic:
last.sent = now
case send:
last.sent = now.Add(-r.jitter(evidenceEvery))
}
last.ok = ok
r.evidence[monitor] = last
@@ -80,10 +98,12 @@ 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),
evidence: map[uuid.UUID]evidenceState{},
jitter: rand.N[time.Duration],
}
}
@@ -170,19 +190,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.
+37
View File
@@ -10,6 +10,7 @@ import (
func TestEvidencePolicy(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler))
r.jitter = func(time.Duration) time.Duration { return 0 }
m := uuid.New()
now := time.Now()
steps := []struct {
@@ -31,3 +32,39 @@ func TestEvidencePolicy(t *testing.T) {
}
}
}
// TestEvidenceSpreadsAfterStart starts with many healthy monitors at once:
// their periodic evidence must not all fall into the same minute again.
func TestEvidenceSpreadsAfterStart(t *testing.T) {
r := New(nil, 1, slog.New(slog.DiscardHandler))
start := time.Now()
const monitors = 600
ids := make([]uuid.UUID, monitors)
for i := range ids {
ids[i] = uuid.New()
if !r.shouldSendEvidence(ids[i], true, start) {
t.Fatal("first result sent no evidence")
}
}
// One result per monitor and minute over the next period.
perMinute := map[int]int{}
for minute := 1; minute <= int(evidenceEvery/time.Minute); minute++ {
for _, id := range ids {
if r.shouldSendEvidence(id, true, start.Add(time.Duration(minute)*time.Minute)) {
perMinute[minute]++
}
}
}
total, peak := 0, 0
for _, n := range perMinute {
total += n
peak = max(peak, n)
}
if total != monitors {
t.Errorf("periodic evidence in the first period = %d, want one per monitor, %d", total, monitors)
}
// 60 a minute on average; all 600 in one minute without the jitter.
if peak > 150 {
t.Errorf("busiest minute sent %d evidence, want them spread at about %d a minute", peak, monitors/10)
}
}
+108
View File
@@ -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)
}
}
+8
View File
@@ -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.
+2
View File
@@ -1130,6 +1130,7 @@
"monitors.ping_intro": "Rufe diese URL am Ende jedes erfolgreichen Laufs auf, per GET, HEAD oder POST. Mit angehängtem /fail meldest du einen Fehler; ein POST-Body oder ?msg= wird als Meldung gespeichert.",
"monitors.ping_secret": "Halte die URL geheim: Wer sie kennt, kann den Job als gesund melden. Nur Mitglieder, die diesen Monitor bearbeiten dürfen, sehen sie.",
"monitors.ping_url": "Ping-URL",
"monitors.platform_regions_limit": "Bis zu {{.Max}} Plattform-Regionen pro Monitor; eigene Regionen zählen nicht.",
"monitors.prom_empty_ok": "Keine Daten sind in Ordnung",
"monitors.prom_hint": "Ziel ist die Basis-URL von Prometheus, z. B. https://prometheus.example.com. Thanos, Mimir und VictoriaMetrics funktionieren ebenso. Für geschützte Server Authorization-Header nutzen.",
"monitors.prom_mode": "Serien",
@@ -1146,6 +1147,7 @@
"monitors.recent": "Letzte Checks",
"monitors.regions": "Regionen",
"monitors.regions_hint": "Geprüft von einem zufälligen Checker jeder gewählten Region. Deine eigenen Regionen stehen oben.",
"monitors.regions_limit": "Bis zu {{.Max}} Regionen pro Monitor.",
"monitors.results_title": "Prüfergebnisse",
"monitors.search": "Nach Name oder Ziel suchen",
"monitors.secret_unchanged": "unverändert",
+2
View File
@@ -1130,6 +1130,7 @@
"monitors.ping_intro": "Call this URL at the end of every successful run, with GET, HEAD or POST. Append /fail to report a failure; a POST body or ?msg= is stored as the message.",
"monitors.ping_secret": "Keep the URL secret: anyone who knows it can report the job as healthy. Only members who may edit this monitor see it.",
"monitors.ping_url": "Ping URL",
"monitors.platform_regions_limit": "Up to {{.Max}} platform regions per monitor; your own regions do not count.",
"monitors.prom_empty_ok": "No data is fine",
"monitors.prom_hint": "Target is the Prometheus base URL, e.g. https://prometheus.example.com. Thanos, Mimir and VictoriaMetrics work as well. Use Authorization headers for protected servers.",
"monitors.prom_mode": "Series",
@@ -1146,6 +1147,7 @@
"monitors.recent": "Recent checks",
"monitors.regions": "Regions",
"monitors.regions_hint": "Checked from a random checker in each selected region. Your own regions are listed first.",
"monitors.regions_limit": "Up to {{.Max}} regions per monitor.",
"monitors.results_title": "Check results",
"monitors.search": "Search by name or target",
"monitors.secret_unchanged": "unchanged",
+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))
}
+99 -12
View File
@@ -7,12 +7,18 @@
// number of API replicas can dispatch concurrently without a leader, and a
// lost job never stops a monitor from running again.
//
// Each monitor has a fixed phase within its interval, derived from its ID.
// After its first run, which is right away, a monitor runs on its phase, so
// runs spread evenly over the interval however the monitors were created,
// and late runs do not all gather at the moment they were dispatched.
//
// Instances announce themselves by polling. One that stops polling is
// considered gone after StaleAfter; its queued jobs return to the region.
package schedule
import (
"context"
"encoding/binary"
"errors"
"fmt"
"strconv"
@@ -33,6 +39,8 @@ const (
const (
keyRegions = "sched:regions"
keyIntervals = "sched:intervals"
// keyPhases holds each monitor's phase within its interval, in ms.
keyPhases = "sched:phases"
// keyTouched records when each monitor was last upserted, so a
// reconciliation based on an older database read leaves it alone.
keyTouched = "sched:touched"
@@ -69,20 +77,55 @@ type Monitor struct {
Regions []string
}
// phaseOf returns the phase of monitor id within interval, in ms. The ID's
// random bits spread the phases of all monitors evenly.
func phaseOf(id uuid.UUID, interval time.Duration) int64 {
ms := interval.Milliseconds()
if ms <= 0 {
return 0
}
return int64(binary.BigEndian.Uint64(id[8:]) % uint64(ms))
}
// nextSlot returns the first time after now, in ms, at which a monitor with
// phase and interval, both in ms, runs. dispatchScript computes the same.
func nextSlot(now, phase, interval int64) int64 {
if interval <= 0 {
return now
}
off := (now - phase) % interval
if off < 0 {
off += interval
}
return now - off + interval
}
// Upsert schedules m in its regions and removes it from others it was in.
// A monitor new to a region runs right away; an existing schedule keeps its
// phase so edits do not cause bursts.
// time so edits do not cause bursts.
func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []string) error {
return s.upsert(ctx, m, previousRegions, true)
}
// upsert is Upsert; without runNow, a monitor new to a region first runs on
// its phase instead of right away.
func (s *Scheduler) upsert(ctx context.Context, m Monitor, previousRegions []string, runNow bool) error {
now := s.now().UnixMilli()
id := m.ID.String()
phase := phaseOf(m.ID, m.Interval)
first := now
if !runNow {
first = nextSlot(now, phase, m.Interval.Milliseconds())
}
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HSet(ctx, keyIntervals, id, int64(m.Interval/time.Millisecond))
p.HSet(ctx, keyIntervals, id, m.Interval.Milliseconds())
p.HSet(ctx, keyPhases, id, phase)
p.HSet(ctx, keyTouched, id, now)
keep := map[string]bool{}
for _, r := range m.Regions {
keep[r] = true
p.SAdd(ctx, keyRegions, r)
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(now), Member: id})
p.ZAddNX(ctx, keyDue(r), redis.Z{Score: float64(first), Member: id})
}
for _, r := range previousRegions {
if !keep[r] {
@@ -99,6 +142,7 @@ func (s *Scheduler) Upsert(ctx context.Context, m Monitor, previousRegions []str
func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string) error {
_, err := s.rdb.TxPipelined(ctx, func(p redis.Pipeliner) error {
p.HDel(ctx, keyIntervals, id.String())
p.HDel(ctx, keyPhases, id.String())
p.HDel(ctx, keyTouched, id.String())
for _, r := range regions {
p.ZRem(ctx, keyDue(r), id.String())
@@ -112,11 +156,12 @@ func (s *Scheduler) Remove(ctx context.Context, id uuid.UUID, regions []string)
// from the database at asOf. It repairs drift after a Redis failover or a
// missed update and is safe to run from several replicas. Monitors upserted
// after asOf are kept even if want lacks them: they were created while the
// database was being read.
// database was being read. Monitors it adds back first run on their phase,
// so recovering a lost schedule causes no burst.
func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Time) error {
byRegion := map[string]map[string]bool{}
for _, m := range want {
if err := s.Upsert(ctx, m, nil); err != nil {
if err := s.upsert(ctx, m, nil, false); err != nil {
return err
}
for _, r := range m.Regions {
@@ -139,7 +184,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if wanted[id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyIntervals, keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -156,7 +201,7 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
if byRegion[r][id] {
continue
}
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched}, id, asOfMS).Err(); err != nil {
if err := pruneScript.Run(ctx, s.rdb, []string{keyDue(r), keyTouched, keyPhases}, id, asOfMS).Err(); err != nil {
return err
}
}
@@ -168,7 +213,8 @@ func (s *Scheduler) Reconcile(ctx context.Context, want []Monitor, asOf time.Tim
// upserted at or after asOf. Checking and removing in one step closes the
// window in which a concurrent upsert would be undone.
//
// KEYS: hash or sorted set to prune, touched hash. ARGV: monitor id, asOf ms.
// KEYS: hash or sorted set to prune, touched hash, phase hash.
// ARGV: monitor id, asOf ms.
var pruneScript = redis.NewScript(`
local touched = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
if touched >= tonumber(ARGV[2]) then return 0 end
@@ -177,6 +223,7 @@ if redis.call('TYPE', KEYS[1]).ok == 'zset' then
else
redis.call('HDEL', KEYS[1], ARGV[1])
redis.call('HDEL', KEYS[2], ARGV[1])
redis.call('HDEL', KEYS[3], ARGV[1])
end
return 1
`)
@@ -188,8 +235,14 @@ func (s *Scheduler) Heartbeat(ctx context.Context, region string, instance uuid.
// dispatchScript runs per region.
//
// KEYS: due set, instance set, interval hash.
// KEYS: due set, instance set, interval hash, phase hash.
// ARGV: now ms, stale-before ms, batch limit, job queue prefix, queue TTL s.
//
// The next run is the monitor's first phase slot after now. A run off its
// slot, like the first one, skips a slot less than half an interval away,
// so the monitor does not run twice in quick succession. Monitors without
// a phase, scheduled before phases existed, run every interval from their
// last due time until reconciliation adds one.
var dispatchScript = redis.NewScript(`
local now = tonumber(ARGV[1])
for _, inst in ipairs(redis.call('ZRANGEBYSCORE', KEYS[2], '-inf', ARGV[2])) do
@@ -216,8 +269,17 @@ for i = 1, #due, 2 do
local q = ARGV[4] .. live[math.random(#live)]
redis.call('RPUSH', q, m .. '|' .. string.format('%.0f', at))
redis.call('EXPIRE', q, ARGV[5])
local nxt = at + interval
if nxt <= now then nxt = now + interval end
local nxt
local phase = tonumber(redis.call('HGET', KEYS[4], m) or '')
if phase == nil then
nxt = at + interval
if nxt <= now then nxt = now + interval end
else
nxt = now - ((now - phase) % interval) + interval
if (at - phase) % interval ~= 0 and nxt - now < interval / 2 then
nxt = nxt + interval
end
end
redis.call('ZADD', KEYS[1], nxt, m)
n = n + 1
end
@@ -236,7 +298,7 @@ func (s *Scheduler) Dispatch(ctx context.Context) (int, error) {
total := 0
for _, r := range regions {
n, err := dispatchScript.Run(ctx, s.rdb,
[]string{keyDue(r), keyInstances(r), keyIntervals},
[]string{keyDue(r), keyInstances(r), keyIntervals, keyPhases},
now.UnixMilli(), now.Add(-StaleAfter).UnixMilli(), 1000, jobsPrefix, int(jobsTTL.Seconds()),
).Int()
if err != nil {
@@ -332,6 +394,31 @@ func (s *Scheduler) Instances(ctx context.Context, region string) (int64, error)
return s.rdb.ZCount(ctx, keyInstances(region), min, "+inf").Result()
}
// 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) {
return overdueScript.Run(ctx, s.rdb, []string{keyDue(region), keyInstances(region)},
s.now().Add(-late).UnixMilli(), jobsPrefix).Int64()
}
func parseEntry(s string) (Entry, bool) {
id, at, ok := strings.Cut(s, "|")
if !ok {
+184 -2
View File
@@ -100,11 +100,20 @@ func TestDispatchReschedulesAndKeepsRegionsApart(t *testing.T) {
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() before next interval = %d, want 0", n)
}
*now = now.Add(30 * time.Second)
// The next run is on the monitor's phase, at least half an interval
// after the first one.
next := dueAt(t, s, "eu", m.ID)
if off := (next.UnixMilli() - phaseOf(m.ID, m.Interval)) % m.Interval.Milliseconds(); off != 0 {
t.Errorf("next run %v is %dms off its phase", next, off)
}
if gap := next.Sub(*now); gap < m.Interval/2 || gap > 3*m.Interval/2 {
t.Errorf("next run %v after the first, want between half and one and a half intervals", gap)
}
*now = next
_ = s.Heartbeat(ctx, "eu", eu)
_ = s.Heartbeat(ctx, "us", us)
if n := mustDispatch(t, s); n != 2 {
t.Errorf("Dispatch() after interval = %d, want 2", n)
t.Errorf("Dispatch() on the next slot = %d, want 2", n)
}
// Leaving a region stops runs there.
@@ -177,6 +186,9 @@ func TestRemoveAndReconcile(t *testing.T) {
if len(got) != 1 || got[0].MonitorID != keep.ID {
t.Errorf("jobs after Reconcile = %+v, want only %v", got, keep.ID)
}
if s.rdb.HExists(ctx, keyPhases, gone.ID.String()).Val() {
t.Error("Reconcile left the phase of a removed monitor")
}
}
func TestTakeWaits(t *testing.T) {
@@ -239,3 +251,173 @@ 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)
}
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 the instance took the runs = %d, want 0", n)
}
}
func dueAt(t *testing.T, s *Scheduler, region string, id uuid.UUID) time.Time {
t.Helper()
score, err := s.rdb.ZScore(context.Background(), keyDue(region), id.String()).Result()
if err != nil {
t.Fatalf("no due time for %v in %s: %v", id, region, err)
}
return time.UnixMilli(int64(score))
}
// TestPhaseSpreadsBurst creates many monitors at once. Their first runs are
// right away; after that they spread over the interval instead of all
// running in the same second again.
func TestPhaseSpreadsBurst(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
const monitors = 600
for range monitors {
if err := s.Upsert(ctx, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}, nil); err != nil {
t.Fatal(err)
}
}
perSecond := make([]int, 180)
for sec := range perSecond {
_ = s.Heartbeat(ctx, "eu", in)
perSecond[sec] = mustDispatch(t, s)
takeAll(t, s, in)
*now = now.Add(time.Second)
}
if perSecond[0] != monitors {
t.Errorf("first second dispatched %d, want all %d first runs", perSecond[0], monitors)
}
total, peak := 0, 0
for _, n := range perSecond[60:] {
total += n
peak = max(peak, n)
}
if total != 2*monitors {
t.Errorf("seconds 60 to 180 dispatched %d runs, want %d: one per monitor and minute", total, 2*monitors)
}
// 10 per second on average; all 600 at once without phases.
if peak > 30 {
t.Errorf("busiest second dispatched %d runs, want them spread at about 10 per second", peak)
}
}
// TestLateRunSnapsToPhase dispatches runs long overdue. Each comes back on
// its own phase instead of all gathering at the dispatch time.
func TestLateRunSnapsToPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
ms := []Monitor{}
for range 50 {
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
ms = append(ms, m)
_ = s.Upsert(ctx, m, nil)
}
_ = s.Heartbeat(ctx, "eu", in)
mustDispatch(t, s)
// No instance for three intervals.
*now = now.Add(3*time.Minute + 7*time.Second)
_ = s.Heartbeat(ctx, "eu", in)
if n := mustDispatch(t, s); n != len(ms) {
t.Fatalf("Dispatch() of the overdue runs = %d, want %d", n, len(ms))
}
distinct := map[time.Time]bool{}
for _, m := range ms {
got := dueAt(t, s, "eu", m.ID)
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if !got.Equal(want) {
t.Errorf("monitor next due %v, want its next slot %v", got, want)
}
distinct[got] = true
}
if len(distinct) < len(ms)-5 {
t.Errorf("%d monitors share %d due times, want them apart", len(ms), len(distinct))
}
}
// TestReconcileAddsOnPhase rebuilds a lost schedule without a burst.
func TestReconcileAddsOnPhase(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
ms := []Monitor{}
for range 20 {
ms = append(ms, Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}})
}
if err := s.Reconcile(ctx, ms, *now); err != nil {
t.Fatal(err)
}
for _, m := range ms {
want := time.UnixMilli(nextSlot(now.UnixMilli(), phaseOf(m.ID, m.Interval), m.Interval.Milliseconds()))
if got := dueAt(t, s, "eu", m.ID); !got.Equal(want) {
t.Errorf("reconciled monitor due %v, want its slot %v", got, want)
}
}
if n := mustDispatch(t, s); n != 0 {
t.Errorf("Dispatch() right after Reconcile = %d, want 0", n)
}
}
// TestPhaseFallback covers monitors scheduled before phases existed.
func TestPhaseFallback(t *testing.T) {
s, now := newTest(t)
ctx := context.Background()
in := uuid.New()
_ = s.Heartbeat(ctx, "eu", in)
m := Monitor{ID: uuid.New(), Interval: time.Minute, Regions: []string{"eu"}}
_ = s.Upsert(ctx, m, nil)
s.rdb.HDel(ctx, keyPhases, m.ID.String())
mustDispatch(t, s)
if got, want := dueAt(t, s, "eu", m.ID), now.Add(time.Minute); !got.Equal(want) {
t.Errorf("monitor without phase next due %v, want one interval later, %v", got, want)
}
}
func TestNextSlot(t *testing.T) {
for _, c := range []struct{ now, phase, interval, want int64 }{
{now: 100, phase: 30, interval: 60, want: 150},
{now: 150, phase: 30, interval: 60, want: 210},
{now: 10, phase: 30, interval: 60, want: 30},
{now: 100, phase: 0, interval: 0, want: 100},
} {
if got := nextSlot(c.now, c.phase, c.interval); got != c.want {
t.Errorf("nextSlot(%d, %d, %d) = %d, want %d", c.now, c.phase, c.interval, got, c.want)
}
}
}
+34 -17
View File
@@ -13,17 +13,18 @@ import (
)
const deleteSuccessEvidence = `-- name: DeleteSuccessEvidence :exec
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok
DELETE FROM check_evidence
WHERE region = $1 AND ok AND monitor_id = ANY($2::uuid[])
`
type DeleteSuccessEvidenceParams struct {
MonitorID uuid.UUID
Region string
Region string
MonitorIds []uuid.UUID
}
// Only the latest success per monitor and region is kept.
func (q *Queries) DeleteSuccessEvidence(ctx context.Context, arg DeleteSuccessEvidenceParams) error {
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.MonitorID, arg.Region)
_, err := q.db.Exec(ctx, deleteSuccessEvidence, arg.Region, arg.MonitorIds)
return err
}
@@ -124,27 +125,43 @@ func (q *Queries) InsertEvidence(ctx context.Context, arg InsertEvidenceParams)
return err
}
const lastFailureEvidence = `-- name: LastFailureEvidence :one
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
WHERE monitor_id = $1 AND region = $2 AND NOT ok
ORDER BY time DESC LIMIT 1
const lastFailureEvidence = `-- name: LastFailureEvidence :many
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
FROM check_evidence
WHERE region = $1 AND NOT ok AND monitor_id = ANY($2::uuid[])
ORDER BY monitor_id, time DESC
`
type LastFailureEvidenceParams struct {
MonitorID uuid.UUID
Region string
Region string
MonitorIds []uuid.UUID
}
type LastFailureEvidenceRow struct {
Time time.Time
Error string
MonitorID uuid.UUID
Time time.Time
Error string
}
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error) {
row := q.db.QueryRow(ctx, lastFailureEvidence, arg.MonitorID, arg.Region)
var i LastFailureEvidenceRow
err := row.Scan(&i.Time, &i.Error)
return i, err
// The newest failure per monitor in region.
func (q *Queries) LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error) {
rows, err := q.db.Query(ctx, lastFailureEvidence, arg.Region, arg.MonitorIds)
if err != nil {
return nil, err
}
defer rows.Close()
items := []LastFailureEvidenceRow{}
for rows.Next() {
var i LastFailureEvidenceRow
if err := rows.Scan(&i.MonitorID, &i.Time, &i.Error); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listEvidence = `-- name: ListEvidence :many
+81
View File
@@ -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
}
+6 -1
View File
@@ -217,7 +217,8 @@ type Querier interface {
InsertRecoveryCodes(ctx context.Context, arg []InsertRecoveryCodesParams) (int64, error)
InvitationOrg(ctx context.Context, hash []byte) (uuid.UUID, error)
IsMember(ctx context.Context, arg IsMemberParams) (bool, error)
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) (LastFailureEvidenceRow, error)
// The newest failure per monitor in region.
LastFailureEvidence(ctx context.Context, arg LastFailureEvidenceParams) ([]LastFailureEvidenceRow, error)
// latest_results holds the newest check result per monitor and region
// (see migration 00055) and has row-level security.
// Whether the newest result of each region of the monitors ids succeeded.
@@ -314,6 +315,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 +344,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.
+8 -5
View File
@@ -4,12 +4,15 @@ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
-- name: DeleteSuccessEvidence :exec
-- Only the latest success per monitor and region is kept.
DELETE FROM check_evidence WHERE monitor_id = $1 AND region = $2 AND ok;
DELETE FROM check_evidence
WHERE region = sqlc.arg(region) AND ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[]);
-- name: LastFailureEvidence :one
SELECT time, coalesce(error, '')::text AS error FROM check_evidence
WHERE monitor_id = $1 AND region = $2 AND NOT ok
ORDER BY time DESC LIMIT 1;
-- name: LastFailureEvidence :many
-- The newest failure per monitor in region.
SELECT DISTINCT ON (monitor_id) monitor_id, time, coalesce(error, '')::text AS error
FROM check_evidence
WHERE region = sqlc.arg(region) AND NOT ok AND monitor_id = ANY(sqlc.arg(monitor_ids)::uuid[])
ORDER BY monitor_id, time DESC;
-- name: ListEvidence :many
-- Newest first, a page from a keyset cursor (see paging.go).
+17
View File
@@ -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;
+23
View File
@@ -164,6 +164,29 @@
font-size: 12px;
}
}
/* Pins whose label would cover another one turn it to the left of their
point, or show only their dot until hovered. */
.is-flipped > .region-pin {
flex-direction: row-reverse;
padding: 3px 5px 3px 9px;
translate: calc(16px - 100%);
}
.maplibregl-marker:is(.is-flipped, .is-compact):not(.is-hover, :hover) { z-index: 2; }
.is-compact > .region-pin { gap: 0; padding: 3px 5px; }
.is-compact:not(.is-hover, :hover) > .region-pin > :last-child { display: none; }
.is-compact.is-hover > .region-pin,
.is-compact:hover > .region-pin { gap: 6px; padding: 3px 9px 3px 5px; }
@media (pointer: coarse) {
.is-flipped > .region-pin { padding: 6px 8px 6px 11px; }
.is-compact > .region-pin { padding: 6px 8px; }
}
/* Regions locked by the monitor's region limit. */
label.is-locked { opacity: 0.5; cursor: not-allowed; }
/* Opaque, so stacked pins do not show through each other. */
.region-pin.is-disabled { color: var(--color-muted); cursor: not-allowed; box-shadow: none; }
.region-pin.is-disabled .region-pin-dot { background: var(--color-unknown); }
.is-hover > .region-pin.is-disabled,
.region-pin.is-disabled:hover { transform: none; }
.region-pin:focus-visible { outline: 2px solid var(--color-maintenance); outline-offset: 2px; }
.region-pick {
width: 14px;
+67
View File
@@ -698,6 +698,7 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
fit();
const selecting = box.dataset.regionMap === "select";
const markers = [];
for (const item of items) {
// The list row (a label or table row) and the marker light up together.
const row = item.closest("label, tr") ?? item;
@@ -708,6 +709,7 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
const holder = document.createElement("div");
holder.append(pin);
const marker = new gl.Marker({ element: holder, anchor: "left", offset: [-8, 0] }).setLngLat(lngLat(item)).addTo(map);
markers.push({ holder, pin, marker });
const hover = (on) => {
holder.classList.toggle("is-hover", on);
row.classList.toggle("is-hover", on);
@@ -724,8 +726,12 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
pin.classList.toggle("is-checked", item.checked);
row.classList.toggle("is-checked", item.checked);
pin.setAttribute("aria-pressed", String(item.checked));
// Locked once the monitor uses as many regions as it may.
pin.classList.toggle("is-disabled", item.disabled);
pin.setAttribute("aria-disabled", String(item.disabled));
};
paint();
item.closest("[data-region-limit]")?.addEventListener("regionlimit", paint);
item.addEventListener("change", () => {
paint();
// A region ticked in the list comes into view on the map.
@@ -743,6 +749,48 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
});
}
}
// Labels run to the right of their point, or to the left where that
// would cover another pin or leave the map, as with regions a few
// kilometres apart. A pin with room on neither side shows only its dot
// and its name on hover; the list names every region. No label covers
// the dot of another pin.
const place = () => {
const width = box.clientWidth;
const height = box.clientHeight;
if (!width) return;
for (const m of markers) m.holder.classList.remove("is-flipped", "is-compact");
const spots = markers.map((m) => {
const at = map.project(m.marker.getLngLat());
const h = m.pin.offsetHeight;
return { m, at, w: m.pin.offsetWidth, h, dot: { left: at.x - 8, right: at.x + 12, top: at.y - h / 2, bottom: at.y + h / 2 } };
});
// The rounded ends of two pills may touch.
const hits = (a, b) => a.left + 4 < b.right - 4 && b.left + 4 < a.right - 4 && a.top < b.bottom && b.top < a.bottom;
const labels = [];
const fits = (a, self) =>
a.left >= 0 && a.right <= width && a.top >= 0 && a.bottom <= height &&
!labels.some((b) => hits(a, b)) &&
// Dots stacked on its own one stay beside it either way.
!spots.some((s) => s !== self && !hits(s.dot, self.dot) && hits(a, s.dot));
for (const s of spots.sort((a, b) => b.at.x - a.at.x)) {
const right = { ...s.dot, right: s.at.x - 8 + s.w };
const left = { ...s.dot, left: s.at.x + 8 - s.w, right: s.at.x + 8 };
if (fits(right, s)) {
labels.push(right);
} else if (fits(left, s)) {
s.m.holder.classList.add("is-flipped");
labels.push(left);
} else {
s.m.holder.classList.add("is-compact");
}
}
};
map.on("load", place);
map.on("zoom", place);
map.on("moveend", place);
map.on("resize", place);
if (selecting) return;
let pick;
map.on("click", (ev) => {
@@ -758,5 +806,24 @@ for (const el of document.querySelectorAll("input[data-tz-default]")) {
pick.setLngLat(point);
});
};
// A monitor may use only so many counted regions: once they are all
// ticked, the other counted ones are locked until one is unticked. The
// server enforces the limit either way.
for (const list of document.querySelectorAll("[data-region-limit]")) {
const limit = Number(list.dataset.regionLimit);
const counted = [...list.querySelectorAll("input[data-counted]")];
const count = list.closest("fieldset")?.querySelector("[data-region-count]");
const update = () => {
const n = counted.filter((i) => i.checked).length;
for (const i of counted) {
i.disabled = !i.checked && n >= limit;
i.closest("label")?.classList.toggle("is-locked", i.disabled);
}
if (count) count.textContent = `(${n}/${limit})`;
list.dispatchEvent(new Event("regionlimit"));
};
list.addEventListener("change", update);
update();
}
for (const box of document.querySelectorAll("[data-region-map]")) initRegionMap(box);
})();
+26 -1
View File
@@ -726,6 +726,9 @@ type RegionOption struct {
Lat, Lon *float64
}
// Counted reports whether r counts towards the form's region limit.
func (f MonitorForm) Counted(r RegionOption) bool { return !r.Own || f.OwnRegionsCount }
// RegionsMapped reports whether any region of the form has a location.
func (f MonitorForm) RegionsMapped() bool {
for _, r := range f.Regions {
@@ -753,6 +756,10 @@ type MonitorForm struct {
TopLevel bool
Regions []RegionOption
MinInterval int
// RegionLimit caps the counted regions a monitor uses; 0 is unlimited.
// Own regions count only with OwnRegionsCount.
RegionLimit int
OwnRegionsCount bool
// Type-specific settings.
Method string
ExpectStatus string
@@ -1132,10 +1139,25 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
<fieldset class="mb-4" data-hide-for="heartbeat alertmanager" hidden?={ passiveType(f.Type) } disabled?={ f.Type == "heartbeat" }>
<legend class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.regions") }</legend>
<p class="mb-2 text-xs text-muted">{ i18n.T(ctx, "monitors.regions_hint") }</p>
if f.RegionLimit > 0 {
<p class="mb-2 text-xs text-muted" data-region-limit-hint>
if f.OwnRegionsCount {
{ i18n.T(ctx, "monitors.regions_limit", "Max", f.RegionLimit) }
} else {
{ i18n.T(ctx, "monitors.platform_regions_limit", "Max", f.RegionLimit) }
}
<span class="font-mono" data-region-count></span>
</p>
}
if f.RegionsMapped() {
@regionMap("select", "#monitor-regions")
}
<div id="monitor-regions">
<div
id="monitor-regions"
if f.RegionLimit > 0 {
data-region-limit={ strconv.Itoa(f.RegionLimit) }
}
>
for _, r := range f.Regions {
<label class="-mx-2 mb-0.5 flex items-center gap-2 px-2 py-1 text-sm">
<input
@@ -1151,6 +1173,9 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
}
data-name={ r.Name }
data-live={ strconv.FormatInt(r.Live, 10) }
if f.Counted(r) {
data-counted
}
/>
{ r.Name }
<span class="font-mono text-xs text-muted">
File diff suppressed because it is too large. Load diff
+40
View File
@@ -0,0 +1,40 @@
<!doctype html><html><body data-msg-network="net">
<form id="monitor"><fieldset>
<p><span data-region-count></span></p>
<div id="monitor-regions" data-region-limit="2">
<label><input type="checkbox" name="regions" value="own" data-multi checked></label>
<label><input type="checkbox" name="regions" value="a" data-multi data-counted checked></label>
<label><input type="checkbox" name="regions" value="b" data-multi data-counted></label>
<label><input type="checkbox" name="regions" value="c" data-multi data-counted></label>
</div>
</fieldset></form>
<pre id="out"></pre>
<script>window.axios = { create: () => ({ interceptors: { request: { use() {} } }, request: async () => ({ data: {} }) }) };</script>
<script src="../assets/app.js"></script>
<script>
(async () => {
const out = [];
const check = (name, got, want) => {
const g = JSON.stringify(got), w = JSON.stringify(want);
out.push((g === w ? "PASS " : "FAIL ") + name + (g === w ? "" : " got=" + g + " want=" + w));
};
const box = (v) => document.querySelector(`[value="${v}"]`);
const locked = () => ["own", "a", "b", "c"].filter((v) => box(v).disabled);
const count = () => document.querySelector("[data-region-count]").textContent;
check("below the limit nothing is locked", locked(), []);
check("count shown", count(), "(1/2)");
box("b").click();
check("at the limit the other counted regions lock", locked(), ["c"]);
check("locked row marked", box("c").closest("label").classList.contains("is-locked"), true);
check("count follows", count(), "(2/2)");
box("c").click();
check("a locked region cannot be ticked", box("c").checked, false);
box("own").click();
box("own").click();
check("uncounted regions stay free", box("own").checked, true);
box("a").click();
check("unticking frees them again", locked(), []);
document.getElementById("out").textContent = out.join("\n");
})();
</script>
</body></html>
+14 -1
View File
@@ -20,6 +20,12 @@
<input name="latitude" data-number data-nullable data-location-field="latitude">
<input name="longitude" data-number data-nullable data-location-field="longitude">
</div></form>
<div id="near-map" data-region-map="edit" data-region-items="#near" data-map-server="stub" data-touch-hint="t" data-scroll-hint="{key} s" data-ctrl-key="Ctrl" hidden style="width:300px;height:200px;position:relative"></div>
<table><tbody id="near">
<tr data-lat="50" data-lon="8" data-name="Nuremberg" data-live="1"><td></td></tr>
<tr data-lat="50.05" data-lon="8.5" data-name="Bamberg" data-live="1"><td></td></tr>
<tr data-lat="55" data-lon="19" data-name="Gdansk" data-live="1"><td></td></tr>
</tbody></table>
<pre id="out"></pre>
<script>
const sent = [];
@@ -35,11 +41,13 @@ window.maplibregl = {
fitBounds(b) { this.bounds = b.points; }
jumpTo(o) { this.center = o.center; }
setStyle(s) { this.style = s; }
// 10 px per degree, 8°E 50°N at the middle of the box.
project({ lng, lat }) { return { x: 100 + (lng - 0) * 10, y: 100 - (lat - 50) * 10 }; }
},
Marker: class {
constructor(o) { this.el = o.element; }
setLngLat(p) { this.at = p; this.el.dataset.at = p.join(","); return this; }
getLngLat() { return this.at; }
getLngLat() { return { lng: this.at[0], lat: this.at[1] }; }
addTo(map) { map.container.append(this.el); return this; }
},
NavigationControl: class {},
@@ -100,6 +108,11 @@ window.maplibregl = {
click(1, 2);
check("closed row falls back to create form", create.elements.latitude.value, "1");
const near = maps[2];
near.fire("load");
const placement = () => [...near.container.querySelectorAll(".region-pin")].map((p) => [p.title, p.parentElement.classList.contains("is-flipped") ? "left" : p.parentElement.classList.contains("is-compact") ? "dot" : "right"]);
check("close labels make room", placement(), [["Nuremberg", "dot"], ["Bamberg", "right"], ["Gdansk", "left"]]);
document.getElementById("out").textContent = out.join("\n");
})();
</script>