Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
94b519b421 | ||
|
|
5e7db9c054 |
No files matched your search
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"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,
|
||||
MinInterval: s.minInterval(), Method: "GET", ExpectStatus: "2xx, 3xx", GraceSeconds: check.DefaultHeartbeatGrace,
|
||||
JSONExpect: "2xx", JSONVerify: true, Assertions: assertionRows(nil),
|
||||
PromOp: ">=", PromThreshold: "1", PromMode: "all", PromVerify: true,
|
||||
FollowRedirects: true, VerifyTLS: true, DNSRecord: "A", TLSMinDays: 14,
|
||||
}
|
||||
var (
|
||||
@@ -543,6 +545,7 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
|
||||
}
|
||||
// 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.PromOp, f.PromThreshold, f.PromMode, f.PromVerify = ">=", "1", "all", true
|
||||
switch check.Type(m.Type) {
|
||||
case check.HTTP:
|
||||
var c check.HTTPConfig
|
||||
@@ -564,6 +567,11 @@ func fillForm(f *web.MonitorForm, m store.Monitor) {
|
||||
var c check.TLSConfig
|
||||
_ = json.Unmarshal(m.Config, &c)
|
||||
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:
|
||||
var c check.HeartbeatConfig
|
||||
_ = json.Unmarshal(m.Config, &c)
|
||||
|
||||
@@ -86,3 +86,33 @@ func asString(v any) string {
|
||||
s, _ := v.(string)
|
||||
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))
|
||||
}
|
||||
}
|
||||
@@ -24,13 +24,15 @@ const (
|
||||
TLS Type = "tls"
|
||||
// JSON checks an HTTP API's JSON response against assertions.
|
||||
JSON Type = "json"
|
||||
// Prometheus compares the result of a PromQL query with a threshold.
|
||||
Prometheus Type = "prometheus"
|
||||
// Heartbeat monitors are pinged by the monitored job; no checker runs
|
||||
// them.
|
||||
Heartbeat Type = "heartbeat"
|
||||
)
|
||||
|
||||
// Types lists every check type.
|
||||
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Heartbeat}
|
||||
var Types = []Type{HTTP, TCP, ICMP, DNS, TLS, JSON, Prometheus, Heartbeat}
|
||||
|
||||
// Passive reports whether t is reported to us rather than run by checkers.
|
||||
func Passive(t Type) bool { return t == Heartbeat }
|
||||
@@ -86,8 +88,9 @@ var impls = map[Type]impl{
|
||||
DNS: dnsCheck{},
|
||||
TLS: tlsCheck{},
|
||||
|
||||
JSON: jsonCheck{},
|
||||
Heartbeat: heartbeatCheck{},
|
||||
JSON: jsonCheck{},
|
||||
Prometheus: prometheusCheck{},
|
||||
Heartbeat: heartbeatCheck{},
|
||||
}
|
||||
|
||||
// Validate checks target and config for type t and returns the normalized
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// PrometheusConfig configures a check of a PromQL query. The target is the
|
||||
// Prometheus base URL; compatible APIs such as Thanos, Mimir or
|
||||
// VictoriaMetrics work too.
|
||||
type PrometheusConfig struct {
|
||||
Query string `json:"query"`
|
||||
Op string `json:"op"`
|
||||
Threshold float64 `json:"threshold"`
|
||||
// Mode "all" requires every series to meet the condition, "any" at
|
||||
// least one.
|
||||
Mode string `json:"mode"`
|
||||
// EmptyOK accepts a query without results; by default no data is a
|
||||
// failure, since a vanished exporter usually is a problem.
|
||||
EmptyOK bool `json:"empty_ok,omitempty"`
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
VerifyTLS bool `json:"verify_tls"`
|
||||
}
|
||||
|
||||
var promOps = []string{"==", "!=", ">", ">=", "<", "<="}
|
||||
|
||||
type prometheusCheck struct{}
|
||||
|
||||
func (prometheusCheck) validate(target string, config json.RawMessage) (json.RawMessage, error) {
|
||||
if !validURL(target) {
|
||||
return nil, invalid("invalid_target")
|
||||
}
|
||||
c := PrometheusConfig{Op: ">=", Threshold: 1, Mode: "all", VerifyTLS: true}
|
||||
if err := json.Unmarshal(config, &c); err != nil {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
c.Query = strings.TrimSpace(c.Query)
|
||||
if c.Query == "" || len(c.Query) > 2000 {
|
||||
return nil, invalid("invalid_query")
|
||||
}
|
||||
if !slices.Contains(promOps, c.Op) {
|
||||
return nil, invalid("invalid_assertion_op")
|
||||
}
|
||||
if c.Mode != "all" && c.Mode != "any" {
|
||||
return nil, invalid("invalid_config")
|
||||
}
|
||||
if math.IsNaN(c.Threshold) || math.IsInf(c.Threshold, 0) {
|
||||
return nil, invalid("invalid_assertion_value")
|
||||
}
|
||||
if !validHeaders(c.Headers) {
|
||||
return nil, invalid("invalid_header")
|
||||
}
|
||||
return encode(c), nil
|
||||
}
|
||||
|
||||
// promResponse is the part of the query API's answer a check needs.
|
||||
type promResponse struct {
|
||||
Status string `json:"status"`
|
||||
ErrorType string `json:"errorType"`
|
||||
Error string `json:"error"`
|
||||
Data struct {
|
||||
ResultType string `json:"resultType"`
|
||||
Result json.RawMessage `json:"result"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// promSample is one series with its value.
|
||||
type promSample struct {
|
||||
Labels map[string]string
|
||||
Value float64
|
||||
}
|
||||
|
||||
func (prometheusCheck) run(ctx context.Context, s Spec) Outcome {
|
||||
c, err := decode[PrometheusConfig](s.Config)
|
||||
if err != nil {
|
||||
return Outcome{Error: "invalid configuration"}
|
||||
}
|
||||
q := s
|
||||
q.Target = strings.TrimSuffix(s.Target, "/") + "/api/v1/query?" + url.Values{"query": {c.Query}}.Encode()
|
||||
resp, err := fetch(ctx, q, request{Method: http.MethodGet, Headers: c.Headers, VerifyTLS: c.VerifyTLS, FollowRedirects: true})
|
||||
if err != nil {
|
||||
return Outcome{Error: describeNetErr(err)}
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
o := Outcome{StatusCode: resp.StatusCode}
|
||||
var r promResponse
|
||||
if err := json.NewDecoder(io.LimitReader(resp.Body, maxBody)).Decode(&r); err != nil {
|
||||
o.Error = fmt.Sprintf("not a Prometheus API response (status %d)", resp.StatusCode)
|
||||
return o
|
||||
}
|
||||
if r.Status != "success" {
|
||||
o.Error = "query failed: " + truncate(r.ErrorType+": "+r.Error, 200)
|
||||
return o
|
||||
}
|
||||
samples, err := parseSamples(r.Data.ResultType, r.Data.Result)
|
||||
if err != nil {
|
||||
o.Error = err.Error()
|
||||
return o
|
||||
}
|
||||
if len(samples) == 0 {
|
||||
o.OK = c.EmptyOK
|
||||
if !o.OK {
|
||||
o.Error = "query returned no data"
|
||||
}
|
||||
return o
|
||||
}
|
||||
var failing []promSample
|
||||
for _, sm := range samples {
|
||||
if !compare(sm.Value, c.Op, c.Threshold) {
|
||||
failing = append(failing, sm)
|
||||
}
|
||||
}
|
||||
if (c.Mode == "all" && len(failing) == 0) || (c.Mode == "any" && len(failing) < len(samples)) {
|
||||
o.OK = true
|
||||
return o
|
||||
}
|
||||
f := failing[0]
|
||||
o.Error = fmt.Sprintf("%s = %s, expected %s %s", seriesName(f.Labels), formatFloat(f.Value), c.Op, formatFloat(c.Threshold))
|
||||
if len(failing) > 1 {
|
||||
o.Error += fmt.Sprintf(" (%d of %d series fail)", len(failing), len(samples))
|
||||
}
|
||||
return o
|
||||
}
|
||||
|
||||
func parseSamples(resultType string, raw json.RawMessage) ([]promSample, error) {
|
||||
value := func(v [2]any) (float64, error) {
|
||||
s, _ := v[1].(string)
|
||||
return strconv.ParseFloat(s, 64)
|
||||
}
|
||||
switch resultType {
|
||||
case "vector":
|
||||
var series []struct {
|
||||
Metric map[string]string `json:"metric"`
|
||||
Value [2]any `json:"value"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &series); err != nil {
|
||||
return nil, fmt.Errorf("unreadable vector result")
|
||||
}
|
||||
out := make([]promSample, 0, len(series))
|
||||
for _, s := range series {
|
||||
v, err := value(s.Value)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unreadable sample value")
|
||||
}
|
||||
out = append(out, promSample{Labels: s.Metric, Value: v})
|
||||
}
|
||||
return out, nil
|
||||
case "scalar":
|
||||
var v [2]any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return nil, fmt.Errorf("unreadable scalar result")
|
||||
}
|
||||
f, err := value(v)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unreadable sample value")
|
||||
}
|
||||
return []promSample{{Value: f}}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("unsupported result type %q; use an instant vector or scalar", resultType)
|
||||
}
|
||||
|
||||
// compare reports whether v op threshold holds. NaN never meets a
|
||||
// condition.
|
||||
func compare(v float64, op string, threshold float64) bool {
|
||||
switch op {
|
||||
case "==":
|
||||
return v == threshold
|
||||
case "!=":
|
||||
return v != threshold
|
||||
case ">":
|
||||
return v > threshold
|
||||
case ">=":
|
||||
return v >= threshold
|
||||
case "<":
|
||||
return v < threshold
|
||||
case "<=":
|
||||
return v <= threshold
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// seriesName renders labels the way Prometheus does: name{k="v",...}.
|
||||
func seriesName(labels map[string]string) string {
|
||||
name := labels["__name__"]
|
||||
keys := make([]string, 0, len(labels))
|
||||
for k := range labels {
|
||||
if k != "__name__" {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
parts := make([]string, len(keys))
|
||||
for i, k := range keys {
|
||||
parts[i] = k + "=" + strconv.Quote(labels[k])
|
||||
}
|
||||
if name == "" && len(parts) == 0 {
|
||||
return "result"
|
||||
}
|
||||
return truncate(name+"{"+strings.Join(parts, ",")+"}", 200)
|
||||
}
|
||||
|
||||
func formatFloat(f float64) string { return strconv.FormatFloat(f, 'g', 6, 64) }
|
||||
|
||||
func truncate(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n-3] + "..."
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package check
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPrometheus(t *testing.T) {
|
||||
results := map[string]string{
|
||||
`up{job="api"}`: `{"status":"success","data":{"resultType":"vector","result":[
|
||||
{"metric":{"__name__":"up","job":"api","instance":"a:9100"},"value":[1700000000,"1"]},
|
||||
{"metric":{"__name__":"up","job":"api","instance":"b:9100"},"value":[1700000000,"0"]}]}}`,
|
||||
`scalar(1)`: `{"status":"success","data":{"resultType":"scalar","result":[1700000000,"1"]}}`,
|
||||
`absent_metric`: `{"status":"success","data":{"resultType":"vector","result":[]}}`,
|
||||
`rate(x[5m])[1h:]`: `{"status":"success","data":{"resultType":"matrix","result":[]}}`,
|
||||
`bad(`: `{"status":"error","errorType":"bad_data","error":"parse error"}`,
|
||||
}
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/prom/api/v1/query" || r.Header.Get("Authorization") != "Basic dTpw" {
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
body, ok := results[r.URL.Query().Get("query")]
|
||||
if !ok {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
base := srv.URL + "/prom/"
|
||||
run := func(cfg map[string]any) Outcome {
|
||||
t.Helper()
|
||||
cfg["headers"] = map[string]string{"Authorization": "Basic dTpw"}
|
||||
raw, _ := json.Marshal(cfg)
|
||||
c, err := Validate(Prometheus, base, raw)
|
||||
if err != nil {
|
||||
t.Fatalf("Validate(%s) = %v", raw, err)
|
||||
}
|
||||
return Run(context.Background(), Spec{Type: Prometheus, Target: base, Timeout: 2 * time.Second, Config: c, AllowPrivate: true})
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cfg map[string]any
|
||||
ok bool
|
||||
msg string
|
||||
}{
|
||||
{"all series up fails on one down", map[string]any{"query": `up{job="api"}`, "op": "==", "threshold": 1}, false,
|
||||
`up{instance="b:9100",job="api"} = 0, expected == 1`},
|
||||
{"any series up", map[string]any{"query": `up{job="api"}`, "op": "==", "threshold": 1, "mode": "any"}, true, ""},
|
||||
{"none above 1 lists count", map[string]any{"query": `up{job="api"}`, "op": ">", "threshold": 1}, false, "(2 of 2 series fail)"},
|
||||
{"scalar", map[string]any{"query": `scalar(1)`, "op": ">=", "threshold": 1}, true, ""},
|
||||
{"no data fails", map[string]any{"query": `absent_metric`}, false, "query returned no data"},
|
||||
{"no data may be fine", map[string]any{"query": `absent_metric`, "empty_ok": true}, true, ""},
|
||||
{"range vectors are refused", map[string]any{"query": `rate(x[5m])[1h:]`}, false, "unsupported result type"},
|
||||
{"query errors are reported", map[string]any{"query": `bad(`}, false, "query failed: bad_data: parse error"},
|
||||
} {
|
||||
o := run(tc.cfg)
|
||||
if o.OK != tc.ok || !strings.Contains(o.Error, tc.msg) {
|
||||
t.Errorf("%s: %+v, want ok=%t with %q", tc.name, o, tc.ok, tc.msg)
|
||||
}
|
||||
}
|
||||
|
||||
for cfg, code := range map[string]string{
|
||||
`{}`: "invalid_query",
|
||||
`{"query":"up","op":"~"}`: "invalid_assertion_op",
|
||||
`{"query":"up","mode":"most"}`: "invalid_config",
|
||||
`{"query":"up","headers":{"Host":"x"}}`: "invalid_header",
|
||||
} {
|
||||
_, err := Validate(Prometheus, base, json.RawMessage(cfg))
|
||||
var inv ErrInvalid
|
||||
if !errors.As(err, &inv) || inv.Code != code {
|
||||
t.Errorf("Validate(%s) = %v, want %s", cfg, err, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -151,7 +151,7 @@ func TestDynamicFamilies(t *testing.T) {
|
||||
en := catalogKeys(t)["en"]
|
||||
families := map[string][]string{
|
||||
"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"},
|
||||
"agents.kind_": {"checker", "statuspage"},
|
||||
"page.status.": {"operational", "degraded", "outage", "unknown", "maintenance"},
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
"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_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_region": "Unbekannte Region.",
|
||||
"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_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.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_not_enough": "Für weniger als die Hälfte dieses Zeitraums liegen bisher Daten vor.",
|
||||
"monitors.range_note": "SLA und Balken: letzte {{.Range}}",
|
||||
@@ -497,6 +505,7 @@
|
||||
"monitors.type_http": "HTTP(S)",
|
||||
"monitors.type_icmp": "Ping (ICMP)",
|
||||
"monitors.type_json": "JSON-API",
|
||||
"monitors.type_prometheus": "Prometheus",
|
||||
"monitors.type_tcp": "TCP-Port",
|
||||
"monitors.type_tls": "TLS-Zertifikat",
|
||||
"monitors.uptime_chart": "Uptime pro Zeitraum",
|
||||
|
||||
@@ -168,6 +168,7 @@
|
||||
"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_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_region": "Unknown region.",
|
||||
"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_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.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_not_enough": "Less than half of this period is covered by data yet.",
|
||||
"monitors.range_note": "SLA and bars: last {{.Range}}",
|
||||
@@ -497,6 +505,7 @@
|
||||
"monitors.type_http": "HTTP(S)",
|
||||
"monitors.type_icmp": "Ping (ICMP)",
|
||||
"monitors.type_json": "JSON API",
|
||||
"monitors.type_prometheus": "Prometheus",
|
||||
"monitors.type_tcp": "TCP port",
|
||||
"monitors.type_tls": "TLS certificate",
|
||||
"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'));
|
||||
@@ -466,6 +466,12 @@ type MonitorForm struct {
|
||||
JSONExpect string
|
||||
JSONVerify bool
|
||||
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.
|
||||
@@ -541,7 +547,7 @@ templ MonitorEditor(p Page, me Me, f MonitorForm) {
|
||||
<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>
|
||||
<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>
|
||||
}
|
||||
</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)
|
||||
@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) {
|
||||
<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>
|
||||
|
||||
+814
-578
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user