/
prometheus.go
66 lines (54 loc) · 1.59 KB
/
prometheus.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 provisioner
import (
"io/ioutil"
"path/filepath"
"strings"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
)
type PrometheusAlertRules struct {
Groups []struct {
Rules []PrometheusRule `yaml:"rules"`
} `yaml:"groups"`
}
type PrometheusRule struct {
Name string `yaml:"alert"`
Annotations map[string]string `yaml:"annotations"`
Expression string `yaml:"expr"`
Labels map[string]string `yaml:"labels"`
}
func LoadPrometheusRulesFromDir(dir string) ([]PrometheusRule, error) {
filesInDir, err := ioutil.ReadDir(dir)
if err != nil {
return nil, errors.Wrapf(err, "can't open the alerts files directory")
}
var rules []PrometheusRule
for _, file := range filesInDir {
if strings.HasSuffix(file.Name(), ".yml") || strings.HasSuffix(file.Name(), ".yaml") {
alertsFile, err := ioutil.ReadFile(filepath.Join(dir, file.Name()))
if err != nil {
return nil, errors.Wrapf(err, "can't open the alerts file: %s", file.Name())
}
ruleConfig := PrometheusAlertRules{}
err = yaml.Unmarshal(alertsFile, &ruleConfig)
if err != nil {
return nil, errors.Wrapf(err, "can't read the alerts file: %s", file.Name())
}
for _, rule := range ruleConfig.Groups {
for _, alert := range rule.Rules {
if alert.Name != "" {
rules = append(rules, alert)
}
}
}
}
}
for i := 0; i < len(rules); i++ {
for j := i + 1; j < len(rules); j++ {
if rules[j].Name == rules[i].Name {
return nil, errors.Errorf("can't load rules with the same alertname: %v, index: %v, %v", rules[j].Name, i+1, j+1)
}
}
}
return rules, nil
}