-
Notifications
You must be signed in to change notification settings - Fork 12
/
rule.go
66 lines (57 loc) · 1.44 KB
/
rule.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
package rulesclient
import (
"errors"
"strings"
"time"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/pkg/rulefmt"
"gopkg.in/yaml.v3"
)
type Rule struct {
Record string `json:"record,omitempty"`
Alert string `json:"alert,omitempty"`
Expr string `json:"expr"`
For string `json:"for,omitempty"`
Labels map[string]string `json:"labels,omitempty"`
Annotations map[string]string `json:"annotations,omitempty"`
}
func (r *Rule) Validate() error {
promRule, err := r.convertToPromRule()
if err != nil {
return err
}
errs := promRule.Validate()
if len(errs) != 0 {
promError := rulefmt.Error{Err: errs[0]}
return errors.New(promError.Error())
}
return nil
}
func (r *Rule) convertToPromRule() (rulefmt.RuleNode, error) {
var duration time.Duration
var err error
if r.For != "" {
duration, err = time.ParseDuration(strings.Trim(r.For, `"`))
if err != nil {
return rulefmt.RuleNode{}, err
}
}
record := YAMLNodeFromString(r.Record)
alert := YAMLNodeFromString(r.Alert)
expr := YAMLNodeFromString(r.Expr)
return rulefmt.RuleNode{
Record: record,
Alert: alert,
Expr: expr,
For: model.Duration(duration),
Labels: r.Labels,
Annotations: r.Annotations,
}, nil
}
func YAMLNodeFromString(value string) yaml.Node {
node := yaml.Node{}
if value != "" {
node.SetString(value)
}
return node
}