forked from sensu/sensu-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
event_store.go
315 lines (259 loc) · 7.92 KB
/
event_store.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
package etcd
import (
"context"
"errors"
"fmt"
"path"
"strings"
"time"
"github.com/coreos/etcd/clientv3"
"github.com/gogo/protobuf/proto"
"github.com/sensu/sensu-go/backend/store"
corev2 "github.com/sensu/sensu-go/api/core/v2"
)
const (
eventsPathPrefix = "events"
)
var (
eventKeyBuilder = store.NewKeyBuilder(eventsPathPrefix)
)
func getEventPath(event *corev2.Event) string {
return path.Join(
EtcdRoot,
eventsPathPrefix,
event.Entity.Namespace,
event.Entity.Name,
event.Check.Name,
)
}
func getEventWithCheckPath(ctx context.Context, entity, check string) (string, error) {
namespace := corev2.ContextNamespace(ctx)
if namespace == "" {
return "", errors.New("namespace missing from context")
}
return path.Join(EtcdRoot, eventsPathPrefix, namespace, entity, check), nil
}
// GetEventsPath gets the path of the event store.
func GetEventsPath(ctx context.Context, entity string) string {
return eventKeyBuilder.WithContext(ctx).Build(entity)
}
// DeleteEventByEntityCheck deletes an event by entity name and check name.
func (s *Store) DeleteEventByEntityCheck(ctx context.Context, entityName, checkName string) error {
if entityName == "" || checkName == "" {
return errors.New("must specify entity and check name")
}
path, err := getEventWithCheckPath(ctx, entityName, checkName)
if err != nil {
return err
}
_, err = s.client.Delete(ctx, path)
return err
}
// GetEvents returns the events for an (optional) namespace. If namespace is the
// empty string, GetEvents returns all events for all namespaces.
func (s *Store) GetEvents(ctx context.Context, pred *store.SelectionPredicate) ([]*corev2.Event, error) {
opts := []clientv3.OpOption{
clientv3.WithLimit(pred.Limit),
}
keyPrefix := GetEventsPath(ctx, "")
rangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)
opts = append(opts, clientv3.WithRange(rangeEnd))
key := keyPrefix
if pred.Continue != "" {
key = path.Join(keyPrefix, pred.Continue)
} else {
if !strings.HasSuffix(key, "/") {
key += "/"
}
}
resp, err := s.client.Get(ctx, key, opts...)
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return []*corev2.Event{}, nil
}
events := []*corev2.Event{}
for _, kv := range resp.Kvs {
event := &corev2.Event{}
if err := unmarshal(kv.Value, event); err != nil {
return nil, err
}
if event.Labels == nil {
event.Labels = make(map[string]string)
}
if event.Annotations == nil {
event.Annotations = make(map[string]string)
}
events = append(events, event)
}
if pred.Limit != 0 && resp.Count > pred.Limit {
pred.Continue = ComputeContinueToken(ctx, events[len(events)-1])
} else {
pred.Continue = ""
}
return events, nil
}
// GetEventsByEntity gets all events matching a given entity name.
func (s *Store) GetEventsByEntity(ctx context.Context, entityName string, pred *store.SelectionPredicate) ([]*corev2.Event, error) {
if entityName == "" {
return nil, errors.New("must specify entity name")
}
opts := []clientv3.OpOption{
clientv3.WithLimit(pred.Limit),
}
keyPrefix := GetEventsPath(ctx, entityName)
rangeEnd := clientv3.GetPrefixRangeEnd(keyPrefix)
opts = append(opts, clientv3.WithRange(rangeEnd))
resp, err := s.client.Get(ctx, path.Join(keyPrefix, pred.Continue), opts...)
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, nil
}
events := []*corev2.Event{}
for _, kv := range resp.Kvs {
event := &corev2.Event{}
if err := unmarshal(kv.Value, event); err != nil {
return nil, err
}
if event.Labels == nil {
event.Labels = make(map[string]string)
}
if event.Annotations == nil {
event.Annotations = make(map[string]string)
}
events = append(events, event)
}
if pred.Limit != 0 && resp.Count > pred.Limit {
lastEvent := events[len(events)-1]
pred.Continue = lastEvent.Check.Name + "\x00"
} else {
pred.Continue = ""
}
return events, nil
}
// GetEventByEntityCheck gets an event by entity and check name.
func (s *Store) GetEventByEntityCheck(ctx context.Context, entityName, checkName string) (*corev2.Event, error) {
if entityName == "" || checkName == "" {
return nil, errors.New("must specify entity and check name")
}
path, err := getEventWithCheckPath(ctx, entityName, checkName)
if err != nil {
return nil, err
}
resp, err := s.client.Get(ctx, path, clientv3.WithPrefix())
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return nil, nil
}
eventBytes := resp.Kvs[0].Value
event := &corev2.Event{}
if err := unmarshal(eventBytes, event); err != nil {
return nil, err
}
if event.Labels == nil {
event.Labels = make(map[string]string)
}
if event.Annotations == nil {
event.Annotations = make(map[string]string)
}
return event, nil
}
// UpdateEvent updates an event.
func (s *Store) UpdateEvent(ctx context.Context, event *corev2.Event) (*corev2.Event, *corev2.Event, error) {
if event == nil || event.Check == nil {
return nil, nil, errors.New("event has no check")
}
if err := event.Check.Validate(); err != nil {
return nil, nil, err
}
if err := event.Entity.Validate(); err != nil {
return nil, nil, err
}
ctx = store.NamespaceContext(ctx, event.Entity.Namespace)
prevEvent, err := s.GetEventByEntityCheck(
ctx, event.Entity.Name, event.Check.Name,
)
if err != nil {
return nil, nil, err
}
// Maintain check history.
if prevEvent != nil {
if !prevEvent.HasCheck() {
return nil, nil, errors.New("invalid previous event")
}
event.Check.MergeWith(prevEvent.Check)
}
updateOccurrences(event.Check)
persistEvent := event
if event.HasMetrics() {
// Taking pains to not modify our input, set metrics to nil so they are
// not persisted.
newEvent := *event
persistEvent = &newEvent
persistEvent.Metrics = nil
}
// Truncate check output if the output is larger than MaxOutputSize
if size := event.Check.MaxOutputSize; size > 0 && int64(len(event.Check.Output)) > size {
// Taking pains to not modify our input, set a bound on the check
// output size.
newEvent := *persistEvent
persistEvent = &newEvent
check := *persistEvent.Check
check.Output = check.Output[:size]
persistEvent.Check = &check
}
if event.Timestamp == 0 {
// If the event is being created for the first time, it may not include
// a timestamp. Use the current time.
event.Timestamp = time.Now().Unix()
}
// update the history
// marshal the new event and store it.
eventBytes, err := proto.Marshal(persistEvent)
if err != nil {
return nil, nil, err
}
cmp := namespaceExistsForResource(event.Entity)
req := clientv3.OpPut(getEventPath(event), string(eventBytes))
res, err := s.client.Txn(ctx).If(cmp).Then(req).Commit()
if err != nil {
return nil, nil, err
}
if !res.Succeeded {
return nil, nil, fmt.Errorf(
"could not create the event %s/%s in namespace %s",
event.Entity.Name,
event.Check.Name,
event.Entity.Namespace,
)
}
return event, prevEvent, nil
}
func updateOccurrences(check *corev2.Check) {
if check == nil {
return
}
historyLen := len(check.History)
if historyLen > 1 && check.History[historyLen-1].Status == check.History[historyLen-2].Status {
// 1. Occurrences should always be incremented if the current Check status is the same as the previous status (this includes events with the Check status of OK)
check.Occurrences++
} else {
// 2. Occurrences should always reset to 1 if the current Check status is different than the previous status
check.Occurrences = 1
}
if historyLen > 1 && check.History[historyLen-1].Status != 0 && check.History[historyLen-2].Status == 0 {
// 3. OccurrencesWatermark only resets on the a first non OK Check status (it does not get reset going between warning, critical, unknown)
check.OccurrencesWatermark = 1
} else if check.Occurrences <= check.OccurrencesWatermark {
// 4. OccurrencesWatermark should remain the same when occurrences is less than or equal to the watermark
return
} else {
// 5. OccurrencesWatermark should be incremented if conditions 3 and 4 have not been met.
check.OccurrencesWatermark++
}
}