blob: 7f6940a750ebe67502915d7e9f1560778a2e6e3d [file] [log] [blame]
William Kurkianea869482019-04-09 15:16:11 -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 */
16package kvstore
17
18import (
19 "context"
20 "errors"
21 "fmt"
22 "github.com/opencord/voltha-go/common/log"
23 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
41// NewEtcdClient returns a new client for the Etcd KV store
42func NewEtcdClient(addr string, timeout int) (*EtcdClient, error) {
43 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 }
53
54 reservations := make(map[string]*v3Client.LeaseID)
55 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
56 lockSessionMap := make(map[string]*v3Concurrency.Session)
57
58 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
59 lockToSessionMap: lockSessionMap}, nil
60}
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
64func (c *EtcdClient) List(key string, timeout int, lock ...bool) (map[string]*KVPair, error) {
65 duration := GetDuration(timeout)
66
67 ctx, cancel := context.WithTimeout(context.Background(), duration)
68
William Kurkianea869482019-04-09 15:16:11 -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 {
Manikkaraj kb1d51442019-07-23 10:41:02 -040077 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
William Kurkianea869482019-04-09 15:16:11 -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
84func (c *EtcdClient) Get(key string, timeout int, lock ...bool) (*KVPair, error) {
85 duration := GetDuration(timeout)
86
87 ctx, cancel := context.WithTimeout(context.Background(), duration)
88
William Kurkianea869482019-04-09 15:16:11 -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
Manikkaraj kb1d51442019-07-23 10:41:02 -040097 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
William Kurkianea869482019-04-09 15:16:11 -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
105func (c *EtcdClient) Put(key string, value interface{}, timeout int, lock ...bool) error {
106
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)
117
William Kurkianea869482019-04-09 15:16:11 -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:
125 log.Warnw("context-cancelled", log.Fields{"error": err})
126 case context.DeadlineExceeded:
127 log.Warnw("context-deadline-exceeded", log.Fields{"error": err})
128 case v3rpcTypes.ErrEmptyKey:
129 log.Warnw("etcd-client-error", log.Fields{"error": err})
130 default:
131 log.Warnw("bad-endpoints", log.Fields{"error": err})
132 }
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
140func (c *EtcdClient) Delete(key string, timeout int, lock ...bool) error {
141
142 duration := GetDuration(timeout)
143
144 ctx, cancel := context.WithTimeout(context.Background(), duration)
145
William Kurkianea869482019-04-09 15:16:11 -0400146 defer cancel()
147
148 c.writeLock.Lock()
149 defer c.writeLock.Unlock()
150
151 // delete the keys
152 if _, err := c.ectdAPI.Delete(ctx, key, v3Client.WithPrefix()); err != nil {
153 log.Errorw("failed-to-delete-key", log.Fields{"key": key, "error": err})
154 return err
155 }
156 log.Debugw("key(s)-deleted", log.Fields{"key": key})
157 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 {
189 log.Error("cannot-release-lease")
190 }
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
218 m, err := c.Get(key, defaultKVGetTimeout, false)
219 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 {
243 log.Errorw("cannot-release-reservation", log.Fields{"key": key, "error": err})
244 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
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400254 log.Debugw("Release-reservation", log.Fields{"key": key})
William Kurkianea869482019-04-09 15:16:11 -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 {
260 return nil
261 }
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 {
288 log.Errorw("lease-may-have-expired", log.Fields{"error": err})
289 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()
311
312 channelMaps := c.addChannelMap(key, channelMap)
313
Manikkaraj kb1d51442019-07-23 10:41:02 -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)})
William Kurkianea869482019-04-09 15:16:11 -0400317 // Launch a go routine to listen for updates
318 go c.listenForKeyChange(channel, ch)
319
320 return ch
321
322}
323
324func (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
356 if channels == nil {
357 return nil, exists
358 }
359
360 return channels.([]map[chan *Event]v3Client.Watcher), exists
361}
362
363// 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
372 if watchedChannels, ok = c.getChannelMaps(key); !ok {
373 log.Warnw("key-has-no-watched-channels", log.Fields{"key": key})
374 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 {
383 log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
384 }
385 close(ch)
386 pos = i
387 break
388 }
389 }
390
391 channelMaps, _ := c.getChannelMaps(key)
392 // Remove that entry if present
393 if pos >= 0 {
394 channelMaps = c.removeChannelMap(key, pos)
395 }
396 log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
397}
398
399func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event) {
400 log.Debug("start-listening-on-channel ...")
401 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)
Manikkaraj kb1d51442019-07-23 10:41:02 -0400404 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
William Kurkianea869482019-04-09 15:16:11 -0400405 }
406 }
407 log.Debug("stop-listening-on-channel ...")
408}
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 {
425 log.Errorw("error-closing-client", log.Fields{"error": err})
426 }
427}
428
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
457func (c *EtcdClient) AcquireLock(lockName string, timeout int) error {
458 duration := GetDuration(timeout)
459 ctx, cancel := context.WithTimeout(context.Background(), duration)
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400460 defer cancel()
William Kurkianea869482019-04-09 15:16:11 -0400461 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
462 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
463 if err := mu.Lock(context.Background()); err != nil {
Matt Jeanneret384d8c92019-05-06 14:27:31 -0400464 cancel()
William Kurkianea869482019-04-09 15:16:11 -0400465 return err
466 }
467 c.addLockName(lockName, mu, session)
William Kurkianea869482019-04-09 15:16:11 -0400468 return nil
469}
470
471func (c *EtcdClient) ReleaseLock(lockName string) error {
472 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
487}