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] + "..." }