Prometheus/Scopes: Update to use scopespec type from app (#84593)

This commit is contained in:
Kyle Brandt
2024-03-18 09:49:26 -04:00
committed by GitHub
parent cc6459deaf
commit aec2ef727a
2 changed files with 39 additions and 14 deletions
+34 -1
View File
@@ -1,16 +1,24 @@
package models
import (
"fmt"
"github.com/grafana/grafana/pkg/apis/scope/v0alpha1"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql/parser"
)
func ApplyQueryScope(rawExpr string, matchers []*labels.Matcher) (string, error) {
func ApplyQueryScope(rawExpr string, scope v0alpha1.ScopeSpec) (string, error) {
expr, err := parser.ParseExpr(rawExpr)
if err != nil {
return "", err
}
matchers, err := scopeFiltersToMatchers(scope.Filters)
if err != nil {
return "", err
}
matcherNamesToIdx := make(map[string]int, len(matchers))
for i, matcher := range matchers {
if matcher == nil {
@@ -50,3 +58,28 @@ func ApplyQueryScope(rawExpr string, matchers []*labels.Matcher) (string, error)
})
return expr.String(), nil
}
func scopeFiltersToMatchers(filters []v0alpha1.ScopeFilter) ([]*labels.Matcher, error) {
matchers := make([]*labels.Matcher, 0, len(filters))
for _, f := range filters {
var mt labels.MatchType
switch f.Operator {
case "=":
mt = labels.MatchEqual
case "!=":
mt = labels.MatchNotEqual
case "=~":
mt = labels.MatchRegexp
case "!~":
mt = labels.MatchNotRegexp
default:
return nil, fmt.Errorf("unknown operator %q", f.Operator)
}
m, err := labels.NewMatcher(mt, f.Key, f.Value)
if err != nil {
return nil, err
}
matchers = append(matchers, m)
}
return matchers, nil
}