/
alerts-checker.go
212 lines (169 loc) · 4.85 KB
/
alerts-checker.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/prometheus/prometheus/pkg/rulefmt"
"github.com/prometheus/prometheus/promql/parser"
)
var (
rulesDir string
prometheusHost string
offendingAlerts []string
erroredAlerts []string
ignoredAlerts map[string]bool = make(map[string]bool)
)
type apiResponse struct {
Status string `json:"status"`
Data struct {
Result []interface{} `json:"result"`
} `json:"data"`
}
func main() {
if len(os.Args) < 3 {
fmt.Printf("USAGE: %s rules-dir prometheus-host [alert-to-ignore,alert-to-ignore]\n", os.Args[0])
os.Exit(1)
}
rulesDir = os.Args[1]
prometheusHost = os.Args[2]
if len(os.Args) > 3 {
ignoredAlertsSeparated := os.Args[3]
for _, ignoredAlert := range strings.Split(ignoredAlertsSeparated, ",") {
ignoredAlerts[ignoredAlert] = true
}
}
matches, err := filepath.Glob(fmt.Sprintf("%s/*.yml", rulesDir))
if err != nil {
log.Fatal(err)
}
for _, file := range matches {
processFile(file)
}
var slackMessage string
if len(erroredAlerts) > 0 {
fmt.Println("====== Failed alerts (check above for errors):")
slackMessage += "*Failed to check these alerts*\n\n"
for _, alert := range erroredAlerts {
fmt.Println(alert)
slackMessage += fmt.Sprintf("* %s\n", alert)
}
}
if len(slackMessage) > 0 {
slackMessage += "\n"
}
if len(offendingAlerts) > 0 {
fmt.Println("====== Possibly obsolete alerts:")
slackMessage += fmt.Sprint("*Possibly obsolete alerts*\n\n")
for _, alert := range offendingAlerts {
fmt.Println(alert)
slackMessage += fmt.Sprintf("* %s\n", alert)
}
}
if (len(erroredAlerts) > 0) || (len(offendingAlerts) > 0) {
if slackWebhookUrl := os.Getenv("SLACK_WEBHOOK_URL"); len(slackWebhookUrl) > 0 {
channel := os.Getenv("SLACK_CHANNEL")
data := url.Values{}
if ciJobUrl := os.Getenv("CI_JOB_URL"); len(ciJobUrl) > 0 {
slackMessage += fmt.Sprintf("\n:ci_failing: %s", ciJobUrl)
}
data.Set("payload", `{"channel":"`+channel+`","text":"`+slackMessage+`","mrkdwn":true}`)
http.PostForm(slackWebhookUrl, data)
}
os.Exit(1)
}
}
func processFile(file string) {
ruleGroups, errs := rulefmt.ParseFile(file)
if len(errs) > 0 {
log.Fatalf("Error parsing file %v", errs)
}
groups := ruleGroups.Groups
for _, group := range groups {
for _, rule := range group.Rules {
if rule.Alert.Value == "" || ignoredAlerts[rule.Alert.Value] {
continue
}
selectors, err := extractSelectors(rule.Expr.Value)
if err != nil {
log.Fatal(err)
}
present, err := checkSelectorsPresence(rule.Alert.Value, selectors)
if err != nil {
log.Println(err)
erroredAlerts = append(erroredAlerts, rule.Alert.Value)
continue
}
if !present {
offendingAlerts = append(offendingAlerts, rule.Alert.Value)
}
}
}
}
func checkSelectorsPresence(alert string, selectors []string) (bool, error) {
for _, selector := range selectors {
hasResults, err := selectorHasResults(selector)
if err != nil {
return false, fmt.Errorf("Error getting results for '%s' (of alert %s): %v\n", selector, alert, err)
}
if !hasResults {
return false, nil
}
}
return true, nil
}
func selectorHasResults(selector string) (bool, error) {
now := time.Now().Unix()
log.Printf("Checking %s\n", selector)
requestUrl := fmt.Sprintf("%s/api/v1/query?query=%s&dedup=true&partial_response=true&time=%d",
prometheusHost,
url.QueryEscape(selector),
now,
)
response, err := http.Get(requestUrl)
if err != nil {
return false, err
}
if response.StatusCode != 200 {
return false, fmt.Errorf("Status code = %d", response.StatusCode)
}
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return false, fmt.Errorf("Error reading response body: %v", err)
}
var responseJson apiResponse
if err := json.Unmarshal(body, &responseJson); err != nil {
return false, fmt.Errorf("Failed response parsing, body was %s", body)
}
if status := responseJson.Status; status != "success" {
return false, fmt.Errorf("`status` != 'success', got %s", status)
}
if len(responseJson.Data.Result) == 0 {
return false, nil
}
return true, nil
}
func extractSelectors(exprStr string) ([]string, error) {
expr, err := parser.ParseExpr(exprStr)
if err != nil {
return nil, fmt.Errorf("Error parsing the expression: %v", err)
}
// Good programmers traverse the tree, great programmers grep for what they
// care for in the tree string representation -- Anonymous
tree := parser.Tree(expr)
selectorRegexp := regexp.MustCompile(`(?m)(?:VectorSelector|MatrixSelector) :: (.*)$`)
rangeRegexp := regexp.MustCompile(`\[.*\]$`)
selectors := []string{}
for _, match := range selectorRegexp.FindAllStringSubmatch(tree, -1) {
selector := rangeRegexp.ReplaceAllString(match[1], "")
selectors = append(selectors, selector)
}
return selectors, nil
}