forked from moira-alert/notifier
/
db.go
291 lines (245 loc) · 8.76 KB
/
db.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
package notifier
import (
"encoding/json"
"fmt"
"time"
"github.com/garyburd/redigo/redis"
)
//DbConnector contains redis pool
type DbConnector struct {
Pool *redis.Pool
}
type database interface {
FetchEvent() (*EventData, error)
GetTrigger(id string) (TriggerData, error)
GetTriggerTags(id string) ([]string, error)
GetTagsSubscriptions(tags []string) ([]SubscriptionData, error)
GetSubscription(id string) (SubscriptionData, error)
GetContact(id string) (ContactData, error)
AddNotification(notification *ScheduledNotification, next time.Time) error
GetTriggerThrottlingTimestamps(id string) (time.Time, time.Time)
GetTriggerNotificationsCount(id string, from int64) int64
SetTriggerThrottlingTimestamp(id string, next time.Time) error
GetNotifications(to int64) ([]*ScheduledNotification, error)
}
// ConvertNotifications extracts ScheduledNotification from redis response
func ConvertNotifications(redisResponse interface{}) ([]*ScheduledNotification, error) {
notificationStrings, err := redis.Strings(redisResponse, nil)
if err != nil {
return nil, err
}
notifications := make([]*ScheduledNotification, 0, len(notificationStrings))
for _, notificationString := range notificationStrings {
notification := &ScheduledNotification{}
if err := json.Unmarshal([]byte(notificationString), notification); err != nil {
log.Warning("Failed to parse scheduled json notification %s: %s", notificationString, err.Error())
continue
}
notifications = append(notifications, notification)
}
return notifications, nil
}
// GetNotifications fetch notifications by given timestamp
func (connector *DbConnector) GetNotifications(to int64) ([]*ScheduledNotification, error) {
c := connector.Pool.Get()
defer c.Close()
c.Send("MULTI")
c.Send("ZRANGEBYSCORE", "moira-notifier-notifications", "-inf", to)
c.Send("ZREMRANGEBYSCORE", "moira-notifier-notifications", "-inf", to)
redisRawResponse, err := c.Do("EXEC")
if err != nil {
return nil, err
}
redisResponse, err := redis.Values(redisRawResponse, nil)
if err != nil {
return nil, err
}
return ConvertNotifications(redisResponse[0])
}
// GetTriggerThrottlingTimestamps get throttling or scheduled notifications delay for given triggerID
func (connector *DbConnector) GetTriggerThrottlingTimestamps(triggerID string) (time.Time, time.Time) {
c := connector.Pool.Get()
defer c.Close()
next, _ := redis.Int64(c.Do("GET", fmt.Sprintf("moira-notifier-next:%s", triggerID)))
beginning, _ := redis.Int64(c.Do("GET", fmt.Sprintf("moira-notifier-throttling-beginning:%s", triggerID)))
return time.Unix(next, 0), time.Unix(beginning, 0)
}
// SetTriggerThrottlingTimestamp store throttling or scheduled notifications delay for given triggerID
func (connector *DbConnector) SetTriggerThrottlingTimestamp(triggerID string, next time.Time) error {
c := connector.Pool.Get()
defer c.Close()
if _, err := c.Do("SET", fmt.Sprintf("moira-notifier-next:%s", triggerID), next.Unix()); err != nil {
return err
}
return nil
}
// GetTriggerNotificationsCount retuns planned notifications count from given timestamp
func (connector *DbConnector) GetTriggerNotificationsCount(triggerID string, from int64) int64 {
c := connector.Pool.Get()
defer c.Close()
eventsKey := fmt.Sprintf("moira-trigger-events:%s", triggerID)
count, _ := redis.Int64(c.Do("ZCOUNT", eventsKey, from, "+inf"))
return count
}
// GetTagsSubscriptions returns all subscriptions for given tags list
func (connector *DbConnector) GetTagsSubscriptions(tags []string) ([]SubscriptionData, error) {
c := connector.Pool.Get()
defer c.Close()
log.Debug("Getting tags %v subscriptions", tags)
tagKeys := make([]interface{}, 0, len(tags))
for _, tag := range tags {
tagKeys = append(tagKeys, fmt.Sprintf("moira-tag-subscriptions:%s", tag))
}
values, err := redis.Values(c.Do("SUNION", tagKeys...))
if err != nil {
return nil, fmt.Errorf("Failed to retrieve subscriptions for tags %v: %s", tags, err.Error())
}
var subscriptions []string
if err := redis.ScanSlice(values, &subscriptions); err != nil {
return nil, fmt.Errorf("Failed to retrieve subscriptions for tags %v: %s", tags, err.Error())
}
if len(subscriptions) == 0 {
log.Debug("No subscriptions found for tag set %v", tags)
return make([]SubscriptionData, 0, 0), nil
}
var subscriptionsData []SubscriptionData
for _, id := range subscriptions {
sub, err := db.GetSubscription(id)
if err != nil {
continue
}
subscriptionsData = append(subscriptionsData, sub)
}
return subscriptionsData, nil
}
// GetContact returns contact data by given id
func (connector *DbConnector) GetContact(id string) (ContactData, error) {
c := connector.Pool.Get()
defer c.Close()
var contact ContactData
contactString, err := redis.Bytes(c.Do("GET", fmt.Sprintf("moira-contact:%s", id)))
if err != nil {
return contact, fmt.Errorf("Failed to get contact data for id %s: %s", id, err.Error())
}
if err := json.Unmarshal(contactString, &contact); err != nil {
return contact, fmt.Errorf("Failed to parse contact json %s: %s", contactString, err.Error())
}
contact.ID = id
return contact, nil
}
// GetSubscription returns subscription data by given id
func (connector *DbConnector) GetSubscription(id string) (SubscriptionData, error) {
c := connector.Pool.Get()
defer c.Close()
sub := SubscriptionData{
ThrottlingEnabled: true,
}
subscriptionString, err := redis.Bytes(c.Do("GET", fmt.Sprintf("moira-subscription:%s", id)))
if err != nil {
subsMalformed.Mark(1)
return sub, fmt.Errorf("Failed to get subscription data for id %s: %s", id, err.Error())
}
if err := json.Unmarshal(subscriptionString, &sub); err != nil {
subsMalformed.Mark(1)
return sub, fmt.Errorf("Failed to parse subscription json %s: %s", subscriptionString, err.Error())
}
sub.ID = id
return sub, nil
}
// GetTriggerTags returns trigger tags
func (connector *DbConnector) GetTriggerTags(triggerID string) ([]string, error) {
c := connector.Pool.Get()
defer c.Close()
var tags []string
values, err := redis.Values(c.Do("SMEMBERS", fmt.Sprintf("moira-trigger-tags:%s", triggerID)))
if err != nil {
return nil, fmt.Errorf("Failed to retrieve tags for trigger id %s: %s", triggerID, err.Error())
}
if err := redis.ScanSlice(values, &tags); err != nil {
return nil, fmt.Errorf("Failed to retrieve tags for trigger id %s: %s", triggerID, err.Error())
}
if len(tags) == 0 {
return nil, fmt.Errorf("No tags found for trigger id %s", triggerID)
}
return tags, nil
}
// GetTrigger returns trigger data
func (connector *DbConnector) GetTrigger(id string) (TriggerData, error) {
c := connector.Pool.Get()
defer c.Close()
var trigger TriggerData
triggerString, err := redis.Bytes(c.Do("GET", fmt.Sprintf("moira-trigger:%s", id)))
if err != nil {
return trigger, fmt.Errorf("Failed to get trigger data for id %s: %s", id, err.Error())
}
if err := json.Unmarshal(triggerString, &trigger); err != nil {
return trigger, fmt.Errorf("Failed to parse trigger json %s: %s", triggerString, err.Error())
}
return trigger, nil
}
// AddNotification store notification at given timestamp
func (connector *DbConnector) AddNotification(notification *ScheduledNotification, next time.Time) error {
notificationString, err := json.Marshal(notification)
if err != nil {
return err
}
c := connector.Pool.Get()
defer c.Close()
if _, err := c.Do("ZADD", "moira-notifier-notifications", next.Unix(), notificationString); err != nil {
return err
}
return nil
}
// FetchEvent waiting for event from Db
func (connector *DbConnector) FetchEvent() (*EventData, error) {
c := connector.Pool.Get()
defer c.Close()
var event EventData
rawRes, err := c.Do("BRPOP", "moira-trigger-events", 1)
if err != nil {
log.Warning("Failed to wait for event: %s", err.Error())
time.Sleep(time.Second * 5)
return nil, nil
}
if rawRes != nil {
var (
eventBytes []byte
key []byte
)
res, _ := redis.Values(rawRes, nil)
if _, err = redis.Scan(res, &key, &eventBytes); err != nil {
log.Warning("Failed to parse event: %s", err.Error())
return nil, err
}
if err := json.Unmarshal(eventBytes, &event); err != nil {
log.Error(fmt.Sprintf("Failed to parse event json %s: %s", eventBytes, err.Error()))
return nil, err
}
return &event, nil
}
return nil, nil
}
// InitRedisDatabase creates Redis pool based on config
func InitRedisDatabase() {
db = &DbConnector{
Pool: NewRedisPool(fmt.Sprintf("%s:%s", config.Get("redis", "host"), config.Get("redis", "port"))),
}
}
// NewRedisPool creates Redis pool
func NewRedisPool(redisURI string) *redis.Pool {
return &redis.Pool{
MaxIdle: 3,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", redisURI)
if err != nil {
return nil, err
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}