blob: 98f055957211483f34823f968a2e5ab5b49f9b91 [file] [log] [blame]
divyadesai81bb7ba2020-03-11 11:45:23 +00001/*
2 * Copyright 2018-present Open Networking Foundation
3
4 * 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
7
8 * http://www.apache.org/licenses/LICENSE-2.0
9
10 * 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.
15 */
16package kvstore
17
18import (
19 "context"
20 "errors"
21 "fmt"
22 "sync"
Neha Sharma87d43d72020-04-08 14:10:40 +000023 "time"
divyadesai81bb7ba2020-03-11 11:45:23 +000024
Maninder12b909f2020-10-23 14:23:36 +053025 "github.com/opencord/voltha-lib-go/v4/pkg/log"
divyadesai81bb7ba2020-03-11 11:45:23 +000026 v3Client "go.etcd.io/etcd/clientv3"
David K. Bainbridge595b6702021-04-09 16:10:58 +000027
divyadesai81bb7ba2020-03-11 11:45:23 +000028 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
29 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
30)
31
32// EtcdClient represents the Etcd KV store client
33type EtcdClient struct {
34 ectdAPI *v3Client.Client
35 keyReservations map[string]*v3Client.LeaseID
36 watchedChannels sync.Map
37 keyReservationsLock sync.RWMutex
38 lockToMutexMap map[string]*v3Concurrency.Mutex
39 lockToSessionMap map[string]*v3Concurrency.Session
40 lockToMutexLock sync.Mutex
41}
42
David K. Bainbridge595b6702021-04-09 16:10:58 +000043// NewEtcdCustomClient returns a new client for the Etcd KV store allowing
44// the called to specify etcd client configuration
45func NewEtcdCustomClient(ctx context.Context, config *v3Client.Config) (*EtcdClient, error) {
46 c, err := v3Client.New(*config)
divyadesai81bb7ba2020-03-11 11:45:23 +000047 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +000048 logger.Error(ctx, err)
divyadesai81bb7ba2020-03-11 11:45:23 +000049 return nil, err
50 }
51
52 reservations := make(map[string]*v3Client.LeaseID)
53 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
54 lockSessionMap := make(map[string]*v3Concurrency.Session)
55
56 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
57 lockToSessionMap: lockSessionMap}, nil
58}
59
David K. Bainbridge595b6702021-04-09 16:10:58 +000060// NewEtcdClient returns a new client for the Etcd KV store
61func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
62 logconfig := log.ConstructZapConfig(log.JSON, level, log.Fields{})
63
64 return NewEtcdCustomClient(
65 ctx,
66 &v3Client.Config{
67 Endpoints: []string{addr},
68 DialTimeout: timeout,
69 LogConfig: &logconfig})
70}
71
divyadesai81bb7ba2020-03-11 11:45:23 +000072// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
73// it is assumed the connection is down or unreachable.
74func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
75 // Let's try to get a non existent key. If the connection is up then there will be no error returned.
76 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
77 return false
78 }
79 //cancel()
80 return true
81}
82
83// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
84// wait for a response
85func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
86 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
87 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +000088 logger.Error(ctx, err)
divyadesai81bb7ba2020-03-11 11:45:23 +000089 return nil, err
90 }
91 m := make(map[string]*KVPair)
92 for _, ev := range resp.Kvs {
93 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
94 }
95 return m, nil
96}
97
98// Get returns a key-value pair for a given key. Timeout defines how long the function will
99// wait for a response
100func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
101
102 resp, err := c.ectdAPI.Get(ctx, key)
103
104 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000105 logger.Error(ctx, err)
divyadesai81bb7ba2020-03-11 11:45:23 +0000106 return nil, err
107 }
108 for _, ev := range resp.Kvs {
109 // Only one value is returned
110 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
111 }
112 return nil, nil
113}
114
115// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
116// accepts only a string as a value for a put operation. Timeout defines how long the function will
117// wait for a response
118func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
119
120 // Validate that we can convert value to a string as etcd API expects a string
121 var val string
122 var er error
123 if val, er = ToString(value); er != nil {
124 return fmt.Errorf("unexpected-type-%T", value)
125 }
126
127 var err error
128 // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make
129 // that KV key permanent instead of automatically removing it after a lease expiration
130 c.keyReservationsLock.RLock()
131 leaseID, ok := c.keyReservations[key]
132 c.keyReservationsLock.RUnlock()
133 if ok {
134 _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID))
135 } else {
136 _, err = c.ectdAPI.Put(ctx, key, val)
137 }
138
139 if err != nil {
140 switch err {
141 case context.Canceled:
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000142 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000143 case context.DeadlineExceeded:
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000144 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000145 case v3rpcTypes.ErrEmptyKey:
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000146 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000147 default:
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000148 logger.Warnw(ctx, "bad-endpoints", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000149 }
150 return err
151 }
152 return nil
153}
154
155// Delete removes a key from the KV store. Timeout defines how long the function will
156// wait for a response
157func (c *EtcdClient) Delete(ctx context.Context, key string) error {
158
159 // delete the key
160 if _, err := c.ectdAPI.Delete(ctx, key); err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000161 logger.Errorw(ctx, "failed-to-delete-key", log.Fields{"key": key, "error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000162 return err
163 }
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000164 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
divyadesai81bb7ba2020-03-11 11:45:23 +0000165 return nil
166}
167
David K. Bainbridge595b6702021-04-09 16:10:58 +0000168func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
169
170 //delete the prefix
171 if _, err := c.ectdAPI.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil {
172 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
173 return err
174 }
175 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
176 return nil
177}
178
divyadesai81bb7ba2020-03-11 11:45:23 +0000179// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
180// the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL
181// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
182// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
183// then the value assigned to that key will be returned.
Neha Sharma87d43d72020-04-08 14:10:40 +0000184func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
divyadesai81bb7ba2020-03-11 11:45:23 +0000185 // Validate that we can convert value to a string as etcd API expects a string
186 var val string
187 var er error
188 if val, er = ToString(value); er != nil {
189 return nil, fmt.Errorf("unexpected-type%T", value)
190 }
191
Neha Sharma87d43d72020-04-08 14:10:40 +0000192 resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds()))
divyadesai81bb7ba2020-03-11 11:45:23 +0000193 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000194 logger.Error(ctx, err)
divyadesai81bb7ba2020-03-11 11:45:23 +0000195 return nil, err
196 }
197 // Register the lease id
198 c.keyReservationsLock.Lock()
199 c.keyReservations[key] = &resp.ID
200 c.keyReservationsLock.Unlock()
201
202 // Revoke lease if reservation is not successful
203 reservationSuccessful := false
204 defer func() {
205 if !reservationSuccessful {
206 if err = c.ReleaseReservation(context.Background(), key); err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000207 logger.Error(ctx, "cannot-release-lease")
divyadesai81bb7ba2020-03-11 11:45:23 +0000208 }
209 }
210 }()
211
212 // Try to grap the Key with the above lease
213 c.ectdAPI.Txn(context.Background())
214 txn := c.ectdAPI.Txn(context.Background())
215 txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0))
216 txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID)))
217 txn = txn.Else(v3Client.OpGet(key))
218 result, er := txn.Commit()
219 if er != nil {
220 return nil, er
221 }
222
223 if !result.Succeeded {
224 // Verify whether we are already the owner of that Key
225 if len(result.Responses) > 0 &&
226 len(result.Responses[0].GetResponseRange().Kvs) > 0 {
227 kv := result.Responses[0].GetResponseRange().Kvs[0]
228 if string(kv.Value) == val {
229 reservationSuccessful = true
230 return value, nil
231 }
232 return kv.Value, nil
233 }
234 } else {
235 // Read the Key to ensure this is our Key
236 m, err := c.Get(ctx, key)
237 if err != nil {
238 return nil, err
239 }
240 if m != nil {
241 if m.Key == key && isEqual(m.Value, value) {
242 // My reservation is successful - register it. For now, support is only for 1 reservation per key
243 // per session.
244 reservationSuccessful = true
245 return value, nil
246 }
247 // My reservation has failed. Return the owner of that key
248 return m.Value, nil
249 }
250 }
251 return nil, nil
252}
253
254// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
255func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
256 c.keyReservationsLock.Lock()
257 defer c.keyReservationsLock.Unlock()
258
259 for key, leaseID := range c.keyReservations {
260 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
261 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000262 logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000263 return err
264 }
265 delete(c.keyReservations, key)
266 }
267 return nil
268}
269
270// ReleaseReservation releases reservation for a specific key.
271func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
272 // Get the leaseid using the key
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000273 logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key})
divyadesai81bb7ba2020-03-11 11:45:23 +0000274 var ok bool
275 var leaseID *v3Client.LeaseID
276 c.keyReservationsLock.Lock()
277 defer c.keyReservationsLock.Unlock()
278 if leaseID, ok = c.keyReservations[key]; !ok {
279 return nil
280 }
281
282 if leaseID != nil {
283 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
284 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000285 logger.Error(ctx, err)
divyadesai81bb7ba2020-03-11 11:45:23 +0000286 return err
287 }
288 delete(c.keyReservations, key)
289 }
290 return nil
291}
292
293// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
294// period specified when reserving the key
295func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
296 // Get the leaseid using the key
297 var ok bool
298 var leaseID *v3Client.LeaseID
299 c.keyReservationsLock.RLock()
300 leaseID, ok = c.keyReservations[key]
301 c.keyReservationsLock.RUnlock()
302
303 if !ok {
304 return errors.New("key-not-reserved")
305 }
306
307 if leaseID != nil {
308 _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID)
309 if err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000310 logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000311 return err
312 }
313 } else {
314 return errors.New("lease-expired")
315 }
316 return nil
317}
318
319// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
320// listen to receive Events.
321func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
322 w := v3Client.NewWatcher(c.ectdAPI)
323 ctx, cancel := context.WithCancel(ctx)
324 var channel v3Client.WatchChan
325 if withPrefix {
326 channel = w.Watch(ctx, key, v3Client.WithPrefix())
327 } else {
328 channel = w.Watch(ctx, key)
329 }
330
331 // Create a new channel
332 ch := make(chan *Event, maxClientChannelBufferSize)
333
334 // Keep track of the created channels so they can be closed when required
335 channelMap := make(map[chan *Event]v3Client.Watcher)
336 channelMap[ch] = w
337
338 channelMaps := c.addChannelMap(key, channelMap)
339
340 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
341 // json format.
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000342 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
divyadesai81bb7ba2020-03-11 11:45:23 +0000343 // Launch a go routine to listen for updates
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000344 go c.listenForKeyChange(ctx, channel, ch, cancel)
divyadesai81bb7ba2020-03-11 11:45:23 +0000345
346 return ch
347
348}
349
350func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
351 var channels interface{}
352 var exists bool
353
354 if channels, exists = c.watchedChannels.Load(key); exists {
355 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
356 } else {
357 channels = []map[chan *Event]v3Client.Watcher{channelMap}
358 }
359 c.watchedChannels.Store(key, channels)
360
361 return channels.([]map[chan *Event]v3Client.Watcher)
362}
363
364func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
365 var channels interface{}
366 var exists bool
367
368 if channels, exists = c.watchedChannels.Load(key); exists {
369 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
370 c.watchedChannels.Store(key, channels)
371 }
372
373 return channels.([]map[chan *Event]v3Client.Watcher)
374}
375
376func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
377 var channels interface{}
378 var exists bool
379
380 channels, exists = c.watchedChannels.Load(key)
381
382 if channels == nil {
383 return nil, exists
384 }
385
386 return channels.([]map[chan *Event]v3Client.Watcher), exists
387}
388
389// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
390// may be multiple listeners on the same key. The previously created channel serves as a key
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000391func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
divyadesai81bb7ba2020-03-11 11:45:23 +0000392 // Get the array of channels mapping
393 var watchedChannels []map[chan *Event]v3Client.Watcher
394 var ok bool
395
396 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000397 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
divyadesai81bb7ba2020-03-11 11:45:23 +0000398 return
399 }
400 // Look for the channels
401 var pos = -1
402 for i, chMap := range watchedChannels {
403 if t, ok := chMap[ch]; ok {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000404 logger.Debug(ctx, "channel-found")
divyadesai81bb7ba2020-03-11 11:45:23 +0000405 // Close the etcd watcher before the client channel. This should close the etcd channel as well
406 if err := t.Close(); err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000407 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000408 }
409 pos = i
410 break
411 }
412 }
413
414 channelMaps, _ := c.getChannelMaps(key)
415 // Remove that entry if present
416 if pos >= 0 {
417 channelMaps = c.removeChannelMap(key, pos)
418 }
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000419 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
divyadesai81bb7ba2020-03-11 11:45:23 +0000420}
421
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000422func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
423 logger.Debug(ctx, "start-listening-on-channel ...")
divyadesai81bb7ba2020-03-11 11:45:23 +0000424 defer cancel()
425 defer close(ch)
426 for resp := range channel {
427 for _, ev := range resp.Events {
428 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
429 }
430 }
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000431 logger.Debug(ctx, "stop-listening-on-channel ...")
divyadesai81bb7ba2020-03-11 11:45:23 +0000432}
433
434func getEventType(event *v3Client.Event) int {
435 switch event.Type {
436 case v3Client.EventTypePut:
437 return PUT
438 case v3Client.EventTypeDelete:
439 return DELETE
440 }
441 return UNKNOWN
442}
443
444// Close closes the KV store client
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000445func (c *EtcdClient) Close(ctx context.Context) {
divyadesai81bb7ba2020-03-11 11:45:23 +0000446 if err := c.ectdAPI.Close(); err != nil {
Rohan Agrawalc32d9932020-06-15 11:01:47 +0000447 logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err})
divyadesai81bb7ba2020-03-11 11:45:23 +0000448 }
449}
450
451func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
452 c.lockToMutexLock.Lock()
453 defer c.lockToMutexLock.Unlock()
454 c.lockToMutexMap[lockName] = lock
455 c.lockToSessionMap[lockName] = session
456}
457
458func (c *EtcdClient) deleteLockName(lockName string) {
459 c.lockToMutexLock.Lock()
460 defer c.lockToMutexLock.Unlock()
461 delete(c.lockToMutexMap, lockName)
462 delete(c.lockToSessionMap, lockName)
463}
464
465func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
466 c.lockToMutexLock.Lock()
467 defer c.lockToMutexLock.Unlock()
468 var lock *v3Concurrency.Mutex
469 var session *v3Concurrency.Session
470 if l, exist := c.lockToMutexMap[lockName]; exist {
471 lock = l
472 }
473 if s, exist := c.lockToSessionMap[lockName]; exist {
474 session = s
475 }
476 return lock, session
477}
478
Neha Sharma87d43d72020-04-08 14:10:40 +0000479func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
divyadesai81bb7ba2020-03-11 11:45:23 +0000480 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
481 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
482 if err := mu.Lock(context.Background()); err != nil {
483 //cancel()
484 return err
485 }
486 c.addLockName(lockName, mu, session)
487 return nil
488}
489
490func (c *EtcdClient) ReleaseLock(lockName string) error {
491 lock, session := c.getLock(lockName)
492 var err error
493 if lock != nil {
494 if e := lock.Unlock(context.Background()); e != nil {
495 err = e
496 }
497 }
498 if session != nil {
499 if e := session.Close(); e != nil {
500 err = e
501 }
502 }
503 c.deleteLockName(lockName)
504
505 return err
506}