blob: d15bb6e309c667f91d475a90fb5e60e62c9f6911 [file] [log] [blame]
Scott Baker2c1c4822019-10-16 11:02:41 -07001/*
Joey Armstrong9cdee9f2024-01-03 04:56:14 -05002* Copyright 2018-2024 Open Networking Foundation (ONF) and the ONF Contributors
Scott Baker2c1c4822019-10-16 11:02:41 -07003
Joey Armstrong7f8436c2023-07-09 20:23:27 -04004* 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
Scott Baker2c1c4822019-10-16 11:02:41 -07007
Joey Armstrong7f8436c2023-07-09 20:23:27 -04008* http://www.apache.org/licenses/LICENSE-2.0
Scott Baker2c1c4822019-10-16 11:02:41 -07009
Joey Armstrong7f8436c2023-07-09 20:23:27 -040010* 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.
Scott Baker2c1c4822019-10-16 11:02:41 -070015 */
16package kvstore
17
18import (
19 "context"
20 "errors"
21 "fmt"
khenaidoo6f415b22021-06-22 18:08:53 -040022 "os"
23 "strconv"
24 "sync"
25 "time"
khenaidoo26721882021-08-11 17:42:52 -040026
27 "github.com/opencord/voltha-lib-go/v7/pkg/log"
28 v3Client "go.etcd.io/etcd/clientv3"
29 v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
khenaidoo6f415b22021-06-22 18:08:53 -040030)
31
32const (
33 poolCapacityEnvName = "VOLTHA_ETCD_CLIENT_POOL_CAPACITY"
34 maxUsageEnvName = "VOLTHA_ETCD_CLIENT_MAX_USAGE"
35)
36
37const (
38 defaultMaxPoolCapacity = 1000 // Default size of an Etcd Client pool
39 defaultMaxPoolUsage = 100 // Maximum concurrent request an Etcd Client is allowed to process
Scott Baker2c1c4822019-10-16 11:02:41 -070040)
41
42// EtcdClient represents the Etcd KV store client
43type EtcdClient struct {
khenaidoo6f415b22021-06-22 18:08:53 -040044 pool EtcdClientAllocator
45 watchedChannels sync.Map
46 watchedClients map[string]*v3Client.Client
47 watchedClientsLock sync.RWMutex
Scott Baker2c1c4822019-10-16 11:02:41 -070048}
49
David K. Bainbridgebc381072021-03-19 20:56:04 +000050// NewEtcdCustomClient returns a new client for the Etcd KV store allowing
51// the called to specify etcd client configuration
khenaidoo6f415b22021-06-22 18:08:53 -040052func NewEtcdCustomClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
53 // Get the capacity and max usage from the environment
54 capacity := defaultMaxPoolCapacity
55 maxUsage := defaultMaxPoolUsage
56 if capacityStr, present := os.LookupEnv(poolCapacityEnvName); present {
57 if val, err := strconv.Atoi(capacityStr); err == nil {
58 capacity = val
59 logger.Infow(ctx, "env-variable-set", log.Fields{"pool-capacity": capacity})
60 } else {
61 logger.Warnw(ctx, "invalid-capacity-value", log.Fields{"error": err, "capacity": capacityStr})
62 }
63 }
64 if maxUsageStr, present := os.LookupEnv(maxUsageEnvName); present {
65 if val, err := strconv.Atoi(maxUsageStr); err == nil {
66 maxUsage = val
67 logger.Infow(ctx, "env-variable-set", log.Fields{"max-usage": maxUsage})
68 } else {
69 logger.Warnw(ctx, "invalid-max-usage-value", log.Fields{"error": err, "max-usage": maxUsageStr})
70 }
Scott Baker2c1c4822019-10-16 11:02:41 -070071 }
72
khenaidoo6f415b22021-06-22 18:08:53 -040073 var err error
Scott Baker2c1c4822019-10-16 11:02:41 -070074
khenaidoo6f415b22021-06-22 18:08:53 -040075 pool, err := NewRoundRobinEtcdClientAllocator([]string{addr}, timeout, capacity, maxUsage, level)
76 if err != nil {
77 logger.Errorw(ctx, "failed-to-create-rr-client", log.Fields{
78 "error": err,
79 })
80 }
81
82 logger.Infow(ctx, "etcd-pool-created", log.Fields{"capacity": capacity, "max-usage": maxUsage})
83
84 return &EtcdClient{pool: pool,
85 watchedClients: make(map[string]*v3Client.Client),
86 }, nil
Scott Baker2c1c4822019-10-16 11:02:41 -070087}
88
David K. Bainbridgebc381072021-03-19 20:56:04 +000089// NewEtcdClient returns a new client for the Etcd KV store
90func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
khenaidoo6f415b22021-06-22 18:08:53 -040091 return NewEtcdCustomClient(ctx, addr, timeout, level)
David K. Bainbridgebc381072021-03-19 20:56:04 +000092}
93
Scott Baker2c1c4822019-10-16 11:02:41 -070094// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
95// it is assumed the connection is down or unreachable.
npujar5bf737f2020-01-16 19:35:25 +053096func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
Scott Baker2c1c4822019-10-16 11:02:41 -070097 // 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 +053098 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -070099 return false
100 }
101 return true
102}
103
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530104// KeyExists returns boolean value based on the existence of the key in kv-store. Timeout defines how long the function will
105// wait for a response
106func (c *EtcdClient) KeyExists(ctx context.Context, key string) (bool, error) {
107 client, err := c.pool.Get(ctx)
108 if err != nil {
109 return false, err
110 }
111 defer c.pool.Put(client)
112 resp, err := client.Get(ctx, key, v3Client.WithKeysOnly(), v3Client.WithCountOnly())
113 if err != nil {
114 logger.Error(ctx, err)
115 return false, err
116 }
117 if resp.Count > 0 {
118 return true, nil
119 }
120 return false, nil
121}
122
Scott Baker2c1c4822019-10-16 11:02:41 -0700123// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
124// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530125func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400126 client, err := c.pool.Get(ctx)
127 if err != nil {
128 return nil, err
129 }
130 defer c.pool.Put(client)
131 resp, err := client.Get(ctx, key, v3Client.WithPrefix())
132
Scott Baker2c1c4822019-10-16 11:02:41 -0700133 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000134 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700135 return nil, err
136 }
137 m := make(map[string]*KVPair)
138 for _, ev := range resp.Kvs {
139 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
140 }
141 return m, nil
142}
143
144// Get returns a key-value pair for a given key. Timeout defines how long the function will
145// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530146func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400147 client, err := c.pool.Get(ctx)
148 if err != nil {
149 return nil, err
150 }
151 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700152
Girish Gowdra248971a2021-06-01 15:14:15 -0700153 attempt := 0
khenaidoo6f415b22021-06-22 18:08:53 -0400154
Girish Gowdra248971a2021-06-01 15:14:15 -0700155startLoop:
156 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400157 resp, err := client.Get(ctx, key)
Girish Gowdra248971a2021-06-01 15:14:15 -0700158 if err != nil {
159 switch err {
160 case context.Canceled:
161 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
162 case context.DeadlineExceeded:
163 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
164 case v3rpcTypes.ErrEmptyKey:
165 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
166 case v3rpcTypes.ErrLeaderChanged,
167 v3rpcTypes.ErrGRPCNoLeader,
168 v3rpcTypes.ErrTimeout,
169 v3rpcTypes.ErrTimeoutDueToLeaderFail,
170 v3rpcTypes.ErrTimeoutDueToConnectionLost:
171 // Retry for these server errors
172 attempt += 1
173 if er := backoff(ctx, attempt); er != nil {
174 logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
175 return nil, err
176 }
177 logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt})
178 goto startLoop
179 default:
180 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
181 }
182 return nil, err
183 }
npujar5bf737f2020-01-16 19:35:25 +0530184
Girish Gowdra248971a2021-06-01 15:14:15 -0700185 for _, ev := range resp.Kvs {
186 // Only one value is returned
187 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
188 }
189 return nil, nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700190 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700191}
192
pnalmas37560752025-01-11 22:05:35 +0530193// GetWithPrefix fetches all key-value pairs with the specified prefix from etcd.
194// Returns a map of key-value pairs or an error if the operation fails.
195func (c *EtcdClient) GetWithPrefix(ctx context.Context, prefixKey string) (map[string]*KVPair, error) {
196 // Acquire a client from the pool
197 client, err := c.pool.Get(ctx)
198 if err != nil {
199 return nil, fmt.Errorf("failed to get client from pool: %w", err)
200 }
201 defer c.pool.Put(client)
202
203 // Fetch keys with the prefix
204 resp, err := client.Get(ctx, prefixKey, v3Client.WithPrefix())
205 if err != nil {
206 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
207 }
208
209 // Initialize the result map
210 result := make(map[string]*KVPair)
211
212 // Iterate through the fetched key-value pairs and populate the map
213 for _, ev := range resp.Kvs {
214 result[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
215 }
216
217 return result, nil
218}
219
220// GetWithPrefixKeysOnly retrieves only the keys that match a given prefix.
221func (c *EtcdClient) GetWithPrefixKeysOnly(ctx context.Context, prefixKey string) ([]string, error) {
222 // Acquire a client from the pool
223 client, err := c.pool.Get(ctx)
224 if err != nil {
225 return nil, fmt.Errorf("failed to get client from pool: %w", err)
226 }
227 defer c.pool.Put(client)
228
229 // Fetch keys with the prefix
230 resp, err := client.Get(ctx, prefixKey, v3Client.WithPrefix(), v3Client.WithKeysOnly())
231 if err != nil {
232 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
233 }
234
235 // Extract keys from the response
236 keys := []string{}
237 for _, kv := range resp.Kvs {
238 keys = append(keys, string(kv.Key))
239 }
240
241 return keys, nil
242}
243
Scott Baker2c1c4822019-10-16 11:02:41 -0700244// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
245// accepts only a string as a value for a put operation. Timeout defines how long the function will
246// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530247func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700248
249 // Validate that we can convert value to a string as etcd API expects a string
250 var val string
khenaidoo6f415b22021-06-22 18:08:53 -0400251 var err error
252 if val, err = ToString(value); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700253 return fmt.Errorf("unexpected-type-%T", value)
254 }
255
khenaidoo6f415b22021-06-22 18:08:53 -0400256 client, err := c.pool.Get(ctx)
257 if err != nil {
258 return err
259 }
260 defer c.pool.Put(client)
261
Girish Gowdra248971a2021-06-01 15:14:15 -0700262 attempt := 0
263startLoop:
264 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400265 _, err = client.Put(ctx, key, val)
Girish Gowdra248971a2021-06-01 15:14:15 -0700266 if err != nil {
267 switch err {
268 case context.Canceled:
269 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
270 case context.DeadlineExceeded:
271 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
272 case v3rpcTypes.ErrEmptyKey:
273 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
274 case v3rpcTypes.ErrLeaderChanged,
275 v3rpcTypes.ErrGRPCNoLeader,
276 v3rpcTypes.ErrTimeout,
277 v3rpcTypes.ErrTimeoutDueToLeaderFail,
278 v3rpcTypes.ErrTimeoutDueToConnectionLost:
279 // Retry for these server errors
280 attempt += 1
281 if er := backoff(ctx, attempt); er != nil {
282 logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
283 return err
284 }
285 logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt})
286 goto startLoop
287 default:
288 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
289 }
290 return err
291 }
292 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700293 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700294}
295
296// Delete removes a key from the KV store. Timeout defines how long the function will
297// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530298func (c *EtcdClient) Delete(ctx context.Context, key string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400299 client, err := c.pool.Get(ctx)
300 if err != nil {
301 return err
302 }
303 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700304
Girish Gowdra248971a2021-06-01 15:14:15 -0700305 attempt := 0
306startLoop:
307 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400308 _, err = client.Delete(ctx, key)
Girish Gowdra248971a2021-06-01 15:14:15 -0700309 if err != nil {
310 switch err {
311 case context.Canceled:
312 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
313 case context.DeadlineExceeded:
314 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
315 case v3rpcTypes.ErrEmptyKey:
316 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
317 case v3rpcTypes.ErrLeaderChanged,
318 v3rpcTypes.ErrGRPCNoLeader,
319 v3rpcTypes.ErrTimeout,
320 v3rpcTypes.ErrTimeoutDueToLeaderFail,
321 v3rpcTypes.ErrTimeoutDueToConnectionLost:
322 // Retry for these server errors
323 attempt += 1
324 if er := backoff(ctx, attempt); er != nil {
325 logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
326 return err
327 }
328 logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt})
329 goto startLoop
330 default:
331 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
332 }
333 return err
334 }
335 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
336 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700337 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700338}
339
Serkant Uluderya198de902020-11-16 20:29:17 +0300340func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
341
khenaidoo6f415b22021-06-22 18:08:53 -0400342 client, err := c.pool.Get(ctx)
343 if err != nil {
344 return err
345 }
346 defer c.pool.Put(client)
347
Serkant Uluderya198de902020-11-16 20:29:17 +0300348 //delete the prefix
khenaidoo6f415b22021-06-22 18:08:53 -0400349 if _, err := client.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil {
Serkant Uluderya198de902020-11-16 20:29:17 +0300350 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
351 return err
352 }
353 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
354 return nil
355}
356
Scott Baker2c1c4822019-10-16 11:02:41 -0700357// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
358// listen to receive Events.
divyadesai8bf96862020-02-07 12:24:26 +0000359func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
khenaidoo6f415b22021-06-22 18:08:53 -0400360 var err error
361 // Reuse the Etcd client when multiple callees are watching the same key.
362 c.watchedClientsLock.Lock()
363 client, exist := c.watchedClients[key]
364 if !exist {
365 client, err = c.pool.Get(ctx)
366 if err != nil {
367 logger.Errorw(ctx, "failed-to-an-etcd-client", log.Fields{"key": key, "error": err})
368 c.watchedClientsLock.Unlock()
369 return nil
370 }
371 c.watchedClients[key] = client
372 }
373 c.watchedClientsLock.Unlock()
374
375 w := v3Client.NewWatcher(client)
npujar5bf737f2020-01-16 19:35:25 +0530376 ctx, cancel := context.WithCancel(ctx)
divyadesai8bf96862020-02-07 12:24:26 +0000377 var channel v3Client.WatchChan
378 if withPrefix {
379 channel = w.Watch(ctx, key, v3Client.WithPrefix())
380 } else {
381 channel = w.Watch(ctx, key)
382 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700383
384 // Create a new channel
385 ch := make(chan *Event, maxClientChannelBufferSize)
386
387 // Keep track of the created channels so they can be closed when required
388 channelMap := make(map[chan *Event]v3Client.Watcher)
389 channelMap[ch] = w
Scott Baker2c1c4822019-10-16 11:02:41 -0700390 channelMaps := c.addChannelMap(key, channelMap)
391
392 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
393 // json format.
Neha Sharma94f16a92020-06-26 04:17:55 +0000394 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
Scott Baker2c1c4822019-10-16 11:02:41 -0700395 // Launch a go routine to listen for updates
Neha Sharma94f16a92020-06-26 04:17:55 +0000396 go c.listenForKeyChange(ctx, channel, ch, cancel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700397
398 return ch
399
400}
401
402func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher {
403 var channels interface{}
404 var exists bool
405
406 if channels, exists = c.watchedChannels.Load(key); exists {
407 channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap)
408 } else {
409 channels = []map[chan *Event]v3Client.Watcher{channelMap}
410 }
411 c.watchedChannels.Store(key, channels)
412
413 return channels.([]map[chan *Event]v3Client.Watcher)
414}
415
416func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher {
417 var channels interface{}
418 var exists bool
419
420 if channels, exists = c.watchedChannels.Load(key); exists {
421 channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...)
422 c.watchedChannels.Store(key, channels)
423 }
424
425 return channels.([]map[chan *Event]v3Client.Watcher)
426}
427
428func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) {
429 var channels interface{}
430 var exists bool
431
432 channels, exists = c.watchedChannels.Load(key)
433
434 if channels == nil {
435 return nil, exists
436 }
437
438 return channels.([]map[chan *Event]v3Client.Watcher), exists
439}
440
441// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
442// may be multiple listeners on the same key. The previously created channel serves as a key
Neha Sharma94f16a92020-06-26 04:17:55 +0000443func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700444 // Get the array of channels mapping
445 var watchedChannels []map[chan *Event]v3Client.Watcher
446 var ok bool
Scott Baker2c1c4822019-10-16 11:02:41 -0700447
448 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000449 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700450 return
451 }
452 // Look for the channels
453 var pos = -1
454 for i, chMap := range watchedChannels {
455 if t, ok := chMap[ch]; ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000456 logger.Debug(ctx, "channel-found")
Scott Baker2c1c4822019-10-16 11:02:41 -0700457 // Close the etcd watcher before the client channel. This should close the etcd channel as well
458 if err := t.Close(); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000459 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700460 }
461 pos = i
462 break
463 }
464 }
465
466 channelMaps, _ := c.getChannelMaps(key)
467 // Remove that entry if present
468 if pos >= 0 {
469 channelMaps = c.removeChannelMap(key, pos)
470 }
khenaidoo6f415b22021-06-22 18:08:53 -0400471
472 // If we don't have any keys being watched then return the Etcd client to the pool
473 if len(channelMaps) == 0 {
474 c.watchedClientsLock.Lock()
475 // Sanity
476 if client, ok := c.watchedClients[key]; ok {
477 c.pool.Put(client)
478 delete(c.watchedClients, key)
479 }
480 c.watchedClientsLock.Unlock()
481 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000482 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
Scott Baker2c1c4822019-10-16 11:02:41 -0700483}
484
Neha Sharma94f16a92020-06-26 04:17:55 +0000485func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
486 logger.Debug(ctx, "start-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700487 defer cancel()
488 defer close(ch)
489 for resp := range channel {
490 for _, ev := range resp.Events {
491 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
492 }
493 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000494 logger.Debug(ctx, "stop-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700495}
496
497func getEventType(event *v3Client.Event) int {
498 switch event.Type {
499 case v3Client.EventTypePut:
500 return PUT
501 case v3Client.EventTypeDelete:
502 return DELETE
503 }
504 return UNKNOWN
505}
506
khenaidoo6f415b22021-06-22 18:08:53 -0400507// Close closes all the connection in the pool store client
Neha Sharma94f16a92020-06-26 04:17:55 +0000508func (c *EtcdClient) Close(ctx context.Context) {
khenaidoo6f415b22021-06-22 18:08:53 -0400509 logger.Debug(ctx, "closing-etcd-pool")
510 c.pool.Close(ctx)
Scott Baker2c1c4822019-10-16 11:02:41 -0700511}
512
khenaidoo6f415b22021-06-22 18:08:53 -0400513// The APIs below are not used
514var errUnimplemented = errors.New("deprecated")
515
516// Reserve is deprecated
517func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
518 return nil, errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700519}
520
khenaidoo6f415b22021-06-22 18:08:53 -0400521// ReleaseAllReservations is deprecated
522func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
523 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700524}
525
khenaidoo6f415b22021-06-22 18:08:53 -0400526// ReleaseReservation is deprecated
527func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
528 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700529}
530
khenaidoo6f415b22021-06-22 18:08:53 -0400531// RenewReservation is deprecated
532func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
533 return errUnimplemented
534}
535
536// AcquireLock is deprecated
Neha Sharma130ac6d2020-04-08 08:46:32 +0000537func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400538 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700539}
540
khenaidoo6f415b22021-06-22 18:08:53 -0400541// ReleaseLock is deprecated
Scott Baker2c1c4822019-10-16 11:02:41 -0700542func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400543 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700544}