blob: c2a38c6c108997278017ccab3f463d291d6a6cc8 [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
yasin sapli5458a1c2021-06-14 22:24:38 +000025 "github.com/opencord/voltha-lib-go/v5/pkg/log"
khenaidoob9203542018-09-17 22:56:37 -040026 v3Client "go.etcd.io/etcd/clientv3"
Himani Chawla27f81212021-04-07 11:37:47 +053027
Stephane Barbarie260a5632019-02-26 16:12:49 -050028 v3Concurrency "go.etcd.io/etcd/clientv3/concurrency"
khenaidoob9203542018-09-17 22:56:37 -040029 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
khenaidoocfee5f42018-07-19 22:47:38 -040030)
31
32// EtcdClient represents the Etcd KV store client
33type EtcdClient struct {
Scott Bakerb9635992020-03-11 21:11:28 -070034 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
khenaidoocfee5f42018-07-19 22:47:38 -040041}
42
Himani Chawla27f81212021-04-07 11:37:47 +053043// 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)
khenaidoocfee5f42018-07-19 22:47:38 -040047 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000048 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -040049 return nil, err
50 }
Stephane Barbariec53a2752019-03-08 17:50:10 -050051
khenaidoocfee5f42018-07-19 22:47:38 -040052 reservations := make(map[string]*v3Client.LeaseID)
khenaidoobdcb8e02019-03-06 16:28:56 -050053 lockMutexMap := make(map[string]*v3Concurrency.Mutex)
54 lockSessionMap := make(map[string]*v3Concurrency.Session)
Stephane Barbarie260a5632019-02-26 16:12:49 -050055
Stephane Barbariec53a2752019-03-08 17:50:10 -050056 return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap,
57 lockToSessionMap: lockSessionMap}, nil
khenaidoocfee5f42018-07-19 22:47:38 -040058}
59
Himani Chawla27f81212021-04-07 11:37:47 +053060// 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
khenaidoob3244212019-08-27 14:32:27 -040072// 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.
npujar467fe752020-01-16 20:17:45 +053074func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
khenaidoob3244212019-08-27 14:32:27 -040075 // 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 +053076 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
khenaidoob3244212019-08-27 14:32:27 -040077 return false
78 }
npujar467fe752020-01-16 20:17:45 +053079 //cancel()
khenaidoob3244212019-08-27 14:32:27 -040080 return true
81}
82
khenaidoocfee5f42018-07-19 22:47:38 -040083// 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
npujar467fe752020-01-16 20:17:45 +053085func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
khenaidoocfee5f42018-07-19 22:47:38 -040086 resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix())
khenaidoocfee5f42018-07-19 22:47:38 -040087 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +000088 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -040089 return nil, err
90 }
91 m := make(map[string]*KVPair)
92 for _, ev := range resp.Kvs {
Stephane Barbarieef6650d2019-07-18 12:15:09 -040093 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
khenaidoocfee5f42018-07-19 22:47:38 -040094 }
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
npujar467fe752020-01-16 20:17:45 +0530100func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
Stephane Barbarie260a5632019-02-26 16:12:49 -0500101
yasin sapli5458a1c2021-06-14 22:24:38 +0000102 attempt := 0
103startLoop:
104 for {
105 resp, err := c.ectdAPI.Get(ctx, key)
106 if err != nil {
107 switch err {
108 case context.Canceled:
109 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
110 case context.DeadlineExceeded:
111 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
112 case v3rpcTypes.ErrEmptyKey:
113 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
114 case v3rpcTypes.ErrLeaderChanged,
115 v3rpcTypes.ErrGRPCNoLeader,
116 v3rpcTypes.ErrTimeout,
117 v3rpcTypes.ErrTimeoutDueToLeaderFail,
118 v3rpcTypes.ErrTimeoutDueToConnectionLost:
119 // Retry for these server errors
120 attempt += 1
121 if er := backoff(ctx, attempt); er != nil {
122 logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
123 return nil, err
124 }
125 logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt})
126 goto startLoop
127 default:
128 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
129 }
130 return nil, err
131 }
npujar467fe752020-01-16 20:17:45 +0530132
yasin sapli5458a1c2021-06-14 22:24:38 +0000133 for _, ev := range resp.Kvs {
134 // Only one value is returned
135 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
136 }
137 return nil, nil
khenaidoocfee5f42018-07-19 22:47:38 -0400138 }
khenaidoocfee5f42018-07-19 22:47:38 -0400139}
140
141// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
142// accepts only a string as a value for a put operation. Timeout defines how long the function will
143// wait for a response
npujar467fe752020-01-16 20:17:45 +0530144func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400145
146 // Validate that we can convert value to a string as etcd API expects a string
147 var val string
148 var er error
149 if val, er = ToString(value); er != nil {
150 return fmt.Errorf("unexpected-type-%T", value)
151 }
152
khenaidoo09771ef2019-10-11 14:25:02 -0400153 // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make
154 // that KV key permanent instead of automatically removing it after a lease expiration
Scott Bakerb9635992020-03-11 21:11:28 -0700155 c.keyReservationsLock.RLock()
156 leaseID, ok := c.keyReservations[key]
157 c.keyReservationsLock.RUnlock()
yasin sapli5458a1c2021-06-14 22:24:38 +0000158 attempt := 0
159startLoop:
160 for {
161 var err error
162 if ok {
163 _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID))
164 } else {
165 _, err = c.ectdAPI.Put(ctx, key, val)
khenaidoocfee5f42018-07-19 22:47:38 -0400166 }
yasin sapli5458a1c2021-06-14 22:24:38 +0000167 if err != nil {
168 switch err {
169 case context.Canceled:
170 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
171 case context.DeadlineExceeded:
172 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
173 case v3rpcTypes.ErrEmptyKey:
174 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
175 case v3rpcTypes.ErrLeaderChanged,
176 v3rpcTypes.ErrGRPCNoLeader,
177 v3rpcTypes.ErrTimeout,
178 v3rpcTypes.ErrTimeoutDueToLeaderFail,
179 v3rpcTypes.ErrTimeoutDueToConnectionLost:
180 // Retry for these server errors
181 attempt += 1
182 if er := backoff(ctx, attempt); er != nil {
183 logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
184 return err
185 }
186 logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt})
187 goto startLoop
188 default:
189 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
190 }
191 return err
192 }
193 return nil
khenaidoocfee5f42018-07-19 22:47:38 -0400194 }
khenaidoocfee5f42018-07-19 22:47:38 -0400195}
196
197// Delete removes a key from the KV store. Timeout defines how long the function will
198// wait for a response
npujar467fe752020-01-16 20:17:45 +0530199func (c *EtcdClient) Delete(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400200
yasin sapli5458a1c2021-06-14 22:24:38 +0000201 attempt := 0
202startLoop:
203 for {
204 _, err := c.ectdAPI.Delete(ctx, key)
205 if err != nil {
206 switch err {
207 case context.Canceled:
208 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
209 case context.DeadlineExceeded:
210 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
211 case v3rpcTypes.ErrEmptyKey:
212 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
213 case v3rpcTypes.ErrLeaderChanged,
214 v3rpcTypes.ErrGRPCNoLeader,
215 v3rpcTypes.ErrTimeout,
216 v3rpcTypes.ErrTimeoutDueToLeaderFail,
217 v3rpcTypes.ErrTimeoutDueToConnectionLost:
218 // Retry for these server errors
219 attempt += 1
220 if er := backoff(ctx, attempt); er != nil {
221 logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
222 return err
223 }
224 logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt})
225 goto startLoop
226 default:
227 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
228 }
229 return err
230 }
231 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
232 return nil
khenaidoocfee5f42018-07-19 22:47:38 -0400233 }
khenaidoocfee5f42018-07-19 22:47:38 -0400234}
235
serkant.uluderyac431f2c2021-02-24 17:32:43 +0300236func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
237
238 //delete the prefix
239 if _, err := c.ectdAPI.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil {
240 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
241 return err
242 }
243 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
244 return nil
245}
246
khenaidoocfee5f42018-07-19 22:47:38 -0400247// Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since
248// the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL
249// defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself.
250// If the key is acquired then the value returned will be the value passed in. If the key is already acquired
251// then the value assigned to that key will be returned.
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000252func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
khenaidoocfee5f42018-07-19 22:47:38 -0400253 // Validate that we can convert value to a string as etcd API expects a string
254 var val string
255 var er error
256 if val, er = ToString(value); er != nil {
257 return nil, fmt.Errorf("unexpected-type%T", value)
258 }
259
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000260 resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds()))
khenaidoocfee5f42018-07-19 22:47:38 -0400261 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000262 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -0400263 return nil, err
264 }
265 // Register the lease id
Scott Bakerb9635992020-03-11 21:11:28 -0700266 c.keyReservationsLock.Lock()
khenaidoocfee5f42018-07-19 22:47:38 -0400267 c.keyReservations[key] = &resp.ID
Scott Bakerb9635992020-03-11 21:11:28 -0700268 c.keyReservationsLock.Unlock()
khenaidoocfee5f42018-07-19 22:47:38 -0400269
270 // Revoke lease if reservation is not successful
271 reservationSuccessful := false
272 defer func() {
273 if !reservationSuccessful {
npujar467fe752020-01-16 20:17:45 +0530274 if err = c.ReleaseReservation(context.Background(), key); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000275 logger.Error(ctx, "cannot-release-lease")
khenaidoocfee5f42018-07-19 22:47:38 -0400276 }
277 }
278 }()
279
280 // Try to grap the Key with the above lease
281 c.ectdAPI.Txn(context.Background())
282 txn := c.ectdAPI.Txn(context.Background())
283 txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0))
284 txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID)))
285 txn = txn.Else(v3Client.OpGet(key))
286 result, er := txn.Commit()
287 if er != nil {
288 return nil, er
289 }
290
291 if !result.Succeeded {
292 // Verify whether we are already the owner of that Key
293 if len(result.Responses) > 0 &&
294 len(result.Responses[0].GetResponseRange().Kvs) > 0 {
295 kv := result.Responses[0].GetResponseRange().Kvs[0]
296 if string(kv.Value) == val {
297 reservationSuccessful = true
298 return value, nil
299 }
300 return kv.Value, nil
301 }
302 } else {
303 // Read the Key to ensure this is our Key
npujar467fe752020-01-16 20:17:45 +0530304 m, err := c.Get(ctx, key)
khenaidoocfee5f42018-07-19 22:47:38 -0400305 if err != nil {
306 return nil, err
307 }
308 if m != nil {
309 if m.Key == key && isEqual(m.Value, value) {
310 // My reservation is successful - register it. For now, support is only for 1 reservation per key
311 // per session.
312 reservationSuccessful = true
313 return value, nil
314 }
315 // My reservation has failed. Return the owner of that key
316 return m.Value, nil
317 }
318 }
319 return nil, nil
320}
321
322// ReleaseAllReservations releases all key reservations previously made (using Reserve API)
npujar467fe752020-01-16 20:17:45 +0530323func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
Scott Bakerb9635992020-03-11 21:11:28 -0700324 c.keyReservationsLock.Lock()
325 defer c.keyReservationsLock.Unlock()
Scott Bakeree6a0872019-10-29 15:59:52 -0700326
khenaidoocfee5f42018-07-19 22:47:38 -0400327 for key, leaseID := range c.keyReservations {
Scott Bakeree6a0872019-10-29 15:59:52 -0700328 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400329 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000330 logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400331 return err
332 }
333 delete(c.keyReservations, key)
334 }
335 return nil
336}
337
338// ReleaseReservation releases reservation for a specific key.
npujar467fe752020-01-16 20:17:45 +0530339func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400340 // Get the leaseid using the key
Rohan Agrawal31f21802020-06-12 05:38:46 +0000341 logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400342 var ok bool
343 var leaseID *v3Client.LeaseID
Scott Bakerb9635992020-03-11 21:11:28 -0700344 c.keyReservationsLock.Lock()
345 defer c.keyReservationsLock.Unlock()
khenaidoocfee5f42018-07-19 22:47:38 -0400346 if leaseID, ok = c.keyReservations[key]; !ok {
khenaidoofc1314d2019-03-14 09:34:21 -0400347 return nil
khenaidoocfee5f42018-07-19 22:47:38 -0400348 }
Scott Bakeree6a0872019-10-29 15:59:52 -0700349
khenaidoocfee5f42018-07-19 22:47:38 -0400350 if leaseID != nil {
Scott Bakeree6a0872019-10-29 15:59:52 -0700351 _, err := c.ectdAPI.Revoke(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400352 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000353 logger.Error(ctx, err)
khenaidoocfee5f42018-07-19 22:47:38 -0400354 return err
355 }
356 delete(c.keyReservations, key)
357 }
358 return nil
359}
360
361// RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live)
362// period specified when reserving the key
npujar467fe752020-01-16 20:17:45 +0530363func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
khenaidoocfee5f42018-07-19 22:47:38 -0400364 // Get the leaseid using the key
365 var ok bool
366 var leaseID *v3Client.LeaseID
Scott Bakerb9635992020-03-11 21:11:28 -0700367 c.keyReservationsLock.RLock()
368 leaseID, ok = c.keyReservations[key]
369 c.keyReservationsLock.RUnlock()
370
371 if !ok {
khenaidoocfee5f42018-07-19 22:47:38 -0400372 return errors.New("key-not-reserved")
373 }
374
375 if leaseID != nil {
Scott Bakeree6a0872019-10-29 15:59:52 -0700376 _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID)
khenaidoocfee5f42018-07-19 22:47:38 -0400377 if err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000378 logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400379 return err
380 }
381 } else {
382 return errors.New("lease-expired")
383 }
384 return nil
385}
386
387// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
388// listen to receive Events.
Scott Baker0e78ba22020-02-24 17:58:47 -0800389func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
khenaidoocfee5f42018-07-19 22:47:38 -0400390 w := v3Client.NewWatcher(c.ectdAPI)
npujar467fe752020-01-16 20:17:45 +0530391 ctx, cancel := context.WithCancel(ctx)
Scott Baker0e78ba22020-02-24 17:58:47 -0800392 var channel v3Client.WatchChan
393 if withPrefix {
394 channel = w.Watch(ctx, key, v3Client.WithPrefix())
395 } else {
396 channel = w.Watch(ctx, key)
397 }
khenaidoocfee5f42018-07-19 22:47:38 -0400398
399 // Create a new channel
400 ch := make(chan *Event, maxClientChannelBufferSize)
401
402 // Keep track of the created channels so they can be closed when required
403 channelMap := make(map[chan *Event]v3Client.Watcher)
404 channelMap[ch] = w
khenaidoocfee5f42018-07-19 22:47:38 -0400405
Stephane Barbariec53a2752019-03-08 17:50:10 -0500406 channelMaps := c.addChannelMap(key, channelMap)
407
khenaidooba6b6c42019-08-02 09:11:56 -0400408 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
409 // json format.
Rohan Agrawal31f21802020-06-12 05:38:46 +0000410 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
khenaidoocfee5f42018-07-19 22:47:38 -0400411 // Launch a go routine to listen for updates
Rohan Agrawal31f21802020-06-12 05:38:46 +0000412 go c.listenForKeyChange(ctx, channel, ch, cancel)
khenaidoocfee5f42018-07-19 22:47:38 -0400413
414 return ch
415
416}
417
Stephane Barbariec53a2752019-03-08 17:50:10 -0500418func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
419 var channels interface{}
420 var exists bool
421
422 if channels, exists = c.watchedChannels.Load(key); exists {
423 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
424 } else {
425 channels = []map[chan *Event]v3Client.Watcher{channelMap}
426 }
427 c.watchedChannels.Store(key, channels)
428
429 return channels.([]map[chan *Event]v3Client.Watcher)
430}
431
432func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
433 var channels interface{}
434 var exists bool
435
436 if channels, exists = c.watchedChannels.Load(key); exists {
437 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
438 c.watchedChannels.Store(key, channels)
439 }
440
441 return channels.([]map[chan *Event]v3Client.Watcher)
442}
443
444func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
445 var channels interface{}
446 var exists bool
447
448 channels, exists = c.watchedChannels.Load(key)
449
khenaidoodaefa372019-03-15 14:04:25 -0400450 if channels == nil {
451 return nil, exists
452 }
453
Stephane Barbariec53a2752019-03-08 17:50:10 -0500454 return channels.([]map[chan *Event]v3Client.Watcher), exists
455}
456
khenaidoocfee5f42018-07-19 22:47:38 -0400457// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
458// may be multiple listeners on the same key. The previously created channel serves as a key
Rohan Agrawal31f21802020-06-12 05:38:46 +0000459func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
khenaidoocfee5f42018-07-19 22:47:38 -0400460 // Get the array of channels mapping
461 var watchedChannels []map[chan *Event]v3Client.Watcher
462 var ok bool
khenaidoocfee5f42018-07-19 22:47:38 -0400463
Stephane Barbariec53a2752019-03-08 17:50:10 -0500464 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000465 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
khenaidoocfee5f42018-07-19 22:47:38 -0400466 return
467 }
468 // Look for the channels
469 var pos = -1
470 for i, chMap := range watchedChannels {
471 if t, ok := chMap[ch]; ok {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000472 logger.Debug(ctx, "channel-found")
khenaidoocfee5f42018-07-19 22:47:38 -0400473 // Close the etcd watcher before the client channel. This should close the etcd channel as well
474 if err := t.Close(); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000475 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400476 }
khenaidoocfee5f42018-07-19 22:47:38 -0400477 pos = i
478 break
479 }
480 }
Stephane Barbariec53a2752019-03-08 17:50:10 -0500481
482 channelMaps, _ := c.getChannelMaps(key)
khenaidoocfee5f42018-07-19 22:47:38 -0400483 // Remove that entry if present
484 if pos >= 0 {
Stephane Barbariec53a2752019-03-08 17:50:10 -0500485 channelMaps = c.removeChannelMap(key, pos)
khenaidoocfee5f42018-07-19 22:47:38 -0400486 }
Rohan Agrawal31f21802020-06-12 05:38:46 +0000487 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
khenaidoocfee5f42018-07-19 22:47:38 -0400488}
489
Rohan Agrawal31f21802020-06-12 05:38:46 +0000490func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
491 logger.Debug(ctx, "start-listening-on-channel ...")
A R Karthick43ba1fb2019-10-03 16:24:21 +0000492 defer cancel()
A R Karthickcbae6232019-10-03 21:37:41 +0000493 defer close(ch)
khenaidoocfee5f42018-07-19 22:47:38 -0400494 for resp := range channel {
495 for _, ev := range resp.Events {
Stephane Barbarieef6650d2019-07-18 12:15:09 -0400496 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
khenaidoocfee5f42018-07-19 22:47:38 -0400497 }
498 }
Rohan Agrawal31f21802020-06-12 05:38:46 +0000499 logger.Debug(ctx, "stop-listening-on-channel ...")
khenaidoocfee5f42018-07-19 22:47:38 -0400500}
501
502func getEventType(event *v3Client.Event) int {
503 switch event.Type {
504 case v3Client.EventTypePut:
505 return PUT
506 case v3Client.EventTypeDelete:
507 return DELETE
508 }
509 return UNKNOWN
510}
511
512// Close closes the KV store client
Rohan Agrawal31f21802020-06-12 05:38:46 +0000513func (c *EtcdClient) Close(ctx context.Context) {
khenaidoocfee5f42018-07-19 22:47:38 -0400514 if err := c.ectdAPI.Close(); err != nil {
Rohan Agrawal31f21802020-06-12 05:38:46 +0000515 logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err})
khenaidoocfee5f42018-07-19 22:47:38 -0400516 }
517}
khenaidoobdcb8e02019-03-06 16:28:56 -0500518
519func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) {
520 c.lockToMutexLock.Lock()
521 defer c.lockToMutexLock.Unlock()
522 c.lockToMutexMap[lockName] = lock
523 c.lockToSessionMap[lockName] = session
524}
525
526func (c *EtcdClient) deleteLockName(lockName string) {
527 c.lockToMutexLock.Lock()
528 defer c.lockToMutexLock.Unlock()
529 delete(c.lockToMutexMap, lockName)
530 delete(c.lockToSessionMap, lockName)
531}
532
533func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) {
534 c.lockToMutexLock.Lock()
535 defer c.lockToMutexLock.Unlock()
536 var lock *v3Concurrency.Mutex
537 var session *v3Concurrency.Session
538 if l, exist := c.lockToMutexMap[lockName]; exist {
539 lock = l
540 }
541 if s, exist := c.lockToSessionMap[lockName]; exist {
542 session = s
543 }
544 return lock, session
545}
546
Neha Sharma7d6f3a92020-04-14 15:26:22 +0000547func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500548 session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx))
Stephane Barbariec53a2752019-03-08 17:50:10 -0500549 mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName)
khenaidoobdcb8e02019-03-06 16:28:56 -0500550 if err := mu.Lock(context.Background()); err != nil {
npujar467fe752020-01-16 20:17:45 +0530551 //cancel()
khenaidoobdcb8e02019-03-06 16:28:56 -0500552 return err
553 }
554 c.addLockName(lockName, mu, session)
khenaidoobdcb8e02019-03-06 16:28:56 -0500555 return nil
556}
557
Stephane Barbariec53a2752019-03-08 17:50:10 -0500558func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoobdcb8e02019-03-06 16:28:56 -0500559 lock, session := c.getLock(lockName)
560 var err error
561 if lock != nil {
562 if e := lock.Unlock(context.Background()); e != nil {
563 err = e
564 }
565 }
566 if session != nil {
567 if e := session.Close(); e != nil {
568 err = e
569 }
570 }
571 c.deleteLockName(lockName)
572
573 return err
Stephane Barbariec53a2752019-03-08 17:50:10 -0500574}