blob: 4f6f90bdf2097a02174729086e4064819674e511 [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
314 log.Debugw("watched-channels", log.Fields{"channels": channelMaps})
khenaidoocfee5f42018-07-19 22:47:38 -0400315 // Launch a go routine to listen for updates
316 go c.listenForKeyChange(channel, ch)
317
318 return ch
319
320}
321
Stephane Barbariec53a2752019-03-08 17:50:10 -0500322func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
323 var channels interface{}
324 var exists bool
325
326 if channels, exists = c.watchedChannels.Load(key); exists {
327 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
328 } else {
329 channels = []map[chan *Event]v3Client.Watcher{channelMap}
330 }
331 c.watchedChannels.Store(key, channels)
332
333 return channels.([]map[chan *Event]v3Client.Watcher)
334}
335
336func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
337 var channels interface{}
338 var exists bool
339
340 if channels, exists = c.watchedChannels.Load(key); exists {
341 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
342 c.watchedChannels.Store(key, channels)
343 }
344
345 return channels.([]map[chan *Event]v3Client.Watcher)
346}
347
348func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
349 var channels interface{}
350 var exists bool
351
352 channels, exists = c.watchedChannels.Load(key)
353
khenaidoodaefa372019-03-15 14:04:25 -0400354 if channels == nil {
355 return nil, exists
356 }
357
Stephane Barbariec53a2752019-03-08 17:50:10 -0500358 return channels.([]map[chan *Event]v3Client.Watcher), exists
359}
360
khenaidoocfee5f42018-07-19 22:47:38 -0400361// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
362// may be multiple listeners on the same key. The previously created channel serves as a key
363func (c *EtcdClient) CloseWatch(key string, ch chan *Event) {
364 // Get the array of channels mapping
365 var watchedChannels []map[chan *Event]v3Client.Watcher
366 var ok bool
367 c.writeLock.Lock()
368 defer c.writeLock.Unlock()
369
Stephane Barbariec53a2752019-03-08 17:50:10 -0500370 if watchedChannels, ok = c.getChannelMaps(key); !ok {
khenaidoo5c11af72018-07-20 17:21:05 -0400371 log.Warnw("key-has-no-watched-channels", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400372 return
373 }
374 // Look for the channels
375 var pos = -1
376 for i, chMap := range watchedChannels {
377 if t, ok := chMap[ch]; ok {
378 log.Debug("channel-found")
379 // Close the etcd watcher before the client channel. This should close the etcd channel as well
380 if err := t.Close(); err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400381 log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400382 }
383 close(ch)
384 pos = i
385 break
386 }
387 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500388
389 channelMaps, _ := c.getChannelMaps(key)
khenaidoocfee5f42018-07-19 22:47:38 -0400390 // Remove that entry if present
391 if pos >= 0 {
Stephane Barbariec53a2752019-03-08 17:50:10 -0500392 channelMaps = c.removeChannelMap(key, pos)
khenaidoocfee5f42018-07-19 22:47:38 -0400393 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500394 log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
khenaidoocfee5f42018-07-19 22:47:38 -0400395}
396
397func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event) {
khenaidoo8f474192019-04-03 17:20:44 -0400398 log.Debug("start-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400399 for resp := range channel {
400 for _, ev := range resp.Events {
401 //log.Debugf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value)
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400402 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
khenaidoocfee5f42018-07-19 22:47:38 -0400403 }
404 }
khenaidoo8f474192019-04-03 17:20:44 -0400405 log.Debug("stop-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400406}
407
408func getEventType(event *v3Client.Event) int {
409 switch event.Type {
410 case v3Client.EventTypePut:
411 return PUT
412 case v3Client.EventTypeDelete:
413 return DELETE
414 }
415 return UNKNOWN
416}
417
418// Close closes the KV store client
419func (c *EtcdClient) Close() {
420 c.writeLock.Lock()
421 defer c.writeLock.Unlock()
422 if err := c.ectdAPI.Close(); err != nil {
khenaidoo5c11af72018-07-20 17:21:05 -0400423 log.Errorw("error-closing-client", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400424 }
425}
khenaidoobdcb8e02019-03-06 16:28:56 -0500426
427func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
428 c.lockToMutexLock.Lock()
429 defer c.lockToMutexLock.Unlock()
430 c.lockToMutexMap[lockName] = lock
431 c.lockToSessionMap[lockName] = session
432}
433
434func (c *EtcdClient) deleteLockName(lockName string) {
435 c.lockToMutexLock.Lock()
436 defer c.lockToMutexLock.Unlock()
437 delete(c.lockToMutexMap, lockName)
438 delete(c.lockToSessionMap, lockName)
439}
440
441func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
442 c.lockToMutexLock.Lock()
443 defer c.lockToMutexLock.Unlock()
444 var lock *v3Concurrency.Mutex
445 var session *v3Concurrency.Session
446 if l, exist := c.lockToMutexMap[lockName]; exist {
447 lock = l
448 }
449 if s, exist := c.lockToSessionMap[lockName]; exist {
450 session = s
451 }
452 return lock, session
453}
454
Stephane Barbariec53a2752019-03-08 17:50:10 -0500455func (c *EtcdClient) AcquireLock(lockName string, timeout int) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500456 duration := GetDuration(timeout)
457 ctx, cancel := context.WithTimeout(context.Background(), duration)
Kent Hagerman0ab4cb22019-04-24 13:13:35 -0400458 defer cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500459 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
Stephane Barbariec53a2752019-03-08 17:50:10 -0500460 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
khenaidoobdcb8e02019-03-06 16:28:56 -0500461 if err := mu.Lock(context.Background()); err != nil {
khenaidoo2c6a0992019-04-29 13:46:56 -0400462 cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500463 return err
464 }
465 c.addLockName(lockName, mu, session)
khenaidoobdcb8e02019-03-06 16:28:56 -0500466 return nil
467}
468
Stephane Barbariec53a2752019-03-08 17:50:10 -0500469func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500470 lock, session := c.getLock(lockName)
471 var err error
472 if lock != nil {
473 if e := lock.Unlock(context.Background()); e != nil {
474 err = e
475 }
476 }
477 if session != nil {
478 if e := session.Close(); e != nil {
479 err = e
480 }
481 }
482 c.deleteLockName(lockName)
483
484 return err
Stephane Barbariec53a2752019-03-08 17:50:10 -0500485}