forked from grafana/cortex-tools
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathruler.go
More file actions
84 lines (68 loc) · 1.94 KB
/
ruler.go
File metadata and controls
84 lines (68 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package analyse
import (
"sort"
"github.com/pkg/errors"
"github.com/prometheus/prometheus/promql/parser"
log "github.com/sirupsen/logrus"
"github.com/cortexproject/cortex-tools/pkg/rules/rwrulefmt"
)
type MetricsInRuler struct {
MetricsUsed []string `json:"metricsUsed"`
OverallMetrics map[string]struct{} `json:"-"`
RuleGroups []RuleGroupMetrics `json:"ruleGroups"`
}
type RuleGroupMetrics struct {
Namespace string `json:"namspace"`
GroupName string `json:"name"`
Metrics []string `json:"metrics"`
ParseErrors []string `json:"parse_errors"`
}
func ParseMetricsInRuleGroup(mir *MetricsInRuler, group rwrulefmt.RuleGroup, ns string) error {
var (
ruleMetrics = make(map[string]struct{})
refMetrics = make(map[string]struct{})
parseErrors []error
)
for _, rule := range group.Rules {
if rule.Record != "" {
ruleMetrics[rule.Record] = struct{}{}
}
query := rule.Expr
expr, err := parser.ParseExpr(query)
if err != nil {
parseErrors = append(parseErrors, errors.Wrapf(err, "query=%v", query))
log.Debugln("msg", "promql parse error", "err", err, "query", query)
continue
}
parser.Inspect(expr, func(node parser.Node, _ []parser.Node) error {
if n, ok := node.(*parser.VectorSelector); ok {
refMetrics[n.Name] = struct{}{}
}
return nil
})
}
// remove defined recording rule metrics in same RG
for ruleMetric := range ruleMetrics {
delete(refMetrics, ruleMetric)
}
var metricsInGroup []string
var parseErrs []string
for metric := range refMetrics {
if metric == "" {
continue
}
metricsInGroup = append(metricsInGroup, metric)
mir.OverallMetrics[metric] = struct{}{}
}
sort.Strings(metricsInGroup)
for _, err := range parseErrors {
parseErrs = append(parseErrs, err.Error())
}
mir.RuleGroups = append(mir.RuleGroups, RuleGroupMetrics{
Namespace: ns,
GroupName: group.Name,
Metrics: metricsInGroup,
ParseErrors: parseErrs,
})
return nil
}