diff --git a/README.md b/README.md index 0c278b8..dcd9950 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,7 @@ The `resources` field accepts the following resource names (case-insensitive, co | `migrate` | Grafana → Perses dashboard migration tool | | `schema` | Plugin schema tools (requires Perses v0.55+) | | `validate` | Dashboard and variable validation tools | +| `prometheus` | Prometheus metric discovery and query tools | #### Environment Variables @@ -464,6 +465,24 @@ For ephemeral dashboard configuration, see [Perses EphemeralDashboard](https://g } ``` +### Prometheus + +Resource: `prometheus` + +These read-only tools discover and query the metrics of Prometheus datasources through the Perses proxy and return +compact JSON: range queries return statistics per series (min, max, avg, last) instead of raw points. `datasource` is +optional: the default Prometheus datasource is used when it is omitted. + +| Tool | Description | Required Parameters | +|-----------------------------------------|------------------------------------------------|---------------------| +| `perses_list_prometheus_metric_names` | List metric names | - | +| `perses_list_prometheus_label_names` | List label names | - | +| `perses_list_prometheus_label_values` | List the values of a label | `label` | +| `perses_get_prometheus_metric_metadata` | Get the type, help and unit of metrics | `metrics` | +| `perses_query_prometheus` | Run a PromQL query and get a compact result | `query` | + +See [Prometheus tools](./docs/tools.md#prometheus) for details. + ### Roles | Tool | Description | Required Parameters | diff --git a/docs/configuration.md b/docs/configuration.md index 8239f94..3400148 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -142,6 +142,7 @@ ignored. The MCP server refuses to start if a name is unknown. | `ephemeraldashboard` | [Ephemeral dashboards](./tools.md#ephemeral-dashboards) | | `datasource` | [Project datasources](./tools.md#datasources) | | `globaldatasource` | [Global datasources](./tools.md#datasources) | +| `prometheus` | [Prometheus](./tools.md#prometheus) | | `variable` | [Project variables](./tools.md#variables) | | `globalvariable` | [Global variables](./tools.md#variables) | | `role` | [Project roles](./tools.md#roles-and-role-bindings) | diff --git a/docs/overview.md b/docs/overview.md index 6d3efc6..9633e1c 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -101,6 +101,10 @@ datasource or a LogQL query on a Loki datasource. The requests go through the See [Querying datasources](./tools.md#querying-datasources) for more details. +For Prometheus datasources, [dedicated tools](./tools.md#prometheus) list the metric names, labels and label values, +get the metadata of metrics and run PromQL queries. They return compact results, for example statistics per series +instead of raw points for range queries, and use the default Prometheus datasource when none is given. + ### Migrate Grafana dashboards The tool `perses_migrate_dashboard` converts a Grafana dashboard into a Perses dashboard, using the diff --git a/docs/tools.md b/docs/tools.md index 678e480..cbcdb6c 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -190,6 +190,101 @@ Example of a range query on a Prometheus datasource of a project: } ``` +## Prometheus + +Resource: `prometheus` + +These read-only tools discover and query the metrics of the Prometheus datasources of Perses. They call the +[Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/) through the Perses proxy, like +`perses_query_*_datasource` (credentials injected by Perses, `allowedEndpoints` enforced), but return compact JSON +instead of the raw response: a range query over 6 hours returning 61 series is about 3 KB with +`perses_query_prometheus` (top 20 series, statistics) and 240 KB with `perses_query_global_datasource` (raw points). + +| Tool | Description | Required parameters | Optional parameters | +|-----------------------------------------|----------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------| +| `perses_list_prometheus_metric_names` | List metric names | - | `datasource`, `match`, `search`, `time_range`, `limit`, `include_metadata` | +| `perses_list_prometheus_label_names` | List label names | - | `datasource`, `match`, `time_range`, `limit` | +| `perses_list_prometheus_label_values` | List the values of a label | `label` | `datasource`, `match`, `search`, `time_range`, `limit` | +| `perses_get_prometheus_metric_metadata` | Get the type, help and unit of 1 to 20 metrics | `metrics` | `datasource` | +| `perses_query_prometheus` | Run a PromQL query and get a compact result | `query` | `datasource`, `type`, `time`, `time_range`, `step`, `limit`, `time_zone` | + +The parameters are: + +- `datasource`: `{name}` for a global datasource, `{name, project}` for a project datasource. It is optional: see + [Default datasource](#default-datasource). +- `match`: a series selector, or a list of series selectors OR-ed together, e.g. `"{job=\"prometheus\"}"`. +- `search`: a case-insensitive substring filter, applied by the MCP server to the list returned by Prometheus. It + doesn't make Prometheus return less: to narrow a large list, use `match`, e.g. `{__name__=~".*memory.*"}`. +- `time_range`: `{past_duration}` (e.g. `"6h"`, `"7d"`), or `{start, end}` in RFC 3339 (`end` defaults to now). + The past hour by default. Prometheus applies it approximately (by storage block): the lists may include series + without samples in it, e.g. series that stopped a few hours ago. +- `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`, also its max), 200 + label names, 100 label values (max 1000), 20 series (max 100). + +The list tools return `{datasource, total, returned, truncated, ...}`. A list over 1 MiB is an error that asks to +narrow it with `match` or `time_range`. With `include_metadata: true`, each metric name comes with its type +and help, shortened to 80 characters. The metadata of all the metrics is fetched in one request; when it is over +1 MiB, the metadata of the returned metrics is looked up one by one instead. When it is unavailable, the metrics are +returned without it, with a warning. + +`perses_get_prometheus_metric_metadata` looks up each metric under its own name, then under the name of its family +when the family has series with this suffix, as Prometheus matches them: `_total` of counters, `_bucket`, `_count` and +`_sum` of histograms, `_bucket`, `_count`, `_sum`, `_gcount` and `_gsum` of gauge histograms, `_count` and `_sum` of +summaries, `_info` of info metrics (e.g. `http_requests_total` of the counter `http_requests`). A `_created` series +isn't matched, as it holds a timestamp, and neither is `x_total_total` with the family `x_total`. + +`perses_query_prometheus` runs an instant query (`type: "instant"`, default) at `time` (default now), or a range query +(`type: "range"`) over `time_range` with `step` (default about 500 points, at least the scrape interval of the +datasource; see [Datasource settings](#datasource-settings)). It returns: + +- for an instant query, the value of each series, highest first: `{resultType: "vector", time, seriesCount, returned, + commonLabels, series: [{labels, value}]}`; +- for a range query, never the raw points but the statistics of each series, highest max first: `{resultType: + "matrix", timeRange, step, seriesCount, returned, commonLabels, series: [{labels, min, max, avg, last, minAt, maxAt, + nonFinite}]}`. `min`, `max` and `avg` leave out the NaN and infinite samples, counted in `nonFinite`; `last` is the + last sample. A series that only has NaN or infinite samples is not returned, with a warning. `minAt` and `maxAt` are + in RFC 3339 with the offset of `time_zone` (default UTC). + +The labels shared by all returned series are returned once in `commonLabels`. The values keep 4 significant digits, +and all the digits of their integer part, so that timestamps and large counters are not rounded (e.g. `12.35`, +`123457`, `1767355200`); NaN and infinities are returned as strings. Native histograms are not summarized: the tool +returns an error that asks to use `histogram_quantile()`, `histogram_count()` or `histogram_sum()`, without `_bucket` +or `le`, e.g. `histogram_quantile(0.99, sum(rate(x[5m])))`. The `warnings` and `infos` of +Prometheus are passed through. The errors of Prometheus are returned unchanged as tool errors, e.g. `bad_data: invalid +parameter "query": 1:9: parse error: ...`; the other HTTP errors, e.g. of Perses, with their status and message. A +response over 1 MiB is an error that asks to aggregate the query. `time` applies to instant queries only, `time_range` +and `step` to range queries only: the other combinations are errors. + +Use `perses_query_*_datasource` for the other endpoints of Prometheus and for the other kinds of datasources. + +### Default datasource + +The parameter `datasource` of the Prometheus tools is resolved as follows: + +- `{name}`: the global datasource `name`; `{name, project}`: the datasource `name` of the project. It must be a + `PrometheusDatasource`. +- `{project}`: the Prometheus datasource of the project marked as default (`spec.default: true`), else the global one. +- omitted: the global Prometheus datasource marked as default. + +When no Prometheus datasource is marked as default but there is exactly one that the Perses proxy can query, it is +used. Otherwise the tool returns an error that lists the available Prometheus datasources. The resolved datasources +are cached for 30 seconds. + +The tools query the datasources through the Perses proxy: a datasource with a `directUrl`, which only the browser can +reach, is an error, also when it is the default one. + +### Datasource settings + +Like the Perses UI, the tools apply two settings of the Prometheus datasource, which the Perses proxy doesn't: + +- `queryParams` are added to every request, unless the request sets the same parameter, e.g. `dedup` or + `partial_response` for Thanos. A value with a dashboard variable (`$`) can't be resolved: it is sent as is, with a + warning. +- `scrapeInterval` (default `1m`) is the minimum default `step` of range queries. An explicit `step` isn't raised to + the scrape interval, but like the default one it is raised if needed to stay under the Prometheus limit of 11000 + points per series. Before, the minimum default step was 15s: range statistics are now computed over fewer points + unless `step` is set. + ## Variables Resources: `globalvariable` for the tools `*_global_variable*`, `variable` for the tools `*_project_variable*`. diff --git a/go.mod b/go.mod index d234b1b..0ac9e96 100644 --- a/go.mod +++ b/go.mod @@ -7,8 +7,12 @@ require ( github.com/modelcontextprotocol/go-sdk v1.8.0 github.com/perses/common v0.33.0 github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959 + github.com/perses/plugins/prometheus v0.59.1 github.com/perses/spec v0.3.0 + github.com/prometheus/client_golang v1.25.0 + github.com/prometheus/common v0.73.1 github.com/sirupsen/logrus v1.10.2 + golang.org/x/sync v0.24.0 ) require ( @@ -85,9 +89,7 @@ require ( github.com/pandatix/go-abnf v0.5.3 // indirect github.com/pb33f/ordered-map/v2 v2.3.1 // indirect github.com/pjbgf/sha1cd v0.6.0 // indirect - github.com/prometheus/client_golang v1.25.0 // indirect github.com/prometheus/client_model v0.6.3 // indirect - github.com/prometheus/common v0.73.1 // indirect github.com/prometheus/procfs v0.22.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/segmentio/asm v1.1.3 // indirect @@ -119,7 +121,6 @@ require ( golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect golang.org/x/net v0.61.0 // indirect golang.org/x/oauth2 v0.37.0 // indirect - golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/term v0.47.0 // indirect golang.org/x/text v0.43.0 // indirect diff --git a/go.sum b/go.sum index 9550aed..720e88f 100644 --- a/go.sum +++ b/go.sum @@ -235,6 +235,8 @@ github.com/perses/common v0.33.0 h1:TXGYw84xn/ZeTUy6P4Gkd0iHSlb4rIO6tzcqD4pfrug= github.com/perses/common v0.33.0/go.mod h1:WOXuYHSGjcfk50Q8pFdYlEOObIjRbpVVxB+s3Gr6pcg= github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959 h1:2RcM+M4MOJc2C8Q+lVGEnmUy7qHvSE/i2JbE9ZR8GYc= github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959/go.mod h1:Hay8084VKDe+UwcmA8y6XXhHy+OKo+JFRWYlE/b3CDM= +github.com/perses/plugins/prometheus v0.59.1 h1:BWTyfkJQK3eUn9LOOAjfmR2r2m0p5Vi/z4WICH6DRrQ= +github.com/perses/plugins/prometheus v0.59.1/go.mod h1:4GOl9brt9mAWIuAUp5L+pQKVCfuIFJGlDraQEOPPyxs= github.com/perses/spec v0.3.0 h1:pAkpwX32lQpdz1YLmGmmAMItdgtuVDVrkAQfWEqX6ZI= github.com/perses/spec v0.3.0/go.mod h1:bbTvfdCprae8P4JHknL2VnIkLkTLXqV4stpOlZyxibo= github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU= diff --git a/internal/permcp/server.go b/internal/permcp/server.go index a7a07fa..4a30374 100644 --- a/internal/permcp/server.go +++ b/internal/permcp/server.go @@ -37,6 +37,7 @@ import ( "github.com/perses/mcp-server/pkg/tools/migrate" "github.com/perses/mcp-server/pkg/tools/plugin" "github.com/perses/mcp-server/pkg/tools/project" + "github.com/perses/mcp-server/pkg/tools/prometheus" "github.com/perses/mcp-server/pkg/tools/resource" "github.com/perses/mcp-server/pkg/tools/role" "github.com/perses/mcp-server/pkg/tools/rolebinding" @@ -147,6 +148,7 @@ func (s *server) registerTools() { schema.New(v1Client), validate.New(s.persesClient), migrate.New(s.persesClient), + prometheus.New(v1Client), } var allTools []*tools.Tool diff --git a/pkg/tools/internal/proxy/proxy.go b/pkg/tools/internal/proxy/proxy.go index a93d811..a288028 100644 --- a/pkg/tools/internal/proxy/proxy.go +++ b/pkg/tools/internal/proxy/proxy.go @@ -24,6 +24,14 @@ import ( apiClient "github.com/perses/perses/pkg/client/api/v1" ) +// NoRedirectClient returns a copy of client that doesn't follow redirects: the datasource APIs don't redirect, and the +// requests carry the Perses credentials, which must not be sent to another URL. A redirect is returned as the response. +func NoRedirectClient(client *http.Client) *http.Client { + noRedirect := *client + noRedirect.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &noRedirect +} + // maxBodyBytes caps response body size to prevent overwhelming LLM context windows. const maxBodyBytes = 1 << 20 // 1 MiB @@ -200,7 +208,7 @@ func (h *Helper) Do(ctx context.Context, input ProxyQuery) (*Response, error) { } // #nosec G704 -- req URL is built from configured base URL and validated above. - resp, err := restClient.Client.Do(req) + resp, err := NoRedirectClient(restClient.Client).Do(req) if err != nil { return nil, err } diff --git a/pkg/tools/internal/proxy/proxy_test.go b/pkg/tools/internal/proxy/proxy_test.go index f0b9d03..180bd23 100644 --- a/pkg/tools/internal/proxy/proxy_test.go +++ b/pkg/tools/internal/proxy/proxy_test.go @@ -89,6 +89,27 @@ func TestResponseText(t *testing.T) { } } +func TestDoDoesNotFollowRedirects(t *testing.T) { + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/moved" { + t.Errorf("the redirect to %s is followed", r.URL.Path) + } + http.Redirect(w, r, "/moved", http.StatusFound) + })) + defer httpServer.Close() + client := apiclient.NewWithClient(&perseshttp.RESTClient{ + BaseURL: common.MustParseURL(httpServer.URL), + Client: httpServer.Client(), + }) + resp, err := New(client.V1()).Do(context.Background(), ProxyQuery{Path: GlobalDatasourceProxyPath("prom", "/api/v1/query")}) + if err != nil { + t.Fatalf("Do() unexpected error: %v", err) + } + if resp.StatusCode != http.StatusFound { + t.Errorf("StatusCode = %d, want %d", resp.StatusCode, http.StatusFound) + } +} + func TestDoTruncation(t *testing.T) { tests := []struct { name string diff --git a/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go new file mode 100644 index 0000000..517cab1 --- /dev/null +++ b/pkg/tools/prometheus/client.go @@ -0,0 +1,238 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/perses/mcp-server/pkg/tools/internal/proxy" + "github.com/prometheus/client_golang/api" + v1 "github.com/prometheus/client_golang/api/prometheus/v1" +) + +const ( + // maxBodyBytes caps the size of the Prometheus responses, like the datasource query tools. + maxBodyBytes = 1 << 20 // 1 MiB + // maxErrorLength caps the error messages returned by Perses or the datasource. + maxErrorLength = 400 +) + +var errTooMuchData = errors.New("the query returns too much data (over 1 MiB): aggregate it (sum by, topk) or narrow the label matchers") + +// newAPI returns a client of the Prometheus HTTP API that sends its requests through the Perses proxy of the +// datasource, with the HTTP client and the default headers (credentials) of the Perses client, and the query +// parameters of the datasource. +func (p *prometheus) newAPI(datasource resolvedDatasource) (v1.API, error) { + restClient := p.client.RESTClient() + if restClient == nil || restClient.Client == nil || restClient.BaseURL == nil { + return nil, errors.New("perses REST client is not configured") + } + ref := datasource.ref + path := proxy.GlobalDatasourceProxyPath(ref.Name, "") + if ref.Project != "" { + path = proxy.ProjectDatasourceProxyPath(ref.Project, ref.Name, "") + } + // The proxy path is appended to the path of the base URL, which may have a query string. + address, err := url.Parse(restClient.BaseURL.String()) + if err != nil { + return nil, fmt.Errorf("invalid Perses base URL: %w", err) + } + address.Path = strings.TrimRight(address.Path, "/") + path + client, err := api.NewClient(api.Config{ + Address: address.String(), + Client: &http.Client{Transport: &persesTransport{ + client: proxy.NoRedirectClient(restClient.Client), headers: restClient.Headers, queryParams: datasource.queryParams, + }}, + }) + if err != nil { + return nil, fmt.Errorf("error creating the Prometheus client of %s: %w", ref, err) + } + return v1.NewAPI(client), nil +} + +// persesTransport sends the requests with the Perses client and caps the size of the response bodies. +// +// The Prometheus client only keeps the body of the errors in the Prometheus format: the other error responses (e.g. +// a Perses error or the error page of a proxy) are turned into a statusError that keeps their message. The responses +// with which the Prometheus client retries a POST request with GET (403, 405 and 501) are passed through. +// +// Like the Perses UI, it adds the query parameters of the datasource to the URL of every request, unless the request +// already has the parameter, in its URL or in its form body (POST): Prometheus merges the values of a repeated +// parameter such as match[] from both. +type persesTransport struct { + client *http.Client + headers map[string]string + queryParams map[string]string +} + +func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + for key, value := range t.headers { + if req.Header.Get(key) == "" { + req.Header.Set(key, value) + } + } + if len(t.queryParams) > 0 { + form, err := formOf(req) + if err != nil { + return nil, err + } + query := req.URL.Query() + for key, value := range t.queryParams { + if !query.Has(key) && !form.Has(key) { + query.Set(key, value) + } + } + req.URL.RawQuery = query.Encode() + } + // #nosec G704 -- the URL is built from the configured Perses base URL and the datasource proxy path. + resp, err := t.client.Do(req) + if err != nil { + return nil, err + } + // The client doesn't follow redirects: a redirect is an error, even with a Prometheus error body, as the Prometheus + // client would follow it with the Perses credentials. + if resp.StatusCode/100 == 3 { + _ = resp.Body.Close() + return nil, &statusError{status: resp.Status, message: fmt.Sprintf( + "the redirect to %s is not followed: if Perses has moved, configure its new URL", resp.Header.Get("Location"))} + } + if resp.StatusCode/100 == 2 || (req.Method == http.MethodPost && isGetFallbackStatus(resp.StatusCode)) { + resp.Body = &limitedBody{ReadCloser: resp.Body, remaining: maxBodyBytes} + return resp, nil + } + // The error bodies are only read up to the cap: errorMessage keeps their beginning. + body, err := io.ReadAll(io.LimitReader(resp.Body, maxBodyBytes)) + _ = resp.Body.Close() + if err != nil { + return nil, err + } + if _, isPrometheusError := prometheusErrorMessage(body); isPrometheusError { + resp.Body = io.NopCloser(bytes.NewReader(body)) + return resp, nil + } + return nil, &statusError{status: resp.Status, message: errorMessage(body)} +} + +// formOf returns the parameters of the form body of a request, read from a copy of the body. +func formOf(req *http.Request) (url.Values, error) { + if req.GetBody == nil || req.Header.Get("Content-Type") != "application/x-www-form-urlencoded" { + return url.Values{}, nil + } + body, err := req.GetBody() + if err != nil { + return nil, fmt.Errorf("error reading the request body: %w", err) + } + defer func() { _ = body.Close() }() + data, err := io.ReadAll(body) + if err != nil { + return nil, fmt.Errorf("error reading the request body: %w", err) + } + return url.ParseQuery(string(data)) +} + +// isGetFallbackStatus reports whether the Prometheus client retries a POST request with GET after this status. +func isGetFallbackStatus(status int) bool { + return status == http.StatusForbidden || status == http.StatusMethodNotAllowed || status == http.StatusNotImplemented +} + +// limitedBody fails with errTooMuchData when the body is larger than its limit. +type limitedBody struct { + io.ReadCloser + remaining int64 +} + +func (b *limitedBody) Read(p []byte) (int, error) { + n, err := b.ReadCloser.Read(p) + b.remaining -= int64(n) + if b.remaining < 0 { + return n, errTooMuchData + } + return n, err +} + +// statusError is an HTTP error response of Perses or of the datasource that is not a Prometheus error. +type statusError struct { + status string + message string +} + +func (e *statusError) Error() string { + if e.message == "" { + return "HTTP " + e.status + } + return fmt.Sprintf("HTTP %s: %s", e.status, e.message) +} + +// prometheusErrorMessage returns ": " when body is an error of the Prometheus HTTP API. +func prometheusErrorMessage(body []byte) (string, bool) { + var response struct { + Status string `json:"status"` + ErrorType string `json:"errorType"` + Error string `json:"error"` + } + if json.Unmarshal(body, &response) != nil || response.Status != "error" { + return "", false + } + return fmt.Sprintf("%s: %s", response.ErrorType, response.Error), true +} + +// errorMessage returns the message of an error body: the message of a Perses error, else the body, shortened. +func errorMessage(body []byte) string { + var persesError struct { + Message string `json:"message"` + } + message := strings.TrimSpace(string(body)) + if json.Unmarshal(body, &persesError) == nil && persesError.Message != "" { + message = persesError.Message + } + // The body may not be UTF-8, e.g. a Latin-1 error page, and the cut below may split a character. + message = strings.ToValidUTF8(message, "") + if len(message) > maxErrorLength { + message = strings.ToValidUTF8(message[:maxErrorLength], "") + "..." + } + return message +} + +// apiError makes the errors of the Prometheus client readable. Prometheus errors are returned unchanged +// ("bad_data: parse error..."), the other HTTP errors with their status and message. +func apiError(datasource DatasourceRef, err error) error { + if errors.Is(err, errTooMuchData) { + return errTooMuchData + } + var promErr *v1.Error + if errors.As(err, &promErr) { + if promErr.Detail == "" { + return promErr + } + // The Prometheus client keeps the body of the errors it doesn't decode, e.g. a 503 Prometheus error. + if message, isPrometheusError := prometheusErrorMessage([]byte(promErr.Detail)); isPrometheusError { + return errors.New(message) + } + return fmt.Errorf("error querying %s: %s: %s", datasource, promErr.Msg, errorMessage([]byte(promErr.Detail))) + } + // The HTTP client wraps the errors of the transport with the request URL: keep the status and message only. + var statusErr *statusError + if errors.As(err, &statusErr) { + return fmt.Errorf("error querying %s: %w", datasource, statusErr) + } + return fmt.Errorf("error querying %s: %w", datasource, err) +} diff --git a/pkg/tools/prometheus/datasource.go b/pkg/tools/prometheus/datasource.go new file mode 100644 index 0000000..5e96a55 --- /dev/null +++ b/pkg/tools/prometheus/datasource.go @@ -0,0 +1,295 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "cmp" + "encoding/json" + "errors" + "fmt" + "maps" + "net/http" + "slices" + "strings" + "sync" + "time" + + apiClient "github.com/perses/perses/pkg/client/api/v1" + "github.com/perses/perses/pkg/client/perseshttp" + promDatasource "github.com/perses/plugins/prometheus/sdk/go/datasource" + "github.com/perses/spec/go/datasource" +) + +// prometheusDatasourceKind is the plugin kind of Prometheus datasources. +const prometheusDatasourceKind = promDatasource.PluginKind + +// defaultScrapeInterval is the scrape interval of a datasource that doesn't set one, as in the Perses UI. +const defaultScrapeInterval = time.Minute + +// cacheTTL is how long a resolved datasource is reused. +const cacheTTL = 30 * time.Second + +// errNoProxy tells that a datasource can't be queried through the Perses proxy. +var errNoProxy = errors.New("the MCP server queries datasources through the Perses proxy: configure a proxy on it") + +// DatasourceRef references a Prometheus datasource. Project is empty for a global datasource. In the tool inputs, +// Name is optional: the default Prometheus datasource is used when it is empty. +type DatasourceRef struct { + Name string `json:"name"` + Project string `json:"project,omitempty"` +} + +func (d DatasourceRef) String() string { + if d.Project == "" { + return fmt.Sprintf("global datasource '%s'", d.Name) + } + return fmt.Sprintf("datasource '%s' of project '%s'", d.Name, d.Project) +} + +// label returns the reference as listed in errors, e.g. "prom (global)". +func (d DatasourceRef) label() string { + if d.Project == "" { + return d.Name + " (global)" + } + return fmt.Sprintf("%s (project %s)", d.Name, d.Project) +} + +// resolvedDatasource is a Prometheus datasource to query, with the settings of its plugin spec that the Perses UI +// applies to its requests (the Perses proxy doesn't). +type resolvedDatasource struct { + ref DatasourceRef + // queryParams are added to every request, unless the request sets the same parameter. + queryParams map[string]string + // scrapeInterval is the minimum step of range queries. + scrapeInterval time.Duration +} + +// warnings returns the warnings about the settings of the datasource that the MCP server can't apply as the UI does. +func (d resolvedDatasource) warnings() []string { + var warnings []string + for _, key := range slices.Sorted(maps.Keys(d.queryParams)) { + if strings.Contains(d.queryParams[key], "$") { + warnings = append(warnings, fmt.Sprintf("the query parameter '%s' of %s may contain a dashboard variable, "+ + "which is sent unresolved: %s", key, d.ref, d.queryParams[key])) + } + } + return warnings +} + +// newResolvedDatasource reads the plugin spec of a Prometheus datasource. It fails with errNoProxy when the +// datasource is only reachable by the browser (directUrl). +func newResolvedDatasource(ref DatasourceRef, spec datasource.Spec) (resolvedDatasource, error) { + pluginSpec := spec.Plugin.Spec + if fields, isMap := pluginSpec.(map[string]any); isMap && fields["scrapeInterval"] == "" { + // Perses accepts an empty scrape interval (the UI saves it when the field is cleared), which means the + // default one, but the SDK rejects it. + withoutInterval := maps.Clone(fields) + delete(withoutInterval, "scrapeInterval") + pluginSpec = withoutInterval + } + data, err := json.Marshal(pluginSpec) + if err != nil { + return resolvedDatasource{}, fmt.Errorf("error reading the plugin spec of %s: %w", ref, err) + } + var plugin promDatasource.PluginSpec + if err = json.Unmarshal(data, &plugin); err != nil { + return resolvedDatasource{}, fmt.Errorf("invalid plugin spec of %s: %w", ref, err) + } + if plugin.Proxy == nil { + return resolvedDatasource{}, fmt.Errorf("%s uses a directUrl, reachable by the browser only: %w", ref, errNoProxy) + } + scrapeInterval := time.Duration(plugin.ScrapeInterval) + if scrapeInterval <= 0 { + scrapeInterval = defaultScrapeInterval + } + return resolvedDatasource{ref: ref, queryParams: plugin.QueryParams, scrapeInterval: scrapeInterval}, nil +} + +type cacheEntry struct { + datasource resolvedDatasource + expires time.Time +} + +// resolver resolves a (possibly partial) datasource reference to an existing Prometheus datasource. +// +// The resolved datasources are cached for cacheTTL and shared by all the tool calls. This is right as long as the +// MCP server queries Perses with a single identity (the credentials of its configuration): with per-user +// credentials, the cache must be keyed by user, as users may see different datasources. +type resolver struct { + client apiClient.ClientInterface + now func() time.Time + mutex sync.Mutex + cache map[DatasourceRef]cacheEntry +} + +func newResolver(client apiClient.ClientInterface) *resolver { + return &resolver{client: client, now: time.Now, cache: map[DatasourceRef]cacheEntry{}} +} + +// resolve returns the datasource to query: +// - name given: that datasource (project datasource when project is set, global otherwise), which must be a +// Prometheus datasource; +// - name omitted, project given: the default Prometheus datasource of the project, else the global one; +// - name and project omitted: the default global Prometheus datasource. +// +// When no Prometheus datasource is marked as default but there is exactly one that the Perses proxy can query +// (project and global), it is used. The datasource must have a proxy: a directUrl is only reachable by the browser. +func (r *resolver) resolve(input *DatasourceRef) (resolvedDatasource, error) { + var key DatasourceRef + if input != nil { + key = *input + } + r.mutex.Lock() + entry, ok := r.cache[key] + r.mutex.Unlock() + if ok && r.now().Before(entry.expires) { + return entry.datasource, nil + } + resolved, err := r.resolveUncached(key) + if err != nil { + return resolvedDatasource{}, err + } + r.mutex.Lock() + now := r.now() + // Remove the expired entries, e.g. of deleted datasources, so that the cache only keeps the recent keys. + for k, e := range r.cache { + if !now.Before(e.expires) { + delete(r.cache, k) + } + } + r.cache[key] = cacheEntry{datasource: resolved, expires: now.Add(cacheTTL)} + r.mutex.Unlock() + return resolved, nil +} + +// candidate is a Prometheus datasource that may be the default one. +type candidate struct { + ref DatasourceRef + spec datasource.Spec +} + +func (r *resolver) resolveUncached(key DatasourceRef) (resolvedDatasource, error) { + if key.Name != "" { + return r.resolveNamed(key) + } + // The default of the project wins over the global one: the global datasources are only listed without it. + var candidates []candidate + if key.Project != "" { + datasources, err := r.client.Datasource(key.Project).List("") + if err != nil { + return resolvedDatasource{}, fmt.Errorf("error listing the datasources of project '%s': %w", key.Project, err) + } + specs := map[string]datasource.Spec{} + for _, ds := range datasources { + specs[ds.Metadata.Name] = ds.Spec + } + projectCandidates := prometheusCandidates(specs, key.Project) + if resolved, found, err := resolveDefault(projectCandidates); found { + return resolved, err + } + candidates = projectCandidates + } + globals, err := r.client.GlobalDatasource().List("") + if err != nil { + // Without the global read permission, the datasources of the project are the only candidates. Without + // project candidates, the error is kept: it explains why no datasource is found. + var reqErr *perseshttp.RequestError + if len(candidates) == 0 || !errors.As(err, &reqErr) || reqErr.StatusCode != http.StatusForbidden { + return resolvedDatasource{}, fmt.Errorf("error listing the global datasources: %w", err) + } + globals = nil + } + specs := map[string]datasource.Spec{} + for _, ds := range globals { + specs[ds.Metadata.Name] = ds.Spec + } + globalCandidates := prometheusCandidates(specs, "") + if resolved, found, err := resolveDefault(globalCandidates); found { + return resolved, err + } + candidates = append(candidates, globalCandidates...) + + // No default: the only datasource that can be queried, if any. + var usable []resolvedDatasource + var available, unusable []string + for _, c := range candidates { + resolved, resolveErr := newResolvedDatasource(c.ref, c.spec) + if resolveErr != nil { + unusable = append(unusable, resolveErr.Error()) + continue + } + usable = append(usable, resolved) + available = append(available, c.ref.label()) + } + switch len(usable) { + case 0: + if len(unusable) > 0 { + return resolvedDatasource{}, fmt.Errorf("no Prometheus datasource can be used: %s", strings.Join(unusable, "; ")) + } + return resolvedDatasource{}, errors.New("no Prometheus datasource found: create one in Perses or pass datasource.name") + case 1: + // No default but a single Prometheus datasource that can be queried: no ambiguity. + return usable[0], nil + } + return resolvedDatasource{}, fmt.Errorf("no default Prometheus datasource found: pass datasource.name (and datasource.project for a project datasource), available Prometheus datasources: %s", + strings.Join(available, ", ")) +} + +// resolveDefault resolves the datasource marked as default among candidates, if any (found). The default is the one +// users expect: when it can't be used, the error is returned rather than another datasource picked. +func resolveDefault(candidates []candidate) (resolved resolvedDatasource, found bool, err error) { + for _, c := range candidates { + if c.spec.Default { + resolved, err = newResolvedDatasource(c.ref, c.spec) + if err != nil { + return resolvedDatasource{}, true, fmt.Errorf("the default Prometheus datasource can't be used: %w", err) + } + return resolved, true, nil + } + } + return resolvedDatasource{}, false, nil +} + +func (r *resolver) resolveNamed(key DatasourceRef) (resolvedDatasource, error) { + var spec datasource.Spec + if key.Project != "" { + ds, err := r.client.Datasource(key.Project).Get(key.Name) + if err != nil { + return resolvedDatasource{}, fmt.Errorf("error retrieving %s: %w", key, err) + } + spec = ds.Spec + } else { + ds, err := r.client.GlobalDatasource().Get(key.Name) + if err != nil { + return resolvedDatasource{}, fmt.Errorf("error retrieving %s (set datasource.project for a project datasource): %w", key, err) + } + spec = ds.Spec + } + if spec.Plugin.Kind != prometheusDatasourceKind { + return resolvedDatasource{}, fmt.Errorf("%s is a %s, not a %s", key, spec.Plugin.Kind, prometheusDatasourceKind) + } + return newResolvedDatasource(key, spec) +} + +// prometheusCandidates returns the Prometheus datasources of a scope (project, or global when empty), sorted by name. +func prometheusCandidates(specs map[string]datasource.Spec, project string) []candidate { + var candidates []candidate + for name, spec := range specs { + if spec.Plugin.Kind == prometheusDatasourceKind { + candidates = append(candidates, candidate{ref: DatasourceRef{Name: name, Project: project}, spec: spec}) + } + } + slices.SortFunc(candidates, func(a, b candidate) int { return cmp.Compare(a.ref.Name, b.ref.Name) }) + return candidates +} diff --git a/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go new file mode 100644 index 0000000..6fcdebb --- /dev/null +++ b/pkg/tools/prometheus/helpers_test.go @@ -0,0 +1,293 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "encoding/json" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/perses/mcp-server/pkg/tools/internal/tooltest" + v1 "github.com/prometheus/client_golang/api/prometheus/v1" +) + +var testNow = time.Date(2026, 1, 2, 12, 0, 0, 0, time.UTC) + +const ( + globalProxy = "/proxy/globaldatasources/prom" + projectProxy = "/proxy/projects/demo/datasources/prom" +) + +// testDatasource is a datasource served by fakePerses. Project is empty for a global datasource. +type testDatasource struct { + Name string + Project string + Kind string + Default bool + // DirectURL makes a datasource reachable by the browser only, without proxy. + DirectURL bool + ScrapeInterval string + QueryParams map[string]string + // PluginSpec, when set, is the plugin spec served as is, e.g. with an empty scrape interval. + PluginSpec map[string]any +} + +// defaultDatasources are a global default Prometheus datasource "prom", a project Prometheus datasource "prom" in +// project "demo" and a global default Loki datasource "logs". +var defaultDatasources = []testDatasource{ + {Name: "prom", Kind: prometheusDatasourceKind, Default: true}, + {Name: "prom", Project: "demo", Kind: prometheusDatasourceKind}, + {Name: "logs", Kind: "LokiDatasource", Default: true}, +} + +type answer struct { + status int + body string + // location is the Location header of a redirect. + location string +} + +// write writes the answer as the response. +func (a answer) write(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + if a.location != "" { + w.Header().Set("Location", a.location) + } + w.WriteHeader(a.status) + _, _ = w.Write([]byte(a.body)) +} + +func ok(data string) answer { + return answer{status: http.StatusOK, body: `{"status":"success","data":` + data + `}`} +} + +// fakePerses serves the datasource API of Perses for its datasources and answers the proxy requests by path, or by +// "METHOD path" first. The embedded tooltest.Perses records the requests. +type fakePerses struct { + tooltest.Perses + t *testing.T + datasources []testDatasource + answers map[string]answer + // metadata, when set, is the metadata catalog served on /api/v1/metadata, filtered by the parameter metric. + metadata map[string][]v1.Metadata + // bulkMetadataTooLarge makes the metadata of all the metrics (no parameter metric) larger than maxBodyBytes. + bulkMetadataTooLarge bool + // answer, when set, answers the proxy requests first: its answer is used unless it returns nil. + answer func(r *http.Request) *answer + // forbidGlobalList makes the list of the global datasources fail with 403. + forbidGlobalList bool +} + +func newFakePerses(t *testing.T, answers map[string]answer) *fakePerses { + f := &fakePerses{t: t, datasources: defaultDatasources, answers: answers} + f.Handler = http.HandlerFunc(f.serve) + return f +} + +func (f *fakePerses) serve(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/v1/") { + f.serveDatasources(w, r) + return + } + if f.answer != nil { + if a := f.answer(r); a != nil { + a.write(w) + return + } + } + if f.metadata != nil && strings.HasSuffix(r.URL.Path, "/api/v1/metadata") { + f.serveMetadata(w, r.URL.Query().Get("metric")) + return + } + a, found := f.answers[r.Method+" "+r.URL.Path] + if !found { + a, found = f.answers[r.URL.Path] + } + if !found { + f.t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + return + } + a.write(w) +} + +func (f *fakePerses) serveMetadata(w http.ResponseWriter, metric string) { + if metric == "" && f.bulkMetadataTooLarge { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(tooLarge("{}"))) + return + } + metadata := f.metadata + if metric != "" { + metadata = map[string][]v1.Metadata{} + if entries, found := f.metadata[metric]; found { + metadata[metric] = entries + } + } + data, err := json.Marshal(metadata) + if err != nil { + // The handler runs in the goroutine of the HTTP server, where t.Fatal must not be called. + f.t.Errorf("encoding the metadata: %v", err) + w.WriteHeader(http.StatusInternalServerError) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":"success","data":` + string(data) + `}`)) +} + +// paramsOf returns the parameters (query string and form) of the last request of path. +func (f *fakePerses) paramsOf(path string) url.Values { + f.t.Helper() + received := f.Received() + for i := len(received) - 1; i >= 0; i-- { + request := received[i] + if request.Path != path { + continue + } + params, err := url.ParseQuery(request.RawQuery) + if err != nil { + f.t.Fatalf("parsing the query of %s: %v", path, err) + } + if request.ContentType == "application/x-www-form-urlencoded" { + form, formErr := url.ParseQuery(request.Body) + if formErr != nil { + f.t.Fatalf("parsing the form of %s: %v", path, formErr) + } + for key, values := range form { + params[key] = append(params[key], values...) + } + } + return params + } + f.t.Fatalf("no request received for %s", path) + return nil +} + +// serveDatasources serves the get and list requests of global and project datasources. +func (f *fakePerses) serveDatasources(w http.ResponseWriter, r *http.Request) { + parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/") + var project, name string + switch { + case len(parts) >= 3 && len(parts) <= 4 && parts[2] == "globaldatasources": + if len(parts) == 4 { + name = parts[3] + } else if f.forbidGlobalList { + w.WriteHeader(http.StatusForbidden) + _, _ = w.Write([]byte(`{"message":"forbidden"}`)) + return + } + case len(parts) >= 5 && len(parts) <= 6 && parts[2] == "projects" && parts[4] == "datasources": + project = parts[3] + if len(parts) == 6 { + name = parts[5] + } + default: + f.t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + return + } + found := []any{} + for _, ds := range f.datasources { + if ds.Project == project && (name == "" || ds.Name == name) { + found = append(found, encodeDatasource(ds)) + } + } + w.Header().Set("Content-Type", "application/json") + if name == "" { + _ = json.NewEncoder(w).Encode(found) + return + } + if len(found) == 0 { + w.WriteHeader(http.StatusNotFound) + _, _ = w.Write([]byte(`{"message":"document not found"}`)) + return + } + _ = json.NewEncoder(w).Encode(found[0]) +} + +// tooLarge returns a successful Prometheus response with data, padded over maxBodyBytes. +func tooLarge(data string) string { + return `{"status":"success","data":` + data + strings.Repeat(" ", maxBodyBytes) + `}` +} + +func encodeDatasource(ds testDatasource) map[string]any { + pluginSpec := map[string]any{} + if ds.Kind == prometheusDatasourceKind { + if ds.DirectURL { + pluginSpec["directUrl"] = "http://prometheus.example.com" + } else { + pluginSpec["proxy"] = map[string]any{"kind": "HTTPProxy", "spec": map[string]any{"url": "http://prometheus.example.com"}} + } + if ds.ScrapeInterval != "" { + pluginSpec["scrapeInterval"] = ds.ScrapeInterval + } + if ds.QueryParams != nil { + pluginSpec["queryParams"] = ds.QueryParams + } + } + if ds.PluginSpec != nil { + pluginSpec = ds.PluginSpec + } + kind := "GlobalDatasource" + metadata := map[string]any{"name": ds.Name} + if ds.Project != "" { + kind = "Datasource" + metadata["project"] = ds.Project + } + return map[string]any{ + "kind": kind, + "metadata": metadata, + "spec": map[string]any{ + "default": ds.Default, + "plugin": map[string]any{"kind": ds.Kind, "spec": pluginSpec}, + }, + } +} + +// newTestPrometheus returns the prometheus resource backed by perses, with the clock at testNow. +func newTestPrometheus(t *testing.T, perses http.Handler) *prometheus { + t.Helper() + p := New(tooltest.NewClient(t, perses).V1()).(*prometheus) + p.now = func() time.Time { return testNow } + return p +} + +// connect registers the Prometheus tools on an in-memory MCP server backed by perses. +func connect(t *testing.T, perses http.Handler) *mcp.ClientSession { + t.Helper() + return tooltest.Connect(t, newTestPrometheus(t, perses).GetTools()) +} + +// call calls a tool and returns its text, failing when isError is not wantError. +func call(t *testing.T, session *mcp.ClientSession, name string, arguments map[string]any, wantError bool) string { + t.Helper() + result, text := tooltest.CallTool(t, session, name, arguments) + if result.IsError != wantError { + t.Fatalf("isError = %v, want %v: %s", result.IsError, wantError, text) + } + return text +} + +func decode(t *testing.T, text string) map[string]any { + t.Helper() + var output map[string]any + if err := json.Unmarshal([]byte(text), &output); err != nil { + t.Fatalf("decoding %s: %v", text, err) + } + return output +} diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go new file mode 100644 index 0000000..2e36148 --- /dev/null +++ b/pkg/tools/prometheus/internal_test.go @@ -0,0 +1,477 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "fmt" + "math" + "reflect" + "regexp" + "strings" + "testing" + "time" + "unicode/utf8" + + "github.com/prometheus/common/model" +) + +func TestResolve(t *testing.T) { + projectDefault := append([]testDatasource{{Name: "local", Project: "demo", Kind: prometheusDatasourceKind, Default: true}}, defaultDatasources...) + single := []testDatasource{{Name: "only", Kind: prometheusDatasourceKind}, {Name: "logs", Kind: "LokiDatasource", Default: true}} + several := []testDatasource{ + {Name: "a", Kind: prometheusDatasourceKind}, + {Name: "b", Kind: prometheusDatasourceKind}, + {Name: "c", Project: "demo", Kind: prometheusDatasourceKind}, + {Name: "c2", Project: "demo", Kind: prometheusDatasourceKind}, + } + direct := []testDatasource{{Name: "browser", Kind: prometheusDatasourceKind, DirectURL: true}, {Name: "proxied", Kind: prometheusDatasourceKind}} + directDefault := []testDatasource{{Name: "browser", Kind: prometheusDatasourceKind, DirectURL: true, Default: true}, {Name: "proxied", Kind: prometheusDatasourceKind}} + tests := []struct { + name string + datasources []testDatasource + input *DatasourceRef + want DatasourceRef + wantErr []string + }{ + {name: "omitted: global default", datasources: defaultDatasources, want: DatasourceRef{Name: "prom"}}, + {name: "explicit global", datasources: defaultDatasources, input: &DatasourceRef{Name: "prom"}, want: DatasourceRef{Name: "prom"}}, + {name: "explicit project", datasources: defaultDatasources, input: &DatasourceRef{Name: "prom", Project: "demo"}, want: DatasourceRef{Name: "prom", Project: "demo"}}, + {name: "project default", datasources: projectDefault, input: &DatasourceRef{Project: "demo"}, want: DatasourceRef{Name: "local", Project: "demo"}}, + {name: "project without default falls back to the global default", datasources: defaultDatasources, input: &DatasourceRef{Project: "demo"}, want: DatasourceRef{Name: "prom"}}, + {name: "single Prometheus datasource without default", datasources: single, want: DatasourceRef{Name: "only"}}, + {name: "wrong kind", datasources: defaultDatasources, input: &DatasourceRef{Name: "logs"}, wantErr: []string{"global datasource 'logs' is a LokiDatasource, not a PrometheusDatasource"}}, + {name: "not found", datasources: defaultDatasources, input: &DatasourceRef{Name: "nope"}, wantErr: []string{"error retrieving global datasource 'nope'", "datasource.project"}}, + {name: "none", datasources: nil, wantErr: []string{"no Prometheus datasource found"}}, + {name: "directUrl datasource", datasources: direct, input: &DatasourceRef{Name: "browser"}, wantErr: []string{"global datasource 'browser' uses a directUrl", "configure a proxy on it"}}, + {name: "directUrl default datasource", datasources: directDefault, wantErr: []string{"the default Prometheus datasource can't be used: global datasource 'browser' uses a directUrl"}}, + {name: "single proxied datasource besides a directUrl one", datasources: direct, want: DatasourceRef{Name: "proxied"}}, + {name: "only directUrl datasources", datasources: direct[:1], wantErr: []string{"no Prometheus datasource can be used: global datasource 'browser' uses a directUrl"}}, + {name: "no default among several", datasources: several, input: &DatasourceRef{Project: "demo"}, wantErr: []string{"no default Prometheus datasource", "c (project demo), c2 (project demo), a (global), b (global)"}}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = tt.datasources + got, err := newTestPrometheus(t, perses).resolver.resolve(tt.input) + if len(tt.wantErr) > 0 { + if err == nil { + t.Fatalf("Resolve() = %+v, want an error", got) + } + for _, want := range tt.wantErr { + if !strings.Contains(err.Error(), want) { + t.Errorf("error %q does not contain %q", err, want) + } + } + return + } + if err != nil { + t.Fatalf("Resolve() error: %v", err) + } + if got.ref != tt.want { + t.Errorf("Resolve() = %+v, want %+v", got.ref, tt.want) + } + }) + } +} + +func TestResolvePluginSpec(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{ + {Name: "set", Kind: prometheusDatasourceKind, ScrapeInterval: "30s", QueryParams: map[string]string{"dedup": "true", "tenant": "$tenant"}}, + {Name: "unset", Kind: prometheusDatasourceKind}, + } + resolver := newTestPrometheus(t, perses).resolver + set, err := resolver.resolve(&DatasourceRef{Name: "set"}) + if err != nil { + t.Fatal(err) + } + if set.scrapeInterval != 30*time.Second || !reflect.DeepEqual(set.queryParams, map[string]string{"dedup": "true", "tenant": "$tenant"}) { + t.Errorf("resolved = %+v", set) + } + if warnings := set.warnings(); len(warnings) != 1 || !strings.Contains(warnings[0], "'tenant'") { + t.Errorf("warnings = %v, want one about tenant", warnings) + } + unset, err := resolver.resolve(&DatasourceRef{Name: "unset"}) + if err != nil { + t.Fatal(err) + } + // Like in the Perses UI, the scrape interval defaults to 1m. + if unset.scrapeInterval != time.Minute || unset.queryParams != nil || unset.warnings() != nil { + t.Errorf("resolved = %+v", unset) + } +} + +func TestResolveCache(t *testing.T) { + perses := newFakePerses(t, nil) + resolver := newTestPrometheus(t, perses).resolver + now := time.Now() + resolver.now = func() time.Time { return now } + for range 3 { + if _, err := resolver.resolve(nil); err != nil { + t.Fatal(err) + } + } + if count := len(perses.Received()); count != 1 { + t.Errorf("%d Perses requests, want 1", count) + } + now = now.Add(cacheTTL + time.Second) + if _, err := resolver.resolve(nil); err != nil { + t.Fatal(err) + } + if count := len(perses.Received()); count != 2 { + t.Errorf("%d Perses requests after expiry, want 2", count) + } +} + +func TestResolveTimeRange(t *testing.T) { + tests := []struct { + name string + input *TimeRangeInput + wantStart time.Time + wantEnd time.Time + wantRange timeRangeOutput + wantErr string + }{ + {name: "default is the past hour", wantStart: testNow.Add(-time.Hour), wantEnd: testNow, wantRange: timeRangeOutput{PastDuration: "1h"}}, + {name: "past duration", input: &TimeRangeInput{PastDuration: "1d12h"}, wantStart: testNow.Add(-36 * time.Hour), wantEnd: testNow, wantRange: timeRangeOutput{PastDuration: "1d12h"}}, + { + name: "absolute range", + input: &TimeRangeInput{Start: "2026-01-02T10:00:00+01:00", End: "2026-01-02T10:30:00Z"}, + wantStart: time.Date(2026, 1, 2, 9, 0, 0, 0, time.UTC), wantEnd: time.Date(2026, 1, 2, 10, 30, 0, 0, time.UTC), + wantRange: timeRangeOutput{Start: "2026-01-02T09:00:00Z", End: "2026-01-02T10:30:00Z"}, + }, + { + name: "absolute range ends now by default", + input: &TimeRangeInput{Start: "2026-01-02T11:00:00Z"}, + wantStart: time.Date(2026, 1, 2, 11, 0, 0, 0, time.UTC), wantEnd: testNow, + wantRange: timeRangeOutput{Start: "2026-01-02T11:00:00Z", End: "2026-01-02T12:00:00Z"}, + }, + { + name: "fractional seconds are kept", + input: &TimeRangeInput{Start: "2026-01-02T10:00:00.100Z", End: "2026-01-02T10:00:00.900Z"}, + wantStart: time.Date(2026, 1, 2, 10, 0, 0, 100_000_000, time.UTC), wantEnd: time.Date(2026, 1, 2, 10, 0, 0, 900_000_000, time.UTC), + wantRange: timeRangeOutput{Start: "2026-01-02T10:00:00.1Z", End: "2026-01-02T10:00:00.9Z"}, + }, + {name: "invalid past duration", input: &TimeRangeInput{PastDuration: "an hour"}, wantErr: "invalid time_range.past_duration 'an hour'"}, + {name: "zero past duration", input: &TimeRangeInput{PastDuration: "0m"}, wantErr: "must be positive"}, + {name: "invalid start", input: &TimeRangeInput{Start: "2026-01-02"}, wantErr: "invalid time_range.start '2026-01-02'"}, + {name: "invalid end", input: &TimeRangeInput{Start: "2026-01-02T11:00:00Z", End: "now"}, wantErr: "invalid time_range.end 'now'"}, + {name: "start after end", input: &TimeRangeInput{Start: "2026-01-02T13:00:00Z"}, wantErr: "time_range.start must be before time_range.end"}, + {name: "end without start", input: &TimeRangeInput{End: "2026-01-02T11:00:00Z"}, wantErr: "time_range.end requires time_range.start"}, + {name: "past duration and start", input: &TimeRangeInput{PastDuration: "1h", Start: "2026-01-02T11:00:00Z"}, wantErr: "not both"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + start, end, timeRange, err := resolveTimeRange(tt.input, testNow) + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("error = %v, want %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatal(err) + } + if !start.Equal(tt.wantStart) || !end.Equal(tt.wantEnd) || timeRange != tt.wantRange { + t.Errorf("got %s - %s %+v, want %s - %s %+v", start, end, timeRange, tt.wantStart, tt.wantEnd, tt.wantRange) + } + }) + } +} + +func TestResolveStep(t *testing.T) { + tests := []struct { + step string + span time.Duration + minStep time.Duration + want time.Duration + }{ + {span: time.Hour, minStep: 15 * time.Second, want: 15 * time.Second}, + // The default step is at least the scrape interval of the datasource. + {span: time.Hour, minStep: time.Minute, want: time.Minute}, + {span: 6 * time.Hour, minStep: 15 * time.Second, want: 44 * time.Second}, + {span: 7 * 24 * time.Hour, minStep: time.Minute, want: 1210 * time.Second}, + // An explicit step is kept, even below the scrape interval. + {step: "1m", span: time.Hour, minStep: 5 * time.Minute, want: time.Minute}, + // The step is raised to stay under the Prometheus limit of points. + {step: "1s", span: 7 * 24 * time.Hour, minStep: time.Minute, want: 55 * time.Second}, + // A subsecond step under the limit is kept (601 points). + {step: "100ms", span: time.Minute, minStep: time.Minute, want: 100 * time.Millisecond}, + // A subsecond step over the limit is raised to the smallest step under it, to the millisecond (60s / 11000). + {step: "1ms", span: time.Minute, minStep: time.Minute, want: 6 * time.Millisecond}, + } + for _, tt := range tests { + t.Run(fmt.Sprintf("step=%q span=%s min=%s", tt.step, tt.span, tt.minStep), func(t *testing.T) { + got, err := resolveStep(tt.step, testNow.Add(-tt.span), testNow, tt.minStep) + if err != nil || got != tt.want { + t.Errorf("resolveStep(%q, %s, %s) = %s, %v, want %s", tt.step, tt.span, tt.minStep, got, err, tt.want) + } + }) + } +} + +func TestEscapeLabelName(t *testing.T) { + tests := []struct{ label, want string }{ + {label: "job", want: "job"}, + {label: "__name__", want: "__name__"}, + {label: "http.method", want: "U__http_2e_method"}, + {label: "a/b", want: "U__a_2f_b"}, + // Prometheus unescapes every name starting with U__: such names are escaped to be read back unchanged. + {label: "U__job", want: "U__U____job"}, + {label: "U__http.method", want: "U__U____http_2e_method"}, + // ':' is valid in legacy metric names but not in label names, nor in the label values path of the Perses proxy. + {label: "http:method", want: "U__http_3a_method"}, + {label: "http.a:b", want: "U__http_2e_a_3a_b"}, + {label: "U__a:b", want: "U__U____a_3a_b"}, + } + // The default allowedEndpoints pattern of the label values endpoint in the Perses proxy. + proxyLabelPattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) + for _, tt := range tests { + t.Run(tt.label, func(t *testing.T) { + got := escapeLabelName(tt.label) + if got != tt.want { + t.Errorf("escapeLabelName(%q) = %q, want %q", tt.label, got, tt.want) + } + if !proxyLabelPattern.MatchString(got) { + t.Errorf("escapeLabelName(%q) = %q, rejected by the Perses proxy", tt.label, got) + } + // The label values endpoint of Prometheus unescapes the names starting with U__ only. + read := got + if strings.HasPrefix(read, "U__") { + read = model.UnescapeName(read, model.ValueEncodingEscaping) + } + if read != tt.label { + t.Errorf("Prometheus reads %q as %q, want %q", got, read, tt.label) + } + }) + } +} + +func TestSeriesStats(t *testing.T) { + samples := []model.SamplePair{ + {Timestamp: 1767355200000, Value: 2}, + {Timestamp: 1767355215000, Value: model.SampleValue(math.NaN())}, + {Timestamp: 1767355230000, Value: 1}, + {Timestamp: 1767355245000, Value: 3.33333}, + {Timestamp: 1767355260000, Value: model.SampleValue(math.Inf(1))}, + } + got, maxValue, ok := seriesStats(samples, time.UTC) + want := stats{Min: 1, Max: 3.333, Avg: 2.111, Last: "+Inf", MinAt: "2026-01-02T12:00:30Z", MaxAt: "2026-01-02T12:00:45Z", NonFinite: 2} + if !ok || !reflect.DeepEqual(got, want) || maxValue != 3.33333 { + t.Errorf("seriesStats() = %+v, %v, %v, want %+v", got, maxValue, ok, want) + } + if _, _, ok := seriesStats([]model.SamplePair{{Value: model.SampleValue(math.Inf(1))}}, time.UTC); ok { + t.Error("seriesStats() of a series without finite values is ok") + } + // The average of large finite values doesn't overflow. + large := []model.SamplePair{{Value: math.MaxFloat64}, {Value: math.MaxFloat64}, {Value: -math.MaxFloat64}} + if got, _, _ := seriesStats(large, time.UTC); math.IsInf(got.Avg, 0) || math.Abs(got.Avg/(math.MaxFloat64/3)-1) > 1e-9 { + t.Errorf("average of large values = %v, want about %v", got.Avg, math.MaxFloat64/3) + } +} + +func TestKeepTopSeries(t *testing.T) { + all := []series{ + {Labels: map[string]string{"job": "p", "handler": "/a"}, sortKey: 1}, + {Labels: map[string]string{"job": "p", "handler": "/b"}, sortKey: 3}, + {Labels: map[string]string{"job": "p", "handler": "/c"}, sortKey: 2}, + } + top, common := keepTopSeries(all, 2) + if !reflect.DeepEqual(common, map[string]string{"job": "p"}) { + t.Errorf("common = %v", common) + } + if len(top) != 2 || !reflect.DeepEqual(top[0].Labels, map[string]string{"handler": "/b"}) || !reflect.DeepEqual(top[1].Labels, map[string]string{"handler": "/c"}) { + t.Errorf("top = %+v", top) + } + + single, common := keepTopSeries([]series{{Labels: map[string]string{"a": "1"}}}, 5) + if common != nil || single[0].Labels["a"] != "1" { + t.Errorf("single series: common = %v, labels = %v", common, single[0].Labels) + } + _, common = keepTopSeries([]series{{Labels: map[string]string{"a": "1"}}, {Labels: map[string]string{}}}, 5) + if common != nil { + t.Errorf("common = %v, want none (a series has no labels)", common) + } +} + +func TestKeepTopSeriesSortsNaNLast(t *testing.T) { + all, err := vectorSeries(model.Vector{ + {Metric: model.Metric{"s": "nan"}, Value: model.SampleValue(math.NaN())}, + {Metric: model.Metric{"s": "-inf"}, Value: model.SampleValue(math.Inf(-1))}, + {Metric: model.Metric{"s": "one"}, Value: 1}, + }) + if err != nil { + t.Fatal(err) + } + // NaN comes first in the result of Prometheus but is dropped: -Inf is lower than any number, NaN is lower still. + top, _ := keepTopSeries(all, 2) + if len(top) != 2 || top[0].Labels["s"] != "one" || top[1].Labels["s"] != "-inf" || top[1].Value != "-Inf" { + t.Errorf("top = %+v, want one and -inf", top) + } +} + +func TestRound(t *testing.T) { + tests := []struct{ value, want float64 }{ + {value: 12.34567, want: 12.35}, + {value: 0.000123456, want: 0.0001235}, + {value: 1234.567, want: 1235}, + {value: 123456.789, want: 123457}, + {value: -98765.4, want: -98765}, + // A timestamp keeps all its digits: with 4 significant digits, it would be 1767000000, 4 days earlier. + {value: 1767355200.123, want: 1767355200}, + } + for _, tt := range tests { + t.Run(fmt.Sprint(tt.value), func(t *testing.T) { + if got := round(tt.value); got != tt.want { + t.Errorf("round(%v) = %v, want %v", tt.value, got, tt.want) + } + }) + } +} + +func TestResolveEmptyScrapeInterval(t *testing.T) { + proxySpec := map[string]any{"kind": "HTTPProxy", "spec": map[string]any{"url": "http://prometheus.example.com"}} + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{ + // Perses accepts an empty scrape interval: the UI saves it when the field is cleared. + {Name: "cleared", Kind: prometheusDatasourceKind, PluginSpec: map[string]any{"proxy": proxySpec, "scrapeInterval": ""}}, + {Name: "invalid", Kind: prometheusDatasourceKind, PluginSpec: map[string]any{"proxy": proxySpec, "scrapeInterval": "fast"}}, + } + resolver := newTestPrometheus(t, perses).resolver + cleared, err := resolver.resolve(&DatasourceRef{Name: "cleared"}) + if err != nil { + t.Fatalf("resolve() error: %v", err) + } + if cleared.scrapeInterval != defaultScrapeInterval { + t.Errorf("scrape interval = %s, want the default %s", cleared.scrapeInterval, defaultScrapeInterval) + } + + // Without default, the error of a datasource that can't be used is its own, not a missing proxy. + perses.datasources = perses.datasources[1:] + _, err = resolver.resolve(nil) + if err == nil || !strings.Contains(err.Error(), "invalid plugin spec of global datasource 'invalid'") || strings.Contains(err.Error(), "proxy") { + t.Errorf("error = %v, want the invalid plugin spec", err) + } +} + +func TestResolveProjectDefaultWithoutGlobalAccess(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{{Name: "local", Project: "demo", Kind: prometheusDatasourceKind, Default: true}} + perses.forbidGlobalList = true + got, err := newTestPrometheus(t, perses).resolver.resolve(&DatasourceRef{Project: "demo"}) + if err != nil { + t.Fatalf("resolve() error: %v", err) + } + if got.ref != (DatasourceRef{Name: "local", Project: "demo"}) { + t.Errorf("resolve() = %+v", got.ref) + } + for _, request := range perses.Received() { + if strings.Contains(request.Path, "globaldatasources") { + t.Errorf("request %s %s: the global datasources are listed although the project has a default", request.Method, request.Path) + } + } +} + +func TestResolveProjectWithoutDefaultWithoutGlobalAccess(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{{Name: "local", Project: "demo", Kind: prometheusDatasourceKind}} + perses.forbidGlobalList = true + got, err := newTestPrometheus(t, perses).resolver.resolve(&DatasourceRef{Project: "demo"}) + if err != nil { + t.Fatalf("resolve() error: %v", err) + } + if got.ref != (DatasourceRef{Name: "local", Project: "demo"}) { + t.Errorf("resolve() = %+v", got.ref) + } +} + +func TestResolveProjectAmbiguousWithoutGlobalAccess(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{ + {Name: "a", Project: "demo", Kind: prometheusDatasourceKind}, + {Name: "b", Project: "demo", Kind: prometheusDatasourceKind}, + } + perses.forbidGlobalList = true + _, err := newTestPrometheus(t, perses).resolver.resolve(&DatasourceRef{Project: "demo"}) + if err == nil || !strings.Contains(err.Error(), "available Prometheus datasources: a (project demo), b (project demo)") { + t.Fatalf("resolve() error = %v, want the available datasources", err) + } +} + +func TestResolveEmptyProjectWithoutGlobalAccess(t *testing.T) { + perses := newFakePerses(t, nil) + perses.forbidGlobalList = true + _, err := newTestPrometheus(t, perses).resolver.resolve(&DatasourceRef{Project: "empty"}) + if err == nil || !strings.Contains(err.Error(), "error listing the global datasources") { + t.Fatalf("resolve() error = %v, want the error of the global list", err) + } +} + +func TestResolveCacheEvictsExpiredEntries(t *testing.T) { + resolver := newTestPrometheus(t, newFakePerses(t, nil)).resolver + now := testNow + resolver.now = func() time.Time { return now } + for _, ref := range []*DatasourceRef{{Name: "prom"}, {Name: "prom", Project: "demo"}, {Project: "demo"}} { + if _, err := resolver.resolve(ref); err != nil { + t.Fatal(err) + } + } + now = now.Add(2 * cacheTTL) + if _, err := resolver.resolve(nil); err != nil { + t.Fatal(err) + } + resolver.mutex.Lock() + defer resolver.mutex.Unlock() + if len(resolver.cache) != 1 { + t.Errorf("the cache has %d entries, want 1: the expired entries are kept", len(resolver.cache)) + } +} + +func TestErrorMessageKeepsValidUTF8(t *testing.T) { + got := errorMessage([]byte("a" + strings.Repeat("é", maxErrorLength))) + if !utf8.ValidString(got) || !strings.HasSuffix(got, "...") { + t.Errorf("errorMessage() = %q, want valid UTF-8 ending with ...", got) + } + // A short body that is not UTF-8, e.g. a Latin-1 error page. + if got = errorMessage([]byte("caf\xe9 down")); got != "caf down" { + t.Errorf("errorMessage() = %q, want the invalid bytes removed", got) + } +} + +func TestResolveCacheRefreshesTheSettings(t *testing.T) { + perses := newFakePerses(t, nil) + perses.datasources = []testDatasource{{Name: "prom", Kind: prometheusDatasourceKind, Default: true, ScrapeInterval: "30s", QueryParams: map[string]string{"dedup": "true"}}} + resolver := newTestPrometheus(t, perses).resolver + now := time.Now() + resolver.now = func() time.Time { return now } + if _, err := resolver.resolve(nil); err != nil { + t.Fatal(err) + } + perses.datasources = []testDatasource{{Name: "prom", Kind: prometheusDatasourceKind, Default: true, ScrapeInterval: "2m", QueryParams: map[string]string{"dedup": "false"}}} + cached, err := resolver.resolve(nil) + if err != nil { + t.Fatal(err) + } + if cached.scrapeInterval != 30*time.Second || cached.queryParams["dedup"] != "true" { + t.Errorf("cached = %+v, want the settings of the first resolution", cached) + } + now = now.Add(cacheTTL + time.Second) + refreshed, err := resolver.resolve(nil) + if err != nil { + t.Fatal(err) + } + if refreshed.scrapeInterval != 2*time.Minute || refreshed.queryParams["dedup"] != "false" { + t.Errorf("refreshed = %+v, want the new settings", refreshed) + } +} diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go new file mode 100644 index 0000000..e1fd8dc --- /dev/null +++ b/pkg/tools/prometheus/list.go @@ -0,0 +1,443 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "slices" + "strings" + "unicode/utf8" + + v1 "github.com/prometheus/client_golang/api/prometheus/v1" + "github.com/prometheus/common/model" + "golang.org/x/sync/errgroup" +) + +const ( + defaultMetricsLimit = 200 + // defaultMetadataMetricsLimit is the default limit of metric names listed with their metadata, which are larger. + defaultMetadataMetricsLimit = 50 + // maxMetadataMetricsLimit caps the metric names listed with their metadata, which may be looked up one by one + // (up to 2 requests each). + maxMetadataMetricsLimit = 50 + defaultLabelsLimit = 200 + defaultValuesLimit = 100 + maxListLimit = 1000 + maxMetadataMetrics = 20 + // metadataConcurrency is the number of metadata requests sent at the same time. + metadataConcurrency = 8 + // maxHelpLength caps the help of metrics listed with their metadata. + maxHelpLength = 80 +) + +// Selectors are series selectors (match[]), given as a list or as a single selector. +type Selectors []string + +func (s *Selectors) UnmarshalJSON(data []byte) error { + var single string + if err := json.Unmarshal(data, &single); err == nil { + *s = nil + if single != "" { + *s = Selectors{single} + } + return nil + } + var list []string + if err := json.Unmarshal(data, &list); err != nil { + return err + } + *s = list + return nil +} + +type ListMetricNamesInput struct { + Datasource *DatasourceRef `json:"datasource,omitempty"` + Match Selectors `json:"match,omitempty"` + Search string `json:"search,omitempty"` + TimeRange *TimeRangeInput `json:"time_range,omitempty"` + Limit int `json:"limit,omitempty"` + IncludeMetadata bool `json:"include_metadata,omitempty"` +} + +type ListLabelNamesInput struct { + Datasource *DatasourceRef `json:"datasource,omitempty"` + Match Selectors `json:"match,omitempty"` + TimeRange *TimeRangeInput `json:"time_range,omitempty"` + Limit int `json:"limit,omitempty"` +} + +type ListLabelValuesInput struct { + Datasource *DatasourceRef `json:"datasource,omitempty"` + Label string `json:"label"` + Match Selectors `json:"match,omitempty"` + Search string `json:"search,omitempty"` + TimeRange *TimeRangeInput `json:"time_range,omitempty"` + Limit int `json:"limit,omitempty"` +} + +type GetMetricMetadataInput struct { + Datasource *DatasourceRef `json:"datasource,omitempty"` + Metrics []string `json:"metrics"` +} + +// page tells which part of a list is returned. +type page struct { + Total int `json:"total"` + Returned int `json:"returned"` + Truncated bool `json:"truncated"` +} + +type metricInfo struct { + Name string `json:"name"` + Type string `json:"type,omitempty"` + Help string `json:"help,omitempty"` +} + +type metricNamesOutput struct { + Datasource DatasourceRef `json:"datasource"` + page + // Metrics holds names, or metricInfo with include_metadata. + Metrics any `json:"metrics"` + Warnings []string `json:"warnings,omitempty"` +} + +type labelNamesOutput struct { + Datasource DatasourceRef `json:"datasource"` + page + Labels []string `json:"labels"` + Warnings []string `json:"warnings,omitempty"` +} + +type labelValuesOutput struct { + Datasource DatasourceRef `json:"datasource"` + Label string `json:"label"` + page + Values []string `json:"values"` + Warnings []string `json:"warnings,omitempty"` +} + +type metricMetadataOutput struct { + Datasource DatasourceRef `json:"datasource"` + Metadata map[string][]v1.Metadata `json:"metadata"` + Missing []string `json:"missing"` + Warnings []string `json:"warnings,omitempty"` +} + +// listing is the result of a label names or label values request. +type listing struct { + datasource resolvedDatasource + values []string + warnings []string +} + +// listRequest is a request for label names or label values. +type listRequest struct { + datasource *DatasourceRef + // label is the label whose values are listed: the label names are listed when it is empty. + label string + match Selectors + timeRange *TimeRangeInput + // search keeps the values that contain it (ignoring case) when it is set. + search string +} + +// list resolves the time range and the datasource, then lists the label names or the values of a label. +func (p *prometheus) list(ctx context.Context, request listRequest) (*listing, error) { + label, match, search := request.label, request.match, request.search + start, end, _, err := resolveTimeRange(request.timeRange, p.now()) + if err != nil { + return nil, err + } + datasource, err := p.resolver.resolve(request.datasource) + if err != nil { + return nil, err + } + promAPI, err := p.newAPI(datasource) + if err != nil { + return nil, err + } + var values []string + var warnings v1.Warnings + var infos v1.Infos + if label == "" { + var names model.LabelNames + names, warnings, infos, err = promAPI.LabelNames(ctx, match, start, end) + for _, name := range names { + values = append(values, string(name)) + } + } else { + var labelValues model.LabelValues + labelValues, warnings, infos, err = promAPI.LabelValues(ctx, escapeLabelName(label), match, start, end) + for _, value := range labelValues { + values = append(values, string(value)) + } + } + if errors.Is(err, errTooMuchData) { + return nil, errListTooLarge + } + if err != nil { + return nil, apiError(datasource.ref, err) + } + if search != "" { + search = strings.ToLower(search) + values = slices.DeleteFunc(values, func(value string) bool { return !strings.Contains(strings.ToLower(value), search) }) + } + if values == nil { + values = []string{} + } + allWarnings := append(datasource.warnings(), warnings...) + return &listing{datasource: datasource, values: values, warnings: append(allWarnings, infos...)}, nil +} + +// errListTooLarge asks to narrow a list that Prometheus returns over maxBodyBytes: search can't, as it filters the list +// once received. +var errListTooLarge = errors.New("the list is too large (over 1 MiB): narrow it with match, e.g. " + + "{__name__=~\".*memory.*\"} or {job=\"node\"}, or a shorter time_range") + +// escapeLabelName returns the name of a label in the path of the label values endpoint, where the Prometheus client +// puts it as is. A name that is not a legacy label name (e.g. http.method or http:method) is escaped as Prometheus +// documents it (U__http_2e_method), which is required for '/' and matches the allowedEndpoints patterns of the Perses +// proxy ([a-zA-Z0-9_-]+): ':' is escaped too, unlike in model.EscapeName where it is valid in metric names. Prometheus +// unescapes every name starting with U__, so such a name is always escaped to be read back unchanged. +func escapeLabelName(label string) string { + if model.LegacyValidation.IsValidLabelName(label) && !strings.HasPrefix(label, "U__") { + return label + } + var escaped strings.Builder + escaped.WriteString("U__") + for i, r := range label { + switch { + case r == '_': + escaped.WriteString("__") + case (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9' && i > 0): + escaped.WriteRune(r) + case !utf8.ValidRune(r): + escaped.WriteString("_FFFD_") + default: + fmt.Fprintf(&escaped, "_%x_", r) + } + } + return escaped.String() +} + +// firstPage returns the first limit values (defaultLimit when limit is not set) and the page they form. +func firstPage(values []string, limit, defaultLimit int) ([]string, page) { + if limit <= 0 { + limit = defaultLimit + } + returned := values[:min(limit, maxListLimit, len(values))] + return returned, page{Total: len(values), Returned: len(returned), Truncated: len(returned) < len(values)} +} + +func (p *prometheus) listMetricNames(ctx context.Context, input ListMetricNamesInput) (*metricNamesOutput, error) { + names, err := p.list(ctx, listRequest{ + datasource: input.Datasource, label: model.MetricNameLabel, match: input.Match, timeRange: input.TimeRange, search: input.Search, + }) + if err != nil { + return nil, err + } + limit, defaultLimit := input.Limit, defaultMetricsLimit + if input.IncludeMetadata { + defaultLimit = defaultMetadataMetricsLimit + if limit > maxMetadataMetricsLimit { + limit = maxMetadataMetricsLimit + } + } + returned, namesPage := firstPage(names.values, limit, defaultLimit) + output := &metricNamesOutput{Datasource: names.datasource.ref, page: namesPage, Metrics: returned, Warnings: names.warnings} + if input.IncludeMetadata { + var metadata map[string][]v1.Metadata + var metadataErr error + if len(returned) > 0 { + metadata, metadataErr = p.metadata(ctx, names.datasource, "") + if errors.Is(metadataErr, errTooMuchData) { + // The metadata of all the metrics is too large: only the returned metrics are looked up. + metadata, metadataErr = p.lookupMetadata(ctx, names.datasource, returned) + } + } + if metadataErr != nil { + output.Warnings = append(output.Warnings, fmt.Sprintf("metadata unavailable (%s): use %s for specific metrics", + metadataErr, GetMetricMetadataToolName)) + } + infos := make([]metricInfo, 0, len(returned)) + for _, name := range returned { + info := metricInfo{Name: name} + if entries := findMetadata(metadata, name); len(entries) > 0 { + info.Type = string(entries[0].Type) + info.Help = shortenHelp(entries[0].Help) + } + infos = append(infos, info) + } + output.Metrics = infos + } + return output, nil +} + +func (p *prometheus) listLabelNames(ctx context.Context, input ListLabelNamesInput) (*labelNamesOutput, error) { + labels, err := p.list(ctx, listRequest{datasource: input.Datasource, match: input.Match, timeRange: input.TimeRange}) + if err != nil { + return nil, err + } + returned, labelsPage := firstPage(labels.values, input.Limit, defaultLabelsLimit) + return &labelNamesOutput{Datasource: labels.datasource.ref, page: labelsPage, Labels: returned, Warnings: labels.warnings}, nil +} + +func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesInput) (*labelValuesOutput, error) { + values, err := p.list(ctx, listRequest{ + datasource: input.Datasource, label: input.Label, match: input.Match, timeRange: input.TimeRange, search: input.Search, + }) + if err != nil { + return nil, err + } + returned, valuesPage := firstPage(values.values, input.Limit, defaultValuesLimit) + return &labelValuesOutput{Datasource: values.datasource.ref, Label: input.Label, page: valuesPage, Values: returned, Warnings: values.warnings}, nil +} + +// suffixTypes are the suffixes of the series of a metric family, with the types of the families that have them, as +// Prometheus matches metadata (metadataForMetric of its search API). A _created series isn't matched: it holds a +// timestamp, not a value of the family type. +var suffixTypes = map[string][]v1.MetricType{ + "_total": {v1.MetricTypeCounter}, + "_bucket": {v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram}, + "_count": {v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}, + "_sum": {v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}, + "_gcount": {v1.MetricTypeGaugeHistogram}, + "_gsum": {v1.MetricTypeGaugeHistogram}, + "_info": {v1.MetricTypeInfo}, +} + +// familyName returns the metric family that a series may belong to, e.g. http_requests for http_requests_total, and +// the types of the families with series of this suffix. As in Prometheus, a family name that already ends with _total +// or _info has a series of the same name (text format): x_total_total isn't a series of the family x_total. +func familyName(name string) (string, []v1.MetricType, bool) { + i := strings.LastIndexByte(name, '_') + if i <= 0 { + return "", nil, false + } + family, suffix := name[:i], name[i:] + types, found := suffixTypes[suffix] + if !found || ((suffix == "_total" || suffix == "_info") && strings.HasSuffix(family, suffix)) { + return "", nil, false + } + return family, types, true +} + +// findMetadata returns the metadata of a metric: its own, else the metadata of its family when the type of the +// family has series with this suffix (e.g. a histogram for _bucket, a counter for _total). +func findMetadata(metadata map[string][]v1.Metadata, name string) []v1.Metadata { + if entries := metadata[name]; len(entries) > 0 { + return entries + } + family, types, ok := familyName(name) + if !ok { + return nil + } + var entries []v1.Metadata + for _, entry := range metadata[family] { + if slices.Contains(types, entry.Type) { + entries = append(entries, entry) + } + } + return entries +} + +func shortenHelp(help string) string { + runes := []rune(help) + if len(runes) <= maxHelpLength { + return help + } + return strings.TrimSpace(string(runes[:maxHelpLength-1])) + "…" +} + +// metadata returns the metadata of a metric, or of all the metrics when metric is empty. +func (p *prometheus) metadata(ctx context.Context, datasource resolvedDatasource, metric string) (map[string][]v1.Metadata, error) { + promAPI, err := p.newAPI(datasource) + if err != nil { + return nil, err + } + metadata, err := promAPI.Metadata(ctx, metric, "") + if err != nil { + return nil, apiError(datasource.ref, err) + } + return metadata, nil +} + +// metricMetadata returns the metadata of a metric, looked up under its own name first, then under its family name. +func (p *prometheus) metricMetadata(ctx context.Context, datasource resolvedDatasource, metric string) ([]v1.Metadata, error) { + metadata, err := p.metadata(ctx, datasource, metric) + if err != nil { + return nil, err + } + if entries := metadata[metric]; len(entries) > 0 { + return entries, nil + } + family, _, ok := familyName(metric) + if !ok { + return nil, nil + } + if metadata, err = p.metadata(ctx, datasource, family); err != nil { + return nil, err + } + return findMetadata(metadata, metric), nil +} + +// lookupMetadata looks up the metadata of each metric (metricMetadata), metadataConcurrency at a time, and returns +// the metadata found by metric name. The first error cancels the lookups in progress and is returned. +func (p *prometheus) lookupMetadata(ctx context.Context, datasource resolvedDatasource, metrics []string) (map[string][]v1.Metadata, error) { + results := make([][]v1.Metadata, len(metrics)) + group, ctx := errgroup.WithContext(ctx) + group.SetLimit(metadataConcurrency) + for i, metric := range metrics { + group.Go(func() error { + var err error + results[i], err = p.metricMetadata(ctx, datasource, metric) + return err + }) + } + // The lookups write results from their goroutines: it can only be read once all of them have returned. + if err := group.Wait(); err != nil { + return nil, err + } + metadata := make(map[string][]v1.Metadata, len(metrics)) + for i, metric := range metrics { + if len(results[i]) > 0 { + metadata[metric] = results[i] + } + } + return metadata, nil +} + +func (p *prometheus) getMetricMetadata(ctx context.Context, input GetMetricMetadataInput) (*metricMetadataOutput, error) { + if len(input.Metrics) > maxMetadataMetrics { + return nil, fmt.Errorf("too many metrics: at most %d per call", maxMetadataMetrics) + } + datasource, err := p.resolver.resolve(input.Datasource) + if err != nil { + return nil, err + } + metadata, err := p.lookupMetadata(ctx, datasource, input.Metrics) + if err != nil { + return nil, err + } + output := &metricMetadataOutput{Datasource: datasource.ref, Metadata: metadata, Missing: []string{}, Warnings: datasource.warnings()} + for _, metric := range input.Metrics { + if _, found := metadata[metric]; !found { + output.Missing = append(output.Missing, metric) + } + } + return output, nil +} diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go new file mode 100644 index 0000000..7277b92 --- /dev/null +++ b/pkg/tools/prometheus/prometheus.go @@ -0,0 +1,311 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Package prometheus exposes compact tools to discover and query the metrics of the Prometheus datasources of +// Perses, through the Perses datasource proxy. +package prometheus + +import ( + "context" + "fmt" + "time" + + "github.com/google/jsonschema-go/jsonschema" + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/perses/mcp-server/pkg/tools" + "github.com/perses/mcp-server/pkg/tools/resource" + apiClient "github.com/perses/perses/pkg/client/api/v1" +) + +const ( + ListMetricNamesToolName = "perses_list_prometheus_metric_names" + ListLabelNamesToolName = "perses_list_prometheus_label_names" + ListLabelValuesToolName = "perses_list_prometheus_label_values" + GetMetricMetadataToolName = "perses_get_prometheus_metric_metadata" + QueryToolName = "perses_query_prometheus" +) + +type prometheus struct { + client apiClient.ClientInterface + resolver *resolver + now func() time.Time +} + +func New(client apiClient.ClientInterface) resource.Resource { + return &prometheus{client: client, resolver: newResolver(client), now: time.Now} +} + +func (p *prometheus) GetTools() []*tools.Tool { + return []*tools.Tool{ + p.ListMetricNames(), + p.ListLabelNames(), + p.ListLabelValues(), + p.GetMetricMetadata(), + p.Query(), + } +} + +// Create is not supported for Prometheus datasources +func (p *prometheus) Create() *tools.Tool { return nil } + +// Update is not supported for Prometheus datasources +func (p *prometheus) Update() *tools.Tool { return nil } + +// Delete is not supported for Prometheus datasources +func (p *prometheus) Delete() *tools.Tool { return nil } + +// List is not used: the listing tools are ListMetricNames, ListLabelNames and ListLabelValues +func (p *prometheus) List() *tools.Tool { return nil } + +// Get is not used: the metadata tool is GetMetricMetadata +func (p *prometheus) Get() *tools.Tool { return nil } + +func (p *prometheus) ListMetricNames() *tools.Tool { + tool := &mcp.Tool{ + Name: ListMetricNamesToolName, + Description: "List the metric names of a Prometheus datasource. Use it before writing PromQL: never guess metric names. " + + "Narrow it with `search` (e.g. \"memory\") and/or `match` (e.g. \"{job=\\\"prometheus\\\"}\"); " + + "`include_metadata: true` adds the type (counter, gauge...) and help of each metric.", + Annotations: readOnlyAnnotations("Lists Prometheus metric names"), + InputSchema: objectSchema(map[string]*jsonschema.Schema{ + "match": matchSchema(), + "search": searchSchema(), + "time_range": discoveryTimeRangeSchema(), + "limit": limitSchema(fmt.Sprintf("Maximum number of metrics returned (default %d, max %d; with include_metadata default %d, max %d).", + defaultMetricsLimit, maxListLimit, defaultMetadataMetricsLimit, maxMetadataMetricsLimit), maxListLimit), + "include_metadata": { + Type: tools.SchemaTypeBoolean, + Description: "Add the type and help (shortened) of each returned metric. Defaults to false.", + }, + }), + } + handler := func(ctx context.Context, _ *mcp.CallToolRequest, input ListMetricNamesInput) (*mcp.CallToolResult, any, error) { //nolint:unparam + output, err := p.listMetricNames(ctx, input) + if err != nil { + return nil, nil, err + } + return jsonResult(output) + } + return readOnlyTool(tool, func(server *mcp.Server) { mcp.AddTool(server, tool, handler) }) +} + +func (p *prometheus) ListLabelNames() *tools.Tool { + tool := &mcp.Tool{ + Name: ListLabelNamesToolName, + Description: "List the label names of a Prometheus datasource, e.g. to know how to group or filter a metric. Pass " + + "`match` to get the labels of specific series, e.g. \"process_cpu_seconds_total\".", + Annotations: readOnlyAnnotations("Lists Prometheus label names"), + InputSchema: objectSchema(map[string]*jsonschema.Schema{ + "match": matchSchema(), + "time_range": discoveryTimeRangeSchema(), + "limit": limitSchema(fmt.Sprintf("Maximum number of labels returned (default %d, max %d).", defaultLabelsLimit, maxListLimit), maxListLimit), + }), + } + handler := func(ctx context.Context, _ *mcp.CallToolRequest, input ListLabelNamesInput) (*mcp.CallToolResult, any, error) { //nolint:unparam + output, err := p.listLabelNames(ctx, input) + if err != nil { + return nil, nil, err + } + return jsonResult(output) + } + return readOnlyTool(tool, func(server *mcp.Server) { mcp.AddTool(server, tool, handler) }) +} + +func (p *prometheus) ListLabelValues() *tools.Tool { + tool := &mcp.Tool{ + Name: ListLabelValuesToolName, + Description: "List the values of a label of a Prometheus datasource, e.g. the jobs (`label: \"job\"`) or the instances " + + "of a job (`label: \"instance\", match: \"{job=\\\"node\\\"}\"`). Use it to write exact label matchers.", + Annotations: readOnlyAnnotations("Lists Prometheus label values"), + InputSchema: objectSchema(map[string]*jsonschema.Schema{ + "label": { + Type: tools.SchemaTypeString, MinLength: new(1), + Description: "Label name, e.g. \"job\", or a UTF-8 label name of Prometheus 3, e.g. \"http.method\".", + }, + "match": matchSchema(), + "search": searchSchema(), + "time_range": discoveryTimeRangeSchema(), + "limit": limitSchema(fmt.Sprintf("Maximum number of values returned (default %d, max %d).", defaultValuesLimit, maxListLimit), maxListLimit), + }, "label"), + } + handler := func(ctx context.Context, _ *mcp.CallToolRequest, input ListLabelValuesInput) (*mcp.CallToolResult, any, error) { //nolint:unparam + output, err := p.listLabelValues(ctx, input) + if err != nil { + return nil, nil, err + } + return jsonResult(output) + } + return readOnlyTool(tool, func(server *mcp.Server) { mcp.AddTool(server, tool, handler) }) +} + +func (p *prometheus) GetMetricMetadata() *tools.Tool { + tool := &mcp.Tool{ + Name: GetMetricMetadataToolName, + Description: "Get the type (counter, gauge, histogram, summary), help and unit of Prometheus metrics, e.g. " + + "`metrics: [\"go_memstats_heap_inuse_bytes\"]`. Use it to pick the right PromQL: rate() on counters, " + + "histogram_quantile() on histogram buckets, units of the values.", + Annotations: readOnlyAnnotations("Gets Prometheus metric metadata"), + InputSchema: objectSchema(map[string]*jsonschema.Schema{ + "metrics": { + Type: tools.SchemaTypeArray, + Items: &jsonschema.Schema{Type: tools.SchemaTypeString, MinLength: new(1)}, + MinItems: new(1), MaxItems: new(maxMetadataMetrics), + Description: fmt.Sprintf("Metric names (1 to %d). The series of histograms, summaries, counters and info "+ + "metrics (_bucket, _count, _sum, _gcount, _gsum, _total, _info) are also looked up under their family "+ + "name.", maxMetadataMetrics), + }, + }, "metrics"), + } + handler := func(ctx context.Context, _ *mcp.CallToolRequest, input GetMetricMetadataInput) (*mcp.CallToolResult, any, error) { //nolint:unparam + output, err := p.getMetricMetadata(ctx, input) + if err != nil { + return nil, nil, err + } + return jsonResult(output) + } + return readOnlyTool(tool, func(server *mcp.Server) { mcp.AddTool(server, tool, handler) }) +} + +func (p *prometheus) Query() *tools.Tool { + tool := &mcp.Tool{ + Name: QueryToolName, + Description: "Run a PromQL query and get a compact result. " + + "type \"instant\" (default) returns the value of each series at `time` (default now), sorted by value, e.g. " + + "`query: \"topk(5, sum by (handler) (rate(prometheus_http_requests_total[5m])))\"`. type \"range\" returns " + + "per-series statistics over `time_range` (min, max, avg, last and when min/max happened), never raw points. " + + "Aggregate (sum by, topk) to keep results small; labels shared by all series are returned once in " + + "commonLabels. Values keep 4 significant digits, and all the digits of their integer part. " + + "Errors of Prometheus (e.g. bad_data: parse error) are returned unchanged.", + Annotations: readOnlyAnnotations("Queries a Prometheus datasource"), + InputSchema: objectSchema(map[string]*jsonschema.Schema{ + "query": {Type: tools.SchemaTypeString, MinLength: new(1), Description: "PromQL expression. Use rate() on counters."}, + "type": { + Type: tools.SchemaTypeString, Enum: []any{instantQuery, rangeQuery}, + Description: "instant (default): values at `time`. range: statistics over `time_range`.", + }, + "time": {Type: tools.SchemaTypeString, Description: "Instant queries only: evaluation time (RFC 3339). Defaults to now."}, + "time_range": timeRangeSchema("Range queries only: time range of the statistics. Defaults to the past hour."), + "step": { + Type: tools.SchemaTypeString, + Description: "Range queries only: resolution, e.g. \"1m\". Defaults to about 500 points, at least the scrape " + + "interval of the datasource (1m when not set). Raised if needed to stay under 11000 points.", + }, + "limit": limitSchema(fmt.Sprintf("Maximum number of series returned, highest values first (default %d, max %d).", + defaultSeriesLimit, maxSeriesLimit), maxSeriesLimit), + "time_zone": {Type: tools.SchemaTypeString, Description: "IANA time zone of minAt/maxAt (RFC 3339 with the offset of the zone), e.g. \"Europe/Berlin\". Defaults to UTC."}, + }, "query"), + } + handler := func(ctx context.Context, _ *mcp.CallToolRequest, input QueryInput) (*mcp.CallToolResult, any, error) { //nolint:unparam + output, err := p.query(ctx, input) + if err != nil { + return nil, nil, err + } + return jsonResult(output) + } + return readOnlyTool(tool, func(server *mcp.Server) { mcp.AddTool(server, tool, handler) }) +} + +func readOnlyTool(tool *mcp.Tool, register func(server *mcp.Server)) *tools.Tool { + return &tools.Tool{ + MCPTool: tool, + IsWriteTool: false, + ResourceType: tools.PrometheusResource, + RegisterWith: register, + } +} + +func readOnlyAnnotations(title string) *mcp.ToolAnnotations { + return &mcp.ToolAnnotations{ + Title: title, + ReadOnlyHint: true, + DestructiveHint: new(false), + IdempotentHint: true, + OpenWorldHint: new(false), + } +} + +func jsonResult(output any) (*mcp.CallToolResult, any, error) { + result, err := tools.JSONResult(output) + if err != nil { + return nil, nil, fmt.Errorf("error marshalling the result: %w", err) + } + return result, nil, nil +} + +// objectSchema returns the input schema of a tool: the properties and the optional datasource. +func objectSchema(properties map[string]*jsonschema.Schema, required ...string) *jsonschema.Schema { + properties["datasource"] = &jsonschema.Schema{ + Type: tools.SchemaTypeObject, + Description: "The Prometheus datasource to query. Omit it (or omit name) to use the default Prometheus " + + "datasource: the project's default when project is set, else the global default.", + Properties: map[string]*jsonschema.Schema{ + "name": { + Type: tools.SchemaTypeString, MinLength: new(1), MaxLength: new(75), Pattern: tools.PatternResourceName, + Description: "Datasource name, e.g. \"prometheus\".", + }, + "project": { + Type: tools.SchemaTypeString, MinLength: new(1), MaxLength: new(75), Pattern: tools.PatternResourceName, + Description: "Project of a project datasource. Omit for a global datasource.", + }, + }, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + } + return &jsonschema.Schema{ + Type: tools.SchemaTypeObject, + Properties: properties, + Required: required, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + } +} + +func matchSchema() *jsonschema.Schema { + selector := func() *jsonschema.Schema { return &jsonschema.Schema{Type: tools.SchemaTypeString, MinLength: new(1)} } + return &jsonschema.Schema{ + Description: "Series selector, or list of series selectors OR-ed together, restricting the result to the " + + "matching series, e.g. \"{job=\\\"prometheus\\\"}\" or [\"up\", \"process_cpu_seconds_total\"].", + AnyOf: []*jsonschema.Schema{ + selector(), + {Type: tools.SchemaTypeArray, Items: selector(), MaxItems: new(10)}, + }, + } +} + +func searchSchema() *jsonschema.Schema { + return &jsonschema.Schema{Type: tools.SchemaTypeString, Description: "Case-insensitive substring filter, e.g. \"memory\"."} +} + +func limitSchema(description string, maxLimit int) *jsonschema.Schema { + return &jsonschema.Schema{Type: "integer", Minimum: new(1.0), Maximum: new(float64(maxLimit)), Description: description} +} + +func timeRangeSchema(description string) *jsonschema.Schema { + return &jsonschema.Schema{ + Type: tools.SchemaTypeObject, + Description: description, + Properties: map[string]*jsonschema.Schema{ + "past_duration": { + Type: tools.SchemaTypeString, + Description: "Relative range ending now: \"15m\", \"1h\" (default), \"6h\", \"24h\", \"7d\"...", + }, + "start": {Type: tools.SchemaTypeString, Description: "Absolute range start (RFC 3339). Do not combine with past_duration."}, + "end": {Type: tools.SchemaTypeString, Description: "Absolute range end (RFC 3339), defaults to now. Requires start."}, + }, + AdditionalProperties: &jsonschema.Schema{Not: &jsonschema.Schema{}}, + } +} + +func discoveryTimeRangeSchema() *jsonschema.Schema { + return timeRangeSchema("Time range of the series to consider. Defaults to the past hour. Prometheus applies it " + + "approximately (by storage block): the list may include series without samples in it, e.g. series that stopped " + + "a few hours ago.") +} diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go new file mode 100644 index 0000000..82aa9ed --- /dev/null +++ b/pkg/tools/prometheus/prometheus_test.go @@ -0,0 +1,748 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "reflect" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/perses/mcp-server/pkg/tools" + "github.com/perses/mcp-server/pkg/tools/internal/tooltest" + apiClient "github.com/perses/perses/pkg/client/api" + "github.com/perses/perses/pkg/client/perseshttp" + "github.com/perses/spec/go/common" + v1 "github.com/prometheus/client_golang/api/prometheus/v1" +) + +func TestGetTools(t *testing.T) { + want := []string{ListMetricNamesToolName, ListLabelNamesToolName, ListLabelValuesToolName, GetMetricMetadataToolName, QueryToolName} + got := New(nil).GetTools() + if len(got) != len(want) { + t.Fatalf("got %d tools, want %d", len(got), len(want)) + } + for i, tool := range got { + if tool.MCPTool.Name != want[i] || tool.IsWriteTool || tool.ResourceType != tools.PrometheusResource { + t.Errorf("tool %d = %s (write %v, resource %s)", i, tool.MCPTool.Name, tool.IsWriteTool, tool.ResourceType) + } + annotations := tool.MCPTool.Annotations + if !annotations.ReadOnlyHint || *annotations.DestructiveHint || !annotations.IdempotentHint || *annotations.OpenWorldHint { + t.Errorf("tool %s annotations = %+v", tool.MCPTool.Name, annotations) + } + } +} + +func TestListMetricNames(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/label/__name__/values": ok(`["go_memstats_heap_inuse_bytes","process_resident_memory_bytes","up","go_memstats_sys_bytes","x_memstats_seconds_bucket"]`), + }) + perses.metadata = map[string][]v1.Metadata{ + "go_memstats_heap_inuse_bytes": {{Type: v1.MetricTypeGauge, Help: strings.Repeat("h", 200)}}, + "x_memstats_seconds": {{Type: v1.MetricTypeHistogram, Help: "h"}}, + } + session := connect(t, perses) + + output := decode(t, call(t, session, ListMetricNamesToolName, map[string]any{ + "search": "MEMSTATS", "match": []any{`{job="prometheus"}`, "up"}, "limit": 1, "include_metadata": true, + }, false)) + if output["total"] != 3.0 || output["returned"] != 1.0 || output["truncated"] != true { + t.Errorf("output = %v", output) + } + if !reflect.DeepEqual(output["datasource"], map[string]any{"name": "prom"}) { + t.Errorf("datasource = %v", output["datasource"]) + } + metric := output["metrics"].([]any)[0].(map[string]any) + if metric["name"] != "go_memstats_heap_inuse_bytes" || metric["type"] != "gauge" || len([]rune(metric["help"].(string))) != maxHelpLength { + t.Errorf("metric = %v", metric) + } + params := perses.paramsOf(globalProxy + "/api/v1/label/__name__/values") + if !reflect.DeepEqual(params["match[]"], []string{`{job="prometheus"}`, "up"}) { + t.Errorf("match[] = %v", params["match[]"]) + } + if params.Get("start") != "1767351600" || params.Get("end") != "1767355200" { + t.Errorf("time range = %s - %s", params.Get("start"), params.Get("end")) + } + + output = decode(t, call(t, session, ListMetricNamesToolName, map[string]any{"search": "memstats", "include_metadata": true}, false)) + if bucket := output["metrics"].([]any)[2].(map[string]any); bucket["type"] != "histogram" { + t.Errorf("histogram bucket = %v", bucket) + } + + // A single selector is accepted as a string. + output = decode(t, call(t, session, ListMetricNamesToolName, map[string]any{"match": "up"}, false)) + if output["total"] != 5.0 || output["truncated"] != false { + t.Errorf("output = %v", output) + } + if _, isString := output["metrics"].([]any)[0].(string); !isString { + t.Errorf("metrics without metadata = %v", output["metrics"]) + } + if got := perses.paramsOf(globalProxy + "/api/v1/label/__name__/values")["match[]"]; !reflect.DeepEqual(got, []string{"up"}) { + t.Errorf("match[] = %v", got) + } +} + +func TestListLabels(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + projectProxy + "/api/v1/labels": ok(`["__name__","instance","job"]`), + projectProxy + "/api/v1/label/job/values": ok(`["avalanche","perses","prometheus"]`), + }) + session := connect(t, perses) + datasource := map[string]any{"name": "prom", "project": "demo"} + + output := decode(t, call(t, session, ListLabelNamesToolName, map[string]any{"datasource": datasource, "limit": 2}, false)) + if !reflect.DeepEqual(output["labels"], []any{"__name__", "instance"}) || output["total"] != 3.0 || output["truncated"] != true { + t.Errorf("label names = %v", output) + } + + output = decode(t, call(t, session, ListLabelValuesToolName, map[string]any{ + "datasource": datasource, "label": "job", "search": "PER", "time_range": map[string]any{"past_duration": "6h"}, + }, false)) + if !reflect.DeepEqual(output["values"], []any{"perses"}) || output["label"] != "job" || output["total"] != 1.0 { + t.Errorf("label values = %v", output) + } + if !reflect.DeepEqual(output["datasource"], datasource) { + t.Errorf("datasource = %v", output["datasource"]) + } + if got := perses.paramsOf(projectProxy + "/api/v1/label/job/values").Get("start"); got != "1767333600" { + t.Errorf("start = %s", got) + } + + call(t, session, ListLabelValuesToolName, map[string]any{"label": ""}, true) +} + +func TestListLabelValuesOfUTF8Label(t *testing.T) { + // The label name is escaped in the path, as Prometheus documents it: the fake answers this path only. + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/label/U__http_2e_method/values": ok(`["GET","POST"]`)}) + session := connect(t, perses) + output := decode(t, call(t, session, ListLabelValuesToolName, map[string]any{"label": "http.method"}, false)) + if output["label"] != "http.method" || !reflect.DeepEqual(output["values"], []any{"GET", "POST"}) { + t.Errorf("output = %v", output) + } + output = decode(t, call(t, session, ListLabelValuesToolName, map[string]any{"label": "http.method", "search": "po"}, false)) + if !reflect.DeepEqual(output["values"], []any{"POST"}) { + t.Errorf("values with search = %v", output["values"]) + } +} + +func TestListLabelValuesOfLabelWithColon(t *testing.T) { + // ':' is escaped in the path, as the Perses proxy allows [a-zA-Z0-9_-]+ only: the fake answers this path only. + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/label/U__http_3a_method/values": ok(`["GET"]`)}) + session := connect(t, perses) + output := decode(t, call(t, session, ListLabelValuesToolName, map[string]any{"label": "http:method"}, false)) + if output["label"] != "http:method" || !reflect.DeepEqual(output["values"], []any{"GET"}) { + t.Errorf("output = %v", output) + } +} + +func TestProxyRequestsUseThePersesCredentials(t *testing.T) { + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/labels": ok(`["job"]`)}) + call(t, connect(t, perses), ListLabelNamesToolName, nil, false) + received := perses.Received() + if len(received) == 0 { + t.Fatal("no request received") + } + for _, request := range received { + if request.Authorization != tooltest.Authorization { + t.Errorf("%s %s: Authorization = %q, want %q", request.Method, request.Path, request.Authorization, tooltest.Authorization) + } + } +} + +func TestProxyPathIsAppendedToTheBasePath(t *testing.T) { + perses := &tooltest.Perses{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"status":"success","data":["node"]}`)) + })} + server := httptest.NewServer(perses) + t.Cleanup(server.Close) + // Perses served under a path, with a query string in its base URL. + client := apiClient.NewWithClient(&perseshttp.RESTClient{ + BaseURL: common.MustParseURL(server.URL + "/perses?tenant=demo"), + Client: server.Client(), + }).V1() + promAPI, err := New(client).(*prometheus).newAPI(resolvedDatasource{ref: DatasourceRef{Name: "prom"}}) + if err != nil { + t.Fatal(err) + } + if _, _, _, err = promAPI.LabelValues(context.Background(), "job", nil, time.Time{}, time.Time{}); err != nil { + t.Fatal(err) + } + received := perses.Received() + if len(received) != 1 || received[0].Path != "/perses"+globalProxy+"/api/v1/label/job/values" || received[0].RawQuery != "tenant=demo" { + t.Errorf("requests = %+v, want the label values of the proxy under /perses, with the query of the base URL", received) + } +} + +func TestListMetricNamesWithUnavailableMetadata(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/label/__name__/values": ok(`["up"]`), + globalProxy + "/api/v1/metadata": {status: http.StatusBadGateway, body: "upstream down"}, + }) + output := decode(t, call(t, connect(t, perses), ListMetricNamesToolName, map[string]any{"include_metadata": true}, false)) + if !reflect.DeepEqual(output["metrics"], []any{map[string]any{"name": "up"}}) { + t.Errorf("metrics = %v, want the names as objects", output["metrics"]) + } + warnings, _ := output["warnings"].([]any) + if len(warnings) != 1 || !strings.Contains(warnings[0].(string), "HTTP 502 Bad Gateway: upstream down") || !strings.Contains(warnings[0].(string), GetMetricMetadataToolName) { + t.Errorf("warnings = %v", output["warnings"]) + } +} + +func TestGetMetricMetadata(t *testing.T) { + perses := newFakePerses(t, nil) + perses.metadata = map[string][]v1.Metadata{ + "up": {{Type: v1.MetricTypeGauge, Help: "Target is up."}}, + "queue_count": {{Type: v1.MetricTypeGauge, Help: "Items in the queue."}}, + "x_seconds": {{Type: v1.MetricTypeHistogram, Help: "Latency."}}, + "requests": {{Type: v1.MetricTypeCounter, Help: "Requests."}}, + "errors_total": {{Type: v1.MetricTypeCounter, Help: "Errors."}}, + "temperature": {{Type: v1.MetricTypeGauge, Help: "Temperature."}}, + "jobs_waiting": {{Type: v1.MetricTypeGaugeHistogram, Help: "Waiting jobs."}}, + "build": {{Type: v1.MetricTypeInfo, Help: "Build information."}}, + } + output := decode(t, call(t, connect(t, perses), GetMetricMetadataToolName, map[string]any{ + "metrics": []any{ + "up", "queue_count", "x_seconds_bucket", "requests_total", "temperature_total", "nope", + "jobs_waiting_gcount", "jobs_waiting_gsum", "jobs_waiting_created", "build_info", + "errors_total", "errors_total_total", "requests_created", + }, + }, false)) + want := map[string]any{ + "up": []any{map[string]any{"type": "gauge", "help": "Target is up.", "unit": ""}}, + "queue_count": []any{map[string]any{"type": "gauge", "help": "Items in the queue.", "unit": ""}}, + "x_seconds_bucket": []any{map[string]any{"type": "histogram", "help": "Latency.", "unit": ""}}, + "requests_total": []any{map[string]any{"type": "counter", "help": "Requests.", "unit": ""}}, + "jobs_waiting_gcount": []any{map[string]any{"type": "gaugehistogram", "help": "Waiting jobs.", "unit": ""}}, + "jobs_waiting_gsum": []any{map[string]any{"type": "gaugehistogram", "help": "Waiting jobs.", "unit": ""}}, + "build_info": []any{map[string]any{"type": "info", "help": "Build information.", "unit": ""}}, + "errors_total": []any{map[string]any{"type": "counter", "help": "Errors.", "unit": ""}}, + } + if !reflect.DeepEqual(output["metadata"], want) { + t.Errorf("metadata =\n%v\nwant\n%v", output["metadata"], want) + } + // Like in Prometheus: temperature is a gauge, not the family of temperature_total; a _created series holds a + // timestamp, not a value of its family; x_total_total isn't a series of the family x_total. + wantMissing := []any{"temperature_total", "nope", "jobs_waiting_created", "errors_total_total", "requests_created"} + if !reflect.DeepEqual(output["missing"], wantMissing) { + t.Errorf("missing = %v, want %v", output["missing"], wantMissing) + } + // A metric with metadata under its own name is looked up once. + if count := countMetadataRequests(perses, "queue_count") + countMetadataRequests(perses, "queue"); count != 1 { + t.Errorf("%d metadata requests for queue_count, want 1", count) + } +} + +// countMetadataRequests returns the number of metadata requests of the global datasource for metric. +func countMetadataRequests(perses *fakePerses, metric string) int { + count := 0 + for _, request := range perses.Received() { + if params, err := url.ParseQuery(request.RawQuery); err == nil && request.Path == globalProxy+"/api/v1/metadata" && params.Get("metric") == metric { + count++ + } + } + return count +} + +func TestQueryInstant(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/query": ok(`{"resultType":"vector","result":[` + + `{"metric":{"__name__":"x","job":"p","handler":"/a"},"value":[1767355200,"0.5"]},` + + `{"metric":{"__name__":"x","job":"p","handler":"/b"},"value":[1767355200,"NaN"]},` + + `{"metric":{"__name__":"x","job":"p","handler":"/c"},"value":[1767355200,"12.34567"]},` + + `{"metric":{"__name__":"x","job":"p","handler":"/d"},"value":[1767355200,"0"]}]},"warnings":["careful"]`), + }) + output := decode(t, call(t, connect(t, perses), QueryToolName, map[string]any{"query": "x", "limit": 3, "time": "2026-01-02T11:00:00+01:00"}, false)) + want := map[string]any{ + "datasource": map[string]any{"name": "prom"}, + "resultType": "vector", + "time": "2026-01-02T10:00:00Z", + "seriesCount": 4.0, + "returned": 3.0, + "commonLabels": map[string]any{"__name__": "x", "job": "p"}, + "series": []any{ + map[string]any{"labels": map[string]any{"handler": "/c"}, "value": 12.35}, + map[string]any{"labels": map[string]any{"handler": "/a"}, "value": 0.5}, + map[string]any{"labels": map[string]any{"handler": "/d"}, "value": 0.0}, + }, + "warnings": []any{"careful"}, + } + if !reflect.DeepEqual(output, want) { + t.Errorf("output =\n%v\nwant\n%v", output, want) + } + params := perses.paramsOf(globalProxy + "/api/v1/query") + if params.Get("time") != "1767348000" || params.Get("query") != "x" { + t.Errorf("params = %v", params) + } +} + +func TestQueryRange(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/query_range": ok(`{"resultType":"matrix","result":[` + + `{"metric":{"job":"a"},"values":[[1767355200,"1"],[1767355260,"3"]]},` + + `{"metric":{"job":"b"},"values":[[1767355200,"5"],[1767355260,"4"]]},` + + `{"metric":{"job":"c"},"values":[[1767355200,"NaN"]]}]}`), + }) + session := connect(t, perses) + output := decode(t, call(t, session, QueryToolName, map[string]any{ + "query": "up", "type": "range", "time_range": map[string]any{"past_duration": "6h"}, "time_zone": "Europe/Berlin", + }, false)) + want := map[string]any{ + "datasource": map[string]any{"name": "prom"}, + "resultType": "matrix", + "timeRange": map[string]any{"pastDuration": "6h"}, + // The datasource sets no scrape interval: the step is at least 1m, its default in the Perses UI. + "step": "1m", + "seriesCount": 3.0, + "returned": 2.0, + "series": []any{ + map[string]any{"labels": map[string]any{"job": "b"}, "min": 4.0, "max": 5.0, "avg": 4.5, "last": 4.0, "minAt": "2026-01-02T13:01:00+01:00", "maxAt": "2026-01-02T13:00:00+01:00"}, + map[string]any{"labels": map[string]any{"job": "a"}, "min": 1.0, "max": 3.0, "avg": 2.0, "last": 3.0, "minAt": "2026-01-02T13:00:00+01:00", "maxAt": "2026-01-02T13:01:00+01:00"}, + }, + "warnings": []any{"1 series are not returned: they only have NaN or infinite samples in the time range"}, + } + if !reflect.DeepEqual(output, want) { + t.Errorf("output =\n%v\nwant\n%v", output, want) + } + params := perses.paramsOf(globalProxy + "/api/v1/query_range") + if params.Get("step") != "60" || params.Get("start") != "1767333600" || params.Get("end") != "1767355200" { + t.Errorf("params = %v", params) + } + + output = decode(t, call(t, session, QueryToolName, map[string]any{ + "query": "up", "type": "range", "step": "5m", + "time_range": map[string]any{"start": "2026-01-02T10:00:00Z", "end": "2026-01-02T11:00:00Z"}, + }, false)) + if output["step"] != "5m" || !reflect.DeepEqual(output["timeRange"], map[string]any{"start": "2026-01-02T10:00:00Z", "end": "2026-01-02T11:00:00Z"}) { + t.Errorf("output = %v", output) + } + if got := perses.paramsOf(globalProxy + "/api/v1/query_range").Get("step"); got != "300" { + t.Errorf("explicit step = %s", got) + } + + // An explicit subsecond step under the limit of points is sent unchanged. + output = decode(t, call(t, session, QueryToolName, map[string]any{ + "query": "up", "type": "range", "step": "100ms", + "time_range": map[string]any{"start": "2026-01-02T10:00:00Z", "end": "2026-01-02T10:01:00Z"}, + }, false)) + if output["step"] != "100ms" { + t.Errorf("subsecond step = %v", output["step"]) + } + if got := perses.paramsOf(globalProxy + "/api/v1/query_range").Get("step"); got != "0.1" { + t.Errorf("subsecond step sent = %s, want 0.1", got) + } +} + +func TestQueryInstantKeepsFractionalSeconds(t *testing.T) { + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/query": ok(`{"resultType":"vector","result":[]}`)}) + output := decode(t, call(t, connect(t, perses), QueryToolName, map[string]any{"query": "up", "time": "2026-01-02T10:00:00.250Z"}, false)) + if output["time"] != "2026-01-02T10:00:00.25Z" { + t.Errorf("time = %v, want the time queried", output["time"]) + } + if got := perses.paramsOf(globalProxy + "/api/v1/query").Get("time"); got != "1767348000.25" { + t.Errorf("time sent = %s", got) + } +} + +func TestQueryScalar(t *testing.T) { + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/query": ok(`{"resultType":"scalar","result":[1767355200,"42.123456"]}`)}) + output := decode(t, call(t, connect(t, perses), QueryToolName, map[string]any{"query": "scalar(up)"}, false)) + if output["resultType"] != "scalar" || output["value"] != 42.12 { + t.Errorf("output = %v", output) + } + if _, found := output["series"]; found { + t.Errorf("scalar output has series: %v", output) + } +} + +// A redirect is never followed, even with a Prometheus error body: the Prometheus client would follow it, and the +// transport would add the Perses credentials to the request. +func TestRedirectWithPrometheusErrorIsNotFollowed(t *testing.T) { + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("the redirect is followed: %s %s (Authorization %q)", r.Method, r.URL.Path, r.Header.Get("Authorization")) + })) + defer other.Close() + location := other.URL + "/steal" + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/query": { + status: http.StatusFound, location: location, body: `{"status":"error","errorType":"bad_data","error":"redirect"}`, + }}) + text := call(t, connect(t, perses), QueryToolName, map[string]any{"query": "up"}, true) + if want := "error querying global datasource 'prom': HTTP 302 Found: the redirect to " + location + " is not followed"; !strings.Contains(text, want) { + t.Errorf("error %q does not contain %q", text, want) + } +} + +func TestQueryErrors(t *testing.T) { + large := `{"status":"success","data":{"resultType":"vector","result":[` + strings.Repeat(" ", maxBodyBytes) + `]}}` + tests := []struct { + name string + answer *answer + arguments map[string]any + want string + }{ + { + name: "bad PromQL is returned unchanged", + answer: &answer{status: http.StatusBadRequest, body: `{"status":"error","errorType":"bad_data","error":"invalid parameter \"query\": 1:5: parse error: unclosed left parenthesis"}`}, + want: `bad_data: invalid parameter "query": 1:5: parse error: unclosed left parenthesis`, + }, + { + name: "Perses error keeps its message", + answer: &answer{status: http.StatusNotFound, body: `{"message":"document not found: unable to forward the request to the datasource"}`}, + want: "error querying global datasource 'prom': HTTP 404 Not Found: document not found: unable to forward the request to the datasource", + }, + { + name: "Perses bad request keeps its message", + answer: &answer{status: http.StatusBadRequest, body: `{"message":"invalid datasource proxy request"}`}, + want: "error querying global datasource 'prom': HTTP 400 Bad Request: invalid datasource proxy request", + }, + { + name: "Prometheus unavailable error is returned unchanged", + answer: &answer{status: http.StatusServiceUnavailable, body: `{"status":"error","errorType":"timeout","error":"query timed out in expression evaluation"}`}, + want: "timeout: query timed out in expression evaluation", + }, + { + name: "text error page", + answer: &answer{status: http.StatusBadGateway, body: "upstream down\n"}, + want: "error querying global datasource 'prom': HTTP 502 Bad Gateway: upstream down", + }, + { + name: "redirect is not followed", + answer: &answer{status: http.StatusFound, location: "/login"}, + want: "error querying global datasource 'prom': HTTP 302 Found: the redirect to /login is not followed: if Perses has moved, configure its new URL", + }, + { + name: "large error page keeps its status", + answer: &answer{status: http.StatusBadGateway, body: "" + strings.Repeat("x", 2*maxBodyBytes) + ""}, + want: "error querying global datasource 'prom': HTTP 502 Bad Gateway: ", + }, + { + name: "native histograms", + answer: new(ok(`{"resultType":"vector","result":[{"metric":{},"histogram":[1767355200,{"count":"2","sum":"3","buckets":[[0,"0","1","2"]]}]}]}`)), + want: "use histogram_quantile(), histogram_count() or histogram_sum() to get numbers, without _bucket or le, e.g. histogram_quantile(0.99, sum(rate(x[5m])))", + }, + { + name: "too much data", + answer: &answer{status: http.StatusOK, body: large}, + want: "aggregate it (sum by, topk) or narrow the label matchers", + }, + { + name: "wrong datasource kind", + arguments: map[string]any{"query": "up", "datasource": map[string]any{"name": "logs"}}, + want: "global datasource 'logs' is a LokiDatasource, not a PrometheusDatasource", + }, + { + name: "unknown datasource", + arguments: map[string]any{"query": "up", "datasource": map[string]any{"name": "nope"}}, + want: "error retrieving global datasource 'nope' (set datasource.project for a project datasource)", + }, + { + name: "time range of an instant query", + arguments: map[string]any{"query": "up", "time_range": map[string]any{"past_duration": "6h"}}, + want: "time_range and step apply to range queries", + }, + { + name: "time of a range query", + arguments: map[string]any{"query": "up", "type": "range", "time": "2026-01-02T10:00:00Z"}, + want: "time applies to instant queries", + }, + { + name: "invalid past duration", + arguments: map[string]any{"query": "up", "type": "range", "time_range": map[string]any{"past_duration": "0s"}}, + want: "invalid time_range.past_duration '0s'", + }, + { + name: "invalid start", + arguments: map[string]any{"query": "up", "type": "range", "time_range": map[string]any{"start": "yesterday"}}, + want: "invalid time_range.start 'yesterday'", + }, + { + name: "invalid step", + arguments: map[string]any{"query": "up", "type": "range", "step": "fast"}, + want: "invalid step 'fast'", + }, + { + name: "invalid time zone", + arguments: map[string]any{"query": "up", "time_zone": "Mars/Olympus"}, + want: "invalid time_zone 'Mars/Olympus'", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + answers := map[string]answer{} + if tt.answer != nil { + answers[globalProxy+"/api/v1/query"] = *tt.answer + } + arguments := tt.arguments + if arguments == nil { + arguments = map[string]any{"query": "rate(x"} + } + text := call(t, connect(t, newFakePerses(t, answers)), QueryToolName, arguments, true) + if !strings.Contains(text, tt.want) { + t.Errorf("error %q does not contain %q", text, tt.want) + } + }) + } +} + +func TestQueryFallsBackToGet(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + "POST " + globalProxy + "/api/v1/query": {status: http.StatusMethodNotAllowed}, + globalProxy + "/api/v1/query": ok(`{"resultType":"scalar","result":[1767355200,"1"]}`), + }) + output := decode(t, call(t, connect(t, perses), QueryToolName, map[string]any{"query": "scalar(up)"}, false)) + if output["value"] != 1.0 { + t.Errorf("output = %v", output) + } + if got := perses.Count(http.MethodGet, globalProxy+"/api/v1/query"); got != 1 { + t.Errorf("%d GET requests, want 1", got) + } +} + +func TestQueryRangeKeepsTheHighestSeries(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/query_range": ok(`{"resultType":"matrix","result":[` + + `{"metric":{"job":"a"},"values":[[1767355200,"1.00001"]]},` + + `{"metric":{"job":"b"},"values":[[1767355200,"1.00004"]]}]}`), + }) + output := decode(t, call(t, connect(t, perses), QueryToolName, map[string]any{"query": "up", "type": "range", "limit": 1}, false)) + if got := output["series"].([]any)[0].(map[string]any)["labels"]; !reflect.DeepEqual(got, map[string]any{"job": "b"}) { + t.Errorf("returned series = %v, want job b (highest unrounded max)", got) + } +} + +func TestQueryInvalidTypeIsRejected(t *testing.T) { + call(t, connect(t, newFakePerses(t, nil)), QueryToolName, map[string]any{"query": "up", "type": "bogus"}, true) +} + +func TestDatasourceSettingsApplyToEveryRequest(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/labels": ok(`["job"]`), + globalProxy + "/api/v1/label/job/values": ok(`["node"]`), + globalProxy + "/api/v1/label/__name__/values": ok(`["up"]`), + globalProxy + "/api/v1/query": ok(`{"resultType":"vector","result":[]}`), + globalProxy + "/api/v1/query_range": ok(`{"resultType":"matrix","result":[]}`), + }) + perses.metadata = map[string][]v1.Metadata{"up": {{Type: v1.MetricTypeGauge}}} + perses.datasources = []testDatasource{{ + Name: "prom", Kind: prometheusDatasourceKind, Default: true, ScrapeInterval: "30s", + QueryParams: map[string]string{"dedup": "true", "start": "0", "tenant": "$tenant"}, + }} + session := connect(t, perses) + calls := []struct { + tool string + arguments map[string]any + }{ + {ListLabelNamesToolName, nil}, + {ListLabelValuesToolName, map[string]any{"label": "job"}}, + {ListMetricNamesToolName, map[string]any{"include_metadata": true}}, + {GetMetricMetadataToolName, map[string]any{"metrics": []any{"up"}}}, + {QueryToolName, map[string]any{"query": "up"}}, + {QueryToolName, map[string]any{"query": "up", "type": "range"}}, + } + for _, c := range calls { + output := decode(t, call(t, session, c.tool, c.arguments, false)) + // The parameter with a variable can't be resolved: the result says so. + warnings, _ := output["warnings"].([]any) + if len(warnings) == 0 || !strings.Contains(warnings[0].(string), "the query parameter 'tenant'") { + t.Errorf("%s: warnings = %v", c.tool, output["warnings"]) + } + } + for _, request := range perses.Received() { + if !strings.HasPrefix(request.Path, "/proxy/") { + continue + } + query, err := url.ParseQuery(request.RawQuery) + if err != nil { + t.Fatal(err) + } + if query.Get("dedup") != "true" || query.Get("tenant") != "$tenant" { + t.Errorf("%s %s: query = %v, want the query parameters of the datasource", request.Method, request.Path, query) + } + } + // A parameter set by the request is kept: the GET request of the label values has its own start. + if got := perses.paramsOf(globalProxy + "/api/v1/label/job/values")["start"]; !reflect.DeepEqual(got, []string{"1767351600"}) { + t.Errorf("start = %v, want the start of the request only", got) + } + // The default step of a range query is at least the scrape interval of the datasource (1h / 500 < 30s). + if got := perses.paramsOf(globalProxy + "/api/v1/query_range").Get("step"); got != "30" { + t.Errorf("step = %s, want 30", got) + } +} + +func TestListTooLarge(t *testing.T) { + path := globalProxy + "/api/v1/label/__name__/values" + perses := newFakePerses(t, map[string]answer{path: {status: http.StatusOK, body: tooLarge(`[]`)}}) + session := connect(t, perses) + // The error tells how to narrow the list, not how to aggregate a query: search can't, as it filters the list once + // received. + for _, arguments := range []map[string]any{nil, {"search": "memory"}, {"search": "memory", "match": "up"}} { + text := call(t, session, ListMetricNamesToolName, arguments, true) + if !strings.Contains(text, errListTooLarge.Error()) { + t.Errorf("error = %s, want %s", text, errListTooLarge) + } + } + if got := perses.Count(http.MethodGet, path); got != 3 { + t.Errorf("%d requests, want 3 (one per call)", got) + } +} + +func TestListMetricNamesWithTooMuchMetadata(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/label/__name__/values": ok(`["go_goroutines","http_requests_total","up"]`), + }) + perses.metadata = map[string][]v1.Metadata{ + "go_goroutines": {{Type: v1.MetricTypeGauge, Help: "Number of goroutines."}}, + "http_requests": {{Type: v1.MetricTypeCounter, Help: "Requests."}}, + } + perses.bulkMetadataTooLarge = true + output := decode(t, call(t, connect(t, perses), ListMetricNamesToolName, map[string]any{"include_metadata": true, "limit": 2}, false)) + want := []any{ + map[string]any{"name": "go_goroutines", "type": "gauge", "help": "Number of goroutines."}, + map[string]any{"name": "http_requests_total", "type": "counter", "help": "Requests."}, + } + if !reflect.DeepEqual(output["metrics"], want) || output["warnings"] != nil { + t.Errorf("output = %v", output) + } + // Only the returned metrics are looked up, after the request of all the metadata. + for _, metric := range []string{"", "go_goroutines", "http_requests_total", "http_requests"} { + if got := countMetadataRequests(perses, metric); got != 1 { + t.Errorf("%d metadata requests for metric %q, want 1", got, metric) + } + } + if got := countMetadataRequests(perses, "up"); got != 0 { + t.Errorf("%d metadata requests for up, which isn't returned", got) + } +} + +func TestGetMetricMetadataError(t *testing.T) { + perses := newFakePerses(t, map[string]answer{ + globalProxy + "/api/v1/metadata": {status: http.StatusBadGateway, body: "upstream down"}, + }) + text := call(t, connect(t, perses), GetMetricMetadataToolName, map[string]any{"metrics": []any{"a", "b", "c"}}, true) + if !strings.Contains(text, "HTTP 502 Bad Gateway: upstream down") { + t.Errorf("error = %s, want the error of the lookup", text) + } +} + +func TestQueryParamsDontOverrideTheRequestParameters(t *testing.T) { + labels := globalProxy + "/api/v1/labels" + for _, fallback := range []bool{false, true} { + t.Run(fmt.Sprintf("GET fallback %v", fallback), func(t *testing.T) { + answers := map[string]answer{labels: ok(`["job"]`), globalProxy + "/api/v1/query_range": ok(`{"resultType":"matrix","result":[]}`)} + if fallback { + answers["POST "+labels] = answer{status: http.StatusMethodNotAllowed} + } + perses := newFakePerses(t, answers) + perses.datasources = []testDatasource{{ + Name: "prom", Kind: prometheusDatasourceKind, Default: true, + QueryParams: map[string]string{"match[]": "up", "start": "0", "dedup": "true"}, + }} + session := connect(t, perses) + call(t, session, ListLabelNamesToolName, map[string]any{"match": `{job="node"}`}, false) + call(t, session, QueryToolName, map[string]any{"query": "up", "type": "range"}, false) + + // Prometheus merges a repeated parameter from the URL and the form body: the request has its own match[]. + method := http.MethodPost + if fallback { + method = http.MethodGet + } + params := effectiveParams(t, perses, method, labels) + if !reflect.DeepEqual(params["match[]"], []string{`{job="node"}`}) { + t.Errorf("match[] = %v, want the matcher of the request only", params["match[]"]) + } + if params.Get("dedup") != "true" { + t.Errorf("dedup = %q, want the query parameter of the datasource", params.Get("dedup")) + } + if got := effectiveParams(t, perses, http.MethodPost, globalProxy+"/api/v1/query_range")["start"]; !reflect.DeepEqual(got, []string{"1767351600"}) { + t.Errorf("start = %v, want the start of the request only", got) + } + }) + } +} + +// effectiveParams returns the parameters that Prometheus reads from the last request of method and path: the form +// body first, then the URL, as with http.Request.ParseForm. +func effectiveParams(t *testing.T, perses *fakePerses, method, path string) url.Values { + t.Helper() + received := perses.Received() + for i := len(received) - 1; i >= 0; i-- { + request := received[i] + if request.Method != method || request.Path != path { + continue + } + params := url.Values{} + if request.ContentType == "application/x-www-form-urlencoded" { + form, err := url.ParseQuery(request.Body) + if err != nil { + t.Fatal(err) + } + params = form + } + query, err := url.ParseQuery(request.RawQuery) + if err != nil { + t.Fatal(err) + } + for key, values := range query { + params[key] = append(params[key], values...) + } + return params + } + t.Fatalf("no request %s %s", method, path) + return nil +} + +func TestMetadataLookupsAreBounded(t *testing.T) { + names := make([]string, 250) + for i := range names { + names[i] = fmt.Sprintf("metric_%03d", i) + } + list, err := json.Marshal(names) + if err != nil { + t.Fatal(err) + } + var inFlight, maxInFlight, lookups atomic.Int32 + perses := newFakePerses(t, map[string]answer{globalProxy + "/api/v1/label/__name__/values": ok(string(list))}) + perses.answer = func(r *http.Request) *answer { + if r.URL.Path != globalProxy+"/api/v1/metadata" { + return nil + } + if r.URL.Query().Get("metric") == "" { + return &answer{status: http.StatusOK, body: tooLarge("{}")} + } + lookups.Add(1) + current := inFlight.Add(1) + defer inFlight.Add(-1) + for previous := maxInFlight.Load(); current > previous && !maxInFlight.CompareAndSwap(previous, current); previous = maxInFlight.Load() { + } + time.Sleep(2 * time.Millisecond) + return new(ok("{}")) + } + output := decode(t, call(t, connect(t, perses), ListMetricNamesToolName, map[string]any{"include_metadata": true, "limit": 1000}, false)) + if output["returned"] != float64(maxMetadataMetricsLimit) || output["truncated"] != true { + t.Errorf("returned = %v, truncated = %v, want %d and true", output["returned"], output["truncated"], maxMetadataMetricsLimit) + } + if got := lookups.Load(); got != maxMetadataMetricsLimit { + t.Errorf("%d metadata lookups, want %d", got, maxMetadataMetricsLimit) + } + if got := maxInFlight.Load(); got > metadataConcurrency { + t.Errorf("%d concurrent lookups, want at most %d", got, metadataConcurrency) + } +} diff --git a/pkg/tools/prometheus/query.go b/pkg/tools/prometheus/query.go new file mode 100644 index 0000000..f10ca78 --- /dev/null +++ b/pkg/tools/prometheus/query.go @@ -0,0 +1,168 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "context" + "errors" + "fmt" + "time" + + v1 "github.com/prometheus/client_golang/api/prometheus/v1" + "github.com/prometheus/common/model" +) + +const ( + instantQuery = "instant" + rangeQuery = "range" + defaultSeriesLimit = 20 + maxSeriesLimit = 100 +) + +type QueryInput struct { + Datasource *DatasourceRef `json:"datasource,omitempty"` + Query string `json:"query"` + Type string `json:"type,omitempty"` + Time string `json:"time,omitempty"` + TimeRange *TimeRangeInput `json:"time_range,omitempty"` + Step string `json:"step,omitempty"` + Limit int `json:"limit,omitempty"` + TimeZone string `json:"time_zone,omitempty"` +} + +type queryOutput struct { + Datasource DatasourceRef `json:"datasource"` + ResultType string `json:"resultType"` + Time string `json:"time,omitempty"` + TimeRange *timeRangeOutput `json:"timeRange,omitempty"` + Step string `json:"step,omitempty"` + SeriesCount *int `json:"seriesCount,omitempty"` + Returned *int `json:"returned,omitempty"` + CommonLabels map[string]string `json:"commonLabels,omitempty"` + Series []series `json:"series,omitempty"` + // Value is the value of a scalar or string result. + Value any `json:"value,omitempty"` + Warnings []string `json:"warnings,omitempty"` + Infos []string `json:"infos,omitempty"` +} + +func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, error) { + location, err := resolveLocation(input.TimeZone) + if err != nil { + return nil, err + } + limit := input.Limit + if limit <= 0 { + limit = defaultSeriesLimit + } + limit = min(limit, maxSeriesLimit) + + // The input is checked before any request. + output := &queryOutput{} + var at time.Time + var queryRange v1.Range + switch input.Type { + case rangeQuery: + if input.Time != "" { + return nil, errors.New("time applies to instant queries: use time_range for a range query") + } + start, end, timeRange, rangeErr := resolveTimeRange(input.TimeRange, p.now()) + if rangeErr != nil { + return nil, rangeErr + } + if input.Step != "" { + if _, stepErr := parseStep(input.Step); stepErr != nil { + return nil, stepErr + } + } + // The step is set once the datasource, and so its scrape interval, is known. + queryRange = v1.Range{Start: start, End: end} + output.TimeRange = &timeRange + case instantQuery, "": + if input.TimeRange != nil || input.Step != "" { + return nil, errors.New("time_range and step apply to range queries: set type to 'range', or use time for an instant query") + } + at = p.now() + if input.Time != "" { + if at, err = parseTime("time", input.Time); err != nil { + return nil, err + } + } + output.Time = formatTimestamp(at) + default: + return nil, fmt.Errorf("invalid type '%s': use '%s' or '%s'", input.Type, instantQuery, rangeQuery) + } + + datasource, err := p.resolver.resolve(input.Datasource) + if err != nil { + return nil, err + } + output.Datasource = datasource.ref + if input.Type == rangeQuery { + if queryRange.Step, err = resolveStep(input.Step, queryRange.Start, queryRange.End, datasource.scrapeInterval); err != nil { + return nil, err + } + output.Step = model.Duration(queryRange.Step).String() + } + promAPI, err := p.newAPI(datasource) + if err != nil { + return nil, err + } + var value model.Value + var warnings v1.Warnings + var infos v1.Infos + if input.Type == rangeQuery { + value, warnings, infos, err = promAPI.QueryRange(ctx, input.Query, queryRange) + } else { + value, warnings, infos, err = promAPI.Query(ctx, input.Query, at) + } + if err != nil { + return nil, apiError(datasource.ref, err) + } + output.Warnings = append(datasource.warnings(), warnings...) + output.Infos = infos + + var all []series + switch result := value.(type) { + case model.Vector: + output.ResultType = "vector" + output.SeriesCount = new(len(result)) + if all, err = vectorSeries(result); err != nil { + return nil, err + } + case model.Matrix: + output.ResultType = "matrix" + output.SeriesCount = new(len(result)) + var withoutFiniteSample int + if all, withoutFiniteSample, err = matrixSeries(result, location); err != nil { + return nil, err + } + if withoutFiniteSample > 0 { + output.Warnings = append(output.Warnings, fmt.Sprintf("%d series are not returned: they only have NaN or infinite samples in the time range", withoutFiniteSample)) + } + case *model.Scalar: + output.ResultType = "scalar" + output.Value, _ = sampleValue(float64(result.Value)) + return output, nil + case *model.String: + output.ResultType = "string" + output.Value = result.Value + return output, nil + default: + return nil, fmt.Errorf("unexpected result type '%s' from %s", value.Type(), datasource.ref) + } + output.Series, output.CommonLabels = keepTopSeries(all, limit) + output.Returned = new(len(output.Series)) + return output, nil +} diff --git a/pkg/tools/prometheus/series.go b/pkg/tools/prometheus/series.go new file mode 100644 index 0000000..90c18b0 --- /dev/null +++ b/pkg/tools/prometheus/series.go @@ -0,0 +1,190 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "cmp" + "errors" + "math" + "slices" + "strconv" + "time" + + "github.com/prometheus/common/model" +) + +// errNativeHistograms shows how to query native histograms: unlike the classic ones, they have no _bucket series or le +// label. +var errNativeHistograms = errors.New("the query returns native histograms, which this tool does not summarize: " + + "use histogram_quantile(), histogram_count() or histogram_sum() to get numbers, without _bucket or le, e.g. " + + "histogram_quantile(0.99, sum(rate(x[5m])))") + +// stats are the statistics of a series of a range query. Min, max and avg leave out NaN and infinite samples. +type stats struct { + Min float64 `json:"min"` + Max float64 `json:"max"` + Avg float64 `json:"avg"` + // Last is the last sample: a number, or a string for NaN and infinities. + Last any `json:"last"` + MinAt string `json:"minAt"` + MaxAt string `json:"maxAt"` + // NonFinite is the number of NaN and infinite samples. + NonFinite int `json:"nonFinite,omitempty"` +} + +// series is a series of a query result: its value for an instant query, its statistics for a range query. +type series struct { + Labels map[string]string `json:"labels"` + // Value is a number, or a string for NaN and infinities. + Value any `json:"value,omitempty"` + *stats + // sortKey orders the series, highest first. + sortKey float64 +} + +func vectorSeries(vector model.Vector) ([]series, error) { + result := make([]series, 0, len(vector)) + for _, sample := range vector { + if sample.Histogram != nil { + return nil, errNativeHistograms + } + value, sortKey := sampleValue(float64(sample.Value)) + result = append(result, series{Labels: labels(sample.Metric), Value: value, sortKey: sortKey}) + } + return result, nil +} + +// matrixSeries returns the statistics of the series of a range query, and the number of series left out because +// they have no finite sample. +func matrixSeries(matrix model.Matrix, location *time.Location) ([]series, int, error) { + result := make([]series, 0, len(matrix)) + withoutFiniteSample := 0 + for _, stream := range matrix { + if len(stream.Histograms) > 0 { + return nil, 0, errNativeHistograms + } + streamStats, maxValue, ok := seriesStats(stream.Values, location) + if !ok { + withoutFiniteSample++ + continue + } + result = append(result, series{Labels: labels(stream.Metric), stats: &streamStats, sortKey: maxValue}) + } + return result, withoutFiniteSample, nil +} + +// keepTopSeries sorts the series by decreasing sort key, keeps the first limit ones and moves the labels shared by +// all of them to the returned common labels. +func keepTopSeries(all []series, limit int) ([]series, map[string]string) { + slices.SortStableFunc(all, func(a, b series) int { return cmp.Compare(b.sortKey, a.sortKey) }) + top := all[:min(limit, len(all))] + if len(top) < 2 { + return top, nil + } + common := map[string]string{} + for key, value := range top[0].Labels { + shared := true + for _, other := range top[1:] { + if otherValue, ok := other.Labels[key]; !ok || otherValue != value { + shared = false + break + } + } + if shared { + common[key] = value + } + } + if len(common) == 0 { + return top, nil + } + for _, s := range top { + for key := range common { + delete(s.Labels, key) + } + } + return top, common +} + +func labels(metric model.Metric) map[string]string { + result := make(map[string]string, len(metric)) + for name, value := range metric { + result[string(name)] = string(value) + } + return result +} + +// sampleValue returns the rounded value of a sample, or a string for NaN and infinities, and its sort key: the value +// itself, as cmp.Compare orders NaN below all the other values, -Inf included (NaN last, highest first). +func sampleValue(value float64) (any, float64) { + switch { + case math.IsNaN(value): + return "NaN", value + case math.IsInf(value, 1): + return "+Inf", value + case math.IsInf(value, -1): + return "-Inf", value + } + return round(value), value +} + +// seriesStats computes the statistics of the samples of a series and returns its unrounded maximum. ok is false when +// the series has no finite sample. +func seriesStats(samples []model.SamplePair, location *time.Location) (result stats, maxValue float64, ok bool) { + var ( + minValue, avg float64 + minAt, maxAt model.Time + count int + ) + for _, sample := range samples { + value := float64(sample.Value) + if math.IsNaN(value) || math.IsInf(value, 0) { + result.NonFinite++ + continue + } + count++ + if count == 1 || value < minValue { + minValue, minAt = value, sample.Timestamp + } + if count == 1 || value > maxValue { + maxValue, maxAt = value, sample.Timestamp + } + // A running mean, weighted so that no intermediate value exceeds the samples: a sum of large values could overflow. + avg = avg*(float64(count-1)/float64(count)) + value/float64(count) + } + if count == 0 { + return stats{}, 0, false + } + result.Min = round(minValue) + result.Max = round(maxValue) + result.Avg = round(avg) + result.Last, _ = sampleValue(float64(samples[len(samples)-1].Value)) + // RFC 3339 like the other times of the outputs, so that they can be reused as time or in time_range, but in the + // requested time zone. + result.MinAt = formatTimeIn(minAt.Time(), location) + result.MaxAt = formatTimeIn(maxAt.Time(), location) + return result, maxValue, true +} + +// round keeps 4 significant digits, but all the digits of the integer part: rounding them would make values such as +// timestamps (e.g. process_start_time_seconds) wrong by days, without making their JSON shorter. +func round(value float64) float64 { + if math.Abs(value) >= 1e4 { + return math.Round(value) + } + rounded, err := strconv.ParseFloat(strconv.FormatFloat(value, 'g', 4, 64), 64) + if err != nil { + return value + } + return rounded +} diff --git a/pkg/tools/prometheus/timerange.go b/pkg/tools/prometheus/timerange.go new file mode 100644 index 0000000..b05b790 --- /dev/null +++ b/pkg/tools/prometheus/timerange.go @@ -0,0 +1,167 @@ +// Copyright The Perses Authors +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package prometheus + +import ( + "errors" + "fmt" + "time" + + "github.com/prometheus/common/model" +) + +const ( + // defaultPastDuration is the time range used when none is given. + defaultPastDuration = "1h" + // statsPoints is the number of points requested by default for range queries. + statsPoints = 500 + // maxPoints is the Prometheus limit of points per series of a range query. + maxPoints = 11000 +) + +// TimeRangeInput is a time range of the tool inputs: relative (PastDuration) or absolute (Start and End). +type TimeRangeInput struct { + PastDuration string `json:"past_duration,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +// timeRangeOutput is the resolved time range returned by the tools: relative (PastDuration) or absolute (Start and End, +// RFC 3339 in UTC). +type timeRangeOutput struct { + PastDuration string `json:"pastDuration,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +// resolveTimeRange returns the start and end of the time range and its representation in the output: the absolute +// range when start is set (end defaults to now), otherwise the past duration (default 1h) ending now. +func resolveTimeRange(input *TimeRangeInput, now time.Time) (time.Time, time.Time, timeRangeOutput, error) { + if input == nil { + input = &TimeRangeInput{} + } + if input.Start == "" { + if input.End != "" { + return time.Time{}, time.Time{}, timeRangeOutput{}, errors.New("time_range.end requires time_range.start") + } + pastDuration := input.PastDuration + if pastDuration == "" { + pastDuration = defaultPastDuration + } + duration, err := parseDuration(pastDuration) + if err != nil { + return time.Time{}, time.Time{}, timeRangeOutput{}, fmt.Errorf("invalid time_range.past_duration '%s': %w", pastDuration, err) + } + return now.Add(-duration), now, timeRangeOutput{PastDuration: pastDuration}, nil + } + if input.PastDuration != "" { + return time.Time{}, time.Time{}, timeRangeOutput{}, errors.New("set either time_range.past_duration or time_range.start, not both") + } + start, err := parseTime("time_range.start", input.Start) + if err != nil { + return time.Time{}, time.Time{}, timeRangeOutput{}, err + } + end := now + if input.End != "" { + if end, err = parseTime("time_range.end", input.End); err != nil { + return time.Time{}, time.Time{}, timeRangeOutput{}, err + } + } + if !start.Before(end) { + return time.Time{}, time.Time{}, timeRangeOutput{}, errors.New("time_range.start must be before time_range.end") + } + return start, end, timeRangeOutput{Start: formatTimestamp(start), End: formatTimestamp(end)}, nil +} + +// formatTimestamp formats a time of the outputs in RFC 3339 in UTC, with its fractional seconds if any, so that the +// output has the time that was queried. +func formatTimestamp(t time.Time) string { + return formatTimeIn(t, time.UTC) +} + +// formatTimeIn formats a time of the outputs in RFC 3339 in a time zone, with its fractional seconds if any. +func formatTimeIn(t time.Time, location *time.Location) string { + return t.In(location).Format(time.RFC3339Nano) +} + +// parseDuration parses a positive Prometheus duration, e.g. "15m", "1h30m" or "7d". +func parseDuration(duration string) (time.Duration, error) { + parsed, err := model.ParseDuration(duration) + if err != nil { + return 0, fmt.Errorf("use a duration like 15m, 1h or 7d: %w", err) + } + if parsed <= 0 { + return 0, errors.New("the duration must be positive") + } + return time.Duration(parsed), nil +} + +func parseTime(field, value string) (time.Time, error) { + parsed, err := time.Parse(time.RFC3339, value) + if err != nil { + return time.Time{}, fmt.Errorf("invalid %s '%s': use RFC 3339, e.g. 2026-01-02T15:04:05Z", field, value) + } + return parsed, nil +} + +// resolveStep returns the step of a range query: the given step, raised if needed to stay under the Prometheus +// limit of points, or by default about statsPoints points and at least minStep, the scrape interval of the datasource +// (a smaller step only repeats the samples). +func resolveStep(step string, start, end time.Time, minStep time.Duration) (time.Duration, error) { + span := end.Sub(start) + if step == "" { + return max(minStep, ceilTo(span/statsPoints, time.Second)), nil + } + parsed, err := parseStep(step) + if err != nil { + return 0, err + } + return max(parsed, minLimitStep(span)), nil +} + +// minLimitStep returns the smallest step that stays under the Prometheus limit of points over span, rounded up to the +// second, or to the millisecond (the precision of the steps) when it is under a second: a valid subsecond step is +// kept. +func minLimitStep(span time.Duration) time.Duration { + limit := (span + maxPoints - 1) / maxPoints + if limit < time.Second { + return ceilTo(limit, time.Millisecond) + } + return ceilTo(limit, time.Second) +} + +func parseStep(step string) (time.Duration, error) { + parsed, err := parseDuration(step) + if err != nil { + return 0, fmt.Errorf("invalid step '%s': %w", step, err) + } + return parsed, nil +} + +// ceilTo rounds a duration up to a multiple of unit. +func ceilTo(duration, unit time.Duration) time.Duration { + return (duration + unit - 1).Truncate(unit) +} + +// resolveLocation returns the IANA time zone used to format times, UTC by default. +func resolveLocation(timeZone string) (*time.Location, error) { + if timeZone == "" { + return time.UTC, nil + } + location, err := time.LoadLocation(timeZone) + if err != nil { + return nil, fmt.Errorf("invalid time_zone '%s': use an IANA time zone, e.g. Europe/Berlin", timeZone) + } + return location, nil +} diff --git a/pkg/tools/tool.go b/pkg/tools/tool.go index d6eb492..5521631 100644 --- a/pkg/tools/tool.go +++ b/pkg/tools/tool.go @@ -45,6 +45,7 @@ const ( MigrateResource Resource = "migrate" SchemaResource Resource = "schema" ValidateResource Resource = "validate" + PrometheusResource Resource = "prometheus" ) var ValidResources = []Resource{ @@ -63,6 +64,7 @@ var ValidResources = []Resource{ MigrateResource, SchemaResource, ValidateResource, + PrometheusResource, } // Tool represents an MCP tool with metadata about write access requirements