forked from cortexproject/cortex
/
alertmanager.go
369 lines (325 loc) · 10.9 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
364
365
366
367
368
369
package alertmanager
import (
"context"
"fmt"
"net/http"
"net/url"
"path/filepath"
"sync"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/alertmanager/api"
"github.com/prometheus/alertmanager/cluster"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/dispatch"
"github.com/prometheus/alertmanager/inhibit"
"github.com/prometheus/alertmanager/nflog"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/notify/email"
"github.com/prometheus/alertmanager/notify/opsgenie"
"github.com/prometheus/alertmanager/notify/pagerduty"
"github.com/prometheus/alertmanager/notify/pushover"
"github.com/prometheus/alertmanager/notify/slack"
"github.com/prometheus/alertmanager/notify/victorops"
"github.com/prometheus/alertmanager/notify/webhook"
"github.com/prometheus/alertmanager/notify/wechat"
"github.com/prometheus/alertmanager/provider/mem"
"github.com/prometheus/alertmanager/silence"
"github.com/prometheus/alertmanager/template"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/alertmanager/ui"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/common/model"
"github.com/prometheus/common/route"
)
const notificationLogMaintenancePeriod = 15 * time.Minute
// Config configures an Alertmanager.
type Config struct {
UserID string
// Used to persist notification logs and silences on disk.
DataDir string
Logger log.Logger
Peer *cluster.Peer
PeerTimeout time.Duration
Retention time.Duration
ExternalURL *url.URL
}
// An Alertmanager manages the alerts for one user.
type Alertmanager struct {
cfg *Config
api *api.API
logger log.Logger
nflog *nflog.Log
silences *silence.Silences
marker types.Marker
alerts *mem.Alerts
dispatcher *dispatch.Dispatcher
inhibitor *inhibit.Inhibitor
pipelineBuilder *notify.PipelineBuilder
stop chan struct{}
wg sync.WaitGroup
mux *http.ServeMux
registry *prometheus.Registry
// The Dispatcher is the only component we need to recreate when we call ApplyConfig.
// Given its metrics don't have any variable labels we need to re-use the same metrics.
dispatcherMetrics *dispatch.DispatcherMetrics
activeMtx sync.Mutex
active bool
}
var (
webReload = make(chan chan error)
)
func init() {
go func() {
// Since this is not a "normal" Alertmanager which reads its config
// from disk, we just accept and ignore web-based reload signals. Config
// updates are only applied externally via ApplyConfig().
for range webReload {
}
}()
}
// New creates a new Alertmanager.
func New(cfg *Config, reg *prometheus.Registry) (*Alertmanager, error) {
am := &Alertmanager{
cfg: cfg,
logger: log.With(cfg.Logger, "user", cfg.UserID),
stop: make(chan struct{}),
active: false,
activeMtx: sync.Mutex{},
}
am.registry = reg
am.wg.Add(1)
nflogID := fmt.Sprintf("nflog:%s", cfg.UserID)
var err error
am.nflog, err = nflog.New(
nflog.WithRetention(cfg.Retention),
nflog.WithSnapshot(filepath.Join(cfg.DataDir, nflogID)),
nflog.WithMaintenance(notificationLogMaintenancePeriod, am.stop, am.wg.Done),
nflog.WithMetrics(am.registry),
nflog.WithLogger(log.With(am.logger, "component", "nflog")),
)
if err != nil {
return nil, fmt.Errorf("failed to create notification log: %v", err)
}
if cfg.Peer != nil {
c := cfg.Peer.AddState("nfl:"+cfg.UserID, am.nflog, am.registry)
am.nflog.SetBroadcast(c.Broadcast)
}
am.marker = types.NewMarker(am.registry)
silencesID := fmt.Sprintf("silences:%s", cfg.UserID)
am.silences, err = silence.New(silence.Options{
SnapshotFile: filepath.Join(cfg.DataDir, silencesID),
Retention: cfg.Retention,
Logger: log.With(am.logger, "component", "silences"),
Metrics: am.registry,
})
if err != nil {
return nil, fmt.Errorf("failed to create silences: %v", err)
}
if cfg.Peer != nil {
c := cfg.Peer.AddState("sil:"+cfg.UserID, am.silences, am.registry)
am.silences.SetBroadcast(c.Broadcast)
}
am.pipelineBuilder = notify.NewPipelineBuilder(am.registry)
am.wg.Add(1)
go func() {
am.silences.Maintenance(15*time.Minute, filepath.Join(cfg.DataDir, silencesID), am.stop)
am.wg.Done()
}()
am.alerts, err = mem.NewAlerts(context.Background(), am.marker, 30*time.Minute, am.logger)
if err != nil {
return nil, fmt.Errorf("failed to create alerts: %v", err)
}
am.api, err = api.New(api.Options{
Alerts: am.alerts,
Silences: am.silences,
StatusFunc: am.marker.Status,
Peer: cfg.Peer,
Registry: am.registry,
Logger: log.With(am.logger, "component", "api"),
GroupFunc: func(f1 func(*dispatch.Route) bool, f2 func(*types.Alert, time.Time) bool) (dispatch.AlertGroups, map[model.Fingerprint][]string) {
return am.dispatcher.Groups(f1, f2)
},
})
if err != nil {
return nil, fmt.Errorf("failed to create api: %v", err)
}
router := route.New().WithPrefix(am.cfg.ExternalURL.Path)
ui.Register(router, webReload, log.With(am.logger, "component", "ui"))
am.mux = am.api.Register(router, am.cfg.ExternalURL.Path)
am.dispatcherMetrics = dispatch.NewDispatcherMetrics(am.registry)
return am, nil
}
// clusterWait returns a function that inspects the current peer state and returns
// a duration of one base timeout for each peer with a higher ID than ourselves.
func clusterWait(p *cluster.Peer, timeout time.Duration) func() time.Duration {
return func() time.Duration {
return time.Duration(p.Position()) * timeout
}
}
// ApplyConfig applies a new configuration to an Alertmanager.
func (am *Alertmanager) ApplyConfig(userID string, conf *config.Config) error {
templateFiles := make([]string, len(conf.Templates))
if len(conf.Templates) > 0 {
for i, t := range conf.Templates {
templateFiles[i] = filepath.Join(am.cfg.DataDir, "templates", userID, t)
}
}
tmpl, err := template.FromGlobs(templateFiles...)
if err != nil {
return err
}
tmpl.ExternalURL = am.cfg.ExternalURL
am.api.Update(conf, func(_ model.LabelSet) {})
// Ensure inhibitor is set before being called
if am.inhibitor != nil {
am.inhibitor.Stop()
}
// Ensure dispatcher is set before being called
if am.dispatcher != nil {
am.dispatcher.Stop()
}
am.inhibitor = inhibit.NewInhibitor(am.alerts, conf.InhibitRules, am.marker, log.With(am.logger, "component", "inhibitor"))
waitFunc := clusterWait(am.cfg.Peer, am.cfg.PeerTimeout)
timeoutFunc := func(d time.Duration) time.Duration {
if d < notify.MinTimeout {
d = notify.MinTimeout
}
return d + waitFunc()
}
integrationsMap, err := buildIntegrationsMap(conf.Receivers, tmpl, am.logger)
if err != nil {
return nil
}
pipeline := am.pipelineBuilder.New(
integrationsMap,
waitFunc,
am.inhibitor,
silence.NewSilencer(am.silences, am.marker, am.logger),
am.nflog,
am.cfg.Peer,
)
am.dispatcher = dispatch.NewDispatcher(
am.alerts,
dispatch.NewRoute(conf.Route, nil),
pipeline,
am.marker,
timeoutFunc,
log.With(am.logger, "component", "dispatcher"),
am.dispatcherMetrics,
)
go am.dispatcher.Run()
go am.inhibitor.Run()
// Ensure the alertmanager is set to active
am.activeMtx.Lock()
am.active = true
am.activeMtx.Unlock()
return nil
}
// IsActive returns if the alertmanager is currently running
// or is paused
func (am *Alertmanager) IsActive() bool {
am.activeMtx.Lock()
defer am.activeMtx.Unlock()
return am.active
}
// Pause running jobs in the alertmanager that are able to be restarted and sets
// to inactives
func (am *Alertmanager) Pause() {
// Set to inactive
am.activeMtx.Lock()
am.active = false
am.activeMtx.Unlock()
// Stop the inhibitor and dispatcher which will be recreated when
// a new config is applied
if am.inhibitor != nil {
am.inhibitor.Stop()
am.inhibitor = nil
}
if am.dispatcher != nil {
am.dispatcher.Stop()
am.dispatcher = nil
}
// Remove all of the active silences from the alertmanager
silences, _, err := am.silences.Query()
if err != nil {
level.Warn(am.logger).Log("msg", "unable to retrieve silences for removal", "err", err)
}
for _, si := range silences {
err = am.silences.Expire(si.Id)
if err != nil {
level.Warn(am.logger).Log("msg", "unable to remove silence", "err", err, "silence", si.Id)
}
}
}
// Stop stops the Alertmanager.
func (am *Alertmanager) Stop() {
if am.inhibitor != nil {
am.inhibitor.Stop()
}
if am.dispatcher != nil {
am.dispatcher.Stop()
}
am.alerts.Close()
close(am.stop)
am.wg.Wait()
}
// buildIntegrationsMap builds a map of name to the list of integration notifiers off of a
// list of receiver config.
func buildIntegrationsMap(nc []*config.Receiver, tmpl *template.Template, logger log.Logger) (map[string][]notify.Integration, error) {
integrationsMap := make(map[string][]notify.Integration, len(nc))
for _, rcv := range nc {
integrations, err := buildReceiverIntegrations(rcv, tmpl, logger)
if err != nil {
return nil, err
}
integrationsMap[rcv.Name] = integrations
}
return integrationsMap, nil
}
// buildReceiverIntegrations builds a list of integration notifiers off of a
// receiver config.
// Taken from https://github.com/prometheus/alertmanager/blob/94d875f1227b29abece661db1a68c001122d1da5/cmd/alertmanager/main.go#L112-L159.
func buildReceiverIntegrations(nc *config.Receiver, tmpl *template.Template, logger log.Logger) ([]notify.Integration, error) {
var (
errs types.MultiError
integrations []notify.Integration
add = func(name string, i int, rs notify.ResolvedSender, f func(l log.Logger) (notify.Notifier, error)) {
n, err := f(log.With(logger, "integration", name))
if err != nil {
errs.Add(err)
return
}
integrations = append(integrations, notify.NewIntegration(n, rs, name, i))
}
)
for i, c := range nc.WebhookConfigs {
add("webhook", i, c, func(l log.Logger) (notify.Notifier, error) { return webhook.New(c, tmpl, l) })
}
for i, c := range nc.EmailConfigs {
add("email", i, c, func(l log.Logger) (notify.Notifier, error) { return email.New(c, tmpl, l), nil })
}
for i, c := range nc.PagerdutyConfigs {
add("pagerduty", i, c, func(l log.Logger) (notify.Notifier, error) { return pagerduty.New(c, tmpl, l) })
}
for i, c := range nc.OpsGenieConfigs {
add("opsgenie", i, c, func(l log.Logger) (notify.Notifier, error) { return opsgenie.New(c, tmpl, l) })
}
for i, c := range nc.WechatConfigs {
add("wechat", i, c, func(l log.Logger) (notify.Notifier, error) { return wechat.New(c, tmpl, l) })
}
for i, c := range nc.SlackConfigs {
add("slack", i, c, func(l log.Logger) (notify.Notifier, error) { return slack.New(c, tmpl, l) })
}
for i, c := range nc.VictorOpsConfigs {
add("victorops", i, c, func(l log.Logger) (notify.Notifier, error) { return victorops.New(c, tmpl, l) })
}
for i, c := range nc.PushoverConfigs {
add("pushover", i, c, func(l log.Logger) (notify.Notifier, error) { return pushover.New(c, tmpl, l) })
}
if errs.Len() > 0 {
return nil, &errs
}
return integrations, nil
}