grafana / grafonnet

Jsonnet library for generating Grafana dashboards.
https://grafana.github.io/grafonnet/
Apache License 2.0
320 stars 18 forks source link

feat(util): dedupe query targets into shared queries #205

Closed Duologic closed 1 month ago

Duologic commented 1 month ago

This PR adds a util function to dedupe query targets into 'shared queries', this could boost performance of dashboards that run the same query multiple times in different panels.

Rudimentary example:

local g = import 'github.com/grafana/grafonnet/gen/grafonnet-latest/main.libsonnet';

local sharedQuery1 =
  g.query.prometheus.new(
    'mimir',
    'query1',
  );

local sharedQuery2 =
  g.query.prometheus.new(
    'mimir',
    'query2',
  );

local panels =
  [
    g.panel.timeSeries.new('Panel 1')
    + g.panel.timeSeries.queryOptions.withTargets([
      sharedQuery1,
    ]),

    g.panel.timeSeries.new('Panel 2')
    + g.panel.timeSeries.queryOptions.withTargets([
      sharedQuery2,
      sharedQuery1, # This will get replaced.
    ]),
    g.panel.timeSeries.new('Panel 3')
    + g.panel.timeSeries.queryOptions.withTargets([
      sharedQuery2, # This will get replaced.
    ]),
  ];

g.dashboard.new('Dashboard')
+ g.dashboard.withPanels(
  std.foldl(
    function(panels, f) f(panels),
    // Apply these functions to the panels
    [
      g.util.panel.setPanelIDs,
      g.util.panel.setRefIDsOnPanels,
      g.util.panel.dedupeQueryTargets,  // Requires `refId` on targets and `id` on panels
    ],
    panels
  ),
  setPanelIDs=false,  // IDs set on inner function
)