blob: 3a7e5123e27e5fd0b8cfa31a32f84eac99cff7cd [file] [log] [blame]
serkant.uluderyae5afeff2021-02-23 18:00:23 +03001/*
Joey Armstrong9cdee9f2024-01-03 04:56:14 -05002* Copyright 2018-2024 Open Networking Foundation (ONF) and the ONF Contributors
serkant.uluderyae5afeff2021-02-23 18:00:23 +03003
Joey Armstrong7f8436c2023-07-09 20:23:27 -04004* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
serkant.uluderyae5afeff2021-02-23 18:00:23 +03007
Joey Armstrong7f8436c2023-07-09 20:23:27 -04008* http://www.apache.org/licenses/LICENSE-2.0
serkant.uluderyae5afeff2021-02-23 18:00:23 +03009
Joey Armstrong7f8436c2023-07-09 20:23:27 -040010* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
serkant.uluderyae5afeff2021-02-23 18:00:23 +030015 */
16package kvstore
17
18import (
19 "context"
20 "errors"
21 "fmt"
22 "strings"
23 "sync"
24 "time"
25
26 "github.com/go-redis/redis/v8"
27 "github.com/opencord/voltha-lib-go/v7/pkg/log"
28)
29
30type RedisClient struct {
31 redisAPI *redis.Client
32 keyReservations map[string]time.Duration
33 watchedChannels sync.Map
34 writeLock sync.Mutex
35 keyReservationsLock sync.RWMutex
36}
37
38func NewRedisClient(addr string, timeout time.Duration, useSentinel bool) (*RedisClient, error) {
39 var r *redis.Client
40 if !useSentinel {
41 r = redis.NewClient(&redis.Options{Addr: addr})
42 } else {
43 // Redis Master-Replicas with Sentinel, sentinel masterSet config
44 // should be set to sebaRedis
45 r = redis.NewFailoverClient(&redis.FailoverOptions{
46 MasterName: "sebaRedis",
47 SentinelAddrs: []string{addr},
48 })
49 }
50
51 reservations := make(map[string]time.Duration)
52 return &RedisClient{redisAPI: r, keyReservations: reservations}, nil
53}
54
55func (c *RedisClient) Get(ctx context.Context, key string) (*KVPair, error) {
56
57 val, err := c.redisAPI.Get(ctx, key).Result()
58 valBytes, _ := ToByte(val)
59 if err != nil {
60 return nil, nil
61 }
62 return NewKVPair(key, valBytes, "", 0, 0), nil
63}
64
65func (c *RedisClient) Put(ctx context.Context, key string, value interface{}) error {
66
67 // Validate that we can convert value to a string as etcd API expects a string
68 var val string
69 var er error
70 if val, er = ToString(value); er != nil {
71 return fmt.Errorf("unexpected-type-%T", value)
72 }
73
74 // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make
75 // that KV key permanent instead of automatically removing it after a lease expiration
76 setErr := c.redisAPI.Set(ctx, key, val, 0)
77 err := setErr.Err()
78
79 if err != nil {
80 switch setErr.Err() {
81 case context.Canceled:
82 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
83 case context.DeadlineExceeded:
84 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err})
85 default:
86 logger.Warnw(ctx, "bad-endpoints", log.Fields{"error": err})
87 }
88 return err
89 }
90 return nil
91}
92
93func (c *RedisClient) scanAllKeysWithPrefix(ctx context.Context, key string) ([]string, error) {
94 var err error
95 allkeys := []string{}
96 cont := true
97 cursor := uint64(0)
98 matchPrefix := key + "*"
99
100 for cont {
101 // search in the first 10000 entries starting from the point indicated by the cursor
102 logger.Debugw(ctx, "redis-scan", log.Fields{"matchPrefix": matchPrefix, "cursor": cursor})
103 var keys []string
104 keys, cursor, err = c.redisAPI.Scan(context.Background(), cursor, matchPrefix, 10000).Result()
105 if err != nil {
106 return nil, err
107 }
108 if cursor == 0 {
109 // all data searched. break the loop
110 logger.Debugw(ctx, "redis-scan-ended", log.Fields{"matchPrefix": matchPrefix, "cursor": cursor})
111 cont = false
112 }
113 if len(keys) == 0 {
114 // no matched data found in this cycle. Continue to search
115 logger.Debugw(ctx, "redis-scan-no-data-found-continue", log.Fields{"matchPrefix": matchPrefix, "cursor": cursor})
116 continue
117 }
118 allkeys = append(allkeys, keys...)
119 }
120 return allkeys, nil
121}
122
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530123func (c *RedisClient) KeyExists(ctx context.Context, key string) (bool, error) {
124 var err error
125 var keyCount int64
126
127 if keyCount, err = c.redisAPI.Exists(ctx, key).Result(); err != nil {
128 return false, err
129 }
130 if keyCount > 0 {
131 return true, nil
132 }
133 return false, nil
134}
135
serkant.uluderyae5afeff2021-02-23 18:00:23 +0300136func (c *RedisClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
137 var err error
138 var keys []string
139 m := make(map[string]*KVPair)
140 var values []interface{}
141
142 if keys, err = c.scanAllKeysWithPrefix(ctx, key); err != nil {
143 return nil, err
144 }
145
146 if len(keys) != 0 {
147 values, err = c.redisAPI.MGet(ctx, keys...).Result()
148 if err != nil {
149 return nil, err
150 }
151 }
152 for i, key := range keys {
153 if valBytes, err := ToByte(values[i]); err == nil {
154 m[key] = NewKVPair(key, interface{}(valBytes), "", 0, 0)
155 }
156 }
157 return m, nil
158}
159
160func (c *RedisClient) Delete(ctx context.Context, key string) error {
161 // delete the key
162 if _, err := c.redisAPI.Del(ctx, key).Result(); err != nil {
163 logger.Errorw(ctx, "failed-to-delete-key", log.Fields{"key": key, "error": err})
164 return err
165 }
166 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
167 return nil
168}
169
170func (c *RedisClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
171 var keys []string
172 var err error
173 if keys, err = c.scanAllKeysWithPrefix(ctx, prefixKey); err != nil {
174 return err
175 }
176 if len(keys) == 0 {
177 logger.Warn(ctx, "nothing-to-delete-from-kv", log.Fields{"key": prefixKey})
178 return nil
179 }
180 //call delete for keys
181 entryCount := int64(0)
182 start := 0
183 pageSize := 5000
184 length := len(keys)
185 for start < length {
186 end := start + pageSize
187 if end >= length {
188 end = length
189 }
190 keysToDelete := keys[start:end]
191 count := int64(0)
192 if count, err = c.redisAPI.Del(ctx, keysToDelete...).Result(); err != nil {
193 logger.Errorw(ctx, "DeleteWithPrefix method failed", log.Fields{"prefixKey": prefixKey, "numOfMatchedKeys": len(keysToDelete), "err": err})
194 return err
195 }
196 entryCount += count
197 start = end
198 }
199 logger.Debugf(ctx, "%d entries matching with the key prefix %s have been deleted successfully", entryCount, prefixKey)
200 return nil
201}
202
203func (c *RedisClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
204 var val string
205 var er error
206 if val, er = ToString(value); er != nil {
207 return nil, fmt.Errorf("unexpected-type%T", value)
208 }
209
210 // SetNX -- Only set the key if it does not already exist.
211 c.redisAPI.SetNX(ctx, key, value, ttl)
212
213 // Check if set is successful
214 redisVal := c.redisAPI.Get(ctx, key).Val()
215 if redisVal == "" {
216 println("NULL")
217 return nil, nil
218 }
219
220 if val == redisVal {
221 // set is successful, return new reservation value
222 c.keyReservationsLock.Lock()
223 c.keyReservations[key] = ttl
224 c.keyReservationsLock.Unlock()
225 bytes, _ := ToByte(val)
226 return bytes, nil
227 } else {
228 // set is not successful, return existing reservation value
229 bytes, _ := ToByte(redisVal)
230 return bytes, nil
231 }
232
233}
234
235func (c *RedisClient) ReleaseReservation(ctx context.Context, key string) error {
236
237 redisVal := c.redisAPI.Get(ctx, key).Val()
238 if redisVal == "" {
239 return nil
240 }
241
242 // Override SetNX value with no TTL
243 _, err := c.redisAPI.Set(ctx, key, redisVal, 0).Result()
244 if err != nil {
245 delete(c.keyReservations, key)
246 } else {
247 return err
248 }
249 return nil
250
251}
252
253func (c *RedisClient) ReleaseAllReservations(ctx context.Context) error {
254 c.writeLock.Lock()
255 defer c.writeLock.Unlock()
256 for key := range c.keyReservations {
257 err := c.ReleaseReservation(ctx, key)
258 if err != nil {
259 logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err})
260 return err
261 }
262 }
263 return nil
264}
265
266func (c *RedisClient) RenewReservation(ctx context.Context, key string) error {
267 c.writeLock.Lock()
268 defer c.writeLock.Unlock()
269
270 // Verify the key was reserved
271 ttl, ok := c.keyReservations[key]
272 if !ok {
273 return errors.New("key-not-reserved. Key not found")
274 }
275
276 redisVal := c.redisAPI.Get(ctx, key).Val()
277 if redisVal != "" {
278 c.redisAPI.Set(ctx, key, redisVal, ttl)
279 }
280 return nil
281}
282
283func (c *RedisClient) listenForKeyChange(ctx context.Context, redisCh <-chan *redis.Message, ch chan<- *Event, cancel context.CancelFunc) {
284 logger.Debug(ctx, "start-listening-on-channel ...")
285 defer cancel()
286 defer close(ch)
287 for msg := range redisCh {
288 words := strings.Split(msg.Channel, ":")
289 key := words[1]
290 msgType := getMessageType(msg.Payload)
291 var valBytes []byte
292 if msgType == PUT {
293 ev, _ := c.Get(ctx, key)
294 valBytes, _ = ToByte(ev.Value)
295 }
296 ch <- NewEvent(getMessageType(msg.Payload), []byte(key), valBytes, 0)
297 }
298 logger.Debug(ctx, "stop-listening-on-channel ...")
299}
300
301func getMessageType(msg string) int {
302 isPut := strings.HasSuffix(msg, "set")
303 isDel := strings.HasSuffix(msg, "del")
304 if isPut {
305 return PUT
306 } else if isDel {
307 return DELETE
308 } else {
309 return UNKNOWN
310 }
311}
312
313func (c *RedisClient) addChannelMap(key string, channelMap map[chan *Event]*redis.PubSub) []map[chan *Event]*redis.PubSub {
314
315 var channels interface{}
316 var exists bool
317
318 if channels, exists = c.watchedChannels.Load(key); exists {
319 channels = append(channels.([]map[chan *Event]*redis.PubSub), channelMap)
320 } else {
321 channels = []map[chan *Event]*redis.PubSub{channelMap}
322 }
323 c.watchedChannels.Store(key, channels)
324
325 return channels.([]map[chan *Event]*redis.PubSub)
326}
327
328func (c *RedisClient) removeChannelMap(key string, pos int) []map[chan *Event]*redis.PubSub {
329 var channels interface{}
330 var exists bool
331
332 if channels, exists = c.watchedChannels.Load(key); exists {
333 channels = append(channels.([]map[chan *Event]*redis.PubSub)[:pos], channels.([]map[chan *Event]*redis.PubSub)[pos+1:]...)
334 c.watchedChannels.Store(key, channels)
335 }
336
337 return channels.([]map[chan *Event]*redis.PubSub)
338}
339
340func (c *RedisClient) getChannelMaps(key string) ([]map[chan *Event]*redis.PubSub, bool) {
341 var channels interface{}
342 var exists bool
343
344 channels, exists = c.watchedChannels.Load(key)
345
346 if channels == nil {
347 return nil, exists
348 }
349
350 return channels.([]map[chan *Event]*redis.PubSub), exists
351}
352
353func (c *RedisClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
354
355 ctx, cancel := context.WithCancel(ctx)
356
357 var subscribePath string
358 subscribePath = "__key*__:" + key
359 if withPrefix {
360 subscribePath += "*"
361 }
362 pubsub := c.redisAPI.PSubscribe(ctx, subscribePath)
363 redisCh := pubsub.Channel()
364
365 // Create new channel
366 ch := make(chan *Event, maxClientChannelBufferSize)
367
368 // Keep track of the created channels so they can be closed when required
369 channelMap := make(map[chan *Event]*redis.PubSub)
370 channelMap[ch] = pubsub
371
372 channelMaps := c.addChannelMap(key, channelMap)
373 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
374
375 // Launch a go routine to listen for updates
376 go c.listenForKeyChange(ctx, redisCh, ch, cancel)
377 return ch
378}
379
380func (c *RedisClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
381 // Get the array of channels mapping
382 var watchedChannels []map[chan *Event]*redis.PubSub
383 var ok bool
384
385 if watchedChannels, ok = c.getChannelMaps(key); !ok {
386 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
387 return
388 }
389 // Look for the channels
390 var pos = -1
391 for i, chMap := range watchedChannels {
392 if t, ok := chMap[ch]; ok {
393 logger.Debug(ctx, "channel-found")
394 // Close the Redis watcher before the client channel. This should close the etcd channel as well
395 if err := t.Close(); err != nil {
396 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
397 }
398 pos = i
399 break
400 }
401 }
402
403 channelMaps, _ := c.getChannelMaps(key)
404 // Remove that entry if present
405 if pos >= 0 {
406 channelMaps = c.removeChannelMap(key, pos)
407 }
408 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
409}
410func (c *RedisClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
411 return nil
412}
413
414func (c *RedisClient) ReleaseLock(lockName string) error {
415 return nil
416}
417
418func (c *RedisClient) IsConnectionUp(ctx context.Context) bool {
419 if _, err := c.redisAPI.Set(ctx, "connection-check", "1", 0).Result(); err != nil {
420 return false
421 }
422 return true
423
424}
425
426func (c *RedisClient) Close(ctx context.Context) {
427 if err := c.redisAPI.Close(); err != nil {
428 logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err})
429 }
430}
pnalmas37560752025-01-11 22:05:35 +0530431
432func (c *RedisClient) GetWithPrefix(ctx context.Context, prefix string) (map[string]*KVPair, error) {
433 var err error
434 var keys []string
435 m := make(map[string]*KVPair)
436 var values []interface{}
437
438 if keys, err = c.scanAllKeysWithPrefix(ctx, prefix); err != nil {
439 return nil, err
440 }
441
442 if len(keys) != 0 {
443 values, err = c.redisAPI.MGet(ctx, keys...).Result()
444 if err != nil {
445 return nil, err
446 }
447 }
448 for i, key := range keys {
449 if valBytes, err := ToByte(values[i]); err == nil {
450 m[key] = NewKVPair(key, interface{}(valBytes), "", 0, 0)
451 }
452 }
453 return m, nil
454}
455
456func (c *RedisClient) GetWithPrefixKeysOnly(ctx context.Context, prefix string) ([]string, error) {
457 // Use the scanAllKeysWithPrefix function to fetch keys matching the prefix
458 keys, err := c.scanAllKeysWithPrefix(ctx, prefix)
459 if err != nil {
460 return nil, fmt.Errorf("failed to scan keys with prefix %s: %v", prefix, err)
461 }
462
463 if len(keys) == 0 {
464 logger.Debugw(ctx, "no-keys-found", log.Fields{"prefix": prefix})
465 }
466
467 return keys, nil
468}