-
Notifications
You must be signed in to change notification settings - Fork 0
/
alertmanager.go
363 lines (289 loc) · 7.58 KB
/
alertmanager.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
package manager
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"regexp"
"time"
"github.com/prometheus/common/model"
alertconfig "github.com/rancher/rancher/pkg/controllers/user/alert/config"
monitorutil "github.com/rancher/rancher/pkg/monitoring"
v1 "github.com/rancher/types/apis/core/v1"
"github.com/rancher/types/config"
"github.com/rancher/types/config/dialer"
"github.com/sirupsen/logrus"
)
type State string
const (
AlertStateUnprocessed State = "unprocessed"
AlertStateActive = "active"
AlertStateSuppressed = "suppressed"
)
type AlertStatus struct {
State State `json:"state"`
SilencedBy []string `json:"silencedBy"`
InhibitedBy []string `json:"inhibitedBy"`
}
type APIAlert struct {
*model.Alert
Status AlertStatus `json:"status"`
Receivers []string `json:"receivers"`
Fingerprint string `json:"fingerprint"`
}
type Matchers []*Matcher
type Matcher struct {
Name string `json:"name"`
Value string `json:"value"`
IsRegex bool `json:"isRegex"`
regex *regexp.Regexp
}
type Silence struct {
ID string `json:"id"`
Matchers Matchers `json:"matchers"`
StartsAt time.Time `json:"startsAt"`
EndsAt time.Time `json:"endsAt"`
UpdatedAt time.Time `json:"updatedAt"`
CreatedBy string `json:"createdBy"`
Comment string `json:"comment,omitempty"`
now func() time.Time
Status SilenceStatus `json:"status"`
}
type SilenceStatus struct {
State SilenceState `json:"state"`
}
type SilenceState string
const (
SilenceStateExpired SilenceState = "expired"
SilenceStateActive SilenceState = "active"
SilenceStatePending SilenceState = "pending"
)
type AlertManager struct {
svcLister v1.ServiceLister
dialer dialer.Factory
clusterName string
client *http.Client
IsDeploy bool
}
func NewAlertManager(cluster *config.UserContext) *AlertManager {
dial, err := cluster.Management.Dialer.ClusterDialer(cluster.ClusterName)
if err != nil {
logrus.Warnf("Failed to get cluster dialer: %v", err)
}
client := &http.Client{
Transport: &http.Transport{
Dial: dial,
},
Timeout: 15 * time.Second,
}
return &AlertManager{
svcLister: cluster.Core.Services("").Controller().Lister(),
client: client,
clusterName: cluster.ClusterName,
}
}
func (m *AlertManager) GetAlertManagerEndpoint() (string, error) {
name, namespace, port := monitorutil.ClusterAlertManagerEndpoint()
svc, err := m.svcLister.Get(namespace, name)
if err != nil {
return "", fmt.Errorf("Failed to get service for alertmanager, %v", err)
}
url := "http://" + svc.Name + "." + svc.Namespace + ".svc.cluster.local:" + port
return url, nil
}
func GetAlertManagerDefaultConfig() *alertconfig.Config {
config := alertconfig.Config{}
resolveTimeout, _ := model.ParseDuration("5m")
config.Global = &alertconfig.GlobalConfig{
SlackAPIURL: "https://api.slack.com",
ResolveTimeout: resolveTimeout,
SMTPRequireTLS: false,
}
slackConfigs := []*alertconfig.SlackConfig{}
initSlackConfig := &alertconfig.SlackConfig{
Channel: "#alert",
}
slackConfigs = append(slackConfigs, initSlackConfig)
receivers := []*alertconfig.Receiver{}
initReceiver := &alertconfig.Receiver{
Name: "rancherlabs",
SlackConfigs: slackConfigs,
}
receivers = append(receivers, initReceiver)
config.Receivers = receivers
groupWait, _ := model.ParseDuration("1m")
groupInterval, _ := model.ParseDuration("10s")
repeatInterval, _ := model.ParseDuration("1h")
config.Route = &alertconfig.Route{
Receiver: "rancherlabs",
GroupWait: &groupWait,
GroupInterval: &groupInterval,
RepeatInterval: &repeatInterval,
}
config.Templates = []string{"/etc/alertmanager/config/notification.tmpl"}
return &config
}
func (m *AlertManager) GetAlertList() ([]*APIAlert, error) {
url, err := m.GetAlertManagerEndpoint()
if err != nil {
return nil, err
}
res := struct {
Data []*APIAlert `json:"data"`
Status string `json:"status"`
}{}
req, err := http.NewRequest(http.MethodGet, url+"/api/v1/alerts", nil)
if err != nil {
return nil, err
}
resp, err := m.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
requestBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err := json.Unmarshal(requestBytes, &res); err != nil {
return nil, err
}
return res.Data, nil
}
func (m *AlertManager) GetState(matcherName, matcherValue string, apiAlerts []*APIAlert) string {
for _, a := range apiAlerts {
if string(a.Labels[model.LabelName(matcherName)]) == matcherValue {
if a.Status.State == "suppressed" {
return "muted"
}
return "alerting"
}
}
return "active"
}
func (m *AlertManager) AddSilenceRule(matcherName, matcherValue string) error {
url, err := m.GetAlertManagerEndpoint()
if err != nil {
return err
}
matchers := []*model.Matcher{}
m1 := &model.Matcher{
Name: model.LabelName(matcherName),
Value: matcherValue,
IsRegex: false,
}
matchers = append(matchers, m1)
now := time.Now()
endsAt := now.AddDate(100, 0, 0)
silence := model.Silence{
Matchers: matchers,
StartsAt: now,
EndsAt: endsAt,
CreatedAt: now,
CreatedBy: "rancherlabs",
Comment: "silence",
}
silenceData, err := json.Marshal(silence)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, url+"/api/v1/silences", bytes.NewBuffer(silenceData))
if err != nil {
return err
}
resp, err := m.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
return nil
}
func (m *AlertManager) RemoveSilenceRule(matcherName, matcherValue string) error {
url, err := m.GetAlertManagerEndpoint()
if err != nil {
return err
}
res := struct {
Data []*Silence `json:"data"`
Status string `json:"status"`
}{}
req, err := http.NewRequest(http.MethodGet, url+"/api/v1/silences", nil)
if err != nil {
return err
}
q := req.URL.Query()
q.Add("filter", fmt.Sprintf("{%s=%s}", matcherName, matcherValue))
req.URL.RawQuery = q.Encode()
resp, err := m.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
requestBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if err := json.Unmarshal(requestBytes, &res); err != nil {
return err
}
if res.Status != "success" {
return fmt.Errorf("Failed to get silence rules for alert")
}
for _, s := range res.Data {
if s.Status.State == SilenceStateActive {
delReq, err := http.NewRequest(http.MethodDelete, url+"/api/v1/silence/"+s.ID, nil)
if err != nil {
return err
}
delResp, err := m.client.Do(delReq)
if err != nil {
return err
}
defer delResp.Body.Close()
_, err = ioutil.ReadAll(delResp.Body)
if err != nil {
return err
}
}
}
return nil
}
func (m *AlertManager) SendAlert(labels map[string]string) error {
url, err := m.GetAlertManagerEndpoint()
if err != nil {
return err
}
alertList := model.Alerts{}
a := &model.Alert{}
a.Labels = map[model.LabelName]model.LabelValue{}
for k, v := range labels {
a.Labels[model.LabelName(k)] = model.LabelValue(v)
}
alertList = append(alertList, a)
alertData, err := json.Marshal(alertList)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, url+"/api/v1/alerts", bytes.NewBuffer(alertData))
if err != nil {
return err
}
resp, err := m.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("alertmanager response is %d, body: %s", resp.StatusCode, string(body))
}
return nil
}