/
redisdatabase.go
423 lines (335 loc) · 9.32 KB
/
redisdatabase.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
// Copyright 2016 IBM Corporation
//
// 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/licenses/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 rules
import (
"encoding/json"
"errors"
"encoding/base64"
"fmt"
"github.com/Sirupsen/logrus"
"github.com/amalgam8/amalgam8/controller/util/encryption"
"github.com/amalgam8/amalgam8/pkg/api"
"github.com/garyburd/redigo/redis"
)
// Entry is used to encapsulate a record with an IV for encryption and decryption.
type Entry struct {
IV string `json:"IV"`
Payload string `json:"payload"`
}
type redisDB struct {
pool *redis.Pool
address string
password string
encryption encryption.Encryption
}
// TODO: The returns from all the redis commands need to be double checked to ensure we are detecting all the errors
// newRedisDB returns an instance of a Redis database
func newRedisDB(address string, password string) *redisDB {
db := &redisDB{
pool: redis.NewPool(func() (redis.Conn, error) {
// Connect to Redis
conn, err := redis.DialURL(
address,
redis.DialPassword(password),
)
if err != nil {
if conn != nil {
conn.Close()
}
return nil, err
}
return conn, nil
}, 240),
address: address,
password: password,
encryption: nil,
}
// TODO: either make configurable, or tweak this number appropriately
db.pool.MaxActive = 30
return db
}
func (rdb *redisDB) ReadAllEntries(namespace string) ([]string, int64, error) {
conn := rdb.pool.Get()
defer conn.Close()
logrus.Debug("HGETALL ", namespace)
entryMap, err := redis.StringMap(conn.Do("HGETALL", buildRulesKey(namespace)))
if err != nil {
return []string{}, 0, err
}
// Transform into an array
entries := make([]string, len(entryMap))
i := 0
for _, entry := range entryMap {
entries[i] = entry
i++
}
entries, err = rdb.decrypt(entries)
if err != nil {
return []string{}, 0, err
}
rev, err := redis.Int64(conn.Do("GET", buildNamespaceKey(namespace, "revision"))) // FIXME: pipeline
if err == redis.ErrNil {
rev = 0
}
return entries, rev, nil
}
func (rdb *redisDB) ReadEntries(namespace string, ids []string) ([]string, int64, error) {
args := make([]interface{}, len(ids)+1)
args[0] = buildRulesKey(namespace)
for i, id := range ids {
args[i+1] = id
}
conn := rdb.pool.Get()
defer conn.Close()
logrus.Debug("HMGET ", args)
entries, err := redis.Strings(conn.Do("HMGET", args...)) // TODO: more error checking?
if err != nil {
return []string{}, 0, err
}
entries, err = rdb.decrypt(entries)
if err != nil {
return []string{}, 0, err
}
rev, err := redis.Int64(conn.Do("GET", buildNamespaceKey(namespace, "revision"))) // FIXME: pipeline
if err == redis.ErrNil {
rev = 0
}
return entries, rev, nil
}
func (rdb *redisDB) InsertEntries(namespace string, entries map[string]string) error {
encrypted, err := rdb.encrypt(entries)
if err != nil {
return err
}
args := buildHMSetArgs(buildRulesKey(namespace), encrypted)
conn := rdb.pool.Get()
defer conn.Close()
logrus.Debug("HMSET ", args)
_, err = redis.String(conn.Do("HMSET", args...))
if err != nil {
return err
}
_, err = conn.Do("INCR", buildNamespaceKey(namespace, "revision")) // FIXME: pipeline
return err
}
// 1. Get all existing IDs
// 2. Ensure the new rules are a subset of the existing rules
// 3. Update the rules
func (rdb *redisDB) UpdateEntries(namespace string, entries map[string]string) error {
key := buildRulesKey(namespace)
conn := rdb.pool.Get()
defer conn.Close()
conn.Do("WATCH", key) // TODO: return codes?
existingIDs, err := redis.Strings(conn.Do("HKEYS", key))
if err != nil {
return err
}
existingIDSet := make(map[string]bool)
for _, id := range existingIDs {
existingIDSet[id] = true
}
// TODO: build a list of all the IDs that are missing?
for id := range entries {
_, exists := existingIDSet[id]
if !exists {
return errors.New("rules: id " + id + " does not exist")
}
}
entries, err = rdb.encrypt(entries)
if err != nil {
return err
}
conn.Send("MULTI")
args := buildHMSetArgs(key, entries)
if err := conn.Send("HMSET", args...); err != nil {
return err
}
// Execute transaction
_, err = redis.Values(conn.Do("EXEC"))
// Nil return indicates that the transaction failed
if err != nil {
if err == redis.ErrNil {
logrus.Error("Transaction failed due to conflict")
}
return err
}
_, err = conn.Do("INCR", buildNamespaceKey(namespace, "revision")) // FIXME: pipeline
return err
}
func (rdb *redisDB) DeleteEntriesByID(namespace string, ids []string) error {
conn := rdb.pool.Get()
defer conn.Close()
args := make([]interface{}, len(ids)+1)
args[0] = buildRulesKey(namespace)
i := 1
for _, id := range ids {
args[i] = id
i++
}
logrus.Debug("HDEL ", args)
_, err := redis.Int(conn.Do("HDEL", args...))
// TODO: more error checking?
if err != nil {
return err
}
_, err = conn.Do("INCR", buildNamespaceKey(namespace, "revision")) // FIXME: pipeline
return err
}
func (rdb *redisDB) DeleteAllEntries(namespace string) error {
conn := rdb.pool.Get()
defer conn.Close()
_, err := redis.Int(conn.Do("DEL", buildRulesKey(namespace)))
if err != nil {
return err
}
_, err = conn.Do("INCR", buildNamespaceKey(namespace, "revision")) // FIXME: pipeline
return err
}
func (rdb *redisDB) DeleteEntriesByFilter(namespace string, filter api.RuleFilter) error {
var err error
key := buildRulesKey(namespace)
conn := rdb.pool.Get()
defer conn.Close() // Automatically calls DISCARD if necessary
conn.Do("WATCH", key)
// Get all rules
existingEntryMap, err := redis.StringMap(conn.Do("HGETALL", key))
if err != nil {
return err
}
existingEntries := make([]string, len(existingEntryMap))
i := 0
for _, entry := range existingEntryMap {
existingEntries[i] = entry
i++
}
existingEntries, err = rdb.decrypt(existingEntries)
if err != nil {
return err
}
// Unmarshal
existingRules := make([]api.Rule, len(existingEntries))
for i, entry := range existingEntries {
rule := api.Rule{}
err := json.Unmarshal([]byte(entry), &rule)
if err != nil {
return err
}
existingRules[i] = rule
}
rulesToDelete := filter.Apply(existingRules)
logrus.WithFields(logrus.Fields{
"pre_filtered": existingRules,
"filtered": rulesToDelete,
"filter": filter,
}).Debug("Filtering")
conn.Send("MULTI")
// Delete IDs
if len(rulesToDelete) > 0 {
args := make([]interface{}, len(rulesToDelete)+1)
args[0] = key
for i, rule := range rulesToDelete {
args[i+1] = rule.ID
}
logrus.Debug("HDEL ", args)
err = conn.Send("HDEL", args...)
if err != nil {
return err
}
}
// Execute transaction
_, err = redis.Values(conn.Do("EXEC"))
if err != nil {
// Nil return indicates that the transaction failed
if err == redis.ErrNil {
logrus.Error("Transaction failed due to conflict")
}
return err
}
_, err = redis.Int64(conn.Do("INCR", buildNamespaceKey(namespace, "revision"))) // TODO: pipeline
return err
}
// encrypt
func (rdb *redisDB) encrypt(entries map[string]string) (map[string]string, error) {
// Short-circuit without encryption
if rdb.encryption == nil {
return entries, nil
}
encryptedMap := make(map[string]string)
for id, entry := range entries {
iv := rdb.encryption.NewIV()
payload, err := rdb.encryption.Encrypt(iv, []byte(entry))
if err != nil {
logrus.Error("Encryption failed")
return encryptedMap, err
}
encodedIV := base64.StdEncoding.EncodeToString(iv)
encodedPayload := base64.StdEncoding.EncodeToString(payload)
e := Entry{
IV: encodedIV,
Payload: encodedPayload,
}
data, err := json.Marshal(&e)
if err != nil {
logrus.Error("Encryption failed")
return encryptedMap, err
}
encryptedMap[id] = string(data)
}
return encryptedMap, nil
}
// decrypt
func (rdb *redisDB) decrypt(entries []string) ([]string, error) {
// Short-circuit without encryption
if rdb.encryption == nil {
return entries, nil
}
e := Entry{}
decryptedEntries := make([]string, len(entries))
for i, entry := range entries {
if err := json.Unmarshal([]byte(entry), &e); err != nil {
return []string{}, err
}
decodedPayload, err := base64.StdEncoding.DecodeString(e.Payload)
if err != nil {
return []string{}, err
}
decodedIV, err := base64.StdEncoding.DecodeString(e.IV)
if err != nil {
return []string{}, err
}
decrypted, err := rdb.encryption.Decrypt(decodedIV, decodedPayload)
if err != nil {
return []string{}, err
}
decryptedEntries[i] = string(decrypted)
}
return decryptedEntries, nil
}
func buildHMSetArgs(key string, fieldMap map[string]string) []interface{} {
args := make([]interface{}, len(fieldMap)*2+1)
args[0] = key
i := 1
for id, entry := range fieldMap {
args[i] = id
args[i+1] = entry
i += 2
}
return args
}
func buildNamespaceKey(namespace, key string) string {
return fmt.Sprintf("controller:%v:%v", namespace, key)
}
func buildRulesKey(namespace string) string {
return fmt.Sprintf("controller:%v:rules", namespace)
}