feat: Prometheus monitors in console and API

Closes #25

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 11:49:07 +01:00
1 parent 5e7db9c054
commit 94b519b421
8 files changed
+904 -565

No files matched your search

+8
View File
@@ -7,6 +7,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"slices" "slices"
"strconv"
"strings" "strings"
"time" "time"
@@ -476,6 +477,7 @@ func (s *Server) monitorEditor(c *gin.Context, p *principal, page web.Page, me w
Type: "http", IntervalSeconds: 60, TimeoutMS: 10000, Confirmations: 2, Enabled: true, Type: "http", IntervalSeconds: 60, TimeoutMS: 10000, Confirmations: 2, Enabled: true,
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx", GraceSeconds: check.DefaultHeartbeatGrace, MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx", GraceSeconds: check.DefaultHeartbeatGrace,
JSONExpect: "2xx", JSONVerify: true, Assertions: assertionRows(nil), JSONExpect: "2xx", JSONVerify: true, Assertions: assertionRows(nil),
PromOp: ">=", PromThreshold: "1", PromMode: "all", PromVerify: true,
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14, FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
} }
var ( var (
@@ -543,6 +545,7 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
} }
// Defaults for the other types, in case the type is switched. // Defaults for the other types, in case the type is switched.
f.JSONExpect, f.JSONVerify, f.Assertions, f.GraceSeconds = "2xx", true, assertionRows(nil), check.DefaultHeartbeatGrace f.JSONExpect, f.JSONVerify, f.Assertions, f.GraceSeconds = "2xx", true, assertionRows(nil), check.DefaultHeartbeatGrace
f.PromOp, f.PromThreshold, f.PromMode, f.PromVerify = ">=", "1", "all", true
switch check.Type(m.Type) { switch check.Type(m.Type) {
case check.HTTP: case check.HTTP:
var c check.HTTPConfig var c check.HTTPConfig
@@ -564,6 +567,11 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
var c check.TLSConfig var c check.TLSConfig
_ = json.Unmarshal(m.Config, &c) _ = json.Unmarshal(m.Config, &c)
f.TLSMinDays, f.TLSServerName = c.MinDaysValid, c.ServerName f.TLSMinDays, f.TLSServerName = c.MinDaysValid, c.ServerName
case check.Prometheus:
var c check.PrometheusConfig
_ = json.Unmarshal(m.Config, &c)
f.PromQuery, f.PromOp, f.PromThreshold, f.PromMode = c.Query, c.Op, strconv.FormatFloat(c.Threshold, 'g', -1, 64), c.Mode
f.PromEmptyOK, f.PromVerify, f.Headers = c.EmptyOK, c.VerifyTLS, headerLines(c.Headers)
case check.Heartbeat: case check.Heartbeat:
var c check.HeartbeatConfig var c check.HeartbeatConfig
_ = json.Unmarshal(m.Config, &c) _ = json.Unmarshal(m.Config, &c)
+30
View File
@@ -86,3 +86,33 @@ func asString(v any) string {
s, _ := v.(string) s, _ := v.(string)
return s return s
} }
func TestPrometheusMonitor(t *testing.T) {
e := newEnv(t)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go e.api.RunScheduler(ctx)
prom := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`{"status":"success","data":{"resultType":"vector","result":[{"metric":{"__name__":"up","job":"api"},"value":[1,"0"]}]}}`))
}))
defer prom.Close()
tok, region := e.platformChecker(t, uniq("eu-"))
e.startChecker(t, tok)
owner := e.browser(t)
owner.signup("o@"+uniq("pm")+".test", uniq("pm-"))
st, body := owner.do("POST", "/api/v1/org/monitors", map[string]any{
"name": "API targets", "type": "prometheus", "target": prom.URL, "interval_seconds": 10, "timeout_ms": 2000,
"confirmations": 1, "regions": []string{region}, "config": map[string]any{"query": `up{job="api"}`, "op": "==", "threshold": 1},
})
if st != http.StatusCreated {
t.Fatalf("create prometheus monitor = %d %v", st, body)
}
waitFor(t, 15*time.Second, "an incident for the down target", func() bool {
_, b := owner.do("GET", "/api/v1/org/incidents", nil)
return len(b["incidents"].([]any)) == 1
})
_, list := owner.do("GET", "/api/v1/org/monitors", nil)
if !strings.Contains(mustJSON(list), `up{job=\"api\"} = 0, expected == 1`) {
t.Errorf("result lacks the failing series: %s", mustJSON(list))
}
}
+1 -1
View File
@@ -151,7 +151,7 @@ func TestDynamicFamilies(t *testing.T) {
en := catalogKeys(t)["en"] en := catalogKeys(t)["en"]
families := map[string][]string{ families := map[string][]string{
"status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"}, "status.": {"up", "degraded", "down", "unknown", "paused", "maintenance"},
"monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "heartbeat"}, "monitors.type_": {"http", "tcp", "tls", "dns", "icmp", "json", "prometheus", "heartbeat"},
"channels.type_": {"webhook", "email"}, "channels.type_": {"webhook", "email"},
"agents.kind_": {"checker", "statuspage"}, "agents.kind_": {"checker", "statuspage"},
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"}, "page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
+9
View File
@@ -168,6 +168,7 @@
"error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.", "error.invalid_method": "Nur GET- und HEAD-Anfragen werden unterstützt.",
"error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.", "error.invalid_monitor": "Einer der Monitore existiert nicht oder ist doppelt aufgeführt.",
"error.invalid_permissions": "Mindestens eine Berechtigung auswählen.", "error.invalid_permissions": "Mindestens eine Berechtigung auswählen.",
"error.invalid_query": "Gib eine PromQL-Abfrage mit höchstens 2000 Zeichen ein.",
"error.invalid_record": "Nicht unterstützter DNS-Record-Typ.", "error.invalid_record": "Nicht unterstützter DNS-Record-Typ.",
"error.invalid_region": "Unbekannte Region.", "error.invalid_region": "Unbekannte Region.",
"error.invalid_region_key": "Regions-Schlüssel haben 1–40 Zeichen: a–z, 0–9 und Bindestrich.", "error.invalid_region_key": "Regions-Schlüssel haben 1–40 Zeichen: a–z, 0–9 und Bindestrich.",
@@ -478,6 +479,13 @@
"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_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_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.ping_url": "Ping-URL",
"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",
"monitors.prom_mode_all": "Jede Serie muss die Bedingung erfüllen",
"monitors.prom_mode_any": "Eine Serie mit erfüllter Bedingung genügt",
"monitors.prom_query": "PromQL-Abfrage",
"monitors.prom_threshold": "Schwellwert",
"monitors.range": "Zeitraum", "monitors.range": "Zeitraum",
"monitors.range_not_enough": "Für weniger als die Hälfte dieses Zeitraums liegen bisher Daten vor.", "monitors.range_not_enough": "Für weniger als die Hälfte dieses Zeitraums liegen bisher Daten vor.",
"monitors.range_note": "SLA und Balken: letzte {{.Range}}", "monitors.range_note": "SLA und Balken: letzte {{.Range}}",
@@ -497,6 +505,7 @@
"monitors.type_http": "HTTP(S)", "monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)", "monitors.type_icmp": "Ping (ICMP)",
"monitors.type_json": "JSON-API", "monitors.type_json": "JSON-API",
"monitors.type_prometheus": "Prometheus",
"monitors.type_tcp": "TCP-Port", "monitors.type_tcp": "TCP-Port",
"monitors.type_tls": "TLS-Zertifikat", "monitors.type_tls": "TLS-Zertifikat",
"monitors.uptime_chart": "Uptime pro Zeitraum", "monitors.uptime_chart": "Uptime pro Zeitraum",
+9
View File
@@ -168,6 +168,7 @@
"error.invalid_method": "Only GET and HEAD requests are supported.", "error.invalid_method": "Only GET and HEAD requests are supported.",
"error.invalid_monitor": "One of the monitors does not exist or is listed twice.", "error.invalid_monitor": "One of the monitors does not exist or is listed twice.",
"error.invalid_permissions": "Choose at least one permission.", "error.invalid_permissions": "Choose at least one permission.",
"error.invalid_query": "Enter a PromQL query of at most 2000 characters.",
"error.invalid_record": "Unsupported DNS record type.", "error.invalid_record": "Unsupported DNS record type.",
"error.invalid_region": "Unknown region.", "error.invalid_region": "Unknown region.",
"error.invalid_region_key": "Region keys use 1–40 characters: a–z, 0–9 and hyphen.", "error.invalid_region_key": "Region keys use 1–40 characters: a–z, 0–9 and hyphen.",
@@ -478,6 +479,13 @@
"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_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_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.ping_url": "Ping URL",
"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",
"monitors.prom_mode_all": "Every series must meet the condition",
"monitors.prom_mode_any": "One series meeting the condition is enough",
"monitors.prom_query": "PromQL query",
"monitors.prom_threshold": "Threshold",
"monitors.range": "Time range", "monitors.range": "Time range",
"monitors.range_not_enough": "Less than half of this period is covered by data yet.", "monitors.range_not_enough": "Less than half of this period is covered by data yet.",
"monitors.range_note": "SLA and bars: last {{.Range}}", "monitors.range_note": "SLA and bars: last {{.Range}}",
@@ -497,6 +505,7 @@
"monitors.type_http": "HTTP(S)", "monitors.type_http": "HTTP(S)",
"monitors.type_icmp": "Ping (ICMP)", "monitors.type_icmp": "Ping (ICMP)",
"monitors.type_json": "JSON API", "monitors.type_json": "JSON API",
"monitors.type_prometheus": "Prometheus",
"monitors.type_tcp": "TCP port", "monitors.type_tcp": "TCP port",
"monitors.type_tls": "TLS certificate", "monitors.type_tls": "TLS certificate",
"monitors.uptime_chart": "Uptime per period", "monitors.uptime_chart": "Uptime per period",
@@ -0,0 +1,10 @@
-- +goose Up
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'prometheus', 'heartbeat'));
-- +goose Down
DELETE FROM monitors WHERE type = 'prometheus';
ALTER TABLE monitors DROP CONSTRAINT monitors_type_check;
ALTER TABLE monitors ADD CONSTRAINT monitors_type_check
CHECK (type IN ('http', 'tcp', 'icmp', 'dns', 'tls', 'json', 'heartbeat'));
+38 -1
View File
@@ -466,6 +466,12 @@ type MonitorForm struct {
JSONExpect string JSONExpect string
JSONVerify bool JSONVerify bool
Assertions []AssertionRow Assertions []AssertionRow
PromQuery string
PromOp string
PromThreshold string
PromMode string
PromEmptyOK bool
PromVerify bool
} }
// AssertionRow is one condition of a JSON check; unused rows are empty. // AssertionRow is one condition of a JSON check; unused rows are empty.
@@ -541,7 +547,7 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
<label class="mb-4 block"> <label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.type") }</span> <span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.type") }</span>
<select name="type" data-type-select class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm"> <select name="type" data-type-select class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
for _, t := range []string{"http", "json", "tcp", "tls", "dns", "icmp", "heartbeat"} { for _, t := range []string{"http", "json", "prometheus", "tcp", "tls", "dns", "icmp", "heartbeat"} {
<option value={ t } selected?={ t == f.Type }>{ i18n.T(ctx, "monitors.type_"+t) }</option> <option value={ t } selected?={ t == f.Type }>{ i18n.T(ctx, "monitors.type_"+t) }</option>
} }
</select> </select>
@@ -572,6 +578,37 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
@checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.VerifyTLS) @checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.VerifyTLS)
@headersField(f.Headers) @headersField(f.Headers)
} }
@typeFields("prometheus", f.Type) {
<p class="mb-4 text-xs text-muted">{ i18n.T(ctx, "monitors.prom_hint") }</p>
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.prom_query") }</span>
<textarea name="config.query" rows="3" placeholder={ `up{job="api"}` } class="w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-xs outline-none focus:border-ink">{ f.PromQuery }</textarea>
</label>
<div class="mb-4 grid grid-cols-[6.5rem_1fr] gap-2">
<label>
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.assertion_op") }</span>
<select name="config.op" class="w-full border border-rule bg-transparent px-1 py-1.5 font-mono text-sm">
for _, op := range AssertionOps[:6] {
<option value={ op } selected?={ op == f.PromOp }>{ i18n.T(ctx, "monitors.op_"+opKey(op)) }</option>
}
</select>
</label>
<label>
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.prom_threshold") }</span>
<input name="config.threshold" data-number type="number" step="any" value={ f.PromThreshold } class="w-full border border-rule bg-transparent px-2.5 py-1.5 font-mono text-sm outline-none focus:border-ink"/>
</label>
</div>
<label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.prom_mode") }</span>
<select name="config.mode" class="w-full border border-rule bg-transparent px-2 py-1.5 text-sm">
<option value="all" selected?={ f.PromMode != "any" }>{ i18n.T(ctx, "monitors.prom_mode_all") }</option>
<option value="any" selected?={ f.PromMode == "any" }>{ i18n.T(ctx, "monitors.prom_mode_any") }</option>
</select>
</label>
@checkbox(i18n.T(ctx, "monitors.prom_empty_ok"), "config.empty_ok", f.PromEmptyOK)
@checkbox(i18n.T(ctx, "monitors.verify_tls"), "config.verify_tls", f.PromVerify)
@headersField(f.Headers)
}
@typeFields("json", f.Type) { @typeFields("json", f.Type) {
<label class="mb-4 block"> <label class="mb-4 block">
<span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.method") }</span> <span class="mb-1 block text-xs font-medium uppercase tracking-wider text-muted">{ i18n.T(ctx, "monitors.method") }</span>
File diff suppressed because it is too large. Load diff