How do I extract the result value out of a Prometheus query in Golang?

40 views Asked by At

Using these packages:

"github.com/prometheus/client_golang/api"
v1 "github.com/prometheus/client_golang/api/prometheus/v1"

I am running minio_cluster_usage_total_bytes{job=1} via Query:

promAPI := v1.NewAPI(client)
promquery := fmt.Sprintf("minio_cluster_usage_total_bytes{job=\"1\"}")

res, _, err := promAPI.Query(context.Background(), promquery, time.Now())
if err != nil {
    log.Println(err)
}

Printing the response, via log.Println(res.String()) and log.Println(res.Type()) shows this:

2024/03/05 11:16:08 minio_cluster_usage_total_bytes{instance="", job="1", server="127.0.0.1:9000"} => 18429647893 @[1709658968.29]
2024/03/05 11:16:08 vector

How can I extract just the resulting value, i.e. 18429647893 in this case? I would very much prefer to avoid string parsing functions if at all possible.

1

There are 1 answers

0
DazWilkin On

Yeah, it's a little gnarly but the documentation helps uncover the solution.

API Query method returns types that implement an interface model.Value

model.Value implementing types require a Type method that returns ValueType

Your code should switch over these values but, in this case it will be ValVector

You can type assert res to model.Vector which is an alias for []*Sample (where Sample and has fields including Value and Timestamp)

In your case, I think you'll have a single []*Sample entry but, for consistency, I've interated over the slice.

So:

switch res.Type() {
case model.ValScalar:
    // Implement model.Scalar
case model.ValVector:
    vector := res.(model.Vector)
    for _, sample := range vector {
        log.Println(sample.Value)
    }
case model.ValMatrix:
    // Implement model.Matrix
case model.ValString:
    // Implemenet String
}