Parsing queries / alerts / expressions

83 views
Skip to first unread message

Wiard van Rij

unread,
Feb 1, 2022, 2:47:16 PM2/1/22
to Prometheus Users
Hi everyone,

I'm automating a way to modify Grafana Dashboards to our liking. For example to use a public Grafana dashboard and append certain query labels to every query in a dashboard. 
For this, I figured to use the Prometheus Parser, which works well to some extend for my use-case. However certain 'expressions' (or queries) don't parse that well (or I'm doing it wrong). 

As a quick draft I have the following code:
------
    parsedExpr, _ := parser.ParseExpr(expr)
    childExprs := parser.Children(parsedExpr)
    parsedMainMetric, _ := parser.ParseMetric(expr)

    fmt.Println(parsedMainMetric)
    for _, childExpr := range childExprs {

        parsedChildExpr, _ := parser.ParseMetric(childExpr.String())
        fmt.Println(parsedChildExpr)
    }
------
Which works for:

> input:    "rate(node_disk_io_time_seconds_total{bar=\"foo\"}[2m])",

As this gives me the following output:

> {__name__="rate"}
> {__name__="node_disk_io_time_seconds_total", bar="foo"}

However, lets say I change the input to: 

> input:    "rate(node_disk_io_time_seconds_total{bar=\"foo\"}[2m]) > 0",

Then it does not exactly go how I expected it to be:

> {__name__="rate"}
> {__name__="rate"}
> {}

(obviously this is mainly due to how I wrote my draft code). 

I have seen https://demo.promlens.com/?l=eF6PYANAlbQ - and I was wondering if someone could give me some pointers on how I should continue (and if this is actually a viable option to update labels). 

Thanks in advance,

Wiard

l.mi...@gmail.com

unread,
Feb 1, 2022, 4:05:36 PM2/1/22
to Prometheus Users
Since rate() is a function, not a metric, you can't pass it to parser.ParseMetric() and expect it to work. You need to stick to ParseExpr and walk down the entire AST.
What you need to do is find all instances of parser.VectorSelector, which is the data structure that hold time series selectors in queries, and append labels there.

Wiard van Rij

unread,
Feb 1, 2022, 4:33:11 PM2/1/22
to Prometheus Users
Wow, I really appreciate this. Thanks so much. 

Op dinsdag 1 februari 2022 om 22:05:36 UTC+1 schreef l.mi...@gmail.com:

l.mi...@gmail.com

unread,
Feb 1, 2022, 4:52:07 PM2/1/22
to Prometheus Users
You might want to see if https://github.com/prometheus-community/prom-label-proxy provides what you need.
Reply all
Reply to author
Forward
0 new messages