blob: 868b3012c1de0a9c40eb7202021428ef87003ce7 [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"
npujar467fe752020-01-16 20:17:45 +053022 "sync"
Neha Sharma7d6f3a92020-04-14 15:26:22 +000023 "time"
npujar467fe752020-01-16 20:17:45 +053024
Maninderdfadc982020-10-28 14:04:33 +053025 "github.com/opencord/voltha-lib-go/v4/pkg/log"
khenaidoob9203542018-09-17 22:56:37 -040026 v3Client "go.etcd.io/etcd/clientv3"
Stephane Barbarie260a5632019-02-26 16:12:49 -050027 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
khenaidoob9203542018-09-17 22:56:37 -040028 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
khenaidoocfee5f42018-07-19 22:47:38 -040029)
30
31// EtcdClient represents the Etcd KV store client
32type EtcdClient struct {
Scott Bakerb9635992020-03-11 21:11:28 -070033 ectdAPI *v3Client.Client
34 keyReservations map[string]*v3Client.LeaseID
35 watchedChannels sync.Map
36 keyReservationsLock sync.RWMutex
37 lockToMutexMap map[string]*v3Concurrency.Mutex
38 lockToSessionMap map[string]*v3Concurrency.Session
39 lockToMutexLock sync.Mutex
khenaidoocfee5f42018-07-19 22:47:38 -040040}
41
42// NewEtcdClient returns a new client for the Etcd KV store
Rohan Agrawal31f21802020-06-12 05:38:46 +000043func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
Scott Baker504b4802020-04-17 10:12:20 -070044 logconfig := log.ConstructZapConfig(log.JSON, level, log.Fields{})
khenaidoocfee5f42018-07-19 22:47:38 -040045
46 c, err := v3Client.New(v3Client.Config{
47 Endpoints: []string{addr},
Neha Sharma7d6f3a92020-04-14 15:26:22 +000048 DialTimeout: timeout,
Scott Baker504b4802020-04-17 10:12:20 -070049 LogConfig: &logconfig,
khenaidoocfee5f42018-07-19 22:47:38 -040050 })
51 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000052 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -040053 return nil, err
54 }
Stephane Barbariec53a2752019-03-08 17:50:10 -050055
khenaidoocfee5f42018-07-19 22:47:38 -040056 reservations := make(map[string]*v3Client.LeaseID)
khenaidoobdcb8e02019-03-06 16:28:56 -050057 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
58 lockSessionMap := make(map[string]*v3Concurrency.Session)
Stephane Barbarie260a5632019-02-26 16:12:49 -050059
Stephane Barbariec53a2752019-03-08 17:50:10 -050060 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
61 lockToSessionMap: lockSessionMap}, nil
khenaidoocfee5f42018-07-19 22:47:38 -040062}
63
khenaidoob3244212019-08-27 14:32:27 -040064// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
65// it is assumed the connection is down or unreachable.
npujar467fe752020-01-16 20:17:45 +053066func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
khenaidoob3244212019-08-27 14:32:27 -040067 // Let's try to get a non existent key. If the connection is up then there will be no error returned.
npujar467fe752020-01-16 20:17:45 +053068 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
khenaidoob3244212019-08-27 14:32:27 -040069 return false
70 }
npujar467fe752020-01-16 20:17:45 +053071 //cancel()
khenaidoob3244212019-08-27 14:32:27 -040072 return true
73}
74
khenaidoocfee5f42018-07-19 22:47:38 -040075// 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
npujar467fe752020-01-16 20:17:45 +053077func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
khenaidoocfee5f42018-07-19 22:47:38 -040078 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
khenaidoocfee5f42018-07-19 22:47:38 -040079 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000080 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -040081 return nil, err
82 }
83 m := make(map[string]*KVPair)
84 for _, ev := range resp.Kvs {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040085 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
khenaidoocfee5f42018-07-19 22:47:38 -040086 }
87 return m, nil
88}
89
90// Get returns a key-value pair for a given key. Timeout defines how long the function will
91// wait for a response
npujar467fe752020-01-16 20:17:45 +053092func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
Stephane Barbarie260a5632019-02-26 16:12:49 -050093
khenaidoocfee5f42018-07-19 22:47:38 -040094 resp, err := c.ectdAPI.Get(ctx, key)
npujar467fe752020-01-16 20:17:45 +053095
khenaidoocfee5f42018-07-19 22:47:38 -040096 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000097 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -040098 return nil, err
99 }
100 for _, ev := range resp.Kvs {
101 // Only one value is returned
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400102 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
khenaidoocfee5f42018-07-19 22:47:38 -0400103 }
104 return nil, nil
105}
106
107// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
108// accepts only a string as a value for a put operation. Timeout defines how long the function will
109// wait for a response
npujar467fe752020-01-16 20:17:45 +0530110func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400111
112 // Validate that we can convert value to a string as etcd API expects a string
113 var val string
114 var er error
115 if val, er = ToString(value); er != nil {
116 return fmt.Errorf("unexpected-type-%T", value)
117 }
118
khenaidoo09771ef2019-10-11 14:25:02 -0400119 var err error
120 // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make
121 // that KV key permanent instead of automatically removing it after a lease expiration
Scott Bakerb9635992020-03-11 21:11:28 -0700122 c.keyReservationsLock.RLock()
123 leaseID, ok := c.keyReservations[key]
124 c.keyReservationsLock.RUnlock()
125 if ok {
khenaidoo09771ef2019-10-11 14:25:02 -0400126 _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID))
127 } else {
128 _, err = c.ectdAPI.Put(ctx, key, val)
129 }
npujar467fe752020-01-16 20:17:45 +0530130
khenaidoocfee5f42018-07-19 22:47:38 -0400131 if err != nil {
132 switch err {
133 case context.Canceled:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000134 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400135 case context.DeadlineExceeded:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000136 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400137 case v3rpcTypes.ErrEmptyKey:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000138 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400139 default:
Rohan Agrawal31f21802020-06-12 05:38:46 +0000140 logger.Warnw(ctx, "bad-endpoints", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400141 }
142 return err
143 }
144 return nil
145}
146
147// Delete removes a key from the KV store. Timeout defines how long the function will
148// wait for a response
npujar467fe752020-01-16 20:17:45 +0530149func (c *EtcdClient) Delete(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400150
khenaidoo09771ef2019-10-11 14:25:02 -0400151 // delete the key
152 if _, err := c.ectdAPI.Delete(ctx, key); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000153 logger.Errorw(ctx, "failed-to-delete-key", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400154 return err
155 }
Rohan Agrawal31f21802020-06-12 05:38:46 +0000156 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400157 return nil
158}
159
serkant.uluderyac431f2c2021-02-24 17:32:43 +0300160func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
161
162 //delete the prefix
163 if _, err := c.ectdAPI.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil {
164 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
165 return err
166 }
167 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
168 return nil
169}
170
khenaidoocfee5f42018-07-19 22:47:38 -0400171// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
172// the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL
173// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
174// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
175// then the value assigned to that key will be returned.
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000176func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
khenaidoocfee5f42018-07-19 22:47:38 -0400177 // Validate that we can convert value to a string as etcd API expects a string
178 var val string
179 var er error
180 if val, er = ToString(value); er != nil {
181 return nil, fmt.Errorf("unexpected-type%T", value)
182 }
183
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000184 resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds()))
khenaidoocfee5f42018-07-19 22:47:38 -0400185 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000186 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -0400187 return nil, err
188 }
189 // Register the lease id
Scott Bakerb9635992020-03-11 21:11:28 -0700190 c.keyReservationsLock.Lock()
khenaidoocfee5f42018-07-19 22:47:38 -0400191 c.keyReservations[key] = &resp.ID
Scott Bakerb9635992020-03-11 21:11:28 -0700192 c.keyReservationsLock.Unlock()
khenaidoocfee5f42018-07-19 22:47:38 -0400193
194 // Revoke lease if reservation is not successful
195 reservationSuccessful := false
196 defer func() {
197 if !reservationSuccessful {
npujar467fe752020-01-16 20:17:45 +0530198 if err = c.ReleaseReservation(context.Background(), key); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000199 logger.Error(ctx, "cannot-release-lease")
khenaidoocfee5f42018-07-19 22:47:38 -0400200 }
201 }
202 }()
203
204 // Try to grap the Key with the above lease
205 c.ectdAPI.Txn(context.Background())
206 txn := c.ectdAPI.Txn(context.Background())
207 txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0))
208 txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID)))
209 txn = txn.Else(v3Client.OpGet(key))
210 result, er := txn.Commit()
211 if er != nil {
212 return nil, er
213 }
214
215 if !result.Succeeded {
216 // Verify whether we are already the owner of that Key
217 if len(result.Responses) > 0 &&
218 len(result.Responses[0].GetResponseRange().Kvs) > 0 {
219 kv := result.Responses[0].GetResponseRange().Kvs[0]
220 if string(kv.Value) == val {
221 reservationSuccessful = true
222 return value, nil
223 }
224 return kv.Value, nil
225 }
226 } else {
227 // Read the Key to ensure this is our Key
npujar467fe752020-01-16 20:17:45 +0530228 m, err := c.Get(ctx, key)
khenaidoocfee5f42018-07-19 22:47:38 -0400229 if err != nil {
230 return nil, err
231 }
232 if m != nil {
233 if m.Key == key && isEqual(m.Value, value) {
234 // My reservation is successful - register it. For now, support is only for 1 reservation per key
235 // per session.
236 reservationSuccessful = true
237 return value, nil
238 }
239 // My reservation has failed. Return the owner of that key
240 return m.Value, nil
241 }
242 }
243 return nil, nil
244}
245
246// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
npujar467fe752020-01-16 20:17:45 +0530247func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
Scott Bakerb9635992020-03-11 21:11:28 -0700248 c.keyReservationsLock.Lock()
249 defer c.keyReservationsLock.Unlock()
Scott Bakeree6a0872019-10-29 15:59:52 -0700250
khenaidoocfee5f42018-07-19 22:47:38 -0400251 for key, leaseID := range c.keyReservations {
Scott Bakeree6a0872019-10-29 15:59:52 -0700252 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400253 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000254 logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400255 return err
256 }
257 delete(c.keyReservations, key)
258 }
259 return nil
260}
261
262// ReleaseReservation releases reservation for a specific key.
npujar467fe752020-01-16 20:17:45 +0530263func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400264 // Get the leaseid using the key
Rohan Agrawal31f21802020-06-12 05:38:46 +0000265 logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400266 var ok bool
267 var leaseID *v3Client.LeaseID
Scott Bakerb9635992020-03-11 21:11:28 -0700268 c.keyReservationsLock.Lock()
269 defer c.keyReservationsLock.Unlock()
khenaidoocfee5f42018-07-19 22:47:38 -0400270 if leaseID, ok = c.keyReservations[key]; !ok {
khenaidoofc1314d2019-03-14 09:34:21 -0400271 return nil
khenaidoocfee5f42018-07-19 22:47:38 -0400272 }
Scott Bakeree6a0872019-10-29 15:59:52 -0700273
khenaidoocfee5f42018-07-19 22:47:38 -0400274 if leaseID != nil {
Scott Bakeree6a0872019-10-29 15:59:52 -0700275 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400276 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000277 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -0400278 return err
279 }
280 delete(c.keyReservations, key)
281 }
282 return nil
283}
284
285// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
286// period specified when reserving the key
npujar467fe752020-01-16 20:17:45 +0530287func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400288 // Get the leaseid using the key
289 var ok bool
290 var leaseID *v3Client.LeaseID
Scott Bakerb9635992020-03-11 21:11:28 -0700291 c.keyReservationsLock.RLock()
292 leaseID, ok = c.keyReservations[key]
293 c.keyReservationsLock.RUnlock()
294
295 if !ok {
khenaidoocfee5f42018-07-19 22:47:38 -0400296 return errors.New("key-not-reserved")
297 }
298
299 if leaseID != nil {
Scott Bakeree6a0872019-10-29 15:59:52 -0700300 _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400301 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000302 logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400303 return err
304 }
305 } else {
306 return errors.New("lease-expired")
307 }
308 return nil
309}
310
311// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
312// listen to receive Events.
Scott Baker0e78ba22020-02-24 17:58:47 -0800313func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
khenaidoocfee5f42018-07-19 22:47:38 -0400314 w := v3Client.NewWatcher(c.ectdAPI)
npujar467fe752020-01-16 20:17:45 +0530315 ctx, cancel := context.WithCancel(ctx)
Scott Baker0e78ba22020-02-24 17:58:47 -0800316 var channel v3Client.WatchChan
317 if withPrefix {
318 channel = w.Watch(ctx, key, v3Client.WithPrefix())
319 } else {
320 channel = w.Watch(ctx, key)
321 }
khenaidoocfee5f42018-07-19 22:47:38 -0400322
323 // Create a new channel
324 ch := make(chan *Event, maxClientChannelBufferSize)
325
326 // Keep track of the created channels so they can be closed when required
327 channelMap := make(map[chan *Event]v3Client.Watcher)
328 channelMap[ch] = w
khenaidoocfee5f42018-07-19 22:47:38 -0400329
Stephane Barbariec53a2752019-03-08 17:50:10 -0500330 channelMaps := c.addChannelMap(key, channelMap)
331
khenaidooba6b6c42019-08-02 09:11:56 -0400332 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
333 // json format.
Rohan Agrawal31f21802020-06-12 05:38:46 +0000334 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
khenaidoocfee5f42018-07-19 22:47:38 -0400335 // Launch a go routine to listen for updates
Rohan Agrawal31f21802020-06-12 05:38:46 +0000336 go c.listenForKeyChange(ctx, channel, ch, cancel)
khenaidoocfee5f42018-07-19 22:47:38 -0400337
338 return ch
339
340}
341
Stephane Barbariec53a2752019-03-08 17:50:10 -0500342func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
343 var channels interface{}
344 var exists bool
345
346 if channels, exists = c.watchedChannels.Load(key); exists {
347 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
348 } else {
349 channels = []map[chan *Event]v3Client.Watcher{channelMap}
350 }
351 c.watchedChannels.Store(key, channels)
352
353 return channels.([]map[chan *Event]v3Client.Watcher)
354}
355
356func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
357 var channels interface{}
358 var exists bool
359
360 if channels, exists = c.watchedChannels.Load(key); exists {
361 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
362 c.watchedChannels.Store(key, channels)
363 }
364
365 return channels.([]map[chan *Event]v3Client.Watcher)
366}
367
368func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
369 var channels interface{}
370 var exists bool
371
372 channels, exists = c.watchedChannels.Load(key)
373
khenaidoodaefa372019-03-15 14:04:25 -0400374 if channels == nil {
375 return nil, exists
376 }
377
Stephane Barbariec53a2752019-03-08 17:50:10 -0500378 return channels.([]map[chan *Event]v3Client.Watcher), exists
379}
380
khenaidoocfee5f42018-07-19 22:47:38 -0400381// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
382// may be multiple listeners on the same key. The previously created channel serves as a key
Rohan Agrawal31f21802020-06-12 05:38:46 +0000383func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
khenaidoocfee5f42018-07-19 22:47:38 -0400384 // Get the array of channels mapping
385 var watchedChannels []map[chan *Event]v3Client.Watcher
386 var ok bool
khenaidoocfee5f42018-07-19 22:47:38 -0400387
Stephane Barbariec53a2752019-03-08 17:50:10 -0500388 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000389 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400390 return
391 }
392 // Look for the channels
393 var pos = -1
394 for i, chMap := range watchedChannels {
395 if t, ok := chMap[ch]; ok {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000396 logger.Debug(ctx, "channel-found")
khenaidoocfee5f42018-07-19 22:47:38 -0400397 // Close the etcd watcher before the client channel. This should close the etcd channel as well
398 if err := t.Close(); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000399 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400400 }
khenaidoocfee5f42018-07-19 22:47:38 -0400401 pos = i
402 break
403 }
404 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500405
406 channelMaps, _ := c.getChannelMaps(key)
khenaidoocfee5f42018-07-19 22:47:38 -0400407 // Remove that entry if present
408 if pos >= 0 {
Stephane Barbariec53a2752019-03-08 17:50:10 -0500409 channelMaps = c.removeChannelMap(key, pos)
khenaidoocfee5f42018-07-19 22:47:38 -0400410 }
Rohan Agrawal31f21802020-06-12 05:38:46 +0000411 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
khenaidoocfee5f42018-07-19 22:47:38 -0400412}
413
Rohan Agrawal31f21802020-06-12 05:38:46 +0000414func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
415 logger.Debug(ctx, "start-listening-on-channel ...")
A R Karthick43ba1fb2019-10-03 16:24:21 +0000416 defer cancel()
A R Karthickcbae6232019-10-03 21:37:41 +0000417 defer close(ch)
khenaidoocfee5f42018-07-19 22:47:38 -0400418 for resp := range channel {
419 for _, ev := range resp.Events {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400420 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
khenaidoocfee5f42018-07-19 22:47:38 -0400421 }
422 }
Rohan Agrawal31f21802020-06-12 05:38:46 +0000423 logger.Debug(ctx, "stop-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400424}
425
426func getEventType(event *v3Client.Event) int {
427 switch event.Type {
428 case v3Client.EventTypePut:
429 return PUT
430 case v3Client.EventTypeDelete:
431 return DELETE
432 }
433 return UNKNOWN
434}
435
436// Close closes the KV store client
Rohan Agrawal31f21802020-06-12 05:38:46 +0000437func (c *EtcdClient) Close(ctx context.Context) {
khenaidoocfee5f42018-07-19 22:47:38 -0400438 if err := c.ectdAPI.Close(); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000439 logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400440 }
441}
khenaidoobdcb8e02019-03-06 16:28:56 -0500442
443func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
444 c.lockToMutexLock.Lock()
445 defer c.lockToMutexLock.Unlock()
446 c.lockToMutexMap[lockName] = lock
447 c.lockToSessionMap[lockName] = session
448}
449
450func (c *EtcdClient) deleteLockName(lockName string) {
451 c.lockToMutexLock.Lock()
452 defer c.lockToMutexLock.Unlock()
453 delete(c.lockToMutexMap, lockName)
454 delete(c.lockToSessionMap, lockName)
455}
456
457func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
458 c.lockToMutexLock.Lock()
459 defer c.lockToMutexLock.Unlock()
460 var lock *v3Concurrency.Mutex
461 var session *v3Concurrency.Session
462 if l, exist := c.lockToMutexMap[lockName]; exist {
463 lock = l
464 }
465 if s, exist := c.lockToSessionMap[lockName]; exist {
466 session = s
467 }
468 return lock, session
469}
470
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000471func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500472 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
Stephane Barbariec53a2752019-03-08 17:50:10 -0500473 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
khenaidoobdcb8e02019-03-06 16:28:56 -0500474 if err := mu.Lock(context.Background()); err != nil {
npujar467fe752020-01-16 20:17:45 +0530475 //cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500476 return err
477 }
478 c.addLockName(lockName, mu, session)
khenaidoobdcb8e02019-03-06 16:28:56 -0500479 return nil
480}
481
Stephane Barbariec53a2752019-03-08 17:50:10 -0500482func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500483 lock, session := c.getLock(lockName)
484 var err error
485 if lock != nil {
486 if e := lock.Unlock(context.Background()); e != nil {
487 err = e
488 }
489 }
490 if session != nil {
491 if e := session.Close(); e != nil {
492 err = e
493 }
494 }
495 c.deleteLockName(lockName)
496
497 return err
Stephane Barbariec53a2752019-03-08 17:50:10 -0500498}