-
Notifications
You must be signed in to change notification settings - Fork 793
/
compat.go
75 lines (63 loc) · 2.03 KB
/
compat.go
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
package rulespb
import (
"time"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/model/rulefmt"
"gopkg.in/yaml.v3"
"github.com/cortexproject/cortex/pkg/cortexpb" //lint:ignore faillint allowed to import other protobuf
)
// ToProto transforms a formatted prometheus rulegroup to a rule group protobuf
func ToProto(user string, namespace string, rl rulefmt.RuleGroup) *RuleGroupDesc {
rg := RuleGroupDesc{
Name: rl.Name,
Namespace: namespace,
Interval: time.Duration(rl.Interval),
Rules: formattedRuleToProto(rl.Rules),
User: user,
}
return &rg
}
func formattedRuleToProto(rls []rulefmt.RuleNode) []*RuleDesc {
rules := make([]*RuleDesc, len(rls))
for i := range rls {
rules[i] = &RuleDesc{
Expr: rls[i].Expr.Value,
Record: rls[i].Record.Value,
Alert: rls[i].Alert.Value,
For: time.Duration(rls[i].For),
Labels: cortexpb.FromLabelsToLabelAdapters(labels.FromMap(rls[i].Labels)),
Annotations: cortexpb.FromLabelsToLabelAdapters(labels.FromMap(rls[i].Annotations)),
}
}
return rules
}
// FromProto generates a rulefmt RuleGroup
func FromProto(rg *RuleGroupDesc) rulefmt.RuleGroup {
formattedRuleGroup := rulefmt.RuleGroup{
Name: rg.GetName(),
Interval: model.Duration(rg.Interval),
Rules: make([]rulefmt.RuleNode, len(rg.GetRules())),
}
for i, rl := range rg.GetRules() {
exprNode := yaml.Node{}
exprNode.SetString(rl.GetExpr())
newRule := rulefmt.RuleNode{
Expr: exprNode,
Labels: cortexpb.FromLabelAdaptersToLabels(rl.Labels).Map(),
Annotations: cortexpb.FromLabelAdaptersToLabels(rl.Annotations).Map(),
For: model.Duration(rl.GetFor()),
}
if rl.GetRecord() != "" {
recordNode := yaml.Node{}
recordNode.SetString(rl.GetRecord())
newRule.Record = recordNode
} else {
alertNode := yaml.Node{}
alertNode.SetString(rl.GetAlert())
newRule.Alert = alertNode
}
formattedRuleGroup.Rules[i] = newRule
}
return formattedRuleGroup
}