blob: 98f055957211483f34823f968a2e5ab5b49f9b91 [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"
npujar5bf737f2020-01-16 19:35:25 +053022 "sync"
Neha Sharma130ac6d2020-04-08 08:46:32 +000023 "time"
npujar5bf737f2020-01-16 19:35:25 +053024
Girish Gowdra89c985b2020-10-14 15:02:09 -070025 "github.com/opencord/voltha-lib-go/v4/pkg/log"
Scott Baker2c1c4822019-10-16 11:02:41 -070026 v3Client "go.etcd.io/etcd/clientv3"
David K. Bainbridgebc381072021-03-19 20:56:04 +000027
Scott Baker2c1c4822019-10-16 11:02:41 -070028 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
29 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
Scott Baker2c1c4822019-10-16 11:02:41 -070030)
31
32// EtcdClient represents the Etcd KV store client
33type EtcdClient struct {
Matteo Scandoloed128822020-02-10 15:52:35 -080034 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
Scott Baker2c1c4822019-10-16 11:02:41 -070041}
42
David K. Bainbridgebc381072021-03-19 20:56:04 +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)
Scott Baker2c1c4822019-10-16 11:02:41 -070047 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +000048 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -070049 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. Bainbridgebc381072021-03-19 20:56:04 +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
Scott Baker2c1c4822019-10-16 11:02:41 -070072// 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.
npujar5bf737f2020-01-16 19:35:25 +053074func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
Scott Baker2c1c4822019-10-16 11:02:41 -070075 // Let's try to get a non existent key. If the connection is up then there will be no error returned.
npujar5bf737f2020-01-16 19:35:25 +053076 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -070077 return false
78 }
npujar5bf737f2020-01-16 19:35:25 +053079 //cancel()
Scott Baker2c1c4822019-10-16 11:02:41 -070080 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
npujar5bf737f2020-01-16 19:35:25 +053085func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -070086 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
Scott Baker2c1c4822019-10-16 11:02:41 -070087 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +000088 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -070089 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
npujar5bf737f2020-01-16 19:35:25 +0530100func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700101
102 resp, err := c.ectdAPI.Get(ctx, key)
npujar5bf737f2020-01-16 19:35:25 +0530103
Scott Baker2c1c4822019-10-16 11:02:41 -0700104 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000105 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700106 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
npujar5bf737f2020-01-16 19:35:25 +0530118func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) 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
Scott Baker2c1c4822019-10-16 11:02:41 -0700127 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
Matteo Scandoloed128822020-02-10 15:52:35 -0800130 c.keyReservationsLock.RLock()
131 leaseID, ok := c.keyReservations[key]
132 c.keyReservationsLock.RUnlock()
133 if ok {
Scott Baker2c1c4822019-10-16 11:02:41 -0700134 _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID))
135 } else {
136 _, err = c.ectdAPI.Put(ctx, key, val)
137 }
npujar5bf737f2020-01-16 19:35:25 +0530138
Scott Baker2c1c4822019-10-16 11:02:41 -0700139 if err != nil {
140 switch err {
141 case context.Canceled:
Neha Sharma94f16a92020-06-26 04:17:55 +0000142 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700143 case context.DeadlineExceeded:
Neha Sharma94f16a92020-06-26 04:17:55 +0000144 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700145 case v3rpcTypes.ErrEmptyKey:
Neha Sharma94f16a92020-06-26 04:17:55 +0000146 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700147 default:
Neha Sharma94f16a92020-06-26 04:17:55 +0000148 logger.Warnw(ctx, "bad-endpoints", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700149 }
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
npujar5bf737f2020-01-16 19:35:25 +0530157func (c *EtcdClient) Delete(ctx context.Context, key string) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700158
Scott Baker2c1c4822019-10-16 11:02:41 -0700159 // delete the key
160 if _, err := c.ectdAPI.Delete(ctx, key); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000161 logger.Errorw(ctx, "failed-to-delete-key", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700162 return err
163 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000164 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700165 return nil
166}
167
Serkant Uluderya198de902020-11-16 20:29:17 +0300168func (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
Scott Baker2c1c4822019-10-16 11:02:41 -0700179// 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 Sharma130ac6d2020-04-08 08:46:32 +0000184func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700185 // 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 Sharma130ac6d2020-04-08 08:46:32 +0000192 resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds()))
Scott Baker2c1c4822019-10-16 11:02:41 -0700193 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000194 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700195 return nil, err
196 }
197 // Register the lease id
Matteo Scandoloed128822020-02-10 15:52:35 -0800198 c.keyReservationsLock.Lock()
Scott Baker2c1c4822019-10-16 11:02:41 -0700199 c.keyReservations[key] = &resp.ID
Matteo Scandoloed128822020-02-10 15:52:35 -0800200 c.keyReservationsLock.Unlock()
Scott Baker2c1c4822019-10-16 11:02:41 -0700201
202 // Revoke lease if reservation is not successful
203 reservationSuccessful := false
204 defer func() {
205 if !reservationSuccessful {
npujar5bf737f2020-01-16 19:35:25 +0530206 if err = c.ReleaseReservation(context.Background(), key); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000207 logger.Error(ctx, "cannot-release-lease")
Scott Baker2c1c4822019-10-16 11:02:41 -0700208 }
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
npujar5bf737f2020-01-16 19:35:25 +0530236 m, err := c.Get(ctx, key)
Scott Baker2c1c4822019-10-16 11:02:41 -0700237 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)
npujar5bf737f2020-01-16 19:35:25 +0530255func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
Matteo Scandoloed128822020-02-10 15:52:35 -0800256 c.keyReservationsLock.Lock()
257 defer c.keyReservationsLock.Unlock()
Thomas Lee S86fc9362019-10-31 11:35:19 +0530258
Scott Baker2c1c4822019-10-16 11:02:41 -0700259 for key, leaseID := range c.keyReservations {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530260 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700261 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000262 logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700263 return err
264 }
265 delete(c.keyReservations, key)
266 }
267 return nil
268}
269
270// ReleaseReservation releases reservation for a specific key.
npujar5bf737f2020-01-16 19:35:25 +0530271func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700272 // Get the leaseid using the key
Neha Sharma94f16a92020-06-26 04:17:55 +0000273 logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700274 var ok bool
275 var leaseID *v3Client.LeaseID
Matteo Scandoloed128822020-02-10 15:52:35 -0800276 c.keyReservationsLock.Lock()
277 defer c.keyReservationsLock.Unlock()
Scott Baker2c1c4822019-10-16 11:02:41 -0700278 if leaseID, ok = c.keyReservations[key]; !ok {
279 return nil
280 }
Thomas Lee S86fc9362019-10-31 11:35:19 +0530281
Scott Baker2c1c4822019-10-16 11:02:41 -0700282 if leaseID != nil {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530283 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700284 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000285 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700286 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
npujar5bf737f2020-01-16 19:35:25 +0530295func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700296 // Get the leaseid using the key
297 var ok bool
298 var leaseID *v3Client.LeaseID
Matteo Scandoloed128822020-02-10 15:52:35 -0800299 c.keyReservationsLock.RLock()
300 leaseID, ok = c.keyReservations[key]
301 c.keyReservationsLock.RUnlock()
302
303 if !ok {
Scott Baker2c1c4822019-10-16 11:02:41 -0700304 return errors.New("key-not-reserved")
305 }
306
307 if leaseID != nil {
Thomas Lee S86fc9362019-10-31 11:35:19 +0530308 _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID)
Scott Baker2c1c4822019-10-16 11:02:41 -0700309 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000310 logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700311 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.
divyadesai8bf96862020-02-07 12:24:26 +0000321func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
Scott Baker2c1c4822019-10-16 11:02:41 -0700322 w := v3Client.NewWatcher(c.ectdAPI)
npujar5bf737f2020-01-16 19:35:25 +0530323 ctx, cancel := context.WithCancel(ctx)
divyadesai8bf96862020-02-07 12:24:26 +0000324 var channel v3Client.WatchChan
325 if withPrefix {
326 channel = w.Watch(ctx, key, v3Client.WithPrefix())
327 } else {
328 channel = w.Watch(ctx, key)
329 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700330
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.
Neha Sharma94f16a92020-06-26 04:17:55 +0000342 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
Scott Baker2c1c4822019-10-16 11:02:41 -0700343 // Launch a go routine to listen for updates
Neha Sharma94f16a92020-06-26 04:17:55 +0000344 go c.listenForKeyChange(ctx, channel, ch, cancel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700345
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
Neha Sharma94f16a92020-06-26 04:17:55 +0000391func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700392 // Get the array of channels mapping
393 var watchedChannels []map[chan *Event]v3Client.Watcher
394 var ok bool
Scott Baker2c1c4822019-10-16 11:02:41 -0700395
396 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000397 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700398 return
399 }
400 // Look for the channels
401 var pos = -1
402 for i, chMap := range watchedChannels {
403 if t, ok := chMap[ch]; ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000404 logger.Debug(ctx, "channel-found")
Scott Baker2c1c4822019-10-16 11:02:41 -0700405 // Close the etcd watcher before the client channel. This should close the etcd channel as well
406 if err := t.Close(); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000407 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700408 }
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 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000419 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
Scott Baker2c1c4822019-10-16 11:02:41 -0700420}
421
Neha Sharma94f16a92020-06-26 04:17:55 +0000422func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
423 logger.Debug(ctx, "start-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700424 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 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000431 logger.Debug(ctx, "stop-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700432}
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
Neha Sharma94f16a92020-06-26 04:17:55 +0000445func (c *EtcdClient) Close(ctx context.Context) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700446 if err := c.ectdAPI.Close(); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000447 logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700448 }
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 Sharma130ac6d2020-04-08 08:46:32 +0000479func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700480 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
481 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
482 if err := mu.Lock(context.Background()); err != nil {
npujar5bf737f2020-01-16 19:35:25 +0530483 //cancel()
Scott Baker2c1c4822019-10-16 11:02:41 -0700484 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}