forked from prometheus/alertmanager
/
boltmem.go
449 lines (375 loc) · 9.4 KB
/
boltmem.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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// Copyright 2016 Prometheus Team
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/lic:wenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package boltmem
import (
"encoding/binary"
"encoding/json"
"path/filepath"
"sync"
"time"
"github.com/boltdb/bolt"
"github.com/prometheus/alertmanager/provider"
"github.com/prometheus/alertmanager/types"
"github.com/prometheus/common/log"
"github.com/prometheus/common/model"
)
var (
bktNotificationInfo = []byte("notification_info")
bktSilences = []byte("silences")
// bktAlerts = []byte("alerts")
)
// Alerts gives access to a set of alerts. All methods are goroutine-safe.
type Alerts struct {
mtx sync.RWMutex
alerts map[model.Fingerprint]*types.Alert
stopGC chan struct{}
listeners map[int]chan *types.Alert
next int
}
// NewAlerts returns a new alert provider.
func NewAlerts(path string) (*Alerts, error) {
a := &Alerts{
alerts: map[model.Fingerprint]*types.Alert{},
stopGC: make(chan struct{}),
listeners: map[int]chan *types.Alert{},
next: 0,
}
go a.runGC()
return a, nil
}
func (a *Alerts) runGC() {
for {
select {
case <-a.stopGC:
return
case <-time.After(30 * time.Minute):
}
a.mtx.Lock()
for fp, alert := range a.alerts {
// As we don't persist alerts, we no longer consider them after
// they are resolved. Alerts waiting for resolved notifications are
// held in memory in aggregation groups redundantly.
if alert.EndsAt.Before(time.Now()) {
delete(a.alerts, fp)
}
}
a.mtx.Unlock()
}
}
// Close the alert provider.
func (a *Alerts) Close() error {
close(a.stopGC)
return nil
}
// Subscribe returns an iterator over active alerts that have not been
// resolved and successfully notified about.
// They are not guaranteed to be in chronological order.
func (a *Alerts) Subscribe() provider.AlertIterator {
var (
ch = make(chan *types.Alert, 200)
done = make(chan struct{})
)
alerts, err := a.getPending()
a.mtx.Lock()
i := a.next
a.next++
a.listeners[i] = ch
a.mtx.Unlock()
go func() {
defer func() {
a.mtx.Lock()
delete(a.listeners, i)
close(ch)
a.mtx.Unlock()
}()
for _, a := range alerts {
select {
case ch <- a:
case <-done:
return
}
}
<-done
}()
return provider.NewAlertIterator(ch, done, err)
}
// GetPending returns an iterator over all alerts that have
// pending notifications.
func (a *Alerts) GetPending() provider.AlertIterator {
var (
ch = make(chan *types.Alert, 200)
done = make(chan struct{})
)
alerts, err := a.getPending()
go func() {
defer close(ch)
for _, a := range alerts {
select {
case ch <- a:
case <-done:
return
}
}
}()
return provider.NewAlertIterator(ch, done, err)
}
func (a *Alerts) getPending() ([]*types.Alert, error) {
a.mtx.RLock()
defer a.mtx.RUnlock()
res := make([]*types.Alert, 0, len(a.alerts))
for _, alert := range a.alerts {
res = append(res, alert)
}
return res, nil
}
// Get returns the alert for a given fingerprint.
func (a *Alerts) Get(fp model.Fingerprint) (*types.Alert, error) {
a.mtx.RLock()
defer a.mtx.RUnlock()
alert, ok := a.alerts[fp]
if !ok {
return nil, provider.ErrNotFound
}
return alert, nil
}
// Put adds the given alert to the set.
func (a *Alerts) Put(alerts ...*types.Alert) error {
a.mtx.Lock()
defer a.mtx.Unlock()
for _, alert := range alerts {
fp := alert.Fingerprint()
if old, ok := a.alerts[fp]; ok {
// Merge alerts if there is an overlap in activity range.
if (alert.EndsAt.After(old.StartsAt) && alert.EndsAt.Before(old.EndsAt)) ||
(alert.StartsAt.After(old.StartsAt) && alert.StartsAt.Before(old.EndsAt)) {
alert = old.Merge(alert)
}
}
a.alerts[fp] = alert
for _, ch := range a.listeners {
ch <- alert
}
}
return nil
}
// Silences gives access to silences. All methods are goroutine-safe.
type Silences struct {
db *bolt.DB
mk types.Marker
mtx sync.RWMutex
cache map[uint64]*types.Silence
}
// NewSilences creates a new Silences provider.
func NewSilences(path string, mk types.Marker) (*Silences, error) {
db, err := bolt.Open(filepath.Join(path, "silences.db"), 0666, nil)
if err != nil {
return nil, err
}
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(bktSilences)
return err
})
if err != nil {
return nil, err
}
s := &Silences{
db: db,
mk: mk,
cache: map[uint64]*types.Silence{},
}
return s, s.initCache()
}
// Close the silences provider.
func (s *Silences) Close() error {
return s.db.Close()
}
// The Silences provider must implement the Muter interface
// for all its silences. The data provider may have access to an
// optimized view of the data to perform this evaluation.
func (s *Silences) Mutes(lset model.LabelSet) bool {
sils, err := s.All()
if err != nil {
log.Errorf("retrieving silences failed: %s", err)
// In doubt, do not silence anything.
return false
}
for _, sil := range sils {
if sil.Mutes(lset) {
s.mk.SetSilenced(lset.Fingerprint(), sil.ID)
return true
}
}
s.mk.SetSilenced(lset.Fingerprint())
return false
}
// All returns all existing silences.
func (s *Silences) All() ([]*types.Silence, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
res := make([]*types.Silence, 0, len(s.cache))
for _, s := range s.cache {
res = append(res, s)
}
return res, nil
}
func (s *Silences) initCache() error {
s.mtx.Lock()
defer s.mtx.Unlock()
err := s.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bktSilences)
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
var ms model.Silence
if err := json.Unmarshal(v, &ms); err != nil {
return err
}
// The ID is duplicated in the value and always equal
// to the stored key.
s.cache[ms.ID] = types.NewSilence(&ms)
}
return nil
})
return err
}
// Set a new silence.
func (s *Silences) Set(sil *types.Silence) (uint64, error) {
s.mtx.Lock()
defer s.mtx.Unlock()
var (
uid uint64
err error
)
err = s.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bktSilences)
// Silences are immutable and we always create a new one.
uid, err = b.NextSequence()
if err != nil {
return err
}
sil.ID = uid
k := make([]byte, 8)
binary.BigEndian.PutUint64(k, uid)
msb, err := json.Marshal(sil.Silence)
if err != nil {
return err
}
return b.Put(k, msb)
})
if err != nil {
return 0, err
}
s.cache[uid] = sil
return uid, nil
}
// Del removes a silence.
func (s *Silences) Del(uid uint64) error {
s.mtx.Lock()
defer s.mtx.Unlock()
err := s.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bktSilences)
k := make([]byte, 8)
binary.BigEndian.PutUint64(k, uid)
return b.Delete(k)
})
if err != nil {
return err
}
delete(s.cache, uid)
return nil
}
// Get a silence associated with a fingerprint.
func (s *Silences) Get(uid uint64) (*types.Silence, error) {
s.mtx.RLock()
defer s.mtx.RUnlock()
sil, ok := s.cache[uid]
if !ok {
return nil, provider.ErrNotFound
}
return sil, nil
}
// NotificationInfo provides information about pending and successful
// notifications. All methods are goroutine-safe.
type NotificationInfo struct {
db *bolt.DB
}
// NewNotification creates a new notification info provider.
func NewNotificationInfo(path string) (*NotificationInfo, error) {
db, err := bolt.Open(filepath.Join(path, "notification_info.db"), 0666, nil)
if err != nil {
return nil, err
}
err = db.Update(func(tx *bolt.Tx) error {
_, err := tx.CreateBucketIfNotExists(bktNotificationInfo)
return err
})
return &NotificationInfo{db: db}, err
}
// Close the notification information provider.
func (n *NotificationInfo) Close() error {
return n.db.Close()
}
// Get notification information for alerts and the given receiver.
func (n *NotificationInfo) Get(recv string, fps ...model.Fingerprint) ([]*types.NotifyInfo, error) {
var res []*types.NotifyInfo
err := n.db.View(func(tx *bolt.Tx) error {
b := tx.Bucket(bktNotificationInfo)
for _, fp := range fps {
k := make([]byte, 8+len([]byte(recv)))
binary.BigEndian.PutUint64(k, uint64(fp))
copy(k[8:], []byte(recv))
v := b.Get(k)
if v == nil {
res = append(res, nil)
continue
}
ni := &types.NotifyInfo{
Alert: fp,
Receiver: recv,
Resolved: v[0] == 1,
}
if err := ni.Timestamp.UnmarshalBinary(v[1:]); err != nil {
return err
}
res = append(res, ni)
}
return nil
})
return res, err
}
// Set several notifies at once. All or none must succeed.
func (n *NotificationInfo) Set(ns ...*types.NotifyInfo) error {
err := n.db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket(bktNotificationInfo)
for _, n := range ns {
k := make([]byte, 8+len([]byte(n.Receiver)))
binary.BigEndian.PutUint64(k, uint64(n.Alert))
copy(k[8:], []byte(n.Receiver))
var v []byte
if n.Resolved {
v = []byte{1}
} else {
v = []byte{0}
}
tsb, err := n.Timestamp.MarshalBinary()
if err != nil {
return err
}
v = append(v, tsb...)
if err := b.Put(k, v); err != nil {
return err
}
}
return nil
})
return err
}