blob: 3ae767ce88c436d42a9f55c0e8563ee233d02aa3 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
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"
Scott Bakerce767002019-10-23 13:30:24 -070022 "github.com/opencord/voltha-lib-go/v2/pkg/log"
Scott Baker2c1c4822019-10-16 11:02:41 -070023 v3Client "go.etcd.io/etcd/clientv3"
24 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
25 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
26 "sync"
27)
28
29// EtcdClient represents the Etcd KV store client
30type EtcdClient struct {
31 ectdAPI *v3Client.Client
32 leaderRev v3Client.Client
33 keyReservations map[string]*v3Client.LeaseID
34 watchedChannels sync.Map
35 writeLock sync.Mutex
36 lockToMutexMap map[string]*v3Concurrency.Mutex
37 lockToSessionMap map[string]*v3Concurrency.Session
38 lockToMutexLock sync.Mutex
39}
40
Thomas Lee S86fc9362019-10-31 11:35:19 +053041// Connection Timeout in Seconds
42var connTimeout int = 2
43
Scott Baker2c1c4822019-10-16 11:02:41 -070044// NewEtcdClient returns a new client for the Etcd KV store
45func NewEtcdClient(addr string, timeout int) (*EtcdClient, error) {
46 duration := GetDuration(timeout)
47
48 c, err := v3Client.New(v3Client.Config{
49 Endpoints: []string{addr},
50 DialTimeout: duration,
51 })
52 if err != nil {
53 log.Error(err)
54 return nil, err
55 }
56
57 reservations := make(map[string]*v3Client.LeaseID)
58 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
59 lockSessionMap := make(map[string]*v3Concurrency.Session)
60
61 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
62 lockToSessionMap: lockSessionMap}, nil
63}
64
65// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
66// it is assumed the connection is down or unreachable.
67func (c *EtcdClient) IsConnectionUp(timeout int) bool {
68 // Let's try to get a non existent key. If the connection is up then there will be no error returned.
69 if _, err := c.Get("non-existent-key", timeout); err != nil {
70 return false
71 }
72 return true
73}
74
75// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
76// wait for a response
sbarbari1e3e29c2019-11-05 10:06:50 -050077func (c *EtcdClient) List(key string, timeout int) (map[string]*KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -070078 duration := GetDuration(timeout)
79
80 ctx, cancel := context.WithTimeout(context.Background(), duration)
81
82 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
83 cancel()
84 if err != nil {
85 log.Error(err)
86 return nil, err
87 }
88 m := make(map[string]*KVPair)
89 for _, ev := range resp.Kvs {
90 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
91 }
92 return m, nil
93}
94
95// Get returns a key-value pair for a given key. Timeout defines how long the function will
96// wait for a response
sbarbari1e3e29c2019-11-05 10:06:50 -050097func (c *EtcdClient) Get(key string, timeout int) (*KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -070098 duration := GetDuration(timeout)
99
100 ctx, cancel := context.WithTimeout(context.Background(), duration)
101
102 resp, err := c.ectdAPI.Get(ctx, key)
103 cancel()
104 if err != nil {
105 log.Error(err)
106 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
sbarbari1e3e29c2019-11-05 10:06:50 -0500118func (c *EtcdClient) Put(key string, value interface{}, timeout int) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700119
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 duration := GetDuration(timeout)
128
129 ctx, cancel := context.WithTimeout(context.Background(), duration)
130
131 c.writeLock.Lock()
132 defer c.writeLock.Unlock()
133
134 var err error
135 // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make
136 // that KV key permanent instead of automatically removing it after a lease expiration
137 if leaseID, ok := c.keyReservations[key]; ok {
138 _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID))
139 } else {
140 _, err = c.ectdAPI.Put(ctx, key, val)
141 }
142 cancel()
143 if err != nil {
144 switch err {
145 case context.Canceled:
146 log.Warnw("context-cancelled", log.Fields{"error": err})
147 case context.DeadlineExceeded:
148 log.Warnw("context-deadline-exceeded", log.Fields{"error": err})
149 case v3rpcTypes.ErrEmptyKey:
150 log.Warnw("etcd-client-error", log.Fields{"error": err})
151 default:
152 log.Warnw("bad-endpoints", log.Fields{"error": err})
153 }
154 return err
155 }
156 return nil
157}
158
159// Delete removes a key from the KV store. Timeout defines how long the function will
160// wait for a response
sbarbari1e3e29c2019-11-05 10:06:50 -0500161func (c *EtcdClient) Delete(key string, timeout int) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700162
163 duration := GetDuration(timeout)
164
165 ctx, cancel := context.WithTimeout(context.Background(), duration)
166
167 defer cancel()
168
169 c.writeLock.Lock()
170 defer c.writeLock.Unlock()
171
172 // delete the key
173 if _, err := c.ectdAPI.Delete(ctx, key); err != nil {
174 log.Errorw("failed-to-delete-key", log.Fields{"key": key, "error": err})
175 return err
176 }
177 log.Debugw("key(s)-deleted", log.Fields{"key": key})
178 return nil
179}
180
181// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
182// the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL
183// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
184// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
185// then the value assigned to that key will be returned.
186func (c *EtcdClient) Reserve(key string, value interface{}, ttl int64) (interface{}, error) {
187 // Validate that we can convert value to a string as etcd API expects a string
188 var val string
189 var er error
190 if val, er = ToString(value); er != nil {
191 return nil, fmt.Errorf("unexpected-type%T", value)
192 }
193
Thomas Lee S86fc9362019-10-31 11:35:19 +0530194 duration := GetDuration(connTimeout)
195
Scott Baker2c1c4822019-10-16 11:02:41 -0700196 // Create a lease
Thomas Lee S86fc9362019-10-31 11:35:19 +0530197 ctx, cancel := context.WithTimeout(context.Background(), duration)
198 defer cancel()
199
200 resp, err := c.ectdAPI.Grant(ctx, ttl)
Scott Baker2c1c4822019-10-16 11:02:41 -0700201 if err != nil {
202 log.Error(err)
203 return nil, err
204 }
205 // Register the lease id
206 c.writeLock.Lock()
207 c.keyReservations[key] = &resp.ID
208 c.writeLock.Unlock()
209
210 // Revoke lease if reservation is not successful
211 reservationSuccessful := false
212 defer func() {
213 if !reservationSuccessful {
214 if err = c.ReleaseReservation(key); err != nil {
215 log.Error("cannot-release-lease")
216 }
217 }
218 }()
219
220 // Try to grap the Key with the above lease
221 c.ectdAPI.Txn(context.Background())
222 txn := c.ectdAPI.Txn(context.Background())
223 txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0))
224 txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID)))
225 txn = txn.Else(v3Client.OpGet(key))
226 result, er := txn.Commit()
227 if er != nil {
228 return nil, er
229 }
230
231 if !result.Succeeded {
232 // Verify whether we are already the owner of that Key
233 if len(result.Responses) > 0 &&
234 len(result.Responses[0].GetResponseRange().Kvs) > 0 {
235 kv := result.Responses[0].GetResponseRange().Kvs[0]
236 if string(kv.Value) == val {
237 reservationSuccessful = true
238 return value, nil
239 }
240 return kv.Value, nil
241 }
242 } else {
243 // Read the Key to ensure this is our Key
sbarbari1e3e29c2019-11-05 10:06:50 -0500244 m, err := c.Get(key, defaultKVGetTimeout)
Scott Baker2c1c4822019-10-16 11:02:41 -0700245 if err != nil {
246 return nil, err
247 }
248 if m != nil {
249 if m.Key == key && isEqual(m.Value, value) {
250 // My reservation is successful - register it. For now, support is only for 1 reservation per key
251 // per session.
252 reservationSuccessful = true
253 return value, nil
254 }
255 // My reservation has failed. Return the owner of that key
256 return m.Value, nil
257 }
258 }
259 return nil, nil
260}
261
262// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
263func (c *EtcdClient) ReleaseAllReservations() error {
264 c.writeLock.Lock()
265 defer c.writeLock.Unlock()
Thomas Lee S86fc9362019-10-31 11:35:19 +0530266 duration := GetDuration(connTimeout)
267 ctx, cancel := context.WithTimeout(context.Background(), duration)
268 defer cancel()
269
Scott Baker2c1c4822019-10-16 11:02:41 -0700270 for key, leaseID := range c.keyReservations {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530271 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700272 if err != nil {
273 log.Errorw("cannot-release-reservation", log.Fields{"key": key, "error": err})
274 return err
275 }
276 delete(c.keyReservations, key)
277 }
278 return nil
279}
280
281// ReleaseReservation releases reservation for a specific key.
282func (c *EtcdClient) ReleaseReservation(key string) error {
283 // Get the leaseid using the key
284 log.Debugw("Release-reservation", log.Fields{"key": key})
285 var ok bool
286 var leaseID *v3Client.LeaseID
287 c.writeLock.Lock()
288 defer c.writeLock.Unlock()
289 if leaseID, ok = c.keyReservations[key]; !ok {
290 return nil
291 }
Thomas Lee S86fc9362019-10-31 11:35:19 +0530292 duration := GetDuration(connTimeout)
293 ctx, cancel := context.WithTimeout(context.Background(), duration)
294 defer cancel()
295
Scott Baker2c1c4822019-10-16 11:02:41 -0700296 if leaseID != nil {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530297 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700298 if err != nil {
299 log.Error(err)
300 return err
301 }
302 delete(c.keyReservations, key)
303 }
304 return nil
305}
306
307// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
308// period specified when reserving the key
309func (c *EtcdClient) RenewReservation(key string) error {
310 // Get the leaseid using the key
311 var ok bool
312 var leaseID *v3Client.LeaseID
313 c.writeLock.Lock()
314 defer c.writeLock.Unlock()
315 if leaseID, ok = c.keyReservations[key]; !ok {
316 return errors.New("key-not-reserved")
317 }
Thomas Lee S86fc9362019-10-31 11:35:19 +0530318 duration := GetDuration(connTimeout)
319 ctx, cancel := context.WithTimeout(context.Background(), duration)
320 defer cancel()
Scott Baker2c1c4822019-10-16 11:02:41 -0700321
322 if leaseID != nil {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530323 _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700324 if err != nil {
325 log.Errorw("lease-may-have-expired", log.Fields{"error": err})
326 return err
327 }
328 } else {
329 return errors.New("lease-expired")
330 }
331 return nil
332}
333
334// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
335// listen to receive Events.
336func (c *EtcdClient) Watch(key string) chan *Event {
337 w := v3Client.NewWatcher(c.ectdAPI)
338 ctx, cancel := context.WithCancel(context.Background())
339 channel := w.Watch(ctx, key)
340
341 // Create a new channel
342 ch := make(chan *Event, maxClientChannelBufferSize)
343
344 // Keep track of the created channels so they can be closed when required
345 channelMap := make(map[chan *Event]v3Client.Watcher)
346 channelMap[ch] = w
347
348 channelMaps := c.addChannelMap(key, channelMap)
349
350 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
351 // json format.
352 log.Debugw("watched-channels", log.Fields{"len": len(channelMaps)})
353 // Launch a go routine to listen for updates
354 go c.listenForKeyChange(channel, ch, cancel)
355
356 return ch
357
358}
359
360func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
361 var channels interface{}
362 var exists bool
363
364 if channels, exists = c.watchedChannels.Load(key); exists {
365 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
366 } else {
367 channels = []map[chan *Event]v3Client.Watcher{channelMap}
368 }
369 c.watchedChannels.Store(key, channels)
370
371 return channels.([]map[chan *Event]v3Client.Watcher)
372}
373
374func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
375 var channels interface{}
376 var exists bool
377
378 if channels, exists = c.watchedChannels.Load(key); exists {
379 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
380 c.watchedChannels.Store(key, channels)
381 }
382
383 return channels.([]map[chan *Event]v3Client.Watcher)
384}
385
386func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
387 var channels interface{}
388 var exists bool
389
390 channels, exists = c.watchedChannels.Load(key)
391
392 if channels == nil {
393 return nil, exists
394 }
395
396 return channels.([]map[chan *Event]v3Client.Watcher), exists
397}
398
399// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
400// may be multiple listeners on the same key. The previously created channel serves as a key
401func (c *EtcdClient) CloseWatch(key string, ch chan *Event) {
402 // Get the array of channels mapping
403 var watchedChannels []map[chan *Event]v3Client.Watcher
404 var ok bool
405 c.writeLock.Lock()
406 defer c.writeLock.Unlock()
407
408 if watchedChannels, ok = c.getChannelMaps(key); !ok {
409 log.Warnw("key-has-no-watched-channels", log.Fields{"key": key})
410 return
411 }
412 // Look for the channels
413 var pos = -1
414 for i, chMap := range watchedChannels {
415 if t, ok := chMap[ch]; ok {
416 log.Debug("channel-found")
417 // Close the etcd watcher before the client channel. This should close the etcd channel as well
418 if err := t.Close(); err != nil {
419 log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
420 }
421 pos = i
422 break
423 }
424 }
425
426 channelMaps, _ := c.getChannelMaps(key)
427 // Remove that entry if present
428 if pos >= 0 {
429 channelMaps = c.removeChannelMap(key, pos)
430 }
431 log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
432}
433
434func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
435 log.Debug("start-listening-on-channel ...")
436 defer cancel()
437 defer close(ch)
438 for resp := range channel {
439 for _, ev := range resp.Events {
440 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
441 }
442 }
443 log.Debug("stop-listening-on-channel ...")
444}
445
446func getEventType(event *v3Client.Event) int {
447 switch event.Type {
448 case v3Client.EventTypePut:
449 return PUT
450 case v3Client.EventTypeDelete:
451 return DELETE
452 }
453 return UNKNOWN
454}
455
456// Close closes the KV store client
457func (c *EtcdClient) Close() {
458 c.writeLock.Lock()
459 defer c.writeLock.Unlock()
460 if err := c.ectdAPI.Close(); err != nil {
461 log.Errorw("error-closing-client", log.Fields{"error": err})
462 }
463}
464
465func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
466 c.lockToMutexLock.Lock()
467 defer c.lockToMutexLock.Unlock()
468 c.lockToMutexMap[lockName] = lock
469 c.lockToSessionMap[lockName] = session
470}
471
472func (c *EtcdClient) deleteLockName(lockName string) {
473 c.lockToMutexLock.Lock()
474 defer c.lockToMutexLock.Unlock()
475 delete(c.lockToMutexMap, lockName)
476 delete(c.lockToSessionMap, lockName)
477}
478
479func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
480 c.lockToMutexLock.Lock()
481 defer c.lockToMutexLock.Unlock()
482 var lock *v3Concurrency.Mutex
483 var session *v3Concurrency.Session
484 if l, exist := c.lockToMutexMap[lockName]; exist {
485 lock = l
486 }
487 if s, exist := c.lockToSessionMap[lockName]; exist {
488 session = s
489 }
490 return lock, session
491}
492
493func (c *EtcdClient) AcquireLock(lockName string, timeout int) error {
494 duration := GetDuration(timeout)
495 ctx, cancel := context.WithTimeout(context.Background(), duration)
496 defer cancel()
497 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
498 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
499 if err := mu.Lock(context.Background()); err != nil {
500 cancel()
501 return err
502 }
503 c.addLockName(lockName, mu, session)
504 return nil
505}
506
507func (c *EtcdClient) ReleaseLock(lockName string) error {
508 lock, session := c.getLock(lockName)
509 var err error
510 if lock != nil {
511 if e := lock.Unlock(context.Background()); e != nil {
512 err = e
513 }
514 }
515 if session != nil {
516 if e := session.Close(); e != nil {
517 err = e
518 }
519 }
520 c.deleteLockName(lockName)
521
522 return err
523}