Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat: add api to fetch v2 dashboards for a metric name (#11784)

Naman Verma5ab6636863aa
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index e253718d03..1a159fb4e0 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -2673,6 +2673,22 @@ components:
updatedBy:
type: string
type: object
+ DashboardtypesDashboardPanelRef:
+ properties:
+ dashboardId:
+ type: string
+ dashboardName:
+ type: string
+ panelId:
+ type: string
+ panelName:
+ type: string
+ required:
+ - dashboardId
+ - dashboardName
+ - panelId
+ - panelName
+ type: object
DashboardtypesDashboardSpec:
properties:
datasources:
@@ -5590,6 +5606,16 @@ components:
- widgetId
- widgetName
type: object
+ MetricsexplorertypesMetricDashboardPanelsResponse:
+ properties:
+ dashboards:
+ items:
+ $ref: '#/components/schemas/DashboardtypesDashboardPanelRef'
+ nullable: true
+ type: array
+ required:
+ - dashboards
+ type: object
MetricsexplorertypesMetricDashboardsResponse:
properties:
dashboards:
@@ -22763,6 +22789,75 @@ paths:
summary: Put profile in Zeus for a deployment.
tags:
- zeus
+ /api/v3/metrics/dashboards:
+ get:
+ deprecated: false
+ description: This endpoint returns associated v2 dashboards for a specified
+ metric
+ operationId: GetMetricDashboardsV2
+ parameters:
+ - description: The name of the metric. May contain slashes (e.g. cloud-provider
+ metrics like run.googleapis.com/request_latencies).
+ in: query
+ name: metricName
+ required: true
+ schema:
+ description: The name of the metric. May contain slashes (e.g. cloud-provider
+ metrics like run.googleapis.com/request_latencies).
+ type: string
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/MetricsexplorertypesMetricDashboardPanelsResponse'
+ status:
+ type: string
+ required:
+ - status
+ - data
+ type: object
+ description: OK
+ "400":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Bad Request
+ "401":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Unauthorized
+ "403":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Forbidden
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - VIEWER
+ - tokenizer:
+ - VIEWER
+ summary: Get metric dashboards (v2)
+ tags:
+ - metrics
/api/v3/traces/{traceID}/flamegraph:
post:
deprecated: false
diff --git a/ee/modules/dashboard/impldashboard/module.go b/ee/modules/dashboard/impldashboard/module.go
index b204022e35..8b2c8e8dea 100644
--- a/ee/modules/dashboard/impldashboard/module.go
+++ b/ee/modules/dashboard/impldashboard/module.go
@@ -290,6 +290,10 @@ func (module *module) GetByMetricNames(ctx context.Context, orgID valuer.UUID, m
return module.pkgDashboardModule.GetByMetricNames(ctx, orgID, metricNames)
}
+func (module *module) GetByMetricNamesV2(ctx context.Context, orgID valuer.UUID, metricNames []string) (map[string][]dashboardtypes.DashboardPanelRef, error) {
+ return module.pkgDashboardModule.GetByMetricNamesV2(ctx, orgID, metricNames)
+}
+
func (module *module) List(ctx context.Context, orgID valuer.UUID) ([]*dashboardtypes.Dashboard, error) {
return module.pkgDashboardModule.List(ctx, orgID)
}
diff --git a/ee/sqlstore/postgressqlstore/formatter.go b/ee/sqlstore/postgressqlstore/formatter.go
index 5fa0f92002..7f7f6a618f 100644
--- a/ee/sqlstore/postgressqlstore/formatter.go
+++ b/ee/sqlstore/postgressqlstore/formatter.go
@@ -152,3 +152,7 @@ func (f *formatter) LowerExpression(expression string) []byte {
sql = append(sql, ')')
return sql
}
+
+func (f *formatter) EscapeLikePattern(value string) string {
+ return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(value)
+}
diff --git a/frontend/src/api/generated/services/metrics/index.ts b/frontend/src/api/generated/services/metrics/index.ts
index 5bcfccd0c4..bb38d8affb 100644
--- a/frontend/src/api/generated/services/metrics/index.ts
+++ b/frontend/src/api/generated/services/metrics/index.ts
@@ -26,6 +26,8 @@ import type {
GetMetricAttributesParams,
GetMetricDashboards200,
GetMetricDashboardsParams,
+ GetMetricDashboardsV2200,
+ GetMetricDashboardsV2Params,
GetMetricHighlights200,
GetMetricHighlightsParams,
GetMetricMetadata200,
@@ -1787,3 +1789,100 @@ export const useGetMetricsTreemap = <
> => {
return useMutation(getGetMetricsTreemapMutationOptions(options));
};
+/**
+ * This endpoint returns associated v2 dashboards for a specified metric
+ * @summary Get metric dashboards (v2)
+ */
+export const getMetricDashboardsV2 = (
+ params: GetMetricDashboardsV2Params,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<GetMetricDashboardsV2200>({
+ url: `/api/v3/metrics/dashboards`,
+ method: 'GET',
+ params,
+ signal,
+ });
+};
+
+export const getGetMetricDashboardsV2QueryKey = (
+ params?: GetMetricDashboardsV2Params,
+) => {
+ return [`/api/v3/metrics/dashboards`, ...(params ? [params] : [])] as const;
+};
+
+export const getGetMetricDashboardsV2QueryOptions = <
+ TData = Awaited<ReturnType<typeof getMetricDashboardsV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ params: GetMetricDashboardsV2Params,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getMetricDashboardsV2>>,
+ TError,
+ TData
+ >;
+ },
+) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey =
+ queryOptions?.queryKey ?? getGetMetricDashboardsV2QueryKey(params);
+
+ const queryFn: QueryFunction<
+ Awaited<ReturnType<typeof getMetricDashboardsV2>>
+ > = ({ signal }) => getMetricDashboardsV2(params, signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof getMetricDashboardsV2>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetMetricDashboardsV2QueryResult = NonNullable<
+ Awaited<ReturnType<typeof getMetricDashboardsV2>>
+>;
+export type GetMetricDashboardsV2QueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Get metric dashboards (v2)
+ */
+
+export function useGetMetricDashboardsV2<
+ TData = Awaited<ReturnType<typeof getMetricDashboardsV2>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(
+ params: GetMetricDashboardsV2Params,
+ options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getMetricDashboardsV2>>,
+ TError,
+ TData
+ >;
+ },
+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetMetricDashboardsV2QueryOptions(params, options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ return { ...query, queryKey: queryOptions.queryKey };
+}
+
+/**
+ * @summary Get metric dashboards (v2)
+ */
+export const invalidateGetMetricDashboardsV2 = async (
+ queryClient: QueryClient,
+ params: GetMetricDashboardsV2Params,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetMetricDashboardsV2QueryKey(params) },
+ options,
+ );
+
+ return queryClient;
+};
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index 1740b20d62..76751b3155 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -3954,6 +3954,25 @@ export interface DashboardtypesDashboardDTO {
updatedBy?: string;
}
+export interface DashboardtypesDashboardPanelRefDTO {
+ /**
+ * @type string
+ */
+ dashboardId: string;
+ /**
+ * @type string
+ */
+ dashboardName: string;
+ /**
+ * @type string
+ */
+ panelId: string;
+ /**
+ * @type string
+ */
+ panelName: string;
+}
+
export enum DashboardtypesDatasourcePluginVariantStructDTOKind {
'signoz/Datasource' = 'signoz/Datasource',
}
@@ -7174,6 +7193,13 @@ export interface MetricsexplorertypesMetricDashboardDTO {
widgetName: string;
}
+export interface MetricsexplorertypesMetricDashboardPanelsResponseDTO {
+ /**
+ * @type array,null
+ */
+ dashboards: DashboardtypesDashboardPanelRefDTO[] | null;
+}
+
export interface MetricsexplorertypesMetricDashboardsResponseDTO {
/**
* @type array,null
@@ -11455,6 +11481,22 @@ export type GetHosts200 = {
status: string;
};
+export type GetMetricDashboardsV2Params = {
+ /**
+ * @type string
+ * @description The name of the metric. May contain slashes (e.g. cloud-provider metrics like run.googleapis.com/request_latencies).
+ */
+ metricName: string;
+};
+
+export type GetMetricDashboardsV2200 = {
+ data: MetricsexplorertypesMetricDashboardPanelsResponseDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type GetFlamegraphPathParameters = {
traceID: string;
};
diff --git a/pkg/apiserver/signozapiserver/metricsexplorer.go b/pkg/apiserver/signozapiserver/metricsexplorer.go
index c6b749f663..0a9ea6c79d 100644
--- a/pkg/apiserver/signozapiserver/metricsexplorer.go
+++ b/pkg/apiserver/signozapiserver/metricsexplorer.go
@@ -187,6 +187,26 @@ func (provider *provider) addMetricsExplorerRoutes(router *mux.Router) error {
return err
}
+ if err := router.Handle("/api/v3/metrics/dashboards", handler.New(
+ provider.authzMiddleware.ViewAccess(provider.metricsExplorerHandler.GetMetricDashboardsV2),
+ handler.OpenAPIDef{
+ ID: "GetMetricDashboardsV2",
+ Tags: []string{"metrics"},
+ Summary: "Get metric dashboards (v2)",
+ Description: "This endpoint returns associated v2 dashboards for a specified metric",
+ Request: nil,
+ RequestQuery: new(metricsexplorertypes.MetricNameQuery),
+ RequestContentType: "",
+ Response: new(metricsexplorertypes.MetricDashboardPanelsResponse),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusUnauthorized, http.StatusNotFound, http.StatusInternalServerError},
+ Deprecated: false,
+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),
+ })).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
if err := router.Handle("/api/v2/metrics/inspect", handler.New(
provider.authzMiddleware.ViewAccess(provider.metricsExplorerHandler.InspectMetrics),
handler.OpenAPIDef{
diff --git a/pkg/modules/dashboard/dashboard.go b/pkg/modules/dashboard/dashboard.go
index c0719b220a..c7527473b4 100644
--- a/pkg/modules/dashboard/dashboard.go
+++ b/pkg/modules/dashboard/dashboard.go
@@ -88,6 +88,8 @@ type Module interface {
UpdateView(ctx context.Context, orgID valuer.UUID, id valuer.UUID, updateable dashboardtypes.UpdatableDashboardView) (*dashboardtypes.DashboardView, error)
DeleteView(ctx context.Context, orgID valuer.UUID, id valuer.UUID) error
+
+ GetByMetricNamesV2(ctx context.Context, orgID valuer.UUID, metricNames []string) (map[string][]dashboardtypes.DashboardPanelRef, error)
}
type Handler interface {
diff --git a/pkg/modules/dashboard/impldashboard/listfilter_visitor.go b/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
index ca0d0f2d20..0340d563f1 100644
--- a/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
+++ b/pkg/modules/dashboard/impldashboard/listfilter_visitor.go
@@ -285,9 +285,9 @@ func (v *visitor) buildStringOperation(builder *sqlbuilder.SelectBuilder, ctx *g
like = "NOT LIKE"
}
// Escape the user's % and _ so they match literally, then wrap in wildcards.
- // ESCAPE declares the backslash we just injected as the escape char — needed
- // on SQLite (no default) and a harmless restatement of the Postgres default.
- escaped := strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(val)
+ // ESCAPE declares the backslash the escaper injected as the escape char —
+ // needed on SQLite (no default) and a harmless restatement of the Postgres default.
+ escaped := v.formatter.EscapeLikePattern(val)
return fmt.Sprintf("%s %s %s ESCAPE '\\'", columnExpression, like, builder.Var("%"+escaped+"%"))
case qbtypesv5.FilterOperatorRegexp, qbtypesv5.FilterOperatorNotRegexp:
v.addError("REGEXP filtering on %q is not yet supported", keyForError)
diff --git a/pkg/modules/dashboard/impldashboard/store.go b/pkg/modules/dashboard/impldashboard/store.go
index dffd08ace6..803082c08f 100644
--- a/pkg/modules/dashboard/impldashboard/store.go
+++ b/pkg/modules/dashboard/impldashboard/store.go
@@ -213,6 +213,41 @@ func (store *store) sortExprForListV2(sort dashboardtypes.ListSort) (string, err
"unsupported sort field %q", sort)
}
+func (store *store) ListByDataContainsAny(ctx context.Context, orgID valuer.UUID, searches []string) ([]*dashboardtypes.StorableDashboard, error) {
+ storableDashboards := make([]*dashboardtypes.StorableDashboard, 0)
+ if len(searches) == 0 {
+ return storableDashboards, nil
+ }
+
+ clause, args := buildContainsAnyClauseForDataColumn(store.sqlstore.Formatter(), searches)
+ err := store.
+ sqlstore.
+ BunDB().
+ NewSelect().
+ Model(&storableDashboards).
+ Where("org_id = ?", orgID).
+ Where(clause, args...).
+ Scan(ctx)
+ if err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "couldn't list dashboards by data")
+ }
+
+ return storableDashboards, nil
+}
+
+// buildContainsAnyClauseForDataColumn builds a parenthesised OR of `data LIKE` predicates, one
+// per search, matching the raw substring literally (LIKE wildcards escaped). It
+// returns the predicate and its bind args, ready for a single bun Where call.
+func buildContainsAnyClauseForDataColumn(formatter sqlstore.SQLFormatter, searches []string) (string, []any) {
+ conditions := make([]string, 0, len(searches))
+ args := make([]any, 0, len(searches))
+ for _, search := range searches {
+ conditions = append(conditions, "data LIKE ? ESCAPE '\\'")
+ args = append(args, "%"+formatter.EscapeLikePattern(search)+"%")
+ }
+ return "(" + strings.Join(conditions, " OR ") + ")", args
+}
+
func (store *store) GetPublic(ctx context.Context, dashboardID string) (*dashboardtypes.StorablePublicDashboard, error) {
storable := new(dashboardtypes.StorablePublicDashboard)
err := store.
diff --git a/pkg/modules/dashboard/impldashboard/store_test.go b/pkg/modules/dashboard/impldashboard/store_test.go
new file mode 100644
index 0000000000..ab690edfd2
--- /dev/null
+++ b/pkg/modules/dashboard/impldashboard/store_test.go
@@ -0,0 +1,43 @@
+package impldashboard
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func TestBuildContainsAnyClauseForDataColumn(t *testing.T) {
+ cases := []struct {
+ subtestName string
+ searches []string
+ expectedSQL string
+ expectedArgs []any
+ }{
+ {
+ subtestName: "single search",
+ searches: []string{"http.server.duration"},
+ expectedSQL: `(data LIKE ? ESCAPE '\')`,
+ expectedArgs: []any{`%http.server.duration%`},
+ },
+ {
+ subtestName: "multiple searches are OR-ed",
+ searches: []string{"metric.a", "metric.b", "metric.c"},
+ expectedSQL: `(data LIKE ? ESCAPE '\' OR data LIKE ? ESCAPE '\' OR data LIKE ? ESCAPE '\')`,
+ expectedArgs: []any{`%metric.a%`, `%metric.b%`, `%metric.c%`},
+ },
+ {
+ subtestName: "like wildcards in the search are escaped",
+ searches: []string{`a%b_c\d`},
+ expectedSQL: `(data LIKE ? ESCAPE '\')`,
+ expectedArgs: []any{`%a\%b\_c\\d%`},
+ },
+ }
+
+ for _, c := range cases {
+ t.Run(c.subtestName, func(t *testing.T) {
+ clause, args := buildContainsAnyClauseForDataColumn(formatter(t), c.searches)
+ assert.Equal(t, c.expectedSQL, clause)
+ assert.Equal(t, c.expectedArgs, args)
+ })
+ }
+}
diff --git a/pkg/modules/dashboard/impldashboard/v2_dashboards_by_metric_name.go b/pkg/modules/dashboard/impldashboard/v2_dashboards_by_metric_name.go
new file mode 100644
index 0000000000..c8c313031a
--- /dev/null
+++ b/pkg/modules/dashboard/impldashboard/v2_dashboards_by_metric_name.go
@@ -0,0 +1,132 @@
+package impldashboard
+
+import (
+ "context"
+ "log/slog"
+ "maps"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types/dashboardtypes"
+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+func (m *module) GetByMetricNamesV2(ctx context.Context, orgID valuer.UUID, metricNames []string) (map[string][]dashboardtypes.DashboardPanelRef, error) {
+ metricNamesMap := make(map[string]bool, len(metricNames))
+ for _, name := range metricNames {
+ metricNamesMap[name] = true
+ }
+
+ candidateDashboards, err := m.getCandidatesDashboardsForMetricNames(ctx, orgID, metricNames)
+ if err != nil {
+ return nil, err
+ }
+
+ return m.selectDashboardsFromCandidates(ctx, metricNamesMap, candidateDashboards), nil
+}
+
+func (m *module) getCandidatesDashboardsForMetricNames(ctx context.Context, orgID valuer.UUID, metricNames []string) ([]*dashboardtypes.DashboardV2, error) {
+ storables, err := m.store.ListByDataContainsAny(ctx, orgID, metricNames)
+ if err != nil {
+ return nil, err
+ }
+
+ candidates := make([]*dashboardtypes.DashboardV2, 0, len(storables))
+ for _, storable := range storables {
+ if storable.Source == dashboardtypes.SourceSystem {
+ continue
+ }
+
+ // tags are not required for this process so sending a nil list here.
+ dashboard, err := storable.ToDashboardV2(nil)
+ if err != nil {
+ m.settings.Logger().WarnContext(ctx, "skipping dashboard that couldn't be parsed as v2", slog.String("dashboard_id", storable.ID.StringValue()), errors.Attr(err))
+ continue
+ }
+ candidates = append(candidates, dashboard)
+ }
+ return candidates, nil
+}
+
+func (m *module) selectDashboardsFromCandidates(ctx context.Context, metricNamesMap map[string]bool, candidateDashboards []*dashboardtypes.DashboardV2) map[string][]dashboardtypes.DashboardPanelRef {
+ result := make(map[string][]dashboardtypes.DashboardPanelRef)
+ for _, dashboard := range candidateDashboards {
+ for panelID, panel := range dashboard.Spec.Panels {
+ if panel == nil {
+ continue
+ }
+ metricsInPanel := make(map[string]bool)
+ for _, query := range panel.Spec.Queries {
+ maps.Copy(metricsInPanel, m.extractMetricNamesFromQuerySpec(ctx, query.Spec.Plugin.Spec))
+ }
+ for metricName := range metricsInPanel {
+ if !metricNamesMap[metricName] {
+ continue
+ }
+ result[metricName] = append(result[metricName], dashboardtypes.DashboardPanelRef{
+ DashboardID: dashboard.ID.StringValue(),
+ DashboardName: dashboard.Spec.Display.Name,
+ PanelID: panelID,
+ PanelName: panel.Spec.Display.Name,
+ })
+ }
+ }
+ }
+ return result
+}
+
+func (m *module) extractMetricNamesFromQuerySpec(ctx context.Context, spec any) map[string]bool {
+ found := make(map[string]bool)
+ switch s := spec.(type) {
+ case *qbtypes.CompositeQuery:
+ for _, envelope := range s.Queries {
+ maps.Copy(found, m.extractMetricNamesFromQueryEnvelope(ctx, envelope))
+ }
+ case *dashboardtypes.BuilderQuerySpec:
+ if builder, ok := s.Spec.(qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]); ok {
+ for _, aggregation := range builder.Aggregations {
+ if aggregation.MetricName != "" {
+ found[aggregation.MetricName] = true
+ }
+ }
+ }
+ case *qbtypes.PromQuery:
+ maps.Copy(found, m.extractMetricNamesFromRawQuery(ctx, qbtypes.QueryTypePromQL, s.Query))
+ case *qbtypes.ClickHouseQuery:
+ maps.Copy(found, m.extractMetricNamesFromRawQuery(ctx, qbtypes.QueryTypeClickHouseSQL, s.Query))
+ }
+ return found
+}
+
+func (m *module) extractMetricNamesFromQueryEnvelope(ctx context.Context, envelope qbtypes.QueryEnvelope) map[string]bool {
+ found := make(map[string]bool)
+ switch s := envelope.Spec.(type) {
+ case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
+ for _, aggregation := range s.Aggregations {
+ if aggregation.MetricName != "" {
+ found[aggregation.MetricName] = true
+ }
+ }
+ case qbtypes.PromQuery:
+ maps.Copy(found, m.extractMetricNamesFromRawQuery(ctx, qbtypes.QueryTypePromQL, s.Query))
+ case qbtypes.ClickHouseQuery:
+ maps.Copy(found, m.extractMetricNamesFromRawQuery(ctx, qbtypes.QueryTypeClickHouseSQL, s.Query))
+ }
+ return found
+}
+
+func (m *module) extractMetricNamesFromRawQuery(ctx context.Context, queryType qbtypes.QueryType, query string) map[string]bool {
+ found := make(map[string]bool)
+ if query == "" {
+ return found
+ }
+ result, err := m.queryParser.AnalyzeQueryFilter(ctx, queryType, query)
+ if err != nil {
+ m.settings.Logger().WarnContext(ctx, "failed to parse query for metric names", slog.String("query", query), errors.Attr(err))
+ return found
+ }
+ for _, metricName := range result.MetricNames {
+ found[metricName] = true
+ }
+ return found
+}
diff --git a/pkg/modules/metricsexplorer/implmetricsexplorer/handler.go b/pkg/modules/metricsexplorer/implmetricsexplorer/handler.go
index 6808b86696..2bdedf5a66 100644
--- a/pkg/modules/metricsexplorer/implmetricsexplorer/handler.go
+++ b/pkg/modules/metricsexplorer/implmetricsexplorer/handler.go
@@ -228,6 +228,38 @@ func (h *handler) GetMetricDashboards(rw http.ResponseWriter, req *http.Request)
render.Success(rw, http.StatusOK, out)
}
+func (h *handler) GetMetricDashboardsV2(rw http.ResponseWriter, req *http.Request) {
+ claims, err := authtypes.ClaimsFromContext(req.Context())
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ var in metricsexplorertypes.MetricNameQuery
+ if err := binding.Query.BindQuery(req.URL.Query(), &in); err != nil {
+ render.Error(rw, err)
+ return
+ }
+ if err := in.Validate(); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ orgID := valuer.MustNewUUID(claims.OrgID)
+
+ if err := h.checkMetricExists(req.Context(), orgID, in.MetricName); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ out, err := h.module.GetMetricDashboardsV2(req.Context(), orgID, in.MetricName)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+ render.Success(rw, http.StatusOK, out)
+}
+
func (h *handler) GetMetricHighlights(rw http.ResponseWriter, req *http.Request) {
claims, err := authtypes.ClaimsFromContext(req.Context())
if err != nil {
diff --git a/pkg/modules/metricsexplorer/implmetricsexplorer/module.go b/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
index d4dbe7c2d7..aae4d1658f 100644
--- a/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
+++ b/pkg/modules/metricsexplorer/implmetricsexplorer/module.go
@@ -373,22 +373,35 @@ func (m *module) GetMetricDashboards(ctx context.Context, orgID valuer.UUID, met
return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to get dashboards for metric")
}
- dashboards := make([]metricsexplorertypes.MetricDashboard, 0)
- if dashboardList, ok := data[metricName]; ok {
- dashboards = make([]metricsexplorertypes.MetricDashboard, 0, len(dashboardList))
- for _, item := range dashboardList {
- dashboards = append(dashboards, metricsexplorertypes.MetricDashboard{
- DashboardName: item["dashboard_name"],
- DashboardID: item["dashboard_id"],
- WidgetID: item["widget_id"],
- WidgetName: item["widget_name"],
- })
- }
+ return newMetricDashboardsResponse(data[metricName]), nil
+}
+
+func (m *module) GetMetricDashboardsV2(ctx context.Context, orgID valuer.UUID, metricName string) (*metricsexplorertypes.MetricDashboardPanelsResponse, error) {
+ if metricName == "" {
+ return nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "metricName is required")
+ }
+ data, err := m.dashboardModule.GetByMetricNamesV2(ctx, orgID, []string{metricName})
+ if err != nil {
+ return nil, errors.WrapInternalf(err, errors.CodeInternal, "failed to get dashboards for metric")
+ }
+
+ return metricsexplorertypes.NewMetricDashboardPanelsResponse(data[metricName]), nil
+}
+
+func newMetricDashboardsResponse(dashboardList []map[string]string) *metricsexplorertypes.MetricDashboardsResponse {
+ dashboards := make([]metricsexplorertypes.MetricDashboard, 0, len(dashboardList))
+ for _, item := range dashboardList {
+ dashboards = append(dashboards, metricsexplorertypes.MetricDashboard{
+ DashboardName: item["dashboard_name"],
+ DashboardID: item["dashboard_id"],
+ WidgetID: item["widget_id"],
+ WidgetName: item["widget_name"],
+ })
}
return &metricsexplorertypes.MetricDashboardsResponse{
Dashboards: dashboards,
- }, nil
+ }
}
// GetMetricHighlights returns highlights for a metric including data points, last received, total time series, and active time series.
diff --git a/pkg/modules/metricsexplorer/metricsexplorer.go b/pkg/modules/metricsexplorer/metricsexplorer.go
index ddd99920b7..9be7e7b5ea 100644
--- a/pkg/modules/metricsexplorer/metricsexplorer.go
+++ b/pkg/modules/metricsexplorer/metricsexplorer.go
@@ -18,6 +18,7 @@ type Handler interface {
UpdateMetricMetadata(http.ResponseWriter, *http.Request)
GetMetricAlerts(http.ResponseWriter, *http.Request)
GetMetricDashboards(http.ResponseWriter, *http.Request)
+ GetMetricDashboardsV2(http.ResponseWriter, *http.Request)
GetMetricHighlights(http.ResponseWriter, *http.Request)
GetOnboardingStatus(http.ResponseWriter, *http.Request)
InspectMetrics(http.ResponseWriter, *http.Request)
@@ -33,6 +34,7 @@ type Module interface {
UpdateMetricMetadata(ctx context.Context, orgID valuer.UUID, req *metricsexplorertypes.UpdateMetricMetadataRequest) error
GetMetricAlerts(ctx context.Context, orgID valuer.UUID, metricName string) (*metricsexplorertypes.MetricAlertsResponse, error)
GetMetricDashboards(ctx context.Context, orgID valuer.UUID, metricName string) (*metricsexplorertypes.MetricDashboardsResponse, error)
+ GetMetricDashboardsV2(ctx context.Context, orgID valuer.UUID, metricName string) (*metricsexplorertypes.MetricDashboardPanelsResponse, error)
GetMetricHighlights(ctx context.Context, orgID valuer.UUID, metricName string) (*metricsexplorertypes.MetricHighlightsResponse, error)
GetMetricAttributes(ctx context.Context, orgID valuer.UUID, req *metricsexplorertypes.MetricAttributesRequest) (*metricsexplorertypes.MetricAttributesResponse, error)
HasNonSigNozMetrics(ctx context.Context) (bool, error)
diff --git a/pkg/sqlstore/sqlitesqlstore/formatter.go b/pkg/sqlstore/sqlitesqlstore/formatter.go
index 7448708df0..1514f1dee6 100644
--- a/pkg/sqlstore/sqlitesqlstore/formatter.go
+++ b/pkg/sqlstore/sqlitesqlstore/formatter.go
@@ -1,6 +1,8 @@
package sqlitesqlstore
import (
+ "strings"
+
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/uptrace/bun/schema"
)
@@ -105,3 +107,7 @@ func (f *formatter) LowerExpression(expression string) []byte {
sql = append(sql, ')')
return sql
}
+
+func (f *formatter) EscapeLikePattern(value string) string {
+ return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(value)
+}
diff --git a/pkg/sqlstore/sqlstore.go b/pkg/sqlstore/sqlstore.go
index 07594874b2..01e98fa52f 100644
--- a/pkg/sqlstore/sqlstore.go
+++ b/pkg/sqlstore/sqlstore.go
@@ -119,4 +119,8 @@ type SQLFormatter interface {
// LowerExpression wraps any SQL expression with lower() function for case-insensitive operations
LowerExpression(expression string) []byte
+
+ // EscapeLikePattern escapes LIKE wildcards (`%`, `_`, and the escape char `\`)
+ // in a value so it matches literally. Pair the pattern with `ESCAPE '\'`.
+ EscapeLikePattern(value string) string
}
diff --git a/pkg/sqlstore/sqlstoretest/formatter.go b/pkg/sqlstore/sqlstoretest/formatter.go
index e40f640dad..bd5a9f7e37 100644
--- a/pkg/sqlstore/sqlstoretest/formatter.go
+++ b/pkg/sqlstore/sqlstoretest/formatter.go
@@ -1,6 +1,8 @@
package sqlstoretest
import (
+ "strings"
+
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/uptrace/bun/schema"
)
@@ -105,3 +107,7 @@ func (f *formatter) LowerExpression(expression string) []byte {
sql = append(sql, ')')
return sql
}
+
+func (f *formatter) EscapeLikePattern(value string) string {
+ return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(value)
+}
diff --git a/pkg/types/dashboardtypes/dashboards_metric_usage.go b/pkg/types/dashboardtypes/dashboards_metric_usage.go
new file mode 100644
index 0000000000..a4d898e3d6
--- /dev/null
+++ b/pkg/types/dashboardtypes/dashboards_metric_usage.go
@@ -0,0 +1,11 @@
+package dashboardtypes
+
+// DashboardPanelRef identifies a single panel within a dashboard. The
+// "dashboards by metric name" lookup returns these to report each panel that
+// references a given metric.
+type DashboardPanelRef struct {
+ DashboardID string `json:"dashboardId" required:"true"`
+ DashboardName string `json:"dashboardName" required:"true"`
+ PanelID string `json:"panelId" required:"true"`
+ PanelName string `json:"panelName" required:"true"`
+}
diff --git a/pkg/types/dashboardtypes/store.go b/pkg/types/dashboardtypes/store.go
index de0507d865..92a2758014 100644
--- a/pkg/types/dashboardtypes/store.go
+++ b/pkg/types/dashboardtypes/store.go
@@ -43,6 +43,10 @@ type Store interface {
ListForUser(ctx context.Context, orgID valuer.UUID, userID valuer.UUID, params *ListDashboardsV2Params) ([]*StorableDashboardWithPinInfo, int64, error)
+ // ListByDataContainsAny returns the org's dashboards whose raw `data` JSON
+ // contains any of the given substrings (matched literally; LIKE wildcards escaped).
+ ListByDataContainsAny(ctx context.Context, orgID valuer.UUID, searches []string) ([]*StorableDashboard, error)
+
// Returns ErrCodePinnedDashboardLimitHit when the user is at MaxPinnedDashboardsPerUser.
PinForUser(ctx context.Context, preference *UserDashboardPreference) error
diff --git a/pkg/types/metricsexplorertypes/metricsexplorer.go b/pkg/types/metricsexplorertypes/metricsexplorer.go
index 7157f0e60f..11c7f837b5 100644
--- a/pkg/types/metricsexplorertypes/metricsexplorer.go
+++ b/pkg/types/metricsexplorertypes/metricsexplorer.go
@@ -4,6 +4,7 @@ import (
"encoding/json"
"github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types/dashboardtypes"
"github.com/SigNoz/signoz/pkg/types/metrictypes"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/valuer"
@@ -252,6 +253,22 @@ type MetricDashboardsResponse struct {
Dashboards []MetricDashboard `json:"dashboards" required:"true" nullable:"true"`
}
+// MetricDashboardPanelsResponse is the response for the v2 metric dashboards
+// endpoint: the dashboard panels that reference the metric.
+type MetricDashboardPanelsResponse struct {
+ Dashboards []dashboardtypes.DashboardPanelRef `json:"dashboards" required:"true" nullable:"true"`
+}
+
+// NewMetricDashboardPanelsResponse wraps the dashboard panels that reference a
+// metric into the v2 API response.
+func NewMetricDashboardPanelsResponse(refs []dashboardtypes.DashboardPanelRef) *MetricDashboardPanelsResponse {
+ if refs == nil {
+ refs = []dashboardtypes.DashboardPanelRef{}
+ }
+
+ return &MetricDashboardPanelsResponse{Dashboards: refs}
+}
+
// MetricHighlightsResponse is the output structure for the metric highlights endpoint.
type MetricHighlightsResponse struct {
DataPoints uint64 `json:"dataPoints" required:"true"`
diff --git a/tests/integration/tests/dashboard/03_v2_dashboard.py b/tests/integration/tests/dashboard/03_v2_dashboard.py
index 6e7d0665db..5616aaab7b 100644
--- a/tests/integration/tests/dashboard/03_v2_dashboard.py
+++ b/tests/integration/tests/dashboard/03_v2_dashboard.py
@@ -6,6 +6,7 @@ import pytest
import requests
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD
+from fixtures.metrics import Metrics
from fixtures.types import Operation, SigNoz
BASE_URL = "/api/v2/dashboards"
@@ -934,3 +935,306 @@ def test_dashboard_v2_like_escaping(
)
assert response.status_code == HTTPStatus.OK, response.text
assert {d["spec"]["display"]["name"] for d in response.json()["data"]["dashboards"]} == expected, query
+
+
+# ─── get dashboards by metric name (v3) ──────────────────────────────────────
+
+
+def test_dashboard_v2_get_by_metric_name(
+ signoz: SigNoz,
+ create_user_admin: Operation, # pylint: disable=unused-argument
+ get_token: Callable[[str, str], str],
+ insert_metrics: Callable[[list[Metrics]], None],
+) -> None:
+ """The v3 endpoint shortlists dashboards via a coarse data prefilter, then
+ confirms matches by parsing the typed v2 panels. It must find the metric in
+ builder, promql, and clickhouse queries, and must NOT report a dashboard where
+ the metric appears only in panel names (the prefilter matches but the parse
+ rejects it)."""
+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
+ _wipe_all_dashboards(signoz, token)
+
+ target_metric = "system.network.dropped"
+ decoy_metric = "system.network.io"
+
+ # The endpoint gates on metric existence (checkMetricExists reads
+ # signoz_metrics.distributed_metadata), so seed the target metric there. A
+ # label is required for a metadata row to be written.
+ insert_metrics(
+ [
+ Metrics(
+ metric_name=target_metric,
+ labels={"host.name": "test-host"},
+ temporality="Cumulative",
+ value=1.0,
+ )
+ ]
+ )
+
+ # D1: a single builder query referencing the target metric.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json={
+ "schemaVersion": "v6",
+ "name": "by-metric-builder",
+ "spec": {
+ "display": {"name": "by-metric-builder"},
+ "panels": {
+ "p-builder": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "D1 builder target"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/BuilderQuery",
+ "spec": {
+ "name": "A",
+ "signal": "metrics",
+ "aggregations": [
+ {
+ "metricName": target_metric,
+ "timeAggregation": "rate",
+ "spaceAggregation": "sum",
+ }
+ ],
+ },
+ }
+ },
+ }
+ ],
+ },
+ }
+ },
+ },
+ "tags": [],
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ d1_id = response.json()["data"]["id"]
+
+ # D2: one clickhouse panel and one promql panel, both referencing the target
+ # metric (one query per panel is enforced by validation). Two matching panels
+ # in one dashboard also guards against a dashboard/widget being returned twice.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json={
+ "schemaVersion": "v6",
+ "name": "by-metric-ch-promql",
+ "spec": {
+ "display": {"name": "by-metric-ch-promql"},
+ "panels": {
+ "p-ch": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "D2 clickhouse target"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/ClickHouseSQL",
+ "spec": {
+ "name": "A",
+ "query": f"select * from signoz_metrics.distributed_samples_v4 where metric_name IN ['{target_metric}']",
+ },
+ }
+ },
+ }
+ ],
+ },
+ },
+ "p-promql": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "D2 promql target"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/PromQLQuery",
+ "spec": {
+ "name": "A",
+ "query": f'sum(rate({{"{target_metric}"}}[5m]))',
+ },
+ }
+ },
+ }
+ ],
+ },
+ },
+ },
+ },
+ "tags": [],
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ d2_id = response.json()["data"]["id"]
+
+ # D3: a promql-only dashboard referencing the target metric, so a promql
+ # extraction regression is caught independently of the clickhouse path above.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json={
+ "schemaVersion": "v6",
+ "name": "by-metric-promql",
+ "spec": {
+ "display": {"name": "by-metric-promql"},
+ "panels": {
+ "p-promql": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": "D3 promql target"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/PromQLQuery",
+ "spec": {
+ "name": "A",
+ "query": f'sum(rate({{"{target_metric}"}}[5m]))',
+ },
+ }
+ },
+ }
+ ],
+ },
+ }
+ },
+ },
+ "tags": [],
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ d3_id = response.json()["data"]["id"]
+
+ # D4: all three query types, but the target name appears only in the panel
+ # names; the queries reference a decoy metric. The data prefilter matches
+ # (panel names contain the target), but parsing the queries must not associate
+ # the target metric, so this dashboard must be excluded from the result.
+ response = requests.post(
+ signoz.self.host_configs["8080"].get(BASE_URL),
+ json={
+ "schemaVersion": "v6",
+ "name": "by-metric-false-positive",
+ "spec": {
+ "display": {"name": "by-metric-false-positive"},
+ "panels": {
+ "p-builder": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": f"{target_metric} builder"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/BuilderQuery",
+ "spec": {
+ "name": "A",
+ "signal": "metrics",
+ "aggregations": [
+ {
+ "metricName": decoy_metric,
+ "timeAggregation": "rate",
+ "spaceAggregation": "sum",
+ }
+ ],
+ },
+ }
+ },
+ }
+ ],
+ },
+ },
+ "p-ch": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": f"{target_metric} clickhouse"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/ClickHouseSQL",
+ "spec": {
+ "name": "A",
+ "query": f"select * from signoz_metrics.distributed_samples_v4 where metric_name IN ['{decoy_metric}']",
+ },
+ }
+ },
+ }
+ ],
+ },
+ },
+ "p-promql": {
+ "kind": "Panel",
+ "spec": {
+ "display": {"name": f"{target_metric} promql"},
+ "plugin": {"kind": "signoz/TimeSeriesPanel", "spec": {}},
+ "queries": [
+ {
+ "kind": "time_series",
+ "spec": {
+ "plugin": {
+ "kind": "signoz/PromQLQuery",
+ "spec": {
+ "name": "A",
+ "query": f'sum(rate({{"{decoy_metric}"}}[5m]))',
+ },
+ }
+ },
+ }
+ ],
+ },
+ },
+ },
+ },
+ "tags": [],
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.CREATED, response.text
+ d4_id = response.json()["data"]["id"]
+
+ response = requests.get(
+ signoz.self.host_configs["8080"].get("/api/v3/metrics/dashboards"),
+ params={"metricName": target_metric},
+ headers={"Authorization": f"Bearer {token}"},
+ timeout=5,
+ )
+ assert response.status_code == HTTPStatus.OK, response.text
+ dashboards = response.json()["data"]["dashboards"]
+
+ # No dashboard/panel should be returned more than once.
+ pairs = [(d["dashboardId"], d["panelId"]) for d in dashboards]
+ assert len(pairs) == len(set(pairs))
+
+ # D1 (1 panel) + D2 (2 panels) + D3 (1 promql panel) match; D4 (target only in
+ # panel names) does not.
+ assert {d["dashboardId"] for d in dashboards} == {d1_id, d2_id, d3_id}
+ assert d4_id not in {d["dashboardId"] for d in dashboards}
+
+ by_dashboard: dict[str, list[str]] = {}
+ for d in dashboards:
+ by_dashboard.setdefault(d["dashboardId"], []).append(d["panelName"])
+ assert sorted(by_dashboard[d1_id]) == ["D1 builder target"]
+ assert sorted(by_dashboard[d2_id]) == ["D2 clickhouse target", "D2 promql target"]
+ assert sorted(by_dashboard[d3_id]) == ["D3 promql target"]