From 0c19445b370bf760af54ad2c546cad5f8b997d47 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Thu, 12 Nov 2026 22:12:33 +0100 Subject: [PATCH 01/21] [FEATURE] add Prometheus discovery and query tools Add the read-only prometheus resource with five tools that call the Prometheus HTTP API of Perses datasources through the Perses proxy: perses_list_prometheus_metric_names, perses_list_prometheus_label_names, perses_list_prometheus_label_values, perses_get_prometheus_metric_metadata and perses_query_prometheus. They use the Prometheus API client of client_golang with the HTTP client and the credentials of the Perses client, and return compact JSON: range queries return statistics per series (min, max, avg, last, when min/max happened) instead of raw points, labels shared by all series are returned once, values keep 4 significant digits, responses are capped at 1 MiB and Prometheus errors are returned unchanged. The datasource is optional: the default Prometheus datasource of the project, else the global one, is used, or the only Prometheus datasource when none is marked as default. Signed-off-by: Akshay Iyyadurai Balasundaram --- README.md | 19 ++ docs/configuration.md | 1 + docs/overview.md | 4 + docs/tools.md | 70 ++++ go.mod | 4 +- internal/permcp/server.go | 2 + pkg/tools/prometheus/client.go | 182 +++++++++++ pkg/tools/prometheus/datasource.go | 192 +++++++++++ pkg/tools/prometheus/helpers_test.go | 234 ++++++++++++++ pkg/tools/prometheus/internal_test.go | 217 +++++++++++++ pkg/tools/prometheus/list.go | 356 ++++++++++++++++++++ pkg/tools/prometheus/prometheus.go | 306 ++++++++++++++++++ pkg/tools/prometheus/prometheus_test.go | 411 ++++++++++++++++++++++++ pkg/tools/prometheus/query.go | 161 ++++++++++ pkg/tools/prometheus/series.go | 183 +++++++++++ pkg/tools/prometheus/timerange.go | 138 ++++++++ pkg/tools/tool.go | 2 + 17 files changed, 2480 insertions(+), 2 deletions(-) create mode 100644 pkg/tools/prometheus/client.go create mode 100644 pkg/tools/prometheus/datasource.go create mode 100644 pkg/tools/prometheus/helpers_test.go create mode 100644 pkg/tools/prometheus/internal_test.go create mode 100644 pkg/tools/prometheus/list.go create mode 100644 pkg/tools/prometheus/prometheus.go create mode 100644 pkg/tools/prometheus/prometheus_test.go create mode 100644 pkg/tools/prometheus/query.go create mode 100644 pkg/tools/prometheus/series.go create mode 100644 pkg/tools/prometheus/timerange.go 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..de4adec 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -190,6 +190,76 @@ 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. +- `time_range`: `{past_duration}` (e.g. `"6h"`, `"7d"`), or `{start, end}` in RFC 3339 (`end` defaults to now). + The past hour by default, so that the list tools only return current series. +- `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`), 200 label + names, 100 label values (max 1000), 20 series (max 100). + +The list tools return `{datasource, total, returned, truncated, ...}`. 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 unavailable (e.g. over 1 MiB), 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: `_bucket`, `_count`, `_sum` and `_created` of histograms and summaries, +`_total` of counters (e.g. `http_requests_total` of the counter `http_requests`). + +`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 15s). 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 + formatted in `time_zone` (default UTC). + +The labels shared by all returned series are returned once in `commonLabels`. The values keep 4 significant digits; +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()`. 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, it is used. Otherwise the tool returns an +error that lists the available Prometheus datasources. The resolved datasources are cached for 30 seconds. + ## Variables Resources: `globalvariable` for the tools `*_global_variable*`, `variable` for the tools `*_project_variable*`. diff --git a/go.mod b/go.mod index d234b1b..04420db 100644 --- a/go.mod +++ b/go.mod @@ -8,6 +8,8 @@ require ( github.com/perses/common v0.33.0 github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959 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 ) @@ -85,9 +87,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 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/prometheus/client.go b/pkg/tools/prometheus/client.go new file mode 100644 index 0000000..b4209c7 --- /dev/null +++ b/pkg/tools/prometheus/client.go @@ -0,0 +1,182 @@ +// 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" + "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. +func (p *prometheus) newAPI(datasource DatasourceRef) (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") + } + path := proxy.GlobalDatasourceProxyPath(datasource.Name, "") + if datasource.Project != "" { + path = proxy.ProjectDatasourceProxyPath(datasource.Project, datasource.Name, "") + } + client, err := api.NewClient(api.Config{ + Address: strings.TrimRight(restClient.BaseURL.String(), "/") + path, + Client: &http.Client{Transport: &persesTransport{client: restClient.Client, headers: restClient.Headers}}, + }) + if err != nil { + return nil, fmt.Errorf("error creating the Prometheus client of %s: %w", datasource, 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. +type persesTransport struct { + client *http.Client + headers 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) + } + } + // #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 + } + resp.Body = &limitedBody{ReadCloser: resp.Body, remaining: maxBodyBytes} + if resp.StatusCode/100 == 2 || (req.Method == http.MethodPost && isGetFallbackStatus(resp.StatusCode)) { + return resp, nil + } + body, err := io.ReadAll(resp.Body) + _ = 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)} +} + +// 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 + } + if len(message) > maxErrorLength { + message = 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..ebc0b84 --- /dev/null +++ b/pkg/tools/prometheus/datasource.go @@ -0,0 +1,192 @@ +// 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" + "sort" + "strings" + "sync" + "time" + + apiClient "github.com/perses/perses/pkg/client/api/v1" + "github.com/perses/spec/go/datasource" +) + +// prometheusDatasourceKind is the plugin kind of Prometheus datasources. +const prometheusDatasourceKind = "PrometheusDatasource" + +// cacheTTL is how long a resolved datasource is reused. +const cacheTTL = 30 * time.Second + +// 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) +} + +type cacheEntry struct { + ref DatasourceRef + expires time.Time +} + +// resolver resolves a (possibly partial) datasource reference to an existing Prometheus datasource. +// +// The resolved references 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 (project and global), it is used. +func (r *resolver) resolve(input *DatasourceRef) (DatasourceRef, 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.ref, nil + } + ref, err := r.resolveUncached(key) + if err != nil { + return DatasourceRef{}, err + } + r.mutex.Lock() + r.cache[key] = cacheEntry{ref: ref, expires: r.now().Add(cacheTTL)} + r.mutex.Unlock() + return ref, nil +} + +func (r *resolver) resolveUncached(key DatasourceRef) (DatasourceRef, error) { + if key.Name != "" { + return r.resolveNamed(key) + } + var available []DatasourceRef + if key.Project != "" { + datasources, err := r.client.Datasource(key.Project).List("") + if err != nil { + return DatasourceRef{}, fmt.Errorf("error listing the datasources of project '%s': %w", key.Project, err) + } + candidates := map[string]datasource.Spec{} + for _, ds := range datasources { + candidates[ds.Metadata.Name] = ds.Spec + } + if name, ok := pickDefault(candidates); ok { + return DatasourceRef{Name: name, Project: key.Project}, nil + } + for _, name := range prometheusNames(candidates) { + available = append(available, DatasourceRef{Name: name, Project: key.Project}) + } + } + globals, err := r.client.GlobalDatasource().List("") + if err != nil { + return DatasourceRef{}, fmt.Errorf("error listing the global datasources: %w", err) + } + candidates := map[string]datasource.Spec{} + for _, ds := range globals { + candidates[ds.Metadata.Name] = ds.Spec + } + if name, ok := pickDefault(candidates); ok { + return DatasourceRef{Name: name}, nil + } + for _, name := range prometheusNames(candidates) { + available = append(available, DatasourceRef{Name: name}) + } + switch len(available) { + case 0: + return DatasourceRef{}, errors.New("no Prometheus datasource found: create one in Perses or pass datasource.name") + case 1: + // No default but a single Prometheus datasource: no ambiguity. + return available[0], nil + } + names := make([]string, 0, len(available)) + for _, ref := range available { + if ref.Project == "" { + names = append(names, ref.Name+" (global)") + } else { + names = append(names, fmt.Sprintf("%s (project %s)", ref.Name, ref.Project)) + } + } + return DatasourceRef{}, fmt.Errorf("no default Prometheus datasource found: pass datasource.name (and datasource.project for a project datasource), available Prometheus datasources: %s", + strings.Join(names, ", ")) +} + +func (r *resolver) resolveNamed(key DatasourceRef) (DatasourceRef, error) { + var spec datasource.Spec + if key.Project != "" { + ds, err := r.client.Datasource(key.Project).Get(key.Name) + if err != nil { + return DatasourceRef{}, fmt.Errorf("error retrieving %s: %w", key, err) + } + spec = ds.Spec + } else { + ds, err := r.client.GlobalDatasource().Get(key.Name) + if err != nil { + return DatasourceRef{}, fmt.Errorf("error retrieving %s (set datasource.project for a project datasource): %w", key, err) + } + spec = ds.Spec + } + if spec.Plugin.Kind != prometheusDatasourceKind { + return DatasourceRef{}, fmt.Errorf("%s is a %s, not a %s", key, spec.Plugin.Kind, prometheusDatasourceKind) + } + return key, nil +} + +// pickDefault returns the Prometheus datasource marked as default. +func pickDefault(candidates map[string]datasource.Spec) (string, bool) { + for _, name := range prometheusNames(candidates) { + if candidates[name].Default { + return name, true + } + } + return "", false +} + +// prometheusNames returns the sorted names of the Prometheus datasources. +func prometheusNames(candidates map[string]datasource.Spec) []string { + var names []string + for name, spec := range candidates { + if spec.Plugin.Kind == prometheusDatasourceKind { + names = append(names, name) + } + } + sort.Strings(names) + return names +} diff --git a/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go new file mode 100644 index 0000000..2045423 --- /dev/null +++ b/pkg/tools/prometheus/helpers_test.go @@ -0,0 +1,234 @@ +// 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 +} + +// 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 +} + +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 +} + +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.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 + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(a.status) + _, _ = w.Write([]byte(a.body)) +} + +func (f *fakePerses) serveMetadata(w http.ResponseWriter, metric string) { + 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] + } + 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]) +} + +func encodeDatasource(ds testDatasource) map[string]any { + 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": map[string]any{}}, + }, + } +} + +// 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..af6cc78 --- /dev/null +++ b/pkg/tools/prometheus/internal_test.go @@ -0,0 +1,217 @@ +// 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 ( + "math" + "reflect" + "strings" + "testing" + "time" + + "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}, + } + 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: "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 != tt.want { + t.Errorf("Resolve() = %+v, want %+v", got, tt.want) + } + }) + } +} + +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: "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 + want time.Duration + }{ + {span: time.Hour, want: 15 * time.Second}, + {span: 6 * time.Hour, want: 44 * time.Second}, + {span: 7 * 24 * time.Hour, want: 1210 * time.Second}, + {step: "1m", span: time.Hour, want: time.Minute}, + // The step is raised to stay under the Prometheus limit of points. + {step: "1s", span: 7 * 24 * time.Hour, want: 55 * time.Second}, + } + for _, tt := range tests { + got, err := resolveStep(tt.step, testNow.Add(-tt.span), testNow) + if err != nil || got != tt.want { + t.Errorf("resolveStep(%q, %s) = %s, %v, want %s", tt.step, tt.span, got, err, tt.want) + } + } +} + +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: "2 Jan 2026, 12:00", MaxAt: "2 Jan 2026, 12:00", 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) || got.Avg != round(math.MaxFloat64/3) { + t.Errorf("average of large values = %v, want %v", got.Avg, round(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) + } +} diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go new file mode 100644 index 0000000..c84bca7 --- /dev/null +++ b/pkg/tools/prometheus/list.go @@ -0,0 +1,356 @@ +// 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" + "slices" + "strings" + "sync" + + v1 "github.com/prometheus/client_golang/api/prometheus/v1" + "github.com/prometheus/common/model" +) + +const ( + defaultMetricsLimit = 200 + // defaultMetadataMetricsLimit is the default limit of metric names listed with their metadata, which are larger. + defaultMetadataMetricsLimit = 50 + defaultLabelsLimit = 200 + defaultValuesLimit = 100 + maxListLimit = 1000 + maxMetadataMetrics = 20 + // 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"` +} + +// listing is the result of a label names or label values request. +type listing struct { + datasource DatasourceRef + values []string + warnings []string +} + +// list resolves the time range and the datasource, then lists the label names (label empty) or the values of a +// label, filtered by search (case-insensitive). +func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, label string, match Selectors, timeRange *TimeRangeInput, search string) (*listing, error) { + start, end, _, err := resolveTimeRange(timeRange, p.now()) + if err != nil { + return nil, err + } + datasource, err := p.resolver.resolve(datasourceInput) + 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, label, match, start, end) + for _, value := range labelValues { + values = append(values, string(value)) + } + } + if err != nil { + return nil, apiError(datasource, err) + } + if search != "" { + needle := strings.ToLower(search) + values = slices.DeleteFunc(values, func(value string) bool { return !strings.Contains(strings.ToLower(value), needle) }) + } + if values == nil { + values = []string{} + } + return &listing{datasource: datasource, values: values, warnings: append(warnings, infos...)}, nil +} + +// 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, input.Datasource, model.MetricNameLabel, input.Match, input.TimeRange, input.Search) + if err != nil { + return nil, err + } + defaultLimit := defaultMetricsLimit + if input.IncludeMetadata { + defaultLimit = defaultMetadataMetricsLimit + } + returned, namesPage := firstPage(names.values, input.Limit, defaultLimit) + output := &metricNamesOutput{Datasource: names.datasource, 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 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, input.Datasource, "", input.Match, input.TimeRange, "") + if err != nil { + return nil, err + } + returned, labelsPage := firstPage(labels.values, input.Limit, defaultLabelsLimit) + return &labelNamesOutput{Datasource: labels.datasource, page: labelsPage, Labels: returned, Warnings: labels.warnings}, nil +} + +func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesInput) (*labelValuesOutput, error) { + values, err := p.list(ctx, input.Datasource, input.Label, input.Match, input.TimeRange, input.Search) + if err != nil { + return nil, err + } + returned, valuesPage := firstPage(values.values, input.Limit, defaultValuesLimit) + return &labelValuesOutput{Datasource: values.datasource, Label: input.Label, page: valuesPage, Values: returned, Warnings: values.warnings}, nil +} + +// familySuffixes are the suffixes of the series of a metric family, with the types of the families that have them. +// The metadata of these series may be under the family name, e.g. http_requests for http_requests_total. +var familySuffixes = []struct { + suffix string + types []v1.MetricType +}{ + {"_bucket", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram}}, + {"_count", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, + {"_sum", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, + {"_created", []v1.MetricType{v1.MetricTypeCounter, v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, + {"_total", []v1.MetricType{v1.MetricTypeCounter}}, +} + +// familyName returns the name of the metric family a series name may belong to, and the types of such a family. +func familyName(name string) (string, []v1.MetricType, bool) { + for _, family := range familySuffixes { + if base, found := strings.CutSuffix(name, family.suffix); found && base != "" { + return base, family.types, true + } + } + return "", nil, false +} + +// 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 DatasourceRef, 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, 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 DatasourceRef, 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 +} + +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 + } + results := make([][]v1.Metadata, len(input.Metrics)) + errs := make([]error, len(input.Metrics)) + var wg sync.WaitGroup + for i, metric := range input.Metrics { + wg.Go(func() { + results[i], errs[i] = p.metricMetadata(ctx, datasource, metric) + }) + } + wg.Wait() + output := &metricMetadataOutput{Datasource: datasource, Metadata: map[string][]v1.Metadata{}, Missing: []string{}} + for i, metric := range input.Metrics { + if errs[i] != nil { + return nil, errs[i] + } + if len(results[i]) == 0 { + output.Missing = append(output.Missing, metric) + continue + } + output.Metadata[metric] = results[i] + } + return output, nil +} diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go new file mode 100644 index 0000000..04f1561 --- /dev/null +++ b/pkg/tools/prometheus/prometheus.go @@ -0,0 +1,306 @@ +// 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" +) + +const labelNamePattern = `^[a-zA-Z_][a-zA-Z0-9_]*$` + +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, %d with include_metadata, max %d).", + defaultMetricsLimit, defaultMetadataMetricsLimit, maxListLimit), 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, Pattern: labelNamePattern, Description: "Label name, e.g. \"job\"."}, + "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 and counters "+ + "(_bucket, _count, _sum, _total) 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. 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 15s).", + }, + "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, 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("Only consider series with samples in this time range. Defaults to the past hour, " + + "so that only current metrics are returned.") +} diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go new file mode 100644 index 0000000..7abd928 --- /dev/null +++ b/pkg/tools/prometheus/prometheus_test.go @@ -0,0 +1,411 @@ +// 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 ( + "net/http" + "net/url" + "reflect" + "strings" + "testing" + + "github.com/perses/mcp-server/pkg/tools" + "github.com/perses/mcp-server/pkg/tools/internal/tooltest" + 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": "bad-label"}, true) +} + +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 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."}}, + "temperature": {{Type: v1.MetricTypeGauge, Help: "Temperature."}}, + } + 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"}, + }, 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": ""}}, + } + if !reflect.DeepEqual(output["metadata"], want) { + t.Errorf("metadata =\n%v\nwant\n%v", output["metadata"], want) + } + // temperature is a gauge: it is not the family of temperature_total. + if !reflect.DeepEqual(output["missing"], []any{"temperature_total", "nope"}) { + t.Errorf("missing = %v", output["missing"]) + } + // A metric with metadata under its own name is looked up once. + if count := countRequests(perses, globalProxy+"/api/v1/metadata", "metric", "queue_count") + countRequests(perses, globalProxy+"/api/v1/metadata", "metric", "queue"); count != 1 { + t.Errorf("%d metadata requests for queue_count, want 1", count) + } +} + +// countRequests returns the number of requests of path with the query parameter key set to value. +func countRequests(perses *fakePerses, path, key, value string) int { + count := 0 + for _, request := range perses.Received() { + if params, err := url.ParseQuery(request.RawQuery); err == nil && request.Path == path && params.Get(key) == value { + 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"}, + "step": "44s", + "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": "2 Jan 2026, 13:01", "maxAt": "2 Jan 2026, 13:00"}, + map[string]any{"labels": map[string]any{"job": "a"}, "min": 1.0, "max": 3.0, "avg": 2.0, "last": 3.0, "minAt": "2 Jan 2026, 13:00", "maxAt": "2 Jan 2026, 13:01"}, + }, + "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") != "44" || 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) + } +} + +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) + } +} + +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: "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()", + }, + { + 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) +} diff --git a/pkg/tools/prometheus/query.go b/pkg/tools/prometheus/query.go new file mode 100644 index 0000000..2160b0f --- /dev/null +++ b/pkg/tools/prometheus/query.go @@ -0,0 +1,161 @@ +// 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 + } + step, stepErr := resolveStep(input.Step, start, end) + if stepErr != nil { + return nil, stepErr + } + queryRange = v1.Range{Start: start, End: end, Step: step} + output.TimeRange = &timeRange + output.Step = model.Duration(step).String() + 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 = at.UTC().Format(time.RFC3339) + 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 + 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, err) + } + output.Warnings = append([]string(nil), 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) + } + 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..d908bee --- /dev/null +++ b/pkg/tools/prometheus/series.go @@ -0,0 +1,183 @@ +// 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" +) + +// timeLayout formats minAt and maxAt, e.g. "2 Jan 2026, 14:05". +const timeLayout = "2 Jan 2006, 15:04" + +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") + +// 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 (NaN last). +func sampleValue(value float64) (any, float64) { + switch { + case math.IsNaN(value): + return "NaN", math.Inf(-1) + 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)) + result.MinAt = minAt.Time().In(location).Format(timeLayout) + result.MaxAt = maxAt.Time().In(location).Format(timeLayout) + return result, maxValue, true +} + +// round keeps 4 significant digits. +func round(value float64) float64 { + 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..67142d5 --- /dev/null +++ b/pkg/tools/prometheus/timerange.go @@ -0,0 +1,138 @@ +// 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 + // minStep is the minimum default step of range queries. + minStep = 15 * time.Second + // 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: start.UTC().Format(time.RFC3339), End: end.UTC().Format(time.RFC3339)}, nil +} + +// 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. +func resolveStep(step string, start, end time.Time) (time.Duration, error) { + span := end.Sub(start) + if step == "" { + return max(minStep, ceilSeconds(span/statsPoints)), nil + } + parsed, err := parseDuration(step) + if err != nil { + return 0, fmt.Errorf("invalid step '%s': %w", step, err) + } + return max(parsed, ceilSeconds(span/maxPoints)), nil +} + +// ceilSeconds rounds a duration up to the second. +func ceilSeconds(duration time.Duration) time.Duration { + return (duration + time.Second - 1).Truncate(time.Second) +} + +// 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 From a0e613d196e316df8286200b5134faa0c8538812 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 10:48:35 +0100 Subject: [PATCH 02/21] [FEATURE] apply the settings of the Prometheus datasource The Perses UI applies two settings of a Prometheus datasource itself, which the Perses proxy doesn't. The tools now apply them as well, so that they return the same data as the dashboards: - queryParams (e.g. dedup or partial_response for Thanos) are added to every request, unless the request has the parameter in its URL or its form body: Prometheus merges a repeated parameter such as match[] from both. A value with a dashboard variable is sent as is, with a warning. - scrapeInterval (default 1m, as in the UI) is the minimum default step of range queries, instead of 15s. An explicit step isn't raised to it. The plugin spec is decoded with the Prometheus plugin SDK (github.com/perses/plugins/prometheus/sdk/go/datasource). An empty scrape interval, which Perses accepts and the UI saves when the field is cleared, means the default one. A datasource with a directUrl, only reachable by the browser, is an error that explains it instead of an HTTP error of the proxy, also when it is the default one. Without default, only the datasources that can be used are candidates, and the others are reported with their own error. The default datasource of a project is still returned before the global datasources are listed. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 23 ++- go.mod | 1 + go.sum | 2 + pkg/tools/prometheus/client.go | 58 ++++++- pkg/tools/prometheus/datasource.go | 214 +++++++++++++++++------- pkg/tools/prometheus/helpers_test.go | 31 +++- pkg/tools/prometheus/internal_test.go | 131 +++++++++++++-- pkg/tools/prometheus/list.go | 22 +-- pkg/tools/prometheus/prometheus.go | 5 +- pkg/tools/prometheus/prometheus_test.go | 134 ++++++++++++++- pkg/tools/prometheus/query.go | 25 ++- pkg/tools/prometheus/timerange.go | 17 +- 12 files changed, 544 insertions(+), 119 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index de4adec..27bc36b 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -228,7 +228,8 @@ when the family has series with this suffix: `_bucket`, `_count`, `_sum` and `_c `_total` of counters (e.g. `http_requests_total` of the counter `http_requests`). `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 15s). It returns: +(`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}]}`; @@ -257,8 +258,24 @@ The parameter `datasource` of the Prometheus tools is resolved as follows: - `{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, it is used. Otherwise the tool returns an -error that lists the available Prometheus datasources. The resolved datasources are cached for 30 seconds. +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 diff --git a/go.mod b/go.mod index 04420db..2a2d327 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ 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 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/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go index b4209c7..1e1ded3 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -20,6 +20,7 @@ import ( "fmt" "io" "net/http" + "net/url" "strings" "github.com/perses/mcp-server/pkg/tools/internal/proxy" @@ -37,22 +38,26 @@ const ( 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. -func (p *prometheus) newAPI(datasource DatasourceRef) (v1.API, error) { +// 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") } - path := proxy.GlobalDatasourceProxyPath(datasource.Name, "") - if datasource.Project != "" { - path = proxy.ProjectDatasourceProxyPath(datasource.Project, datasource.Name, "") + ref := datasource.ref + path := proxy.GlobalDatasourceProxyPath(ref.Name, "") + if ref.Project != "" { + path = proxy.ProjectDatasourceProxyPath(ref.Project, ref.Name, "") } client, err := api.NewClient(api.Config{ Address: strings.TrimRight(restClient.BaseURL.String(), "/") + path, - Client: &http.Client{Transport: &persesTransport{client: restClient.Client, headers: restClient.Headers}}, + Client: &http.Client{Transport: &persesTransport{ + client: restClient.Client, headers: restClient.Headers, queryParams: datasource.queryParams, + }}, }) if err != nil { - return nil, fmt.Errorf("error creating the Prometheus client of %s: %w", datasource, err) + return nil, fmt.Errorf("error creating the Prometheus client of %s: %w", ref, err) } return v1.NewAPI(client), nil } @@ -62,9 +67,14 @@ func (p *prometheus) newAPI(datasource DatasourceRef) (v1.API, error) { // 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 + client *http.Client + headers map[string]string + queryParams map[string]string } func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { @@ -74,6 +84,19 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { 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 { @@ -95,6 +118,23 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { 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 diff --git a/pkg/tools/prometheus/datasource.go b/pkg/tools/prometheus/datasource.go index ebc0b84..5f20e40 100644 --- a/pkg/tools/prometheus/datasource.go +++ b/pkg/tools/prometheus/datasource.go @@ -14,23 +14,33 @@ package prometheus import ( + "encoding/json" "errors" "fmt" + "maps" + "slices" "sort" "strings" "sync" "time" apiClient "github.com/perses/perses/pkg/client/api/v1" + 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 = "PrometheusDatasource" +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 { @@ -45,14 +55,73 @@ func (d DatasourceRef) String() string { 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 { - ref DatasourceRef - expires time.Time + datasource resolvedDatasource + expires time.Time } // resolver resolves a (possibly partial) datasource reference to an existing Prometheus datasource. // -// The resolved references are cached for cacheTTL and shared by all the tool calls. This is right as long as the +// 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 { @@ -72,8 +141,9 @@ func newResolver(client apiClient.ClientInterface) *resolver { // - 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 (project and global), it is used. -func (r *resolver) resolve(input *DatasourceRef) (DatasourceRef, error) { +// 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 @@ -82,111 +152,129 @@ func (r *resolver) resolve(input *DatasourceRef) (DatasourceRef, error) { entry, ok := r.cache[key] r.mutex.Unlock() if ok && r.now().Before(entry.expires) { - return entry.ref, nil + return entry.datasource, nil } - ref, err := r.resolveUncached(key) + resolved, err := r.resolveUncached(key) if err != nil { - return DatasourceRef{}, err + return resolvedDatasource{}, err } r.mutex.Lock() - r.cache[key] = cacheEntry{ref: ref, expires: r.now().Add(cacheTTL)} + r.cache[key] = cacheEntry{datasource: resolved, expires: r.now().Add(cacheTTL)} r.mutex.Unlock() - return ref, nil + 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) (DatasourceRef, error) { +func (r *resolver) resolveUncached(key DatasourceRef) (resolvedDatasource, error) { if key.Name != "" { return r.resolveNamed(key) } - var available []DatasourceRef + // 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 DatasourceRef{}, fmt.Errorf("error listing the datasources of project '%s': %w", key.Project, err) + return resolvedDatasource{}, fmt.Errorf("error listing the datasources of project '%s': %w", key.Project, err) } - candidates := map[string]datasource.Spec{} + specs := map[string]datasource.Spec{} for _, ds := range datasources { - candidates[ds.Metadata.Name] = ds.Spec - } - if name, ok := pickDefault(candidates); ok { - return DatasourceRef{Name: name, Project: key.Project}, nil + specs[ds.Metadata.Name] = ds.Spec } - for _, name := range prometheusNames(candidates) { - available = append(available, DatasourceRef{Name: name, Project: key.Project}) + 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 { - return DatasourceRef{}, fmt.Errorf("error listing the global datasources: %w", err) + return resolvedDatasource{}, fmt.Errorf("error listing the global datasources: %w", err) } - candidates := map[string]datasource.Spec{} + specs := map[string]datasource.Spec{} for _, ds := range globals { - candidates[ds.Metadata.Name] = ds.Spec + specs[ds.Metadata.Name] = ds.Spec } - if name, ok := pickDefault(candidates); ok { - return DatasourceRef{Name: name}, nil + globalCandidates := prometheusCandidates(specs, "") + if resolved, found, err := resolveDefault(globalCandidates); found { + return resolved, err } - for _, name := range prometheusNames(candidates) { - available = append(available, DatasourceRef{Name: name}) + 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(available) { + switch len(usable) { case 0: - return DatasourceRef{}, errors.New("no Prometheus datasource found: create one in Perses or pass datasource.name") + 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: no ambiguity. - return available[0], nil - } - names := make([]string, 0, len(available)) - for _, ref := range available { - if ref.Project == "" { - names = append(names, ref.Name+" (global)") - } else { - names = append(names, fmt.Sprintf("%s (project %s)", ref.Name, ref.Project)) + // 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 DatasourceRef{}, fmt.Errorf("no default Prometheus datasource found: pass datasource.name (and datasource.project for a project datasource), available Prometheus datasources: %s", - strings.Join(names, ", ")) + return resolvedDatasource{}, false, nil } -func (r *resolver) resolveNamed(key DatasourceRef) (DatasourceRef, error) { +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 DatasourceRef{}, fmt.Errorf("error retrieving %s: %w", key, err) + 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 DatasourceRef{}, fmt.Errorf("error retrieving %s (set datasource.project for a project datasource): %w", key, err) + 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 DatasourceRef{}, fmt.Errorf("%s is a %s, not a %s", key, spec.Plugin.Kind, prometheusDatasourceKind) - } - return key, nil -} - -// pickDefault returns the Prometheus datasource marked as default. -func pickDefault(candidates map[string]datasource.Spec) (string, bool) { - for _, name := range prometheusNames(candidates) { - if candidates[name].Default { - return name, true - } + return resolvedDatasource{}, fmt.Errorf("%s is a %s, not a %s", key, spec.Plugin.Kind, prometheusDatasourceKind) } - return "", false + return newResolvedDatasource(key, spec) } -// prometheusNames returns the sorted names of the Prometheus datasources. -func prometheusNames(candidates map[string]datasource.Spec) []string { - var names []string - for name, spec := range candidates { +// 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 { - names = append(names, name) + candidates = append(candidates, candidate{ref: DatasourceRef{Name: name, Project: project}, spec: spec}) } } - sort.Strings(names) - return names + sort.Slice(candidates, func(i, j int) bool { return candidates[i].ref.Name < candidates[j].ref.Name }) + return candidates } diff --git a/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go index 2045423..db571a8 100644 --- a/pkg/tools/prometheus/helpers_test.go +++ b/pkg/tools/prometheus/helpers_test.go @@ -39,6 +39,12 @@ type testDatasource struct { 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 @@ -67,6 +73,8 @@ type fakePerses struct { 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 + // forbidGlobalList makes the list of the global datasources fail with 403. + forbidGlobalList bool } func newFakePerses(t *testing.T, answers map[string]answer) *fakePerses { @@ -153,6 +161,10 @@ func (f *fakePerses) serveDatasources(w http.ResponseWriter, r *http.Request) { 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] @@ -184,6 +196,23 @@ func (f *fakePerses) serveDatasources(w http.ResponseWriter, r *http.Request) { } 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 != "" { @@ -195,7 +224,7 @@ func encodeDatasource(ds testDatasource) map[string]any { "metadata": metadata, "spec": map[string]any{ "default": ds.Default, - "plugin": map[string]any{"kind": ds.Kind, "spec": map[string]any{}}, + "plugin": map[string]any{"kind": ds.Kind, "spec": pluginSpec}, }, } } diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index af6cc78..02f0a98 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -32,6 +32,8 @@ func TestResolve(t *testing.T) { {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 @@ -48,6 +50,10 @@ func TestResolve(t *testing.T) { {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 { @@ -69,13 +75,40 @@ func TestResolve(t *testing.T) { if err != nil { t.Fatalf("Resolve() error: %v", err) } - if got != tt.want { - t.Errorf("Resolve() = %+v, want %+v", got, tt.want) + 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 @@ -150,21 +183,25 @@ func TestResolveTimeRange(t *testing.T) { func TestResolveStep(t *testing.T) { tests := []struct { - step string - span time.Duration - want time.Duration + step string + span time.Duration + minStep time.Duration + want time.Duration }{ - {span: time.Hour, want: 15 * time.Second}, - {span: 6 * time.Hour, want: 44 * time.Second}, - {span: 7 * 24 * time.Hour, want: 1210 * time.Second}, - {step: "1m", span: time.Hour, want: time.Minute}, + {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, want: 55 * time.Second}, + {step: "1s", span: 7 * 24 * time.Hour, minStep: time.Minute, want: 55 * time.Second}, } for _, tt := range tests { - got, err := resolveStep(tt.step, testNow.Add(-tt.span), testNow) + got, err := resolveStep(tt.step, testNow.Add(-tt.span), testNow, tt.minStep) if err != nil || got != tt.want { - t.Errorf("resolveStep(%q, %s) = %s, %v, want %s", tt.step, tt.span, got, err, tt.want) + t.Errorf("resolveStep(%q, %s, %s) = %s, %v, want %s", tt.step, tt.span, tt.minStep, got, err, tt.want) } } } @@ -215,3 +252,73 @@ func TestKeepTopSeries(t *testing.T) { t.Errorf("common = %v, want none (a series has no labels)", common) } } + +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 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 index c84bca7..f09516c 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -127,11 +127,12 @@ 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 DatasourceRef + datasource resolvedDatasource values []string warnings []string } @@ -168,7 +169,7 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l } } if err != nil { - return nil, apiError(datasource, err) + return nil, apiError(datasource.ref, err) } if search != "" { needle := strings.ToLower(search) @@ -177,7 +178,8 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l if values == nil { values = []string{} } - return &listing{datasource: datasource, values: values, warnings: append(warnings, infos...)}, nil + allWarnings := append(datasource.warnings(), warnings...) + return &listing{datasource: datasource, values: values, warnings: append(allWarnings, infos...)}, nil } // firstPage returns the first limit values (defaultLimit when limit is not set) and the page they form. @@ -199,7 +201,7 @@ func (p *prometheus) listMetricNames(ctx context.Context, input ListMetricNamesI defaultLimit = defaultMetadataMetricsLimit } returned, namesPage := firstPage(names.values, input.Limit, defaultLimit) - output := &metricNamesOutput{Datasource: names.datasource, page: namesPage, Metrics: returned, Warnings: names.warnings} + 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 @@ -230,7 +232,7 @@ func (p *prometheus) listLabelNames(ctx context.Context, input ListLabelNamesInp return nil, err } returned, labelsPage := firstPage(labels.values, input.Limit, defaultLabelsLimit) - return &labelNamesOutput{Datasource: labels.datasource, page: labelsPage, Labels: returned, Warnings: labels.warnings}, nil + 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) { @@ -239,7 +241,7 @@ func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesI return nil, err } returned, valuesPage := firstPage(values.values, input.Limit, defaultValuesLimit) - return &labelValuesOutput{Datasource: values.datasource, Label: input.Label, page: valuesPage, Values: returned, Warnings: values.warnings}, nil + return &labelValuesOutput{Datasource: values.datasource.ref, Label: input.Label, page: valuesPage, Values: returned, Warnings: values.warnings}, nil } // familySuffixes are the suffixes of the series of a metric family, with the types of the families that have them. @@ -293,20 +295,20 @@ func shortenHelp(help string) string { } // metadata returns the metadata of a metric, or of all the metrics when metric is empty. -func (p *prometheus) metadata(ctx context.Context, datasource DatasourceRef, metric string) (map[string][]v1.Metadata, error) { +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, err) + 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 DatasourceRef, metric string) ([]v1.Metadata, error) { +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 @@ -341,7 +343,7 @@ func (p *prometheus) getMetricMetadata(ctx context.Context, input GetMetricMetad }) } wg.Wait() - output := &metricMetadataOutput{Datasource: datasource, Metadata: map[string][]v1.Metadata{}, Missing: []string{}} + output := &metricMetadataOutput{Datasource: datasource.ref, Metadata: map[string][]v1.Metadata{}, Missing: []string{}, Warnings: datasource.warnings()} for i, metric := range input.Metrics { if errs[i] != nil { return nil, errs[i] diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 04f1561..9323403 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -193,8 +193,9 @@ func (p *prometheus) Query() *tools.Tool { "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 15s).", + 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), diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 7abd928..e89f33a 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -14,6 +14,7 @@ package prometheus import ( + "fmt" "net/http" "net/url" "reflect" @@ -235,10 +236,11 @@ func TestQueryRange(t *testing.T) { "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"}, - "step": "44s", + "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{ @@ -251,7 +253,7 @@ func TestQueryRange(t *testing.T) { t.Errorf("output =\n%v\nwant\n%v", output, want) } params := perses.paramsOf(globalProxy + "/api/v1/query_range") - if params.Get("step") != "44" || params.Get("start") != "1767333600" || params.Get("end") != "1767355200" { + if params.Get("step") != "60" || params.Get("start") != "1767333600" || params.Get("end") != "1767355200" { t.Errorf("params = %v", params) } @@ -409,3 +411,125 @@ func TestQueryRangeKeepsTheHighestSeries(t *testing.T) { 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 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 +} diff --git a/pkg/tools/prometheus/query.go b/pkg/tools/prometheus/query.go index 2160b0f..7c8aa78 100644 --- a/pkg/tools/prometheus/query.go +++ b/pkg/tools/prometheus/query.go @@ -81,13 +81,14 @@ func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, if rangeErr != nil { return nil, rangeErr } - step, stepErr := resolveStep(input.Step, start, end) - if stepErr != nil { - return nil, stepErr + if input.Step != "" { + if _, stepErr := parseStep(input.Step); stepErr != nil { + return nil, stepErr + } } - queryRange = v1.Range{Start: start, End: end, Step: step} + // The step is set once the datasource, and so its scrape interval, is known. + queryRange = v1.Range{Start: start, End: end} output.TimeRange = &timeRange - output.Step = model.Duration(step).String() 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") @@ -107,7 +108,13 @@ func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, if err != nil { return nil, err } - output.Datasource = datasource + 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 @@ -121,9 +128,9 @@ func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, value, warnings, infos, err = promAPI.Query(ctx, input.Query, at) } if err != nil { - return nil, apiError(datasource, err) + return nil, apiError(datasource.ref, err) } - output.Warnings = append([]string(nil), warnings...) + output.Warnings = append(datasource.warnings(), warnings...) output.Infos = infos var all []series @@ -153,7 +160,7 @@ func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, output.Value = result.Value return output, nil default: - return nil, fmt.Errorf("unexpected result type '%s' from %s", value.Type(), datasource) + 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)) diff --git a/pkg/tools/prometheus/timerange.go b/pkg/tools/prometheus/timerange.go index 67142d5..46ded07 100644 --- a/pkg/tools/prometheus/timerange.go +++ b/pkg/tools/prometheus/timerange.go @@ -26,8 +26,6 @@ const ( defaultPastDuration = "1h" // statsPoints is the number of points requested by default for range queries. statsPoints = 500 - // minStep is the minimum default step of range queries. - minStep = 15 * time.Second // maxPoints is the Prometheus limit of points per series of a range query. maxPoints = 11000 ) @@ -107,17 +105,26 @@ func parseTime(field, value string) (time.Time, error) { } // 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. -func resolveStep(step string, start, end time.Time) (time.Duration, error) { +// 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, ceilSeconds(span/statsPoints)), nil } + parsed, err := parseStep(step) + if err != nil { + return 0, err + } + return max(parsed, ceilSeconds(span/maxPoints)), nil +} + +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 max(parsed, ceilSeconds(span/maxPoints)), nil + return parsed, nil } // ceilSeconds rounds a duration up to the second. From 88f10794bb727ebef08dfa8634799951bcfe4817 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 10:49:14 +0100 Subject: [PATCH 03/21] [IGNORE] explain how to narrow lists over 1 MiB A list of metric names, label names or label values over 1 MiB returned the advice for queries ("aggregate it (sum by, topk)"). It now asks to narrow the list with match, search or time_range. search was only applied once the whole list was downloaded, so it didn't help with large lists. When the list is too large and search is set without match, the list is requested again with search as a matcher, e.g. {__name__=~"(?is).*memory.*"}, so that Prometheus filters it. The filter isn't sent from the start as it may cost Prometheus more than a plain listing. The local filter uses the same case-insensitive regular expression, so that both return the same values, also for non-ASCII values. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 7 ++-- pkg/tools/prometheus/helpers_test.go | 15 +++++++ pkg/tools/prometheus/internal_test.go | 28 +++++++++++++ pkg/tools/prometheus/list.go | 56 +++++++++++++++++++------ pkg/tools/prometheus/prometheus_test.go | 33 +++++++++++++++ 5 files changed, 123 insertions(+), 16 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index 27bc36b..cf1e87a 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -219,9 +219,10 @@ The parameters are: - `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`), 200 label names, 100 label values (max 1000), 20 series (max 100). -The list tools return `{datasource, total, returned, truncated, ...}`. 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 unavailable (e.g. over 1 MiB), the metrics are returned without it, with a warning. +The list tools return `{datasource, total, returned, truncated, ...}`. A list over 1 MiB is an error that asks to +narrow it with `match`, `search` 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 +unavailable (e.g. over 1 MiB), 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: `_bucket`, `_count`, `_sum` and `_created` of histograms and summaries, diff --git a/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go index db571a8..68988ea 100644 --- a/pkg/tools/prometheus/helpers_test.go +++ b/pkg/tools/prometheus/helpers_test.go @@ -73,6 +73,8 @@ type fakePerses struct { 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 + // 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 } @@ -88,6 +90,14 @@ func (f *fakePerses) serve(w http.ResponseWriter, r *http.Request) { f.serveDatasources(w, r) return } + if f.answer != nil { + if a := f.answer(r); a != nil { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(a.status) + _, _ = w.Write([]byte(a.body)) + return + } + } if f.metadata != nil && strings.HasSuffix(r.URL.Path, "/api/v1/metadata") { f.serveMetadata(w, r.URL.Query().Get("metric")) return @@ -195,6 +205,11 @@ func (f *fakePerses) serveDatasources(w http.ResponseWriter, r *http.Request) { _ = 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 { diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 02f0a98..d3d1f63 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -16,6 +16,8 @@ package prometheus import ( "math" "reflect" + "regexp" + "strconv" "strings" "testing" "time" @@ -206,6 +208,12 @@ func TestResolveStep(t *testing.T) { } } +func TestSearchSelector(t *testing.T) { + if got, want := searchSelector("__name__", `mem.x"y`), `{__name__=~"(?is).*mem\\.x\"y.*"}`; got != want { + t.Errorf("searchSelector() = %s, want %s", got, want) + } +} + func TestSeriesStats(t *testing.T) { samples := []model.SamplePair{ {Timestamp: 1767355200000, Value: 2}, @@ -322,3 +330,23 @@ func TestResolveCacheRefreshesTheSettings(t *testing.T) { t.Errorf("refreshed = %+v, want the new settings", refreshed) } } + +func TestSearchMatchesLikePrometheus(t *testing.T) { + values := []string{"İstanbul", "ISTANBUL", "istanbul", "Kelvin", "\u212aelvin", "Straße", "STRASSE", "line\nmemory", "MEMORY", "x.y", "xay"} + for _, search := range []string{"istanbul", "k", "ss", "memory", "x.y"} { + local := regexp.MustCompile(searchPattern(search)) + selector := searchSelector("label", search) + quoted, found := strings.CutPrefix(selector, "{label=~") + pattern, err := strconv.Unquote(strings.TrimSuffix(quoted, "}")) + if !found || err != nil { + t.Fatalf("searchSelector(%q) = %s: %v", search, selector, err) + } + // Prometheus anchors the regular expressions of matchers. + remote := regexp.MustCompile("^(?:" + pattern + ")$") + for _, value := range values { + if local.MatchString(value) != remote.MatchString(value) { + t.Errorf("search %q, value %q: local match %v, Prometheus match %v", search, value, local.MatchString(value), remote.MatchString(value)) + } + } + } +} diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index f09516c..d79c780 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -16,8 +16,11 @@ package prometheus import ( "context" "encoding/json" + "errors" "fmt" + "regexp" "slices" + "strconv" "strings" "sync" @@ -139,6 +142,10 @@ type listing struct { // list resolves the time range and the datasource, then lists the label names (label empty) or the values of a // label, filtered by search (case-insensitive). +// +// When the list is too large and search is set without match, it is requested again with search as a regular +// expression matcher on the label, so that Prometheus filters it: the filter isn't sent from the start as it may cost +// Prometheus more than a plain listing. func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, label string, match Selectors, timeRange *TimeRangeInput, search string) (*listing, error) { start, end, _, err := resolveTimeRange(timeRange, p.now()) if err != nil { @@ -152,28 +159,35 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l 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)) + fetch := func(match Selectors) ([]string, v1.Warnings, v1.Infos, error) { + var values []string + if label == "" { + names, warnings, infos, fetchErr := promAPI.LabelNames(ctx, match, start, end) + for _, name := range names { + values = append(values, string(name)) + } + return values, warnings, infos, fetchErr } - } else { - var labelValues model.LabelValues - labelValues, warnings, infos, err = promAPI.LabelValues(ctx, label, match, start, end) + labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, label, match, start, end) for _, value := range labelValues { values = append(values, string(value)) } + return values, warnings, infos, fetchErr + } + values, warnings, infos, err := fetch(match) + if errors.Is(err, errTooMuchData) && search != "" && label != "" && len(match) == 0 { + values, warnings, infos, err = fetch(Selectors{searchSelector(label, search)}) + } + if errors.Is(err, errTooMuchData) { + return nil, errListTooLarge } if err != nil { return nil, apiError(datasource.ref, err) } if search != "" { - needle := strings.ToLower(search) - values = slices.DeleteFunc(values, func(value string) bool { return !strings.Contains(strings.ToLower(value), needle) }) + // The same matching as searchSelector, so that a list filtered by Prometheus has the same values. + matcher := regexp.MustCompile(searchPattern(search)) + values = slices.DeleteFunc(values, func(value string) bool { return !matcher.MatchString(value) }) } if values == nil { values = []string{} @@ -182,6 +196,22 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l return &listing{datasource: datasource, values: values, warnings: append(allWarnings, infos...)}, nil } +var errListTooLarge = errors.New("the list is too large (over 1 MiB): narrow it with match (e.g. {job=\"node\"}), " + + "search or a shorter time_range") + +// searchPattern returns the regular expression of the values that contain search, ignoring case. Prometheus uses the +// regular expressions of Go (RE2) for its matchers, so the values match the same way here and in Prometheus. +func searchPattern(search string) string { + return "(?i)" + regexp.QuoteMeta(search) +} + +// searchSelector returns a series selector of the values of label that contain search, ignoring case. Prometheus +// anchors the regular expressions of matchers, hence the surrounding ".*", which also matches newlines with the +// flag s (the default since Prometheus 3 only). +func searchSelector(label, search string) string { + return fmt.Sprintf("{%s=~%s}", label, strconv.Quote("(?is).*"+regexp.QuoteMeta(search)+".*")) +} + // 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 { diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index e89f33a..f360c5b 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -467,6 +467,39 @@ func TestDatasourceSettingsApplyToEveryRequest(t *testing.T) { } } +func TestListTooLarge(t *testing.T) { + path := globalProxy + "/api/v1/label/__name__/values" + perses := newFakePerses(t, nil) + perses.answer = func(r *http.Request) *answer { + if r.URL.Path != path { + return nil + } + // Prometheus filters the names when the search is sent as a matcher. + if r.URL.Query().Get("match[]") == `{__name__=~"(?is).*MEMORY.*"}` { + return new(ok(`["process_resident_memory_bytes","up_memory"]`)) + } + return &answer{status: http.StatusOK, body: tooLarge(`[]`)} + } + session := connect(t, perses) + + // With search and without match, the list is requested again with search as a matcher. + output := decode(t, call(t, session, ListMetricNamesToolName, map[string]any{"search": "MEMORY"}, false)) + if !reflect.DeepEqual(output["metrics"], []any{"process_resident_memory_bytes", "up_memory"}) { + t.Errorf("metrics = %v", output["metrics"]) + } + if got := perses.Count(http.MethodGet, path); got != 2 { + t.Errorf("%d requests, want 2", got) + } + + // Otherwise, the error tells how to narrow the list, not how to aggregate a query. + for _, arguments := range []map[string]any{nil, {"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) + } + } +} + func TestQueryParamsDontOverrideTheRequestParameters(t *testing.T) { labels := globalProxy + "/api/v1/labels" for _, fallback := range []bool{false, true} { From 35bee8fe5c9cf635c21571495dc77b0991f2755f Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 10:49:33 +0100 Subject: [PATCH 04/21] [IGNORE] look up the metadata of the listed metrics when it is too large With include_metadata, the metadata of all the metrics is fetched in one request, then most of it is dropped: on large instances it is over 1 MiB, and the metrics were returned without metadata. The metadata of the returned metrics is now looked up one by one in that case, at most 8 at a time with errgroup, which cancels the lookups in progress on the first error. The limit with include_metadata is capped at 200. perses_get_prometheus_metric_metadata uses the same lookups. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 14 ++-- go.mod | 2 +- pkg/tools/prometheus/helpers_test.go | 7 ++ pkg/tools/prometheus/list.go | 73 ++++++++++++++------- pkg/tools/prometheus/prometheus.go | 4 +- pkg/tools/prometheus/prometheus_test.go | 87 +++++++++++++++++++++++-- 6 files changed, 152 insertions(+), 35 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index cf1e87a..fbff7f6 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -213,16 +213,20 @@ 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. +- `search`: a case-insensitive substring filter, applied by the MCP server. When the list is over 1 MiB and `match` is + not set, the list is requested again with `search` as a regular expression matcher (e.g. + `{__name__=~"(?is).*memory.*"}`), so that Prometheus filters it. Both match the same way: Prometheus uses the + same regular expressions (RE2). - `time_range`: `{past_duration}` (e.g. `"6h"`, `"7d"`), or `{start, end}` in RFC 3339 (`end` defaults to now). The past hour by default, so that the list tools only return current series. -- `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`), 200 label - names, 100 label values (max 1000), 20 series (max 100). +- `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`, max 200), 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`, `search` 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 -unavailable (e.g. over 1 MiB), the metrics are returned without it, with a warning. +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: `_bucket`, `_count`, `_sum` and `_created` of histograms and summaries, diff --git a/go.mod b/go.mod index 2a2d327..0ac9e96 100644 --- a/go.mod +++ b/go.mod @@ -12,6 +12,7 @@ require ( 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 ( @@ -120,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/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go index 68988ea..6c74bbf 100644 --- a/pkg/tools/prometheus/helpers_test.go +++ b/pkg/tools/prometheus/helpers_test.go @@ -73,6 +73,8 @@ type fakePerses struct { 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. @@ -117,6 +119,11 @@ func (f *fakePerses) serve(w http.ResponseWriter, r *http.Request) { } 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{} diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index d79c780..62867e3 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -22,20 +22,24 @@ import ( "slices" "strconv" "strings" - "sync" 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 - defaultLabelsLimit = 200 - defaultValuesLimit = 100 - maxListLimit = 1000 - maxMetadataMetrics = 20 + // maxMetadataMetricsLimit caps the metric names listed with their metadata, which may be looked up one by one. + maxMetadataMetricsLimit = 200 + 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 ) @@ -226,17 +230,24 @@ func (p *prometheus) listMetricNames(ctx context.Context, input ListMetricNamesI if err != nil { return nil, err } - defaultLimit := defaultMetricsLimit + limit, defaultLimit := input.Limit, defaultMetricsLimit if input.IncludeMetadata { defaultLimit = defaultMetadataMetricsLimit + if limit > maxMetadataMetricsLimit { + limit = maxMetadataMetricsLimit + } } - returned, namesPage := firstPage(names.values, input.Limit, defaultLimit) + 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", @@ -356,6 +367,32 @@ func (p *prometheus) metricMetadata(ctx context.Context, datasource resolvedData 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) @@ -364,25 +401,15 @@ func (p *prometheus) getMetricMetadata(ctx context.Context, input GetMetricMetad if err != nil { return nil, err } - results := make([][]v1.Metadata, len(input.Metrics)) - errs := make([]error, len(input.Metrics)) - var wg sync.WaitGroup - for i, metric := range input.Metrics { - wg.Go(func() { - results[i], errs[i] = p.metricMetadata(ctx, datasource, metric) - }) + metadata, err := p.lookupMetadata(ctx, datasource, input.Metrics) + if err != nil { + return nil, err } - wg.Wait() - output := &metricMetadataOutput{Datasource: datasource.ref, Metadata: map[string][]v1.Metadata{}, Missing: []string{}, Warnings: datasource.warnings()} - for i, metric := range input.Metrics { - if errs[i] != nil { - return nil, errs[i] - } - if len(results[i]) == 0 { + 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) - continue } - output.Metadata[metric] = results[i] } return output, nil } diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 9323403..991a067 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -83,8 +83,8 @@ func (p *prometheus) ListMetricNames() *tools.Tool { "match": matchSchema(), "search": searchSchema(), "time_range": discoveryTimeRangeSchema(), - "limit": limitSchema(fmt.Sprintf("Maximum number of metrics returned (default %d, %d with include_metadata, max %d).", - defaultMetricsLimit, defaultMetadataMetricsLimit, maxListLimit), maxListLimit), + "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.", diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index f360c5b..b469d6e 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -14,12 +14,15 @@ package prometheus import ( + "encoding/json" "fmt" "net/http" "net/url" "reflect" "strings" + "sync/atomic" "testing" + "time" "github.com/perses/mcp-server/pkg/tools" "github.com/perses/mcp-server/pkg/tools/internal/tooltest" @@ -176,16 +179,16 @@ func TestGetMetricMetadata(t *testing.T) { t.Errorf("missing = %v", output["missing"]) } // A metric with metadata under its own name is looked up once. - if count := countRequests(perses, globalProxy+"/api/v1/metadata", "metric", "queue_count") + countRequests(perses, globalProxy+"/api/v1/metadata", "metric", "queue"); count != 1 { + if count := countMetadataRequests(perses, "queue_count") + countMetadataRequests(perses, "queue"); count != 1 { t.Errorf("%d metadata requests for queue_count, want 1", count) } } -// countRequests returns the number of requests of path with the query parameter key set to value. -func countRequests(perses *fakePerses, path, key, value string) int { +// 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 == path && params.Get(key) == value { + if params, err := url.ParseQuery(request.RawQuery); err == nil && request.Path == globalProxy+"/api/v1/metadata" && params.Get("metric") == metric { count++ } } @@ -500,6 +503,44 @@ func TestListTooLarge(t *testing.T) { } } +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} { @@ -566,3 +607,41 @@ func effectiveParams(t *testing.T, perses *fakePerses, method, path string) url. 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) + } +} From 1286d9b3f1427546db566e65a62995736fd324d9 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 11:39:38 +0100 Subject: [PATCH 05/21] [IGNORE] address the review of the Prometheus tools - The metadata of the _gcount and _gsum series of gauge histograms and of the _info series of info metrics is looked up under their family name, as Prometheus does. Gauge histograms have no _created series. - perses_list_prometheus_label_values accepts the UTF-8 label names of Prometheus 3, e.g. http.method. The name is escaped in the URL path (U__http_2e_method) as Prometheus documents it, which also matches the allowedEndpoints patterns of the Perses proxy, and quoted in the selector of search. - NaN is sorted after -Inf, so that a limited instant result keeps the numbers first. - Values keep all the digits of their integer part: with 4 significant digits, a timestamp such as process_start_time_seconds was wrong by days. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 10 +++--- pkg/tools/prometheus/internal_test.go | 41 +++++++++++++++++++++-- pkg/tools/prometheus/list.go | 23 ++++++++++--- pkg/tools/prometheus/prometheus.go | 15 +++++---- pkg/tools/prometheus/prometheus_test.go | 43 +++++++++++++++++-------- pkg/tools/prometheus/series.go | 11 +++++-- 6 files changed, 110 insertions(+), 33 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index fbff7f6..2dd4013 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -229,8 +229,9 @@ and help, shortened to 80 characters. The metadata of all the metrics is fetched 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: `_bucket`, `_count`, `_sum` and `_created` of histograms and summaries, -`_total` of counters (e.g. `http_requests_total` of the counter `http_requests`). +when the family has series with this suffix: `_total` and `_created` of counters, `_bucket`, `_count`, `_sum` and +`_created` of histograms, `_bucket`, `_count`, `_sum`, `_gcount` and `_gsum` of gauge histograms, `_count`, `_sum` and +`_created` of summaries, `_info` of info metrics (e.g. `http_requests_total` of the counter `http_requests`). `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 @@ -244,8 +245,9 @@ datasource; see [Datasource settings](#datasource-settings)). It returns: last sample. A series that only has NaN or infinite samples is not returned, with a warning. `minAt` and `maxAt` are formatted in `time_zone` (default UTC). -The labels shared by all returned series are returned once in `commonLabels`. The values keep 4 significant digits; -NaN and infinities are returned as strings. Native histograms are not summarized: the tool returns an error that +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()`. 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 diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index d3d1f63..3849631 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -212,6 +212,10 @@ func TestSearchSelector(t *testing.T) { if got, want := searchSelector("__name__", `mem.x"y`), `{__name__=~"(?is).*mem\\.x\"y.*"}`; got != want { t.Errorf("searchSelector() = %s, want %s", got, want) } + // A UTF-8 label name is quoted. + if got, want := searchSelector("http.method", "get"), `{"http.method"=~"(?is).*get.*"}`; got != want { + t.Errorf("searchSelector() = %s, want %s", got, want) + } } func TestSeriesStats(t *testing.T) { @@ -232,8 +236,8 @@ func TestSeriesStats(t *testing.T) { } // 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) || got.Avg != round(math.MaxFloat64/3) { - t.Errorf("average of large values = %v, want %v", got.Avg, round(math.MaxFloat64/3)) + 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) } } @@ -261,6 +265,39 @@ func TestKeepTopSeries(t *testing.T) { } } +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 { + 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) diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index 62867e3..2a3c488 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -172,7 +172,11 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l } return values, warnings, infos, fetchErr } - labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, label, match, start, end) + // The Prometheus client puts the label name in the URL path as is: a UTF-8 name (e.g. 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. Other names are kept unchanged. + escapedLabel := model.EscapeName(label, model.ValueEncodingEscaping) + labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, escapedLabel, match, start, end) for _, value := range labelValues { values = append(values, string(value)) } @@ -211,9 +215,14 @@ func searchPattern(search string) string { // searchSelector returns a series selector of the values of label that contain search, ignoring case. Prometheus // anchors the regular expressions of matchers, hence the surrounding ".*", which also matches newlines with the -// flag s (the default since Prometheus 3 only). +// flag s (the default since Prometheus 3 only). A UTF-8 label name is quoted, as Prometheus 3 requires; other names are +// not, so that the selector also works with older versions. func searchSelector(label, search string) string { - return fmt.Sprintf("{%s=~%s}", label, strconv.Quote("(?is).*"+regexp.QuoteMeta(search)+".*")) + name := label + if !model.LegacyValidation.IsValidLabelName(label) { + name = strconv.Quote(label) + } + return fmt.Sprintf("{%s=~%s}", name, strconv.Quote("(?is).*"+regexp.QuoteMeta(search)+".*")) } // firstPage returns the first limit values (defaultLimit when limit is not set) and the page they form. @@ -286,7 +295,8 @@ func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesI } // familySuffixes are the suffixes of the series of a metric family, with the types of the families that have them. -// The metadata of these series may be under the family name, e.g. http_requests for http_requests_total. +// The metadata of these series may be under the family name, e.g. http_requests for http_requests_total. They are the +// suffixes with which Prometheus matches metadata, plus _created (OpenMetrics), which gauge histograms don't have. var familySuffixes = []struct { suffix string types []v1.MetricType @@ -294,8 +304,11 @@ var familySuffixes = []struct { {"_bucket", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram}}, {"_count", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, {"_sum", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, - {"_created", []v1.MetricType{v1.MetricTypeCounter, v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, + {"_gcount", []v1.MetricType{v1.MetricTypeGaugeHistogram}}, + {"_gsum", []v1.MetricType{v1.MetricTypeGaugeHistogram}}, + {"_created", []v1.MetricType{v1.MetricTypeCounter, v1.MetricTypeHistogram, v1.MetricTypeSummary}}, {"_total", []v1.MetricType{v1.MetricTypeCounter}}, + {"_info", []v1.MetricType{v1.MetricTypeInfo}}, } // familyName returns the name of the metric family a series name may belong to, and the types of such a family. diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 991a067..763a023 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -35,8 +35,6 @@ const ( QueryToolName = "perses_query_prometheus" ) -const labelNamePattern = `^[a-zA-Z_][a-zA-Z0-9_]*$` - type prometheus struct { client apiClient.ClientInterface resolver *resolver @@ -130,7 +128,10 @@ func (p *prometheus) ListLabelValues() *tools.Tool { "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, Pattern: labelNamePattern, Description: "Label name, e.g. \"job\"."}, + "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(), @@ -159,8 +160,9 @@ func (p *prometheus) GetMetricMetadata() *tools.Tool { 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 and counters "+ - "(_bucket, _count, _sum, _total) are also looked up under their family name.", maxMetadataMetrics), + Description: fmt.Sprintf("Metric names (1 to %d). The series of histograms, summaries, counters and info "+ + "metrics (_bucket, _count, _sum, _gcount, _gsum, _created, _total, _info) are also looked up under their "+ + "family name.", maxMetadataMetrics), }, }, "metrics"), } @@ -182,7 +184,8 @@ func (p *prometheus) Query() *tools.Tool { "`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. Errors of Prometheus (e.g. bad_data: parse error) are returned unchanged.", + "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."}, diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index b469d6e..e39dfc7 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -121,7 +121,16 @@ func TestListLabels(t *testing.T) { t.Errorf("start = %s", got) } - call(t, session, ListLabelValuesToolName, map[string]any{"label": "bad-label"}, true) + 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"]`)}) + output := decode(t, call(t, connect(t, perses), 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) + } } func TestProxyRequestsUseThePersesCredentials(t *testing.T) { @@ -156,26 +165,34 @@ func TestListMetricNamesWithUnavailableMetadata(t *testing.T) { 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."}}, - "temperature": {{Type: v1.MetricTypeGauge, Help: "Temperature."}}, + "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."}}, + "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"}, + "metrics": []any{ + "up", "queue_count", "x_seconds_bucket", "requests_total", "temperature_total", "nope", + "jobs_waiting_gcount", "jobs_waiting_gsum", "jobs_waiting_created", "build_info", + }, }, 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": ""}}, + "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": ""}}, } if !reflect.DeepEqual(output["metadata"], want) { t.Errorf("metadata =\n%v\nwant\n%v", output["metadata"], want) } - // temperature is a gauge: it is not the family of temperature_total. - if !reflect.DeepEqual(output["missing"], []any{"temperature_total", "nope"}) { + // temperature is a gauge: it is not the family of temperature_total. Gauge histograms have no _created series. + if !reflect.DeepEqual(output["missing"], []any{"temperature_total", "nope", "jobs_waiting_created"}) { t.Errorf("missing = %v", output["missing"]) } // A metric with metadata under its own name is looked up once. diff --git a/pkg/tools/prometheus/series.go b/pkg/tools/prometheus/series.go index d908bee..8b8f0f0 100644 --- a/pkg/tools/prometheus/series.go +++ b/pkg/tools/prometheus/series.go @@ -124,11 +124,12 @@ func labels(metric model.Metric) map[string]string { return result } -// sampleValue returns the rounded value of a sample, or a string for NaN and infinities, and its sort key (NaN last). +// 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", math.Inf(-1) + return "NaN", value case math.IsInf(value, 1): return "+Inf", value case math.IsInf(value, -1): @@ -173,8 +174,12 @@ func seriesStats(samples []model.SamplePair, location *time.Location) (result st return result, maxValue, true } -// round keeps 4 significant digits. +// 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 From 1d735866c086243718df377e9340feb3fc603a13 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 11:58:51 +0100 Subject: [PATCH 06/21] [IGNORE] keep subsecond steps and escape U__ label names - An explicit step is only raised to the smallest step that stays under the Prometheus limit of 11000 points, rounded up to the millisecond under a second: a step of 100ms over 1 minute was raised to 1s. - Prometheus unescapes every label name starting with U__ on the label values endpoint, so these names are always escaped: the label U__job was read as job. Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/internal_test.go | 30 +++++++++++++++++++ pkg/tools/prometheus/list.go | 18 ++++++++---- pkg/tools/prometheus/prometheus_test.go | 39 +++++++++++++++++++++++-- pkg/tools/prometheus/timerange.go | 21 +++++++++---- 4 files changed, 96 insertions(+), 12 deletions(-) diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 3849631..39164f0 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -199,6 +199,10 @@ func TestResolveStep(t *testing.T) { {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 { got, err := resolveStep(tt.step, testNow.Add(-tt.span), testNow, tt.minStep) @@ -218,6 +222,32 @@ func TestSearchSelector(t *testing.T) { } } +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"}, + } + for _, tt := range tests { + got := escapeLabelName(tt.label) + if got != tt.want { + t.Errorf("escapeLabelName(%q) = %q, want %q", tt.label, got, tt.want) + } + // 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}, diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index 2a3c488..9b79bb6 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -172,11 +172,7 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l } return values, warnings, infos, fetchErr } - // The Prometheus client puts the label name in the URL path as is: a UTF-8 name (e.g. 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. Other names are kept unchanged. - escapedLabel := model.EscapeName(label, model.ValueEncodingEscaping) - labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, escapedLabel, match, start, end) + labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, escapeLabelName(label), match, start, end) for _, value := range labelValues { values = append(values, string(value)) } @@ -207,6 +203,18 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l var errListTooLarge = errors.New("the list is too large (over 1 MiB): narrow it with match (e.g. {job=\"node\"}), " + "search 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 UTF-8 name (e.g. 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; other names are kept unchanged. +// 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 strings.HasPrefix(label, "U__") && model.LegacyValidation.IsValidMetricName(label) { + // EscapeName keeps the legacy names unchanged: in them, only the underscores are escaped (doubled). + return "U__" + strings.ReplaceAll(label, "_", "__") + } + return model.EscapeName(label, model.ValueEncodingEscaping) +} + // searchPattern returns the regular expression of the values that contain search, ignoring case. Prometheus uses the // regular expressions of Go (RE2) for its matchers, so the values match the same way here and in Prometheus. func searchPattern(search string) string { diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index e39dfc7..6bb76c0 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -126,11 +126,34 @@ func TestListLabels(t *testing.T) { 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"]`)}) - output := decode(t, call(t, connect(t, perses), ListLabelValuesToolName, map[string]any{"label": "http.method"}, false)) + path := globalProxy + "/api/v1/label/U__http_2e_method/values" + var tooLargeList atomic.Bool + perses := newFakePerses(t, nil) + perses.answer = func(r *http.Request) *answer { + if r.URL.Path != path { + return nil + } + // Prometheus filters the values when the search is sent as a matcher on the quoted label name. + if r.URL.Query().Get("match[]") == `{"http.method"=~"(?is).*get.*"}` { + return new(ok(`["GET"]`)) + } + if tooLargeList.Load() { + return &answer{status: http.StatusOK, body: tooLarge(`[]`)} + } + return new(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) } + + // When the list is too large, it is requested again with search as a matcher. + tooLargeList.Store(true) + output = decode(t, call(t, session, ListLabelValuesToolName, map[string]any{"label": "http.method", "search": "get"}, false)) + if !reflect.DeepEqual(output["values"], []any{"GET"}) { + t.Errorf("values with search = %v", output["values"]) + } } func TestProxyRequestsUseThePersesCredentials(t *testing.T) { @@ -287,6 +310,18 @@ func TestQueryRange(t *testing.T) { 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 TestQueryScalar(t *testing.T) { diff --git a/pkg/tools/prometheus/timerange.go b/pkg/tools/prometheus/timerange.go index 46ded07..b6ebfc8 100644 --- a/pkg/tools/prometheus/timerange.go +++ b/pkg/tools/prometheus/timerange.go @@ -110,13 +110,24 @@ func parseTime(field, value string) (time.Time, error) { func resolveStep(step string, start, end time.Time, minStep time.Duration) (time.Duration, error) { span := end.Sub(start) if step == "" { - return max(minStep, ceilSeconds(span/statsPoints)), nil + return max(minStep, ceilTo(span/statsPoints, time.Second)), nil } parsed, err := parseStep(step) if err != nil { return 0, err } - return max(parsed, ceilSeconds(span/maxPoints)), nil + 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) { @@ -127,9 +138,9 @@ func parseStep(step string) (time.Duration, error) { return parsed, nil } -// ceilSeconds rounds a duration up to the second. -func ceilSeconds(duration time.Duration) time.Duration { - return (duration + time.Second - 1).Truncate(time.Second) +// 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. From 8acd3587194a64029e4f448d1c2971fd685d4efa Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 16:01:37 +0100 Subject: [PATCH 07/21] [IGNORE] keep the base URL query and fractional seconds - The proxy path is appended to the path of the Perses base URL instead of the serialized URL, like the datasource query tools do: with a query string in the base URL, the path was appended to the query. - The times of the outputs (instant query time, absolute time range) keep their fractional seconds (RFC 3339 with nanoseconds), so that they are the times that were queried. Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/client.go | 8 ++++- pkg/tools/prometheus/internal_test.go | 6 ++++ pkg/tools/prometheus/prometheus_test.go | 41 +++++++++++++++++++++++++ pkg/tools/prometheus/query.go | 2 +- pkg/tools/prometheus/timerange.go | 8 ++++- 5 files changed, 62 insertions(+), 3 deletions(-) diff --git a/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go index 1e1ded3..47cb406 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -50,8 +50,14 @@ func (p *prometheus) newAPI(datasource resolvedDatasource) (v1.API, error) { 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: strings.TrimRight(restClient.BaseURL.String(), "/") + path, + Address: address.String(), Client: &http.Client{Transport: &persesTransport{ client: restClient.Client, headers: restClient.Headers, queryParams: datasource.queryParams, }}, diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 39164f0..f4da160 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -156,6 +156,12 @@ func TestResolveTimeRange(t *testing.T) { 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'"}, diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 6bb76c0..af2f7f3 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -14,9 +14,11 @@ package prometheus import ( + "context" "encoding/json" "fmt" "net/http" + "net/http/httptest" "net/url" "reflect" "strings" @@ -26,6 +28,9 @@ import ( "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" ) @@ -170,6 +175,31 @@ func TestProxyRequestsUseThePersesCredentials(t *testing.T) { } } +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"]`), @@ -324,6 +354,17 @@ func TestQueryRange(t *testing.T) { } } +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)) diff --git a/pkg/tools/prometheus/query.go b/pkg/tools/prometheus/query.go index 7c8aa78..f10ca78 100644 --- a/pkg/tools/prometheus/query.go +++ b/pkg/tools/prometheus/query.go @@ -99,7 +99,7 @@ func (p *prometheus) query(ctx context.Context, input QueryInput) (*queryOutput, return nil, err } } - output.Time = at.UTC().Format(time.RFC3339) + output.Time = formatTimestamp(at) default: return nil, fmt.Errorf("invalid type '%s': use '%s' or '%s'", input.Type, instantQuery, rangeQuery) } diff --git a/pkg/tools/prometheus/timerange.go b/pkg/tools/prometheus/timerange.go index b6ebfc8..0ceed76 100644 --- a/pkg/tools/prometheus/timerange.go +++ b/pkg/tools/prometheus/timerange.go @@ -81,7 +81,13 @@ func resolveTimeRange(input *TimeRangeInput, now time.Time) (time.Time, time.Tim 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: start.UTC().Format(time.RFC3339), End: end.UTC().Format(time.RFC3339)}, nil + 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 t.UTC().Format(time.RFC3339Nano) } // parseDuration parses a positive Prometheus duration, e.g. "15m", "1h30m" or "7d". From c348903115a37e2efa89fbcfc0984c0e8e149af9 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 16:19:22 +0100 Subject: [PATCH 08/21] [IGNORE] match metadata like Prometheus and drop the search fallback - The metadata of a series is looked up under its family name exactly as Prometheus does (metadataForMetric of its search API): the suffix after the last underscore, with the types of the families that have it. A _created series isn't matched anymore, as it holds a timestamp, and x_total_total isn't a series of the family x_total. - A list over 1 MiB is no longer requested again with search as a PromQL matcher: the error asks to narrow it with match (e.g. {__name__=~".*memory.*"}). search is a plain case-insensitive substring filter of the list, so no label name is encoded in a PromQL selector. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 15 ++-- pkg/tools/prometheus/internal_test.go | 32 ------- pkg/tools/prometheus/list.go | 106 +++++++++--------------- pkg/tools/prometheus/prometheus.go | 4 +- pkg/tools/prometheus/prometheus_test.go | 65 ++++----------- 5 files changed, 68 insertions(+), 154 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index 2dd4013..94dca4b 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -213,25 +213,24 @@ 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. When the list is over 1 MiB and `match` is - not set, the list is requested again with `search` as a regular expression matcher (e.g. - `{__name__=~"(?is).*memory.*"}`), so that Prometheus filters it. Both match the same way: Prometheus uses the - same regular expressions (RE2). +- `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, so that the list tools only return current series. - `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`, max 200), 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`, `search` or `time_range`. With `include_metadata: true`, each metric name comes with its type +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: `_total` and `_created` of counters, `_bucket`, `_count`, `_sum` and -`_created` of histograms, `_bucket`, `_count`, `_sum`, `_gcount` and `_gsum` of gauge histograms, `_count`, `_sum` and -`_created` of summaries, `_info` of info metrics (e.g. `http_requests_total` of the counter `http_requests`). +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 diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index f4da160..85a6816 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -16,8 +16,6 @@ package prometheus import ( "math" "reflect" - "regexp" - "strconv" "strings" "testing" "time" @@ -218,16 +216,6 @@ func TestResolveStep(t *testing.T) { } } -func TestSearchSelector(t *testing.T) { - if got, want := searchSelector("__name__", `mem.x"y`), `{__name__=~"(?is).*mem\\.x\"y.*"}`; got != want { - t.Errorf("searchSelector() = %s, want %s", got, want) - } - // A UTF-8 label name is quoted. - if got, want := searchSelector("http.method", "get"), `{"http.method"=~"(?is).*get.*"}`; got != want { - t.Errorf("searchSelector() = %s, want %s", got, want) - } -} - func TestEscapeLabelName(t *testing.T) { tests := []struct{ label, want string }{ {label: "job", want: "job"}, @@ -403,23 +391,3 @@ func TestResolveCacheRefreshesTheSettings(t *testing.T) { t.Errorf("refreshed = %+v, want the new settings", refreshed) } } - -func TestSearchMatchesLikePrometheus(t *testing.T) { - values := []string{"İstanbul", "ISTANBUL", "istanbul", "Kelvin", "\u212aelvin", "Straße", "STRASSE", "line\nmemory", "MEMORY", "x.y", "xay"} - for _, search := range []string{"istanbul", "k", "ss", "memory", "x.y"} { - local := regexp.MustCompile(searchPattern(search)) - selector := searchSelector("label", search) - quoted, found := strings.CutPrefix(selector, "{label=~") - pattern, err := strconv.Unquote(strings.TrimSuffix(quoted, "}")) - if !found || err != nil { - t.Fatalf("searchSelector(%q) = %s: %v", search, selector, err) - } - // Prometheus anchors the regular expressions of matchers. - remote := regexp.MustCompile("^(?:" + pattern + ")$") - for _, value := range values { - if local.MatchString(value) != remote.MatchString(value) { - t.Errorf("search %q, value %q: local match %v, Prometheus match %v", search, value, local.MatchString(value), remote.MatchString(value)) - } - } - } -} diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index 9b79bb6..747e2a0 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -18,9 +18,7 @@ import ( "encoding/json" "errors" "fmt" - "regexp" "slices" - "strconv" "strings" v1 "github.com/prometheus/client_golang/api/prometheus/v1" @@ -145,11 +143,7 @@ type listing struct { } // list resolves the time range and the datasource, then lists the label names (label empty) or the values of a -// label, filtered by search (case-insensitive). -// -// When the list is too large and search is set without match, it is requested again with search as a regular -// expression matcher on the label, so that Prometheus filters it: the filter isn't sent from the start as it may cost -// Prometheus more than a plain listing. +// label, keeping the values that contain search (ignoring case) when it is set. func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, label string, match Selectors, timeRange *TimeRangeInput, search string) (*listing, error) { start, end, _, err := resolveTimeRange(timeRange, p.now()) if err != nil { @@ -163,24 +157,21 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l if err != nil { return nil, err } - fetch := func(match Selectors) ([]string, v1.Warnings, v1.Infos, error) { - var values []string - if label == "" { - names, warnings, infos, fetchErr := promAPI.LabelNames(ctx, match, start, end) - for _, name := range names { - values = append(values, string(name)) - } - return values, warnings, infos, fetchErr + 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)) } - labelValues, warnings, infos, fetchErr := promAPI.LabelValues(ctx, escapeLabelName(label), match, start, end) + } 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)) } - return values, warnings, infos, fetchErr - } - values, warnings, infos, err := fetch(match) - if errors.Is(err, errTooMuchData) && search != "" && label != "" && len(match) == 0 { - values, warnings, infos, err = fetch(Selectors{searchSelector(label, search)}) } if errors.Is(err, errTooMuchData) { return nil, errListTooLarge @@ -189,9 +180,8 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l return nil, apiError(datasource.ref, err) } if search != "" { - // The same matching as searchSelector, so that a list filtered by Prometheus has the same values. - matcher := regexp.MustCompile(searchPattern(search)) - values = slices.DeleteFunc(values, func(value string) bool { return !matcher.MatchString(value) }) + search = strings.ToLower(search) + values = slices.DeleteFunc(values, func(value string) bool { return !strings.Contains(strings.ToLower(value), search) }) } if values == nil { values = []string{} @@ -200,8 +190,10 @@ func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, l return &listing{datasource: datasource, values: values, warnings: append(allWarnings, infos...)}, nil } -var errListTooLarge = errors.New("the list is too large (over 1 MiB): narrow it with match (e.g. {job=\"node\"}), " + - "search or a shorter time_range") +// 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 UTF-8 name (e.g. http.method) is escaped as Prometheus documents it (U__http_2e_method), which is @@ -215,24 +207,6 @@ func escapeLabelName(label string) string { return model.EscapeName(label, model.ValueEncodingEscaping) } -// searchPattern returns the regular expression of the values that contain search, ignoring case. Prometheus uses the -// regular expressions of Go (RE2) for its matchers, so the values match the same way here and in Prometheus. -func searchPattern(search string) string { - return "(?i)" + regexp.QuoteMeta(search) -} - -// searchSelector returns a series selector of the values of label that contain search, ignoring case. Prometheus -// anchors the regular expressions of matchers, hence the surrounding ".*", which also matches newlines with the -// flag s (the default since Prometheus 3 only). A UTF-8 label name is quoted, as Prometheus 3 requires; other names are -// not, so that the selector also works with older versions. -func searchSelector(label, search string) string { - name := label - if !model.LegacyValidation.IsValidLabelName(label) { - name = strconv.Quote(label) - } - return fmt.Sprintf("{%s=~%s}", name, strconv.Quote("(?is).*"+regexp.QuoteMeta(search)+".*")) -} - // 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 { @@ -302,31 +276,33 @@ func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesI return &labelValuesOutput{Datasource: values.datasource.ref, Label: input.Label, page: valuesPage, Values: returned, Warnings: values.warnings}, nil } -// familySuffixes are the suffixes of the series of a metric family, with the types of the families that have them. -// The metadata of these series may be under the family name, e.g. http_requests for http_requests_total. They are the -// suffixes with which Prometheus matches metadata, plus _created (OpenMetrics), which gauge histograms don't have. -var familySuffixes = []struct { - suffix string - types []v1.MetricType -}{ - {"_bucket", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram}}, - {"_count", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, - {"_sum", []v1.MetricType{v1.MetricTypeHistogram, v1.MetricTypeGaugeHistogram, v1.MetricTypeSummary}}, - {"_gcount", []v1.MetricType{v1.MetricTypeGaugeHistogram}}, - {"_gsum", []v1.MetricType{v1.MetricTypeGaugeHistogram}}, - {"_created", []v1.MetricType{v1.MetricTypeCounter, v1.MetricTypeHistogram, v1.MetricTypeSummary}}, - {"_total", []v1.MetricType{v1.MetricTypeCounter}}, - {"_info", []v1.MetricType{v1.MetricTypeInfo}}, +// 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 name of the metric family a series name may belong to, and the types of such a family. +// 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) { - for _, family := range familySuffixes { - if base, found := strings.CutSuffix(name, family.suffix); found && base != "" { - return base, family.types, true - } + 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 "", 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 diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 763a023..176ba72 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -161,8 +161,8 @@ func (p *prometheus) GetMetricMetadata() *tools.Tool { 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, _created, _total, _info) are also looked up under their "+ - "family name.", maxMetadataMetrics), + "metrics (_bucket, _count, _sum, _gcount, _gsum, _total, _info) are also looked up under their family "+ + "name.", maxMetadataMetrics), }, }, "metrics"), } diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index af2f7f3..2f691ed 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -131,32 +131,14 @@ func TestListLabels(t *testing.T) { func TestListLabelValuesOfUTF8Label(t *testing.T) { // The label name is escaped in the path, as Prometheus documents it: the fake answers this path only. - path := globalProxy + "/api/v1/label/U__http_2e_method/values" - var tooLargeList atomic.Bool - perses := newFakePerses(t, nil) - perses.answer = func(r *http.Request) *answer { - if r.URL.Path != path { - return nil - } - // Prometheus filters the values when the search is sent as a matcher on the quoted label name. - if r.URL.Query().Get("match[]") == `{"http.method"=~"(?is).*get.*"}` { - return new(ok(`["GET"]`)) - } - if tooLargeList.Load() { - return &answer{status: http.StatusOK, body: tooLarge(`[]`)} - } - return new(ok(`["GET","POST"]`)) - } + 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) } - - // When the list is too large, it is requested again with search as a matcher. - tooLargeList.Store(true) - output = decode(t, call(t, session, ListLabelValuesToolName, map[string]any{"label": "http.method", "search": "get"}, false)) - if !reflect.DeepEqual(output["values"], []any{"GET"}) { + 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"]) } } @@ -222,6 +204,7 @@ func TestGetMetricMetadata(t *testing.T) { "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."}}, @@ -230,6 +213,7 @@ func TestGetMetricMetadata(t *testing.T) { "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{ @@ -240,13 +224,16 @@ func TestGetMetricMetadata(t *testing.T) { "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) } - // temperature is a gauge: it is not the family of temperature_total. Gauge histograms have no _created series. - if !reflect.DeepEqual(output["missing"], []any{"temperature_total", "nope", "jobs_waiting_created"}) { - t.Errorf("missing = %v", output["missing"]) + // 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 { @@ -565,35 +552,19 @@ func TestDatasourceSettingsApplyToEveryRequest(t *testing.T) { func TestListTooLarge(t *testing.T) { path := globalProxy + "/api/v1/label/__name__/values" - perses := newFakePerses(t, nil) - perses.answer = func(r *http.Request) *answer { - if r.URL.Path != path { - return nil - } - // Prometheus filters the names when the search is sent as a matcher. - if r.URL.Query().Get("match[]") == `{__name__=~"(?is).*MEMORY.*"}` { - return new(ok(`["process_resident_memory_bytes","up_memory"]`)) - } - return &answer{status: http.StatusOK, body: tooLarge(`[]`)} - } + perses := newFakePerses(t, map[string]answer{path: {status: http.StatusOK, body: tooLarge(`[]`)}}) session := connect(t, perses) - - // With search and without match, the list is requested again with search as a matcher. - output := decode(t, call(t, session, ListMetricNamesToolName, map[string]any{"search": "MEMORY"}, false)) - if !reflect.DeepEqual(output["metrics"], []any{"process_resident_memory_bytes", "up_memory"}) { - t.Errorf("metrics = %v", output["metrics"]) - } - if got := perses.Count(http.MethodGet, path); got != 2 { - t.Errorf("%d requests, want 2", got) - } - - // Otherwise, the error tells how to narrow the list, not how to aggregate a query. - for _, arguments := range []map[string]any{nil, {"search": "memory", "match": "up"}} { + // 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) { From bcf288fd255bf8eb020ebbbde588d9a68e883cd1 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 22:23:37 +0100 Subject: [PATCH 09/21] [IGNORE] show the native histogram syntax in the error Native histograms have no _bucket series or le label, unlike the classic ones: a query written for classic histograms, e.g. histogram_quantile(0.99, sum by (le) (rate(x_bucket[5m]))), returns no series. The error of a query that returns native histograms now gives the native form, e.g. histogram_quantile(0.99, sum(rate(x[5m]))). Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 5 +++-- pkg/tools/prometheus/prometheus_test.go | 2 +- pkg/tools/prometheus/series.go | 5 ++++- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index 94dca4b..fd62e55 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -246,8 +246,9 @@ datasource; see [Datasource settings](#datasource-settings)). It returns: 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()`. The `warnings` and `infos` of +`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` diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 2f691ed..6ba27bc 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -399,7 +399,7 @@ func TestQueryErrors(t *testing.T) { { 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()", + 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", diff --git a/pkg/tools/prometheus/series.go b/pkg/tools/prometheus/series.go index 8b8f0f0..ed27833 100644 --- a/pkg/tools/prometheus/series.go +++ b/pkg/tools/prometheus/series.go @@ -27,8 +27,11 @@ import ( // timeLayout formats minAt and maxAt, e.g. "2 Jan 2026, 14:05". const timeLayout = "2 Jan 2006, 15:04" +// 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") + "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 { From b0776a7e01ade58fdbbe8eb1827601b9530029b4 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Fri, 13 Nov 2026 22:34:09 +0100 Subject: [PATCH 10/21] [IGNORE] describe the list time range as approximate Prometheus applies the start and end of its label names and values endpoints approximately, by storage block: as its API documentation says, the result may contain series without samples in the interval, e.g. all the series of the head block for the past hour. The time_range of the list tools no longer claims that only the series with samples in it, or only current series, are listed. Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 3 ++- pkg/tools/prometheus/prometheus.go | 5 +++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index fd62e55..ea97568 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -216,7 +216,8 @@ The parameters are: - `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, so that the list tools only return current series. + 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`, max 200), 200 label names, 100 label values (max 1000), 20 series (max 100). diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 176ba72..4e677bb 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -305,6 +305,7 @@ func timeRangeSchema(description string) *jsonschema.Schema { } func discoveryTimeRangeSchema() *jsonschema.Schema { - return timeRangeSchema("Only consider series with samples in this time range. Defaults to the past hour, " + - "so that only current metrics are returned.") + 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.") } From d63f3eeb8d028bebc996a818b60aaeb0ae83b642 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Sun, 15 Nov 2026 12:11:35 +0100 Subject: [PATCH 11/21] [IGNORE] escape colons in label names for the Perses proxy A colon is valid in legacy metric names but not in label names, so model.EscapeName kept it as is: a Prometheus 3 label such as http:method was sent unchanged in the path of the label values endpoint, which the default allowedEndpoints pattern of the Perses proxy (/api/v1/label/([a-zA-Z0-9_-]+)/values) rejects. Every name that is not a legacy label name, or that starts with U__, is now escaped with the Prometheus value encoding, colons included (U__http_3a_method). Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/internal_test.go | 10 +++++++++ pkg/tools/prometheus/list.go | 29 +++++++++++++++++++------ pkg/tools/prometheus/prometheus_test.go | 10 +++++++++ 3 files changed, 42 insertions(+), 7 deletions(-) diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 85a6816..19117bf 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -16,6 +16,7 @@ package prometheus import ( "math" "reflect" + "regexp" "strings" "testing" "time" @@ -225,12 +226,21 @@ func TestEscapeLabelName(t *testing.T) { // 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 { 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__") { diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index 747e2a0..9ea8449 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -20,6 +20,7 @@ import ( "fmt" "slices" "strings" + "unicode/utf8" v1 "github.com/prometheus/client_golang/api/prometheus/v1" "github.com/prometheus/common/model" @@ -196,15 +197,29 @@ var errListTooLarge = errors.New("the list is too large (over 1 MiB): narrow it "{__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 UTF-8 name (e.g. 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; other names are kept unchanged. -// Prometheus unescapes every name starting with U__, so such a name is always escaped to be read back unchanged. +// 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 strings.HasPrefix(label, "U__") && model.LegacyValidation.IsValidMetricName(label) { - // EscapeName keeps the legacy names unchanged: in them, only the underscores are escaped (doubled). - return "U__" + strings.ReplaceAll(label, "_", "__") + 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 model.EscapeName(label, model.ValueEncodingEscaping) + return escaped.String() } // firstPage returns the first limit values (defaultLimit when limit is not set) and the page they form. diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 6ba27bc..109c896 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -143,6 +143,16 @@ func TestListLabelValuesOfUTF8Label(t *testing.T) { } } +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) From 66d09f0723877687752aabc37ba70c1b3b73e711 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:22:04 +0100 Subject: [PATCH 12/21] [IGNORE] resolve the project datasources without the global read permission Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/datasource.go | 10 +++++++- pkg/tools/prometheus/internal_test.go | 35 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/pkg/tools/prometheus/datasource.go b/pkg/tools/prometheus/datasource.go index 5f20e40..414fd09 100644 --- a/pkg/tools/prometheus/datasource.go +++ b/pkg/tools/prometheus/datasource.go @@ -18,6 +18,7 @@ import ( "errors" "fmt" "maps" + "net/http" "slices" "sort" "strings" @@ -25,6 +26,7 @@ import ( "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" ) @@ -193,7 +195,13 @@ func (r *resolver) resolveUncached(key DatasourceRef) (resolvedDatasource, error } globals, err := r.client.GlobalDatasource().List("") if err != nil { - return resolvedDatasource{}, fmt.Errorf("error listing the global datasources: %w", err) + // 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 { diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 19117bf..50a6261 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -375,6 +375,41 @@ func TestResolveProjectDefaultWithoutGlobalAccess(t *testing.T) { } } +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 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"}}} From 6184fdfafc6373f730c0685db3ebf93a0ea8a497 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:22:23 +0100 Subject: [PATCH 13/21] [IGNORE] remove the expired datasources from the cache Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/datasource.go | 9 ++++++++- pkg/tools/prometheus/internal_test.go | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/pkg/tools/prometheus/datasource.go b/pkg/tools/prometheus/datasource.go index 414fd09..c4f0905 100644 --- a/pkg/tools/prometheus/datasource.go +++ b/pkg/tools/prometheus/datasource.go @@ -161,7 +161,14 @@ func (r *resolver) resolve(input *DatasourceRef) (resolvedDatasource, error) { return resolvedDatasource{}, err } r.mutex.Lock() - r.cache[key] = cacheEntry{datasource: resolved, expires: r.now().Add(cacheTTL)} + 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 } diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 50a6261..b47fcf2 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -410,6 +410,26 @@ func TestResolveEmptyProjectWithoutGlobalAccess(t *testing.T) { } } +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 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"}}} From 36387a480e878cdbc3e8608889dfd9bf0992d7db Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:22:39 +0100 Subject: [PATCH 14/21] [IGNORE] keep the status of large error pages and valid UTF-8 in errors Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/client.go | 9 ++++++--- pkg/tools/prometheus/internal_test.go | 12 ++++++++++++ pkg/tools/prometheus/prometheus_test.go | 5 +++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go index 47cb406..297975a 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -108,11 +108,12 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { if err != nil { return nil, err } - resp.Body = &limitedBody{ReadCloser: resp.Body, remaining: maxBodyBytes} if resp.StatusCode/100 == 2 || (req.Method == http.MethodPost && isGetFallbackStatus(resp.StatusCode)) { + resp.Body = &limitedBody{ReadCloser: resp.Body, remaining: maxBodyBytes} return resp, nil } - body, err := io.ReadAll(resp.Body) + // 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 @@ -196,8 +197,10 @@ func errorMessage(body []byte) string { 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 = message[:maxErrorLength] + "..." + message = strings.ToValidUTF8(message[:maxErrorLength], "") + "..." } return message } diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index b47fcf2..7e2037c 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -20,6 +20,7 @@ import ( "strings" "testing" "time" + "unicode/utf8" "github.com/prometheus/common/model" ) @@ -430,6 +431,17 @@ func TestResolveCacheEvictsExpiredEntries(t *testing.T) { } } +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"}}} diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 109c896..0b018dd 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -406,6 +406,11 @@ func TestQueryErrors(t *testing.T) { answer: &answer{status: http.StatusBadGateway, body: "upstream down\n"}, want: "error querying global datasource 'prom': HTTP 502 Bad Gateway: upstream down", }, + { + 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"]]}]}]}`)), From ff6ec14898173c1cd9b56592f3ca6d462b30cfe2 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:22:54 +0100 Subject: [PATCH 15/21] [IGNORE] don't follow redirects to other hosts Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/internal/proxy/proxy.go | 22 +++++++++++++++- pkg/tools/internal/proxy/proxy_test.go | 35 +++++++++++++++++++++++++ pkg/tools/prometheus/client.go | 3 ++- pkg/tools/prometheus/helpers_test.go | 20 +++++++++----- pkg/tools/prometheus/prometheus_test.go | 5 ++++ 5 files changed, 77 insertions(+), 8 deletions(-) diff --git a/pkg/tools/internal/proxy/proxy.go b/pkg/tools/internal/proxy/proxy.go index a93d811..adcfa7f 100644 --- a/pkg/tools/internal/proxy/proxy.go +++ b/pkg/tools/internal/proxy/proxy.go @@ -24,6 +24,26 @@ import ( apiClient "github.com/perses/perses/pkg/client/api/v1" ) +// maxRedirects is the number of redirects followed, as by the default HTTP client. +const maxRedirects = 10 + +// SameHostClient returns a copy of client that follows the redirects to the host of the request only, e.g. from http +// to https: a redirect to another host is returned as the response, as the requests carry the Perses credentials and +// must not leave the Perses host. +func SameHostClient(client *http.Client) *http.Client { + sameHost := *client + sameHost.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) >= maxRedirects { + return fmt.Errorf("stopped after %d redirects", maxRedirects) + } + if !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) { + return http.ErrUseLastResponse + } + return nil + } + return &sameHost +} + // maxBodyBytes caps response body size to prevent overwhelming LLM context windows. const maxBodyBytes = 1 << 20 // 1 MiB @@ -200,7 +220,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 := SameHostClient(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..0a4daaa 100644 --- a/pkg/tools/internal/proxy/proxy_test.go +++ b/pkg/tools/internal/proxy/proxy_test.go @@ -89,6 +89,41 @@ func TestResponseText(t *testing.T) { } } +func TestDoRedirects(t *testing.T) { + tests := []struct { + name string + location string + wantStatus int + }{ + // e.g. from http to https: the requests stay on the Perses host. + {name: "same host is followed", location: "/moved", wantStatus: http.StatusOK}, + {name: "another host is not followed", location: "http://login.example.com/", wantStatus: http.StatusFound}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/moved" { + _, _ = w.Write([]byte("{}")) + return + } + http.Redirect(w, r, tt.location, 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 != tt.wantStatus { + t.Errorf("StatusCode = %d, want %d", resp.StatusCode, tt.wantStatus) + } + }) + } +} + func TestDoTruncation(t *testing.T) { tests := []struct { name string diff --git a/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go index 297975a..bd4c99c 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -59,7 +59,8 @@ func (p *prometheus) newAPI(datasource resolvedDatasource) (v1.API, error) { client, err := api.NewClient(api.Config{ Address: address.String(), Client: &http.Client{Transport: &persesTransport{ - client: restClient.Client, headers: restClient.Headers, queryParams: datasource.queryParams, + // A redirect to another host is returned as an error instead of being followed. + client: proxy.SameHostClient(restClient.Client), headers: restClient.Headers, queryParams: datasource.queryParams, }}, }) if err != nil { diff --git a/pkg/tools/prometheus/helpers_test.go b/pkg/tools/prometheus/helpers_test.go index 6c74bbf..6fcdebb 100644 --- a/pkg/tools/prometheus/helpers_test.go +++ b/pkg/tools/prometheus/helpers_test.go @@ -58,6 +58,18 @@ var defaultDatasources = []testDatasource{ 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 { @@ -94,9 +106,7 @@ func (f *fakePerses) serve(w http.ResponseWriter, r *http.Request) { } if f.answer != nil { if a := f.answer(r); a != nil { - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(a.status) - _, _ = w.Write([]byte(a.body)) + a.write(w) return } } @@ -113,9 +123,7 @@ func (f *fakePerses) serve(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) return } - w.Header().Set("Content-Type", "application/json") - w.WriteHeader(a.status) - _, _ = w.Write([]byte(a.body)) + a.write(w) } func (f *fakePerses) serveMetadata(w http.ResponseWriter, metric string) { diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 0b018dd..6299fb1 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -406,6 +406,11 @@ func TestQueryErrors(t *testing.T) { answer: &answer{status: http.StatusBadGateway, body: "upstream down\n"}, want: "error querying global datasource 'prom': HTTP 502 Bad Gateway: upstream down", }, + { + name: "redirect to another host is not followed", + answer: &answer{status: http.StatusFound, location: "http://login.example.com/"}, + want: "error querying global datasource 'prom': HTTP 302 Found", + }, { name: "large error page keeps its status", answer: &answer{status: http.StatusBadGateway, body: "" + strings.Repeat("x", 2*maxBodyBytes) + ""}, From 1d8f1042e93bbca3a98fc399061d831c6a0e8ed6 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:23:10 +0100 Subject: [PATCH 16/21] [IGNORE] format minAt and maxAt in RFC 3339 Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 2 +- pkg/tools/prometheus/internal_test.go | 2 +- pkg/tools/prometheus/prometheus.go | 2 +- pkg/tools/prometheus/prometheus_test.go | 4 ++-- pkg/tools/prometheus/series.go | 9 ++++----- pkg/tools/prometheus/timerange.go | 7 ++++++- 6 files changed, 15 insertions(+), 11 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index ea97568..ad01cc5 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -243,7 +243,7 @@ datasource; see [Datasource settings](#datasource-settings)). It returns: "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 - formatted in `time_zone` (default UTC). + 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`, diff --git a/pkg/tools/prometheus/internal_test.go b/pkg/tools/prometheus/internal_test.go index 7e2037c..9da659a 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -262,7 +262,7 @@ func TestSeriesStats(t *testing.T) { {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: "2 Jan 2026, 12:00", MaxAt: "2 Jan 2026, 12:00", NonFinite: 2} + 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) } diff --git a/pkg/tools/prometheus/prometheus.go b/pkg/tools/prometheus/prometheus.go index 4e677bb..7277b92 100644 --- a/pkg/tools/prometheus/prometheus.go +++ b/pkg/tools/prometheus/prometheus.go @@ -202,7 +202,7 @@ func (p *prometheus) Query() *tools.Tool { }, "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, e.g. \"Europe/Berlin\". Defaults to UTC."}, + "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 diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 6299fb1..c52284a 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -314,8 +314,8 @@ func TestQueryRange(t *testing.T) { "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": "2 Jan 2026, 13:01", "maxAt": "2 Jan 2026, 13:00"}, - map[string]any{"labels": map[string]any{"job": "a"}, "min": 1.0, "max": 3.0, "avg": 2.0, "last": 3.0, "minAt": "2 Jan 2026, 13:00", "maxAt": "2 Jan 2026, 13:01"}, + 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"}, } diff --git a/pkg/tools/prometheus/series.go b/pkg/tools/prometheus/series.go index ed27833..90c18b0 100644 --- a/pkg/tools/prometheus/series.go +++ b/pkg/tools/prometheus/series.go @@ -24,9 +24,6 @@ import ( "github.com/prometheus/common/model" ) -// timeLayout formats minAt and maxAt, e.g. "2 Jan 2026, 14:05". -const timeLayout = "2 Jan 2006, 15:04" - // 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: " + @@ -172,8 +169,10 @@ func seriesStats(samples []model.SamplePair, location *time.Location) (result st result.Max = round(maxValue) result.Avg = round(avg) result.Last, _ = sampleValue(float64(samples[len(samples)-1].Value)) - result.MinAt = minAt.Time().In(location).Format(timeLayout) - result.MaxAt = maxAt.Time().In(location).Format(timeLayout) + // 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 } diff --git a/pkg/tools/prometheus/timerange.go b/pkg/tools/prometheus/timerange.go index 0ceed76..b05b790 100644 --- a/pkg/tools/prometheus/timerange.go +++ b/pkg/tools/prometheus/timerange.go @@ -87,7 +87,12 @@ func resolveTimeRange(input *TimeRangeInput, now time.Time) (time.Time, time.Tim // 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 t.UTC().Format(time.RFC3339Nano) + 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". From 5985fef2fbcfde0446fa20fd0e4f0ee6d952702f Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:23:25 +0100 Subject: [PATCH 17/21] [IGNORE] list at most 50 metrics with their metadata Signed-off-by: Akshay Iyyadurai Balasundaram --- docs/tools.md | 2 +- pkg/tools/prometheus/list.go | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/tools.md b/docs/tools.md index ad01cc5..cbcdb6c 100644 --- a/docs/tools.md +++ b/docs/tools.md @@ -218,7 +218,7 @@ The parameters are: - `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`, max 200), 200 +- `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 diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index 9ea8449..c26910f 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -31,8 +31,9 @@ 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. - maxMetadataMetricsLimit = 200 + // 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 From e318d4e93f952fbad003ac6ad487d7a945aa7810 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:23:40 +0100 Subject: [PATCH 18/21] [IGNORE] use slices.SortFunc, a list request struct and subtests Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/prometheus/datasource.go | 4 +-- pkg/tools/prometheus/internal_test.go | 51 +++++++++++++++------------ pkg/tools/prometheus/list.go | 31 +++++++++++----- 3 files changed, 54 insertions(+), 32 deletions(-) diff --git a/pkg/tools/prometheus/datasource.go b/pkg/tools/prometheus/datasource.go index c4f0905..5e96a55 100644 --- a/pkg/tools/prometheus/datasource.go +++ b/pkg/tools/prometheus/datasource.go @@ -14,13 +14,13 @@ package prometheus import ( + "cmp" "encoding/json" "errors" "fmt" "maps" "net/http" "slices" - "sort" "strings" "sync" "time" @@ -290,6 +290,6 @@ func prometheusCandidates(specs map[string]datasource.Spec, project string) []ca candidates = append(candidates, candidate{ref: DatasourceRef{Name: name, Project: project}, spec: spec}) } } - sort.Slice(candidates, func(i, j int) bool { return candidates[i].ref.Name < candidates[j].ref.Name }) + 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/internal_test.go b/pkg/tools/prometheus/internal_test.go index 9da659a..2e36148 100644 --- a/pkg/tools/prometheus/internal_test.go +++ b/pkg/tools/prometheus/internal_test.go @@ -14,6 +14,7 @@ package prometheus import ( + "fmt" "math" "reflect" "regexp" @@ -211,10 +212,12 @@ func TestResolveStep(t *testing.T) { {step: "1ms", span: time.Minute, minStep: time.Minute, want: 6 * time.Millisecond}, } for _, tt := range tests { - 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) - } + 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) + } + }) } } @@ -235,21 +238,23 @@ func TestEscapeLabelName(t *testing.T) { // The default allowedEndpoints pattern of the label values endpoint in the Perses proxy. proxyLabelPattern := regexp.MustCompile(`^[a-zA-Z0-9_-]+$`) for _, tt := range tests { - 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) - } + 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) + } + }) } } @@ -327,9 +332,11 @@ func TestRound(t *testing.T) { {value: 1767355200.123, want: 1767355200}, } for _, tt := range tests { - if got := round(tt.value); got != tt.want { - t.Errorf("round(%v) = %v, want %v", tt.value, got, tt.want) - } + 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) + } + }) } } diff --git a/pkg/tools/prometheus/list.go b/pkg/tools/prometheus/list.go index c26910f..e1fd8dc 100644 --- a/pkg/tools/prometheus/list.go +++ b/pkg/tools/prometheus/list.go @@ -144,14 +144,25 @@ type listing struct { warnings []string } -// list resolves the time range and the datasource, then lists the label names (label empty) or the values of a -// label, keeping the values that contain search (ignoring case) when it is set. -func (p *prometheus) list(ctx context.Context, datasourceInput *DatasourceRef, label string, match Selectors, timeRange *TimeRangeInput, search string) (*listing, error) { - start, end, _, err := resolveTimeRange(timeRange, p.now()) +// 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(datasourceInput) + datasource, err := p.resolver.resolve(request.datasource) if err != nil { return nil, err } @@ -233,7 +244,9 @@ func firstPage(values []string, limit, defaultLimit int) ([]string, page) { } func (p *prometheus) listMetricNames(ctx context.Context, input ListMetricNamesInput) (*metricNamesOutput, error) { - names, err := p.list(ctx, input.Datasource, model.MetricNameLabel, input.Match, input.TimeRange, input.Search) + 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 } @@ -275,7 +288,7 @@ func (p *prometheus) listMetricNames(ctx context.Context, input ListMetricNamesI } func (p *prometheus) listLabelNames(ctx context.Context, input ListLabelNamesInput) (*labelNamesOutput, error) { - labels, err := p.list(ctx, input.Datasource, "", input.Match, input.TimeRange, "") + labels, err := p.list(ctx, listRequest{datasource: input.Datasource, match: input.Match, timeRange: input.TimeRange}) if err != nil { return nil, err } @@ -284,7 +297,9 @@ func (p *prometheus) listLabelNames(ctx context.Context, input ListLabelNamesInp } func (p *prometheus) listLabelValues(ctx context.Context, input ListLabelValuesInput) (*labelValuesOutput, error) { - values, err := p.list(ctx, input.Datasource, input.Label, input.Match, input.TimeRange, input.Search) + 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 } From 6b69dab64318b9f19ea382dfdf74bb0118309cc5 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:34:30 +0100 Subject: [PATCH 19/21] [IGNORE] don't follow https to http redirects nor redirects with a Prometheus error body Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/internal/proxy/proxy.go | 11 +++++++++-- pkg/tools/internal/proxy/proxy_test.go | 19 +++++++++++++++++++ pkg/tools/prometheus/client.go | 16 +++++++++++----- pkg/tools/prometheus/prometheus_test.go | 16 ++++++++++++++++ 4 files changed, 55 insertions(+), 7 deletions(-) diff --git a/pkg/tools/internal/proxy/proxy.go b/pkg/tools/internal/proxy/proxy.go index adcfa7f..6d3e388 100644 --- a/pkg/tools/internal/proxy/proxy.go +++ b/pkg/tools/internal/proxy/proxy.go @@ -28,8 +28,8 @@ import ( const maxRedirects = 10 // SameHostClient returns a copy of client that follows the redirects to the host of the request only, e.g. from http -// to https: a redirect to another host is returned as the response, as the requests carry the Perses credentials and -// must not leave the Perses host. +// to https. The requests carry the Perses credentials: a redirect to another host, or from https to http (which would +// send them in plaintext), is returned as the response instead of being followed. func SameHostClient(client *http.Client) *http.Client { sameHost := *client sameHost.CheckRedirect = func(req *http.Request, via []*http.Request) error { @@ -39,6 +39,13 @@ func SameHostClient(client *http.Client) *http.Client { if !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) { return http.ErrUseLastResponse } + if !strings.EqualFold(req.URL.Scheme, "https") { + for _, previous := range via { + if strings.EqualFold(previous.URL.Scheme, "https") { + return http.ErrUseLastResponse + } + } + } return nil } return &sameHost diff --git a/pkg/tools/internal/proxy/proxy_test.go b/pkg/tools/internal/proxy/proxy_test.go index 0a4daaa..e6e7b04 100644 --- a/pkg/tools/internal/proxy/proxy_test.go +++ b/pkg/tools/internal/proxy/proxy_test.go @@ -124,6 +124,25 @@ func TestDoRedirects(t *testing.T) { } } +func TestSameHostClientRejectsHTTPSDowngrade(t *testing.T) { + plain := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + t.Errorf("the redirect from https to http is followed: %s", r.URL) + })) + defer plain.Close() + secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, plain.URL+"/plaintext", http.StatusFound) + })) + defer secure.Close() + resp, err := SameHostClient(secure.Client()).Get(secure.URL) + if err != nil { + t.Fatalf("Get() unexpected error: %v", err) + } + _ = resp.Body.Close() + 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 index bd4c99c..b498f7f 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -58,10 +58,14 @@ func (p *prometheus) newAPI(datasource resolvedDatasource) (v1.API, error) { address.Path = strings.TrimRight(address.Path, "/") + path client, err := api.NewClient(api.Config{ Address: address.String(), - Client: &http.Client{Transport: &persesTransport{ - // A redirect to another host is returned as an error instead of being followed. - client: proxy.SameHostClient(restClient.Client), headers: restClient.Headers, queryParams: datasource.queryParams, - }}, + Client: &http.Client{ + Transport: &persesTransport{ + // A redirect to another host is returned as an error instead of being followed. + client: proxy.SameHostClient(restClient.Client), headers: restClient.Headers, queryParams: datasource.queryParams, + }, + // The transport adds the Perses credentials to every request: the redirects it returns must not be followed. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, }) if err != nil { return nil, fmt.Errorf("error creating the Prometheus client of %s: %w", ref, err) @@ -119,7 +123,9 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { if err != nil { return nil, err } - if _, isPrometheusError := prometheusErrorMessage(body); isPrometheusError { + // Only the error statuses are passed to the Prometheus client: a redirect, even with a Prometheus error body, is an + // error. + if _, isPrometheusError := prometheusErrorMessage(body); isPrometheusError && resp.StatusCode >= http.StatusBadRequest { resp.Body = io.NopCloser(bytes.NewReader(body)) return resp, nil } diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index c52284a..06b9b75 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -373,6 +373,22 @@ func TestQueryScalar(t *testing.T) { } } +func TestCrossHostRedirectWithPrometheusErrorIsNotFollowed(t *testing.T) { + other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Errorf("the redirect to another host is followed: %s %s (Authorization %q)", r.Method, r.URL.Path, r.Header.Get("Authorization")) + })) + defer other.Close() + // Another hostname than the 127.0.0.1 of the fake Perses, on the same machine. + location := strings.Replace(other.URL, "127.0.0.1", "localhost", 1) + "/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"; !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 { From 522afb643faf875df61a166c45b277ee6457c37a Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:41:14 +0100 Subject: [PATCH 20/21] [IGNORE] don't follow redirects to another port Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/internal/proxy/proxy.go | 33 +++++++++++++++++--- pkg/tools/internal/proxy/proxy_test.go | 43 ++++++++++++++++++++++++++ 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/pkg/tools/internal/proxy/proxy.go b/pkg/tools/internal/proxy/proxy.go index 6d3e388..49142aa 100644 --- a/pkg/tools/internal/proxy/proxy.go +++ b/pkg/tools/internal/proxy/proxy.go @@ -27,16 +27,17 @@ import ( // maxRedirects is the number of redirects followed, as by the default HTTP client. const maxRedirects = 10 -// SameHostClient returns a copy of client that follows the redirects to the host of the request only, e.g. from http -// to https. The requests carry the Perses credentials: a redirect to another host, or from https to http (which would -// send them in plaintext), is returned as the response instead of being followed. +// SameHostClient returns a copy of client that follows the redirects to the host and port of the request only, or +// from http on port 80 to https on port 443 of the same host. The requests carry the Perses credentials: a redirect to +// another host or port (another service), or from https to http (which would send them in plaintext), is returned as +// the response instead of being followed. func SameHostClient(client *http.Client) *http.Client { sameHost := *client sameHost.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) >= maxRedirects { return fmt.Errorf("stopped after %d redirects", maxRedirects) } - if !strings.EqualFold(req.URL.Hostname(), via[0].URL.Hostname()) { + if !sameService(via[0].URL, req.URL) { return http.ErrUseLastResponse } if !strings.EqualFold(req.URL.Scheme, "https") { @@ -51,6 +52,30 @@ func SameHostClient(client *http.Client) *http.Client { return &sameHost } +// sameService reports whether a redirect from one URL to another stays on the same host and port, or upgrades the +// default http port of the host to its default https port. +func sameService(from, to *url.URL) bool { + if !strings.EqualFold(from.Hostname(), to.Hostname()) { + return false + } + fromPort, toPort := portOf(from), portOf(to) + if fromPort == toPort { + return true + } + return strings.EqualFold(from.Scheme, "http") && fromPort == "80" && strings.EqualFold(to.Scheme, "https") && toPort == "443" +} + +// portOf returns the port of a URL, or the default port of its scheme. +func portOf(u *url.URL) string { + if port := u.Port(); port != "" { + return port + } + if strings.EqualFold(u.Scheme, "https") { + return "443" + } + return "80" +} + // maxBodyBytes caps response body size to prevent overwhelming LLM context windows. const maxBodyBytes = 1 << 20 // 1 MiB diff --git a/pkg/tools/internal/proxy/proxy_test.go b/pkg/tools/internal/proxy/proxy_test.go index e6e7b04..8599472 100644 --- a/pkg/tools/internal/proxy/proxy_test.go +++ b/pkg/tools/internal/proxy/proxy_test.go @@ -143,6 +143,49 @@ func TestSameHostClientRejectsHTTPSDowngrade(t *testing.T) { } } +func TestSameHostClientRejectsOtherPort(t *testing.T) { + other := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { + t.Errorf("the redirect to another port is followed: %s", r.URL) + })) + defer other.Close() + // Same host (127.0.0.1), another port: another service. + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, other.URL+"/steal", http.StatusFound) + })) + defer server.Close() + resp, err := SameHostClient(server.Client()).Get(server.URL) + if err != nil { + t.Fatalf("Get() unexpected error: %v", err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusFound { + t.Errorf("StatusCode = %d, want %d", resp.StatusCode, http.StatusFound) + } +} + +func TestSameService(t *testing.T) { + tests := []struct { + from, to string + want bool + }{ + {from: "http://perses.example.com/a", to: "http://perses.example.com/b", want: true}, + {from: "http://perses.example.com/a", to: "https://perses.example.com/a", want: true}, + {from: "http://perses.example.com:80/a", to: "https://PERSES.example.com:443/a", want: true}, + {from: "http://perses.example.com:8080/a", to: "https://perses.example.com:8080/a", want: true}, + {from: "http://perses.example.com:8080/a", to: "http://perses.example.com:9090/a", want: false}, + {from: "http://perses.example.com:8080/a", to: "https://perses.example.com/a", want: false}, + {from: "https://perses.example.com/a", to: "http://perses.example.com:443/a", want: true}, // the downgrade is refused by CheckRedirect + {from: "http://perses.example.com/a", to: "http://other.example.com/a", want: false}, + } + for _, tt := range tests { + t.Run(tt.from+" -> "+tt.to, func(t *testing.T) { + if got := sameService(common.MustParseURL(tt.from).URL, common.MustParseURL(tt.to).URL); got != tt.want { + t.Errorf("sameService() = %v, want %v", got, tt.want) + } + }) + } +} + func TestDoTruncation(t *testing.T) { tests := []struct { name string From 73152458054779ec244cf1c0d2c88a87e4b5acb5 Mon Sep 17 00:00:00 2001 From: Akshay Iyyadurai Balasundaram Date: Tue, 17 Nov 2026 11:45:54 +0100 Subject: [PATCH 21/21] [IGNORE] never follow redirects The datasource APIs don't redirect, and the requests carry the Perses credentials: a redirect is returned as the response by the proxy tools, and as an error that names its location by the Prometheus tools. This replaces the same host, port and scheme rules. Signed-off-by: Akshay Iyyadurai Balasundaram --- pkg/tools/internal/proxy/proxy.go | 58 ++------------ pkg/tools/internal/proxy/proxy_test.go | 102 +++--------------------- pkg/tools/prometheus/client.go | 22 ++--- pkg/tools/prometheus/prometheus_test.go | 17 ++-- 4 files changed, 40 insertions(+), 159 deletions(-) diff --git a/pkg/tools/internal/proxy/proxy.go b/pkg/tools/internal/proxy/proxy.go index 49142aa..a288028 100644 --- a/pkg/tools/internal/proxy/proxy.go +++ b/pkg/tools/internal/proxy/proxy.go @@ -24,56 +24,12 @@ import ( apiClient "github.com/perses/perses/pkg/client/api/v1" ) -// maxRedirects is the number of redirects followed, as by the default HTTP client. -const maxRedirects = 10 - -// SameHostClient returns a copy of client that follows the redirects to the host and port of the request only, or -// from http on port 80 to https on port 443 of the same host. The requests carry the Perses credentials: a redirect to -// another host or port (another service), or from https to http (which would send them in plaintext), is returned as -// the response instead of being followed. -func SameHostClient(client *http.Client) *http.Client { - sameHost := *client - sameHost.CheckRedirect = func(req *http.Request, via []*http.Request) error { - if len(via) >= maxRedirects { - return fmt.Errorf("stopped after %d redirects", maxRedirects) - } - if !sameService(via[0].URL, req.URL) { - return http.ErrUseLastResponse - } - if !strings.EqualFold(req.URL.Scheme, "https") { - for _, previous := range via { - if strings.EqualFold(previous.URL.Scheme, "https") { - return http.ErrUseLastResponse - } - } - } - return nil - } - return &sameHost -} - -// sameService reports whether a redirect from one URL to another stays on the same host and port, or upgrades the -// default http port of the host to its default https port. -func sameService(from, to *url.URL) bool { - if !strings.EqualFold(from.Hostname(), to.Hostname()) { - return false - } - fromPort, toPort := portOf(from), portOf(to) - if fromPort == toPort { - return true - } - return strings.EqualFold(from.Scheme, "http") && fromPort == "80" && strings.EqualFold(to.Scheme, "https") && toPort == "443" -} - -// portOf returns the port of a URL, or the default port of its scheme. -func portOf(u *url.URL) string { - if port := u.Port(); port != "" { - return port - } - if strings.EqualFold(u.Scheme, "https") { - return "443" - } - return "80" +// 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. @@ -252,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 := SameHostClient(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 8599472..180bd23 100644 --- a/pkg/tools/internal/proxy/proxy_test.go +++ b/pkg/tools/internal/proxy/proxy_test.go @@ -89,103 +89,27 @@ func TestResponseText(t *testing.T) { } } -func TestDoRedirects(t *testing.T) { - tests := []struct { - name string - location string - wantStatus int - }{ - // e.g. from http to https: the requests stay on the Perses host. - {name: "same host is followed", location: "/moved", wantStatus: http.StatusOK}, - {name: "another host is not followed", location: "http://login.example.com/", wantStatus: http.StatusFound}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.URL.Path == "/moved" { - _, _ = w.Write([]byte("{}")) - return - } - http.Redirect(w, r, tt.location, 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 != tt.wantStatus { - t.Errorf("StatusCode = %d, want %d", resp.StatusCode, tt.wantStatus) - } - }) - } -} - -func TestSameHostClientRejectsHTTPSDowngrade(t *testing.T) { - plain := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { - t.Errorf("the redirect from https to http is followed: %s", r.URL) - })) - defer plain.Close() - secure := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, plain.URL+"/plaintext", http.StatusFound) - })) - defer secure.Close() - resp, err := SameHostClient(secure.Client()).Get(secure.URL) - if err != nil { - t.Fatalf("Get() unexpected error: %v", err) - } - _ = resp.Body.Close() - if resp.StatusCode != http.StatusFound { - t.Errorf("StatusCode = %d, want %d", resp.StatusCode, http.StatusFound) - } -} - -func TestSameHostClientRejectsOtherPort(t *testing.T) { - other := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { - t.Errorf("the redirect to another port is followed: %s", r.URL) +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 other.Close() - // Same host (127.0.0.1), another port: another service. - server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, other.URL+"/steal", http.StatusFound) - })) - defer server.Close() - resp, err := SameHostClient(server.Client()).Get(server.URL) + 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("Get() unexpected error: %v", err) + t.Fatalf("Do() unexpected error: %v", err) } - _ = resp.Body.Close() if resp.StatusCode != http.StatusFound { t.Errorf("StatusCode = %d, want %d", resp.StatusCode, http.StatusFound) } } -func TestSameService(t *testing.T) { - tests := []struct { - from, to string - want bool - }{ - {from: "http://perses.example.com/a", to: "http://perses.example.com/b", want: true}, - {from: "http://perses.example.com/a", to: "https://perses.example.com/a", want: true}, - {from: "http://perses.example.com:80/a", to: "https://PERSES.example.com:443/a", want: true}, - {from: "http://perses.example.com:8080/a", to: "https://perses.example.com:8080/a", want: true}, - {from: "http://perses.example.com:8080/a", to: "http://perses.example.com:9090/a", want: false}, - {from: "http://perses.example.com:8080/a", to: "https://perses.example.com/a", want: false}, - {from: "https://perses.example.com/a", to: "http://perses.example.com:443/a", want: true}, // the downgrade is refused by CheckRedirect - {from: "http://perses.example.com/a", to: "http://other.example.com/a", want: false}, - } - for _, tt := range tests { - t.Run(tt.from+" -> "+tt.to, func(t *testing.T) { - if got := sameService(common.MustParseURL(tt.from).URL, common.MustParseURL(tt.to).URL); got != tt.want { - t.Errorf("sameService() = %v, want %v", got, tt.want) - } - }) - } -} - func TestDoTruncation(t *testing.T) { tests := []struct { name string diff --git a/pkg/tools/prometheus/client.go b/pkg/tools/prometheus/client.go index b498f7f..517cab1 100644 --- a/pkg/tools/prometheus/client.go +++ b/pkg/tools/prometheus/client.go @@ -58,14 +58,9 @@ func (p *prometheus) newAPI(datasource resolvedDatasource) (v1.API, error) { address.Path = strings.TrimRight(address.Path, "/") + path client, err := api.NewClient(api.Config{ Address: address.String(), - Client: &http.Client{ - Transport: &persesTransport{ - // A redirect to another host is returned as an error instead of being followed. - client: proxy.SameHostClient(restClient.Client), headers: restClient.Headers, queryParams: datasource.queryParams, - }, - // The transport adds the Perses credentials to every request: the redirects it returns must not be followed. - CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, - }, + 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) @@ -113,6 +108,13 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { 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 @@ -123,9 +125,7 @@ func (t *persesTransport) RoundTrip(req *http.Request) (*http.Response, error) { if err != nil { return nil, err } - // Only the error statuses are passed to the Prometheus client: a redirect, even with a Prometheus error body, is an - // error. - if _, isPrometheusError := prometheusErrorMessage(body); isPrometheusError && resp.StatusCode >= http.StatusBadRequest { + if _, isPrometheusError := prometheusErrorMessage(body); isPrometheusError { resp.Body = io.NopCloser(bytes.NewReader(body)) return resp, nil } diff --git a/pkg/tools/prometheus/prometheus_test.go b/pkg/tools/prometheus/prometheus_test.go index 06b9b75..82aa9ed 100644 --- a/pkg/tools/prometheus/prometheus_test.go +++ b/pkg/tools/prometheus/prometheus_test.go @@ -373,18 +373,19 @@ func TestQueryScalar(t *testing.T) { } } -func TestCrossHostRedirectWithPrometheusErrorIsNotFollowed(t *testing.T) { +// 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 to another host is followed: %s %s (Authorization %q)", r.Method, r.URL.Path, r.Header.Get("Authorization")) + t.Errorf("the redirect is followed: %s %s (Authorization %q)", r.Method, r.URL.Path, r.Header.Get("Authorization")) })) defer other.Close() - // Another hostname than the 127.0.0.1 of the fake Perses, on the same machine. - location := strings.Replace(other.URL, "127.0.0.1", "localhost", 1) + "/steal" + 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"; !strings.Contains(text, want) { + 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) } } @@ -423,9 +424,9 @@ func TestQueryErrors(t *testing.T) { want: "error querying global datasource 'prom': HTTP 502 Bad Gateway: upstream down", }, { - name: "redirect to another host is not followed", - answer: &answer{status: http.StatusFound, location: "http://login.example.com/"}, - want: "error querying global datasource 'prom': HTTP 302 Found", + 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",