blob: 7f6940a750ebe67502915d7e9f1560778a2e6e3d [file] [log] [blame]
khenaidoobf6e7bb2018-08-14 22:27:29 -04001/*
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 */
khenaidoocfee5f42018-07-19 22:47:38 -040016package kvstore
17
18import (
khenaidoocfee5f42018-07-19 22:47:38 -040019 "context"
20 "errors"
khenaidoocfee5f42018-07-19 22:47:38 -040021 "fmt"
Stephane Barbarie260a5632019-02-26 16:12:49 -050022 "github.com/opencord/voltha-go/common/log"
khenaidoob9203542018-09-17 22:56:37 -040023 v3Client "go.etcd.io/etcd/clientv3"
Stephane Barbarie260a5632019-02-26 16:12:49 -050024 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
khenaidoob9203542018-09-17 22:56:37 -040025 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
khenaidoo5c11af72018-07-20 17:21:05 -040026 "sync"
khenaidoocfee5f42018-07-19 22:47:38 -040027)
28
29// EtcdClient represents the Etcd KV store client
30type EtcdClient struct {
Stephane Barbariec53a2752019-03-08 17:50:10 -050031 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
khenaidoobdcb8e02019-03-06 16:28:56 -050037 lockToSessionMap map[string]*v3Concurrency.Session
Stephane Barbariec53a2752019-03-08 17:50:10 -050038 lockToMutexLock sync.Mutex
khenaidoocfee5f42018-07-19 22:47:38 -040039}
40
41// NewEtcdClient returns a new client for the Etcd KV store
42func NewEtcdClient(addr string, timeout int) (*EtcdClient, error) {
khenaidoocfee5f42018-07-19 22:47:38 -040043 duration := GetDuration(timeout)
44
45 c, err := v3Client.New(v3Client.Config{
46 Endpoints: []string{addr},
47 DialTimeout: duration,
48 })
49 if err != nil {
50 log.Error(err)
51 return nil, err
52 }
Stephane Barbariec53a2752019-03-08 17:50:10 -050053
khenaidoocfee5f42018-07-19 22:47:38 -040054 reservations := make(map[string]*v3Client.LeaseID)
khenaidoobdcb8e02019-03-06 16:28:56 -050055 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
56 lockSessionMap := make(map[string]*v3Concurrency.Session)
Stephane Barbarie260a5632019-02-26 16:12:49 -050057
Stephane Barbariec53a2752019-03-08 17:50:10 -050058 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
59 lockToSessionMap: lockSessionMap}, nil
khenaidoocfee5f42018-07-19 22:47:38 -040060}
61
62// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
63// wait for a response
Stephane Barbarie260a5632019-02-26 16:12:49 -050064func (c *EtcdClient) List(key string, timeout int, lock ...bool) (map[string]*KVPair, error) {
khenaidoocfee5f42018-07-19 22:47:38 -040065 duration := GetDuration(timeout)
66
67 ctx, cancel := context.WithTimeout(context.Background(), duration)
Stephane Barbarie260a5632019-02-26 16:12:49 -050068
khenaidoocfee5f42018-07-19 22:47:38 -040069 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
70 cancel()
71 if err != nil {
72 log.Error(err)
73 return nil, err
74 }
75 m := make(map[string]*KVPair)
76 for _, ev := range resp.Kvs {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040077 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
khenaidoocfee5f42018-07-19 22:47:38 -040078 }
79 return m, nil
80}
81
82// Get returns a key-value pair for a given key. Timeout defines how long the function will
83// wait for a response
Stephane Barbarie260a5632019-02-26 16:12:49 -050084func (c *EtcdClient) Get(key string, timeout int, lock ...bool) (*KVPair, error) {
khenaidoocfee5f42018-07-19 22:47:38 -040085 duration := GetDuration(timeout)
86
87 ctx, cancel := context.WithTimeout(context.Background(), duration)
Stephane Barbarie260a5632019-02-26 16:12:49 -050088
khenaidoocfee5f42018-07-19 22:47:38 -040089 resp, err := c.ectdAPI.Get(ctx, key)
90 cancel()
91 if err != nil {
92 log.Error(err)
93 return nil, err
94 }
95 for _, ev := range resp.Kvs {
96 // Only one value is returned
Stephane Barbarieef6650d2019-07-18 12:15:09 -040097 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
khenaidoocfee5f42018-07-19 22:47:38 -040098 }
99 return nil, nil
100}
101
102// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
103// accepts only a string as a value for a put operation. Timeout defines how long the function will
104// wait for a response
Stephane Barbarie260a5632019-02-26 16:12:49 -0500105func (c *EtcdClient) Put(key string, value interface{}, timeout int, lock ...bool) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400106
107 // Validate that we can convert value to a string as etcd API expects a string
108 var val string
109 var er error
110 if val, er = ToString(value); er != nil {
111 return fmt.Errorf("unexpected-type-%T", value)
112 }
113
114 duration := GetDuration(timeout)
115
116 ctx, cancel := context.WithTimeout(context.Background(), duration)
Stephane Barbarie260a5632019-02-26 16:12:49 -0500117
khenaidoocfee5f42018-07-19 22:47:38 -0400118 c.writeLock.Lock()
119 defer c.writeLock.Unlock()
120 _, err := c.ectdAPI.Put(ctx, key, val)
121 cancel()
122 if err != nil {
123 switch err {
124 case context.Canceled:
khenaidoo5c11af72018-07-20 17:21:05 -0400125 log.Warnw("context-cancelled", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400126 case context.DeadlineExceeded:
khenaidoo5c11af72018-07-20 17:21:05 -0400127 log.Warnw("context-deadline-exceeded", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400128 case v3rpcTypes.ErrEmptyKey:
khenaidoo5c11af72018-07-20 17:21:05 -0400129 log.Warnw("etcd-client-error", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400130 default:
khenaidoo5c11af72018-07-20 17:21:05 -0400131 log.Warnw("bad-endpoints", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400132 }
133 return err
134 }
135 return nil
136}
137
138// Delete removes a key from the KV store. Timeout defines how long the function will
139// wait for a response
Stephane Barbarie260a5632019-02-26 16:12:49 -0500140func (c *EtcdClient) Delete(key string, timeout int, lock ...bool) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400141
142 duration := GetDuration(timeout)
143
144 ctx, cancel := context.WithTimeout(context.Background(), duration)
Stephane Barbarie260a5632019-02-26 16:12:49 -0500145
khenaidoocfee5f42018-07-19 22:47:38 -0400146 defer cancel()
147
148 c.writeLock.Lock()
149 defer c.writeLock.Unlock()
150
khenaidoocfee5f42018-07-19 22:47:38 -0400151 // delete the keys
khenaidoo1ce37ad2019-03-24 22:07:24 -0400152 if _, err := c.ectdAPI.Delete(ctx, key, v3Client.WithPrefix()); err != nil {
153 log.Errorw("failed-to-delete-key", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400154 return err
155 }
khenaidoo1ce37ad2019-03-24 22:07:24 -0400156 log.Debugw("key(s)-deleted", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400157 return nil
158}
159
160// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
161// the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL
162// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
163// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
164// then the value assigned to that key will be returned.
165func (c *EtcdClient) Reserve(key string, value interface{}, ttl int64) (interface{}, error) {
166 // Validate that we can convert value to a string as etcd API expects a string
167 var val string
168 var er error
169 if val, er = ToString(value); er != nil {
170 return nil, fmt.Errorf("unexpected-type%T", value)
171 }
172
173 // Create a lease
174 resp, err := c.ectdAPI.Grant(context.Background(), ttl)
175 if err != nil {
176 log.Error(err)
177 return nil, err
178 }
179 // Register the lease id
180 c.writeLock.Lock()
181 c.keyReservations[key] = &resp.ID
182 c.writeLock.Unlock()
183
184 // Revoke lease if reservation is not successful
185 reservationSuccessful := false
186 defer func() {
187 if !reservationSuccessful {
188 if err = c.ReleaseReservation(key); err != nil {
khenaidoo1ce37ad2019-03-24 22:07:24 -0400189 log.Error("cannot-release-lease")
khenaidoocfee5f42018-07-19 22:47:38 -0400190 }
191 }
192 }()
193
194 // Try to grap the Key with the above lease
195 c.ectdAPI.Txn(context.Background())
196 txn := c.ectdAPI.Txn(context.Background())
197 txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0))
198 txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID)))
199 txn = txn.Else(v3Client.OpGet(key))
200 result, er := txn.Commit()
201 if er != nil {
202 return nil, er
203 }
204
205 if !result.Succeeded {
206 // Verify whether we are already the owner of that Key
207 if len(result.Responses) > 0 &&
208 len(result.Responses[0].GetResponseRange().Kvs) > 0 {
209 kv := result.Responses[0].GetResponseRange().Kvs[0]
210 if string(kv.Value) == val {
211 reservationSuccessful = true
212 return value, nil
213 }
214 return kv.Value, nil
215 }
216 } else {
217 // Read the Key to ensure this is our Key
Stephane Barbarie260a5632019-02-26 16:12:49 -0500218 m, err := c.Get(key, defaultKVGetTimeout, false)
khenaidoocfee5f42018-07-19 22:47:38 -0400219 if err != nil {
220 return nil, err
221 }
222 if m != nil {
223 if m.Key == key && isEqual(m.Value, value) {
224 // My reservation is successful - register it. For now, support is only for 1 reservation per key
225 // per session.
226 reservationSuccessful = true
227 return value, nil
228 }
229 // My reservation has failed. Return the owner of that key
230 return m.Value, nil
231 }
232 }
233 return nil, nil
234}
235
236// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
237func (c *EtcdClient) ReleaseAllReservations() error {
238 c.writeLock.Lock()
239 defer c.writeLock.Unlock()
240 for key, leaseID := range c.keyReservations {
241 _, err := c.ectdAPI.Revoke(context.Background(), *leaseID)
242 if err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400243 log.Errorw("cannot-release-reservation", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400244 return err
245 }
246 delete(c.keyReservations, key)
247 }
248 return nil
249}
250
251// ReleaseReservation releases reservation for a specific key.
252func (c *EtcdClient) ReleaseReservation(key string) error {
253 // Get the leaseid using the key
khenaidoo2c6a0992019-04-29 13:46:56 -0400254 log.Debugw("Release-reservation", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400255 var ok bool
256 var leaseID *v3Client.LeaseID
257 c.writeLock.Lock()
258 defer c.writeLock.Unlock()
259 if leaseID, ok = c.keyReservations[key]; !ok {
khenaidoofc1314d2019-03-14 09:34:21 -0400260 return nil
khenaidoocfee5f42018-07-19 22:47:38 -0400261 }
262 if leaseID != nil {
263 _, err := c.ectdAPI.Revoke(context.Background(), *leaseID)
264 if err != nil {
265 log.Error(err)
266 return err
267 }
268 delete(c.keyReservations, key)
269 }
270 return nil
271}
272
273// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
274// period specified when reserving the key
275func (c *EtcdClient) RenewReservation(key string) error {
276 // Get the leaseid using the key
277 var ok bool
278 var leaseID *v3Client.LeaseID
279 c.writeLock.Lock()
280 defer c.writeLock.Unlock()
281 if leaseID, ok = c.keyReservations[key]; !ok {
282 return errors.New("key-not-reserved")
283 }
284
285 if leaseID != nil {
286 _, err := c.ectdAPI.KeepAliveOnce(context.Background(), *leaseID)
287 if err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400288 log.Errorw("lease-may-have-expired", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400289 return err
290 }
291 } else {
292 return errors.New("lease-expired")
293 }
294 return nil
295}
296
297// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
298// listen to receive Events.
299func (c *EtcdClient) Watch(key string) chan *Event {
300 w := v3Client.NewWatcher(c.ectdAPI)
301 channel := w.Watch(context.Background(), key, v3Client.WithPrefix())
302
303 // Create a new channel
304 ch := make(chan *Event, maxClientChannelBufferSize)
305
306 // Keep track of the created channels so they can be closed when required
307 channelMap := make(map[chan *Event]v3Client.Watcher)
308 channelMap[ch] = w
309 //c.writeLock.Lock()
310 //defer c.writeLock.Unlock()
khenaidoocfee5f42018-07-19 22:47:38 -0400311
Stephane Barbariec53a2752019-03-08 17:50:10 -0500312 channelMaps := c.addChannelMap(key, channelMap)
313
khenaidooba6b6c42019-08-02 09:11:56 -0400314 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
315 // json format.
316 log.Debugw("watched-channels", log.Fields{"len": len(channelMaps)})
khenaidoocfee5f42018-07-19 22:47:38 -0400317 // Launch a go routine to listen for updates
318 go c.listenForKeyChange(channel, ch)
319
320 return ch
321
322}
323
Stephane Barbariec53a2752019-03-08 17:50:10 -0500324func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
325 var channels interface{}
326 var exists bool
327
328 if channels, exists = c.watchedChannels.Load(key); exists {
329 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
330 } else {
331 channels = []map[chan *Event]v3Client.Watcher{channelMap}
332 }
333 c.watchedChannels.Store(key, channels)
334
335 return channels.([]map[chan *Event]v3Client.Watcher)
336}
337
338func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
339 var channels interface{}
340 var exists bool
341
342 if channels, exists = c.watchedChannels.Load(key); exists {
343 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
344 c.watchedChannels.Store(key, channels)
345 }
346
347 return channels.([]map[chan *Event]v3Client.Watcher)
348}
349
350func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
351 var channels interface{}
352 var exists bool
353
354 channels, exists = c.watchedChannels.Load(key)
355
khenaidoodaefa372019-03-15 14:04:25 -0400356 if channels == nil {
357 return nil, exists
358 }
359
Stephane Barbariec53a2752019-03-08 17:50:10 -0500360 return channels.([]map[chan *Event]v3Client.Watcher), exists
361}
362
khenaidoocfee5f42018-07-19 22:47:38 -0400363// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
364// may be multiple listeners on the same key. The previously created channel serves as a key
365func (c *EtcdClient) CloseWatch(key string, ch chan *Event) {
366 // Get the array of channels mapping
367 var watchedChannels []map[chan *Event]v3Client.Watcher
368 var ok bool
369 c.writeLock.Lock()
370 defer c.writeLock.Unlock()
371
Stephane Barbariec53a2752019-03-08 17:50:10 -0500372 if watchedChannels, ok = c.getChannelMaps(key); !ok {
khenaidoo5c11af72018-07-20 17:21:05 -0400373 log.Warnw("key-has-no-watched-channels", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400374 return
375 }
376 // Look for the channels
377 var pos = -1
378 for i, chMap := range watchedChannels {
379 if t, ok := chMap[ch]; ok {
380 log.Debug("channel-found")
381 // Close the etcd watcher before the client channel. This should close the etcd channel as well
382 if err := t.Close(); err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400383 log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400384 }
385 close(ch)
386 pos = i
387 break
388 }
389 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500390
391 channelMaps, _ := c.getChannelMaps(key)
khenaidoocfee5f42018-07-19 22:47:38 -0400392 // Remove that entry if present
393 if pos >= 0 {
Stephane Barbariec53a2752019-03-08 17:50:10 -0500394 channelMaps = c.removeChannelMap(key, pos)
khenaidoocfee5f42018-07-19 22:47:38 -0400395 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500396 log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
khenaidoocfee5f42018-07-19 22:47:38 -0400397}
398
399func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event) {
khenaidoo8f474192019-04-03 17:20:44 -0400400 log.Debug("start-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400401 for resp := range channel {
402 for _, ev := range resp.Events {
403 //log.Debugf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400404 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
khenaidoocfee5f42018-07-19 22:47:38 -0400405 }
406 }
khenaidoo8f474192019-04-03 17:20:44 -0400407 log.Debug("stop-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400408}
409
410func getEventType(event *v3Client.Event) int {
411 switch event.Type {
412 case v3Client.EventTypePut:
413 return PUT
414 case v3Client.EventTypeDelete:
415 return DELETE
416 }
417 return UNKNOWN
418}
419
420// Close closes the KV store client
421func (c *EtcdClient) Close() {
422 c.writeLock.Lock()
423 defer c.writeLock.Unlock()
424 if err := c.ectdAPI.Close(); err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400425 log.Errorw("error-closing-client", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400426 }
427}
khenaidoobdcb8e02019-03-06 16:28:56 -0500428
429func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
430 c.lockToMutexLock.Lock()
431 defer c.lockToMutexLock.Unlock()
432 c.lockToMutexMap[lockName] = lock
433 c.lockToSessionMap[lockName] = session
434}
435
436func (c *EtcdClient) deleteLockName(lockName string) {
437 c.lockToMutexLock.Lock()
438 defer c.lockToMutexLock.Unlock()
439 delete(c.lockToMutexMap, lockName)
440 delete(c.lockToSessionMap, lockName)
441}
442
443func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
444 c.lockToMutexLock.Lock()
445 defer c.lockToMutexLock.Unlock()
446 var lock *v3Concurrency.Mutex
447 var session *v3Concurrency.Session
448 if l, exist := c.lockToMutexMap[lockName]; exist {
449 lock = l
450 }
451 if s, exist := c.lockToSessionMap[lockName]; exist {
452 session = s
453 }
454 return lock, session
455}
456
Stephane Barbariec53a2752019-03-08 17:50:10 -0500457func (c *EtcdClient) AcquireLock(lockName string, timeout int) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500458 duration := GetDuration(timeout)
459 ctx, cancel := context.WithTimeout(context.Background(), duration)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400460 defer cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500461 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
Stephane Barbariec53a2752019-03-08 17:50:10 -0500462 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
khenaidoobdcb8e02019-03-06 16:28:56 -0500463 if err := mu.Lock(context.Background()); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400464 cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500465 return err
466 }
467 c.addLockName(lockName, mu, session)
khenaidoobdcb8e02019-03-06 16:28:56 -0500468 return nil
469}
470
Stephane Barbariec53a2752019-03-08 17:50:10 -0500471func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500472 lock, session := c.getLock(lockName)
473 var err error
474 if lock != nil {
475 if e := lock.Unlock(context.Background()); e != nil {
476 err = e
477 }
478 }
479 if session != nil {
480 if e := session.Close(); e != nil {
481 err = e
482 }
483 }
484 c.deleteLockName(lockName)
485
486 return err
Stephane Barbariec53a2752019-03-08 17:50:10 -0500487}