forked from TykTechnologies/tyk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage_handlers.go
499 lines (421 loc) · 12.3 KB
/
storage_handlers.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
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
package main
import (
"github.com/garyburd/redigo/redis"
"strconv"
"strings"
"github.com/spaolacci/murmur3"
"time"
"encoding/hex"
"hash"
)
// KeyError is a standard error for when a key is not found in the storage engine
type KeyError struct{}
func (e KeyError) Error() string {
return "Key not found"
}
// StorageHandler is a standard interface to a storage backend,
// used by AuthorisationManager to read and write key values to the backend
type StorageHandler interface {
GetKey(string) (string, error) // Returned string is expected to be a JSON object (SessionState)
SetKey(string, string, int64) // Second input string is expected to be a JSON object (SessionState)
GetExp(string) (int64, error) // Returns expiry of a key
GetKeys(string) []string
DeleteKey(string) bool
DeleteRawKey(string) bool
Connect() bool
GetKeysAndValues() map[string]string
GetKeysAndValuesWithFilter(string) map[string]string
DeleteKeys([]string) bool
Decrement(string)
IncrememntWithExpire(string, int64) int64
}
// InMemoryStorageManager implements the StorageHandler interface,
// it uses an in-memory map to store sessions, should only be used
// for testing purposes
type InMemoryStorageManager struct {
Sessions map[string]string
}
// Decrement is a dummy function
func (s *InMemoryStorageManager) Decrement(n string) {
log.Warning("Not implemented!")
}
func (s *InMemoryStorageManager) IncrememntWithExpire(n string, i int64) int64 {
log.Warning("Not implemented!")
return 0
}
func (s *InMemoryStorageManager) Connect() bool {
return true
}
// GetKey retrieves the key from the in-memory map
func (s InMemoryStorageManager) GetKey(keyName string) (string, error) {
value, ok := s.Sessions[keyName]
if !ok {
return "", KeyError{}
}
return value, nil
}
// SetKey updates the in-memory key
func (s InMemoryStorageManager) SetKey(keyName string, sessionState string, timeout int64) {
s.Sessions[keyName] = sessionState
}
func (s InMemoryStorageManager) GetExp(keyName string) (int64, error) {
return 0, nil
}
// GetKeys will retreive multiple keys based on a filter (prefix, e.g. tyk.keys)
func (s InMemoryStorageManager) GetKeys(filter string) []string {
sessions := make([]string, 0, len(s.Sessions))
for key := range s.Sessions {
if strings.Contains(key, filter) {
sessions = append(sessions, key)
}
}
return sessions
}
// GetKeysAndValues returns all keys and their data, very expensive call.
func (s InMemoryStorageManager) GetKeysAndValues() map[string]string {
return s.Sessions
}
// GetKeysAndValuesWithFilter does nothing here
func (s InMemoryStorageManager) GetKeysAndValuesWithFilter(filter string) map[string]string {
log.Warning("NOT IMPLEMENTED")
return s.Sessions
}
// DeleteKey will remove a key from the storage engine
func (s InMemoryStorageManager) DeleteKey(keyName string) bool {
delete(s.Sessions, keyName)
return true
}
// DeleteRawKey will remove a key from the storage engine
func (s InMemoryStorageManager) DeleteRawKey(keyName string) bool {
delete(s.Sessions, keyName)
return true
}
// DeleteKeys remove keys from sessions DB
func (s InMemoryStorageManager) DeleteKeys(keys []string) bool {
for _, keyName := range keys {
delete(s.Sessions, keyName)
}
return true
}
// ------------------- REDIS STORAGE MANAGER -------------------------------
// RedisStorageManager is a storage manager that uses the redis database.
type RedisStorageManager struct {
pool *redis.Pool
KeyPrefix string
}
func (r *RedisStorageManager) newPool(server, password string, database int) *redis.Pool {
maxIdle := 100
if config.Storage.MaxIdle > 0 {
maxIdle = config.Storage.MaxIdle
}
return &redis.Pool{
MaxIdle: maxIdle,
IdleTimeout: 240 * time.Second,
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", server)
if err != nil {
return nil, err
}
if password != "" {
if _, err := c.Do("AUTH", password); err != nil {
c.Close()
return nil, err
}
}
if database > 0 {
if _, err := c.Do("SELECT", database); err != nil {
c.Close()
return nil, err
}
}
return c, err
},
TestOnBorrow: func(c redis.Conn, t time.Time) error {
_, err := c.Do("PING")
return err
},
}
}
// Connect will establish a connection to the DB
func (r *RedisStorageManager) Connect() bool {
fullPath := config.Storage.Host + ":" + strconv.Itoa(config.Storage.Port)
log.Info("Connecting to redis on: ", fullPath)
r.pool = r.newPool(fullPath, config.Storage.Password, config.Storage.Database)
return true
}
func getHash(in string) string {
if !config.HashKeys {
// Not hashing? Return the raw key
return in
}
var h hash.Hash32 = murmur3.New32()
h.Write([]byte(in))
return hex.EncodeToString(h.Sum(nil))
}
func (r *RedisStorageManager) fixKey(keyName string) string {
setKeyName := r.KeyPrefix + getHash(keyName)
log.Debug("Input key was: ", setKeyName)
return setKeyName
}
func (r *RedisStorageManager) cleanKey(keyName string) string {
setKeyName := strings.Replace(keyName, r.KeyPrefix, "", 1)
return setKeyName
}
// GetKey will retreive a key from the database
func (r *RedisStorageManager) GetKey(keyName string) (string, error) {
db := r.pool.Get()
defer db.Close()
log.Debug("Getting key: ", r.fixKey(keyName))
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.GetKey(keyName)
}
log.Debug("Getting: ", r.fixKey(keyName))
value, err := redis.String(db.Do("GET", r.fixKey(keyName)))
if err != nil {
log.Debug("Error trying to get value:", err)
return "", KeyError{}
}
return value, nil
}
func (r *RedisStorageManager) GetExp(keyName string) (int64, error) {
db := r.pool.Get()
defer db.Close()
log.Debug("Getting exp for key: ", r.fixKey(keyName))
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.GetExp(keyName)
}
value, err := redis.Int64(db.Do("TTL", r.fixKey(keyName)))
if err != nil {
log.Error("Error trying to get TTL: ", err)
} else {
return value, nil
}
return 0, KeyError{}
}
// SetKey will create (or update) a key value in the store
func (r *RedisStorageManager) SetKey(keyName string, sessionState string, timeout int64) {
db := r.pool.Get()
defer db.Close()
log.Debug("Setting key: ", r.fixKey(keyName))
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
r.SetKey(keyName, sessionState, timeout)
} else {
_, err := db.Do("SET", r.fixKey(keyName), sessionState)
if timeout > 0 {
_, expErr := db.Do("EXPIRE", r.fixKey(keyName), timeout)
if expErr != nil {
log.Error("Could not EXPIRE key")
log.Error(expErr)
}
}
if err != nil {
log.Error("Error trying to set value:")
log.Error(err)
}
}
}
// Decrement will decrement a key in redis
func (r *RedisStorageManager) Decrement(keyName string) {
db := r.pool.Get()
defer db.Close()
keyName = r.fixKey(keyName)
log.Debug("Decrementing key: ", keyName)
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
r.Decrement(keyName)
} else {
err := db.Send("DECR", keyName)
if err != nil {
log.Error("Error trying to decrement value:", err)
}
}
}
// IncrementWithExpire will increment a key in redis
func (r *RedisStorageManager) IncrememntWithExpire(keyName string, expire int64) int64 {
db := r.pool.Get()
defer db.Close()
log.Debug("Incrementing raw key: ", keyName)
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
r.IncrememntWithExpire(keyName, expire)
} else {
// This function uses a raw key, so we shouldn't call fixKey
fixedKey := keyName
val, err := redis.Int64(db.Do("INCR", fixedKey))
log.Debug("Incremented key: ", fixedKey, ", val is: ", val)
if val == 1 {
log.Debug("--> Setting Expire")
db.Send("EXPIRE", fixedKey, expire)
}
if err != nil {
log.Error("Error trying to increment value:", err)
}
return val
}
return 0
}
// GetKeys will return all keys according to the filter (filter is a prefix - e.g. tyk.keys.*)
func (r *RedisStorageManager) GetKeys(filter string) []string {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.GetKeys(filter)
}
searchStr := r.KeyPrefix + getHash(filter) + "*"
sessionsInterface, err := db.Do("KEYS", searchStr)
if err != nil {
log.Error("Error trying to get all keys:")
log.Error(err)
} else {
sessions, _ := redis.Strings(sessionsInterface, err)
for i, v := range sessions {
sessions[i] = r.cleanKey(v)
}
return sessions
}
return []string{}
}
// GetKeysAndValuesWithFilter will return all keys and their values with a filter
func (r *RedisStorageManager) GetKeysAndValuesWithFilter(filter string) map[string]string {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.GetKeysAndValuesWithFilter(filter)
}
searchStr := r.KeyPrefix + getHash(filter) + "*"
sessionsInterface, err := db.Do("KEYS", searchStr)
if err != nil {
log.Error("Error trying to get filtered client keys:")
log.Error(err)
} else {
keys, _ := redis.Strings(sessionsInterface, err)
valueObj, err := db.Do("MGET", sessionsInterface.([]interface{})...)
values, err := redis.Strings(valueObj, err)
returnValues := make(map[string]string)
for i, v := range keys {
returnValues[r.cleanKey(v)] = values[i]
}
return returnValues
}
return map[string]string{}
}
// GetKeysAndValues will return all keys and their values - not to be used lightly
func (r *RedisStorageManager) GetKeysAndValues() map[string]string {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.GetKeysAndValues()
}
searchStr := r.KeyPrefix + "*"
sessionsInterface, err := db.Do("KEYS", searchStr)
if err != nil {
log.Error("Error trying to get all keys:")
log.Error(err)
} else {
keys, _ := redis.Strings(sessionsInterface, err)
valueObj, err := db.Do("MGET", sessionsInterface.([]interface{})...)
values, err := redis.Strings(valueObj, err)
returnValues := make(map[string]string)
for i, v := range keys {
returnValues[r.cleanKey(v)] = values[i]
}
return returnValues
}
return map[string]string{}
}
// DeleteKey will remove a key from the database
func (r *RedisStorageManager) DeleteKey(keyName string) bool {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.DeleteKey(keyName)
}
_, err := db.Do("DEL", r.fixKey(keyName))
if err != nil {
log.Error("Error trying to delete key:")
log.Error(err)
}
return true
}
// DeleteKey will remove a key from the database without prefixing, assumes user knows what they are doing
func (r *RedisStorageManager) DeleteRawKey(keyName string) bool {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.DeleteRawKey(keyName)
}
_, err := db.Do("DEL", keyName)
if err != nil {
log.Error("Error trying to delete key:")
log.Error(err)
}
return true
}
// DeleteKeys will remove a group of keys in bulk
func (r *RedisStorageManager) DeleteKeys(keys []string) bool {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.DeleteKeys(keys)
}
if len(keys) > 0 {
asInterface := make([]interface{}, len(keys))
for i, v := range keys {
asInterface[i] = interface{}(r.fixKey(v))
}
log.Debug("Deleting: ", asInterface)
_, err := db.Do("DEL", asInterface...)
if err != nil {
log.Error("Error trying to delete keys:")
log.Error(err)
}
} else {
log.Debug("RedisStorageManager called DEL - Nothing to delete")
}
return true
}
// DeleteKeys will remove a group of keys in bulk without a prefix handler
func (r *RedisStorageManager) DeleteRawKeys(keys []string, prefix string) bool {
db := r.pool.Get()
defer db.Close()
if db == nil {
log.Info("Connection dropped, connecting..")
r.Connect()
return r.DeleteKeys(keys)
}
if len(keys) > 0 {
asInterface := make([]interface{}, len(keys))
for i, v := range keys {
asInterface[i] = interface{}(prefix + v)
}
log.Debug("Deleting: ", asInterface)
_, err := db.Do("DEL", asInterface...)
if err != nil {
log.Error("Error trying to delete keys:")
log.Error(err)
}
} else {
log.Debug("RedisStorageManager called DEL - Nothing to delete")
}
return true
}