forked from influxdata/kapacitor
/
dao.go
346 lines (295 loc) · 9.46 KB
/
dao.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
package alert
//go:generate easyjson dao.go
import (
"encoding/json"
"fmt"
"path"
"regexp"
"time"
"github.com/influxdata/kapacitor/alert"
"github.com/influxdata/kapacitor/services/storage"
"github.com/mailru/easyjson/jlexer"
"github.com/pkg/errors"
)
var (
ErrHandlerSpecExists = errors.New("handler spec already exists")
ErrNoHandlerSpecExists = errors.New("no handler spec exists")
)
// Data access object for HandlerSpec data.
type HandlerSpecDAO interface {
// Retrieve a handler
Get(topic, id string) (HandlerSpec, error)
GetTx(tx storage.ReadOnlyTx, topic, id string) (HandlerSpec, error)
// Create a handler.
// ErrHandlerSpecExists is returned if a handler already exists with the same ID.
Create(h HandlerSpec) error
CreateTx(tx storage.Tx, h HandlerSpec) error
// Replace an existing handler.
// ErrNoHandlerSpecExists is returned if the handler does not exist.
Replace(h HandlerSpec) error
ReplaceTx(tx storage.Tx, h HandlerSpec) error
// Delete a handler.
// It is not an error to delete an non-existent handler.
Delete(topic, id string) error
DeleteTx(tx storage.Tx, topic, id string) error
// List handlers matching a pattern.
// The pattern is shell/glob matching see https://golang.org/pkg/path/#Match
// Offset and limit are pagination bounds. Offset is inclusive starting at index 0.
// More results may exist while the number of returned items is equal to limit.
List(topic, pattern string, offset, limit int) ([]HandlerSpec, error)
ListTx(tx storage.ReadOnlyTx, topic, pattern string, offset, limit int) ([]HandlerSpec, error)
Rebuild() error
}
//--------------------------------------------------------------------
// The following structures are stored in a database via gob encoding.
// Changes to the structures could break existing data.
//
// Many of these structures are exact copies of structures found elsewhere,
// this is intentional so that all structures stored in the database are
// defined here and nowhere else. So as to not accidentally change
// the gob serialization format in incompatible ways.
const (
handlerSpecVersion1 = 1
handlerSpecVersion2 = 2
)
// HandlerSpec provides all the necessary information to create a handler.
type HandlerSpec struct {
ID string `json:"id"`
Topic string `json:"topic"`
Kind string `json:"kind"`
Options map[string]interface{} `json:"options"`
Match string `json:"match"`
}
var validHandlerID = regexp.MustCompile(`^[-\._\p{L}0-9]+$`)
var validTopicID = regexp.MustCompile(`^[-:\._\p{L}0-9]+$`)
func (h HandlerSpec) Validate() error {
if !validTopicID.MatchString(h.Topic) {
return fmt.Errorf("handler topic must contain only letters, numbers, '-', '.' and '_'. %q", h.ID)
}
if !validHandlerID.MatchString(h.ID) {
return fmt.Errorf("handler ID must contain only letters, numbers, '-', '.' and '_'. %q", h.ID)
}
if h.Kind == "" {
return errors.New("handler Kind must not be empty")
}
return nil
}
func fullID(topic, handler string) string {
return path.Join(topic, handler)
}
func (h HandlerSpec) ObjectID() string {
return fullID(h.Topic, h.ID)
}
func (h HandlerSpec) MarshalBinary() ([]byte, error) {
if err := h.Validate(); err != nil {
return nil, errors.Wrap(err, "invalid spec")
}
return storage.VersionJSONEncode(handlerSpecVersion2, h)
}
func (h *HandlerSpec) UnmarshalBinary(data []byte) error {
return storage.VersionJSONDecode(data, func(version int, dec *json.Decoder) error {
switch version {
case handlerSpecVersion1:
return errors.New("version 1 is invalid cannot decode")
case handlerSpecVersion2:
return dec.Decode(h)
default:
return fmt.Errorf("unknown spec version %d: cannot decode", version)
}
})
}
// Key/Value store based implementation of the HandlerSpecDAO
type handlerSpecKV struct {
store *storage.IndexedStore
}
const (
handlerPrefix = "handlers"
)
func newHandlerSpecKV(store storage.Interface) (*handlerSpecKV, error) {
c := storage.DefaultIndexedStoreConfig(handlerPrefix, func() storage.BinaryObject {
return new(HandlerSpec)
})
istore, err := storage.NewIndexedStore(store, c)
if err != nil {
return nil, err
}
return &handlerSpecKV{
store: istore,
}, nil
}
func (kv *handlerSpecKV) error(err error) error {
if err == storage.ErrObjectExists {
return ErrHandlerSpecExists
} else if err == storage.ErrNoObjectExists {
return ErrNoHandlerSpecExists
}
return err
}
func (kv *handlerSpecKV) Get(topic, id string) (HandlerSpec, error) {
return kv.getHelper(kv.store.Get(fullID(topic, id)))
}
func (kv *handlerSpecKV) GetTx(tx storage.ReadOnlyTx, topic, id string) (HandlerSpec, error) {
return kv.getHelper(kv.store.GetTx(tx, fullID(topic, id)))
}
func (kv *handlerSpecKV) getHelper(o storage.BinaryObject, err error) (HandlerSpec, error) {
if err != nil {
return HandlerSpec{}, kv.error(err)
}
h, ok := o.(*HandlerSpec)
if !ok {
return HandlerSpec{}, storage.ImpossibleTypeErr(h, o)
}
return *h, nil
}
func (kv *handlerSpecKV) Create(h HandlerSpec) error {
return kv.store.Create(&h)
}
func (kv *handlerSpecKV) CreateTx(tx storage.Tx, h HandlerSpec) error {
return kv.store.CreateTx(tx, &h)
}
func (kv *handlerSpecKV) Replace(h HandlerSpec) error {
return kv.store.Replace(&h)
}
func (kv *handlerSpecKV) ReplaceTx(tx storage.Tx, h HandlerSpec) error {
return kv.store.ReplaceTx(tx, &h)
}
func (kv *handlerSpecKV) Delete(topic, id string) error {
return kv.store.Delete(fullID(topic, id))
}
func (kv *handlerSpecKV) DeleteTx(tx storage.Tx, topic, id string) error {
return kv.store.DeleteTx(tx, fullID(topic, id))
}
func (kv *handlerSpecKV) List(topic, pattern string, offset, limit int) ([]HandlerSpec, error) {
if pattern == "" {
pattern = "*"
}
return kv.listHelper(kv.store.List(storage.DefaultIDIndex, fullID(topic, pattern), offset, limit))
}
func (kv *handlerSpecKV) ListTx(tx storage.ReadOnlyTx, topic, pattern string, offset, limit int) ([]HandlerSpec, error) {
if pattern == "" {
pattern = "*"
}
return kv.listHelper(kv.store.ListTx(tx, storage.DefaultIDIndex, fullID(topic, pattern), offset, limit))
}
func (kv *handlerSpecKV) listHelper(objects []storage.BinaryObject, err error) ([]HandlerSpec, error) {
if err != nil {
return nil, err
}
specs := make([]HandlerSpec, len(objects))
for i, o := range objects {
h, ok := o.(*HandlerSpec)
if !ok {
return nil, storage.ImpossibleTypeErr(h, o)
}
specs[i] = *h
}
return specs, nil
}
func (kv *handlerSpecKV) Rebuild() error {
return kv.store.Rebuild()
}
var (
ErrNoTopicStateExists = errors.New("no topic state exists")
)
// Data access object for TopicState data.
type TopicStateDAO interface {
// Retrieve a handler
Get(id string) (TopicState, error)
// Put a topic state, replaces any existing state.
Put(h TopicState) error
// Delete a handler.
// It is not an error to delete an non-existent handler.
Delete(id string) error
// List handlers matching a pattern.
// The pattern is shell/glob matching see https://golang.org/pkg/path/#Match
// Offset and limit are pagination bounds. Offset is inclusive starting at index 0.
// More results may exist while the number of returned items is equal to limit.
List(pattern string, offset, limit int) ([]TopicState, error)
Rebuild() error
}
const topicStateVersion = 1
//easyjson:json
type TopicState struct {
Topic string `json:"topic"`
EventStates map[string]EventState `json:"event-states"`
}
//easyjson:json
type EventState struct {
Message string `json:"message"`
Details string `json:"details"`
Time time.Time `json:"time"`
Duration time.Duration `json:"duration"`
Level alert.Level `json:"level"`
}
func (t TopicState) ObjectID() string {
return t.Topic
}
func (t TopicState) MarshalBinary() ([]byte, error) {
return storage.VersionJSONEncode(topicStateVersion, t)
}
func (t *TopicState) UnmarshalBinary(data []byte) error {
return storage.VersionEasyJSONDecode(data, func(version int, dec *jlexer.Lexer) error {
t.UnmarshalEasyJSON(dec)
return dec.Error()
})
}
// Key/Value store based implementation of the TopicStateDAO
type topicStateKV struct {
store *storage.IndexedStore
}
func newTopicStateKV(store storage.Interface) (*topicStateKV, error) {
c := storage.DefaultIndexedStoreConfig("topics", func() storage.BinaryObject {
return new(TopicState)
})
istore, err := storage.NewIndexedStore(store, c)
if err != nil {
return nil, err
}
return &topicStateKV{
store: istore,
}, nil
}
func (kv *topicStateKV) error(err error) error {
if err == storage.ErrNoObjectExists {
return ErrNoTopicStateExists
}
return err
}
func (kv *topicStateKV) Get(id string) (TopicState, error) {
o, err := kv.store.Get(id)
if err != nil {
return TopicState{}, kv.error(err)
}
t, ok := o.(*TopicState)
if !ok {
return TopicState{}, storage.ImpossibleTypeErr(t, o)
}
return *t, nil
}
func (kv *topicStateKV) Put(t TopicState) error {
return kv.store.Put(&t)
}
func (kv *topicStateKV) Replace(t TopicState) error {
return kv.store.Replace(&t)
}
func (kv *topicStateKV) Delete(id string) error {
return kv.store.Delete(id)
}
func (kv *topicStateKV) List(pattern string, offset, limit int) ([]TopicState, error) {
objects, err := kv.store.List(storage.DefaultIDIndex, pattern, offset, limit)
if err != nil {
return nil, err
}
specs := make([]TopicState, len(objects))
for i, o := range objects {
t, ok := o.(*TopicState)
if !ok {
return nil, storage.ImpossibleTypeErr(t, o)
}
specs[i] = *t
}
return specs, nil
}
func (kv *topicStateKV) Rebuild() error {
return kv.store.Rebuild()
}