blob: 6828700a4e130aa55227f7b9cb73df41c021cfd7 [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"
Abhay Kumar40252eb2025-10-13 13:25:53 +000028 v3rpcTypes "go.etcd.io/etcd/api/v3/v3rpc/rpctypes"
29
30 clientv3 "go.etcd.io/etcd/client/v3"
khenaidoo6f415b22021-06-22 18:08:53 -040031)
32
33const (
34 poolCapacityEnvName = "VOLTHA_ETCD_CLIENT_POOL_CAPACITY"
35 maxUsageEnvName = "VOLTHA_ETCD_CLIENT_MAX_USAGE"
36)
37
38const (
39 defaultMaxPoolCapacity = 1000 // Default size of an Etcd Client pool
40 defaultMaxPoolUsage = 100 // Maximum concurrent request an Etcd Client is allowed to process
Scott Baker2c1c4822019-10-16 11:02:41 -070041)
42
43// EtcdClient represents the Etcd KV store client
44type EtcdClient struct {
khenaidoo6f415b22021-06-22 18:08:53 -040045 pool EtcdClientAllocator
46 watchedChannels sync.Map
Abhay Kumar40252eb2025-10-13 13:25:53 +000047 watchedClients map[string]*clientv3.Client
khenaidoo6f415b22021-06-22 18:08:53 -040048 watchedClientsLock sync.RWMutex
Scott Baker2c1c4822019-10-16 11:02:41 -070049}
50
David K. Bainbridgebc381072021-03-19 20:56:04 +000051// NewEtcdCustomClient returns a new client for the Etcd KV store allowing
52// the called to specify etcd client configuration
khenaidoo6f415b22021-06-22 18:08:53 -040053func NewEtcdCustomClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
54 // Get the capacity and max usage from the environment
55 capacity := defaultMaxPoolCapacity
56 maxUsage := defaultMaxPoolUsage
57 if capacityStr, present := os.LookupEnv(poolCapacityEnvName); present {
58 if val, err := strconv.Atoi(capacityStr); err == nil {
59 capacity = val
60 logger.Infow(ctx, "env-variable-set", log.Fields{"pool-capacity": capacity})
61 } else {
62 logger.Warnw(ctx, "invalid-capacity-value", log.Fields{"error": err, "capacity": capacityStr})
63 }
64 }
65 if maxUsageStr, present := os.LookupEnv(maxUsageEnvName); present {
66 if val, err := strconv.Atoi(maxUsageStr); err == nil {
67 maxUsage = val
68 logger.Infow(ctx, "env-variable-set", log.Fields{"max-usage": maxUsage})
69 } else {
70 logger.Warnw(ctx, "invalid-max-usage-value", log.Fields{"error": err, "max-usage": maxUsageStr})
71 }
Scott Baker2c1c4822019-10-16 11:02:41 -070072 }
73
khenaidoo6f415b22021-06-22 18:08:53 -040074 var err error
Scott Baker2c1c4822019-10-16 11:02:41 -070075
khenaidoo6f415b22021-06-22 18:08:53 -040076 pool, err := NewRoundRobinEtcdClientAllocator([]string{addr}, timeout, capacity, maxUsage, level)
77 if err != nil {
78 logger.Errorw(ctx, "failed-to-create-rr-client", log.Fields{
79 "error": err,
80 })
81 }
82
83 logger.Infow(ctx, "etcd-pool-created", log.Fields{"capacity": capacity, "max-usage": maxUsage})
84
85 return &EtcdClient{pool: pool,
Abhay Kumar40252eb2025-10-13 13:25:53 +000086 watchedClients: make(map[string]*clientv3.Client),
khenaidoo6f415b22021-06-22 18:08:53 -040087 }, nil
Scott Baker2c1c4822019-10-16 11:02:41 -070088}
89
David K. Bainbridgebc381072021-03-19 20:56:04 +000090// NewEtcdClient returns a new client for the Etcd KV store
91func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
khenaidoo6f415b22021-06-22 18:08:53 -040092 return NewEtcdCustomClient(ctx, addr, timeout, level)
David K. Bainbridgebc381072021-03-19 20:56:04 +000093}
94
Scott Baker2c1c4822019-10-16 11:02:41 -070095// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
96// it is assumed the connection is down or unreachable.
npujar5bf737f2020-01-16 19:35:25 +053097func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
Scott Baker2c1c4822019-10-16 11:02:41 -070098 // 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 +053099 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700100 return false
101 }
102 return true
103}
104
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530105// KeyExists returns boolean value based on the existence of the key in kv-store. Timeout defines how long the function will
106// wait for a response
107func (c *EtcdClient) KeyExists(ctx context.Context, key string) (bool, error) {
108 client, err := c.pool.Get(ctx)
109 if err != nil {
110 return false, err
111 }
112 defer c.pool.Put(client)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000113 resp, err := client.Get(ctx, key, clientv3.WithKeysOnly(), clientv3.WithCountOnly())
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530114 if err != nil {
115 logger.Error(ctx, err)
116 return false, err
117 }
118 if resp.Count > 0 {
119 return true, nil
120 }
121 return false, nil
122}
123
Scott Baker2c1c4822019-10-16 11:02:41 -0700124// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
125// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530126func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400127 client, err := c.pool.Get(ctx)
128 if err != nil {
129 return nil, err
130 }
131 defer c.pool.Put(client)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000132 resp, err := client.Get(ctx, key, clientv3.WithPrefix())
khenaidoo6f415b22021-06-22 18:08:53 -0400133
Scott Baker2c1c4822019-10-16 11:02:41 -0700134 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000135 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700136 return nil, err
137 }
138 m := make(map[string]*KVPair)
139 for _, ev := range resp.Kvs {
140 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
141 }
142 return m, nil
143}
144
145// Get returns a key-value pair for a given key. Timeout defines how long the function will
146// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530147func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400148 client, err := c.pool.Get(ctx)
149 if err != nil {
150 return nil, err
151 }
152 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700153
Girish Gowdra248971a2021-06-01 15:14:15 -0700154 attempt := 0
khenaidoo6f415b22021-06-22 18:08:53 -0400155
Girish Gowdra248971a2021-06-01 15:14:15 -0700156startLoop:
157 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400158 resp, err := client.Get(ctx, key)
Girish Gowdra248971a2021-06-01 15:14:15 -0700159 if err != nil {
160 switch err {
161 case context.Canceled:
162 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
163 case context.DeadlineExceeded:
164 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
165 case v3rpcTypes.ErrEmptyKey:
166 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
167 case v3rpcTypes.ErrLeaderChanged,
168 v3rpcTypes.ErrGRPCNoLeader,
169 v3rpcTypes.ErrTimeout,
170 v3rpcTypes.ErrTimeoutDueToLeaderFail,
171 v3rpcTypes.ErrTimeoutDueToConnectionLost:
172 // Retry for these server errors
173 attempt += 1
174 if er := backoff(ctx, attempt); er != nil {
175 logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
176 return nil, err
177 }
178 logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt})
179 goto startLoop
180 default:
181 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
182 }
183 return nil, err
184 }
npujar5bf737f2020-01-16 19:35:25 +0530185
Girish Gowdra248971a2021-06-01 15:14:15 -0700186 for _, ev := range resp.Kvs {
187 // Only one value is returned
188 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
189 }
190 return nil, nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700191 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700192}
193
pnalmas37560752025-01-11 22:05:35 +0530194// GetWithPrefix fetches all key-value pairs with the specified prefix from etcd.
195// Returns a map of key-value pairs or an error if the operation fails.
196func (c *EtcdClient) GetWithPrefix(ctx context.Context, prefixKey string) (map[string]*KVPair, error) {
197 // Acquire a client from the pool
198 client, err := c.pool.Get(ctx)
199 if err != nil {
200 return nil, fmt.Errorf("failed to get client from pool: %w", err)
201 }
202 defer c.pool.Put(client)
203
204 // Fetch keys with the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000205 resp, err := client.Get(ctx, prefixKey, clientv3.WithPrefix())
pnalmas37560752025-01-11 22:05:35 +0530206 if err != nil {
207 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
208 }
209
210 // Initialize the result map
211 result := make(map[string]*KVPair)
212
213 // Iterate through the fetched key-value pairs and populate the map
214 for _, ev := range resp.Kvs {
215 result[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
216 }
217
218 return result, nil
219}
220
221// GetWithPrefixKeysOnly retrieves only the keys that match a given prefix.
222func (c *EtcdClient) GetWithPrefixKeysOnly(ctx context.Context, prefixKey string) ([]string, error) {
223 // Acquire a client from the pool
224 client, err := c.pool.Get(ctx)
225 if err != nil {
226 return nil, fmt.Errorf("failed to get client from pool: %w", err)
227 }
228 defer c.pool.Put(client)
229
230 // Fetch keys with the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000231 resp, err := client.Get(ctx, prefixKey, clientv3.WithPrefix(), clientv3.WithKeysOnly())
pnalmas37560752025-01-11 22:05:35 +0530232 if err != nil {
233 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
234 }
235
236 // Extract keys from the response
237 keys := []string{}
238 for _, kv := range resp.Kvs {
239 keys = append(keys, string(kv.Key))
240 }
241
242 return keys, nil
243}
244
Scott Baker2c1c4822019-10-16 11:02:41 -0700245// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
246// accepts only a string as a value for a put operation. Timeout defines how long the function will
247// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530248func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700249
250 // Validate that we can convert value to a string as etcd API expects a string
251 var val string
khenaidoo6f415b22021-06-22 18:08:53 -0400252 var err error
253 if val, err = ToString(value); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700254 return fmt.Errorf("unexpected-type-%T", value)
255 }
256
khenaidoo6f415b22021-06-22 18:08:53 -0400257 client, err := c.pool.Get(ctx)
258 if err != nil {
259 return err
260 }
261 defer c.pool.Put(client)
262
Girish Gowdra248971a2021-06-01 15:14:15 -0700263 attempt := 0
264startLoop:
265 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400266 _, err = client.Put(ctx, key, val)
Girish Gowdra248971a2021-06-01 15:14:15 -0700267 if err != nil {
268 switch err {
269 case context.Canceled:
270 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
271 case context.DeadlineExceeded:
272 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
273 case v3rpcTypes.ErrEmptyKey:
274 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
275 case v3rpcTypes.ErrLeaderChanged,
276 v3rpcTypes.ErrGRPCNoLeader,
277 v3rpcTypes.ErrTimeout,
278 v3rpcTypes.ErrTimeoutDueToLeaderFail,
279 v3rpcTypes.ErrTimeoutDueToConnectionLost:
280 // Retry for these server errors
281 attempt += 1
282 if er := backoff(ctx, attempt); er != nil {
283 logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
284 return err
285 }
286 logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt})
287 goto startLoop
288 default:
289 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
290 }
291 return err
292 }
293 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700294 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700295}
296
297// Delete removes a key from the KV store. Timeout defines how long the function will
298// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530299func (c *EtcdClient) Delete(ctx context.Context, key string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400300 client, err := c.pool.Get(ctx)
301 if err != nil {
302 return err
303 }
304 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700305
Girish Gowdra248971a2021-06-01 15:14:15 -0700306 attempt := 0
307startLoop:
308 for {
khenaidoo6f415b22021-06-22 18:08:53 -0400309 _, err = client.Delete(ctx, key)
Girish Gowdra248971a2021-06-01 15:14:15 -0700310 if err != nil {
311 switch err {
312 case context.Canceled:
313 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
314 case context.DeadlineExceeded:
315 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx})
316 case v3rpcTypes.ErrEmptyKey:
317 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
318 case v3rpcTypes.ErrLeaderChanged,
319 v3rpcTypes.ErrGRPCNoLeader,
320 v3rpcTypes.ErrTimeout,
321 v3rpcTypes.ErrTimeoutDueToLeaderFail,
322 v3rpcTypes.ErrTimeoutDueToConnectionLost:
323 // Retry for these server errors
324 attempt += 1
325 if er := backoff(ctx, attempt); er != nil {
326 logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
327 return err
328 }
329 logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt})
330 goto startLoop
331 default:
332 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
333 }
334 return err
335 }
336 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
337 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700338 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700339}
340
Serkant Uluderya198de902020-11-16 20:29:17 +0300341func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
342
khenaidoo6f415b22021-06-22 18:08:53 -0400343 client, err := c.pool.Get(ctx)
344 if err != nil {
345 return err
346 }
347 defer c.pool.Put(client)
348
Serkant Uluderya198de902020-11-16 20:29:17 +0300349 //delete the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000350 if _, err := client.Delete(ctx, prefixKey, clientv3.WithPrefix()); err != nil {
Serkant Uluderya198de902020-11-16 20:29:17 +0300351 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
352 return err
353 }
354 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
355 return nil
356}
357
Scott Baker2c1c4822019-10-16 11:02:41 -0700358// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
359// listen to receive Events.
divyadesai8bf96862020-02-07 12:24:26 +0000360func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
khenaidoo6f415b22021-06-22 18:08:53 -0400361 var err error
362 // Reuse the Etcd client when multiple callees are watching the same key.
363 c.watchedClientsLock.Lock()
364 client, exist := c.watchedClients[key]
365 if !exist {
366 client, err = c.pool.Get(ctx)
367 if err != nil {
368 logger.Errorw(ctx, "failed-to-an-etcd-client", log.Fields{"key": key, "error": err})
369 c.watchedClientsLock.Unlock()
370 return nil
371 }
372 c.watchedClients[key] = client
373 }
374 c.watchedClientsLock.Unlock()
375
Abhay Kumar40252eb2025-10-13 13:25:53 +0000376 w := clientv3.NewWatcher(client)
npujar5bf737f2020-01-16 19:35:25 +0530377 ctx, cancel := context.WithCancel(ctx)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000378 var channel clientv3.WatchChan
divyadesai8bf96862020-02-07 12:24:26 +0000379 if withPrefix {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000380 channel = w.Watch(ctx, key, clientv3.WithPrefix())
divyadesai8bf96862020-02-07 12:24:26 +0000381 } else {
382 channel = w.Watch(ctx, key)
383 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700384
385 // Create a new channel
386 ch := make(chan *Event, maxClientChannelBufferSize)
387
388 // Keep track of the created channels so they can be closed when required
Abhay Kumar40252eb2025-10-13 13:25:53 +0000389 channelMap := make(map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700390 channelMap[ch] = w
Scott Baker2c1c4822019-10-16 11:02:41 -0700391 channelMaps := c.addChannelMap(key, channelMap)
392
393 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
394 // json format.
Neha Sharma94f16a92020-06-26 04:17:55 +0000395 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
Scott Baker2c1c4822019-10-16 11:02:41 -0700396 // Launch a go routine to listen for updates
Neha Sharma94f16a92020-06-26 04:17:55 +0000397 go c.listenForKeyChange(ctx, channel, ch, cancel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700398
399 return ch
400
401}
402
Abhay Kumar40252eb2025-10-13 13:25:53 +0000403func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]clientv3.Watcher) []map[chan *Event]clientv3.Watcher {
Scott Baker2c1c4822019-10-16 11:02:41 -0700404 var channels interface{}
405 var exists bool
406
407 if channels, exists = c.watchedChannels.Load(key); exists {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000408 channels = append(channels.([]map[chan *Event]clientv3.Watcher), channelMap)
Scott Baker2c1c4822019-10-16 11:02:41 -0700409 } else {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000410 channels = []map[chan *Event]clientv3.Watcher{channelMap}
Scott Baker2c1c4822019-10-16 11:02:41 -0700411 }
412 c.watchedChannels.Store(key, channels)
413
Abhay Kumar40252eb2025-10-13 13:25:53 +0000414 return channels.([]map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700415}
416
Abhay Kumar40252eb2025-10-13 13:25:53 +0000417func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]clientv3.Watcher {
Scott Baker2c1c4822019-10-16 11:02:41 -0700418 var channels interface{}
419 var exists bool
420
421 if channels, exists = c.watchedChannels.Load(key); exists {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000422 channels = append(channels.([]map[chan *Event]clientv3.Watcher)[:pos], channels.([]map[chan *Event]clientv3.Watcher)[pos+1:]...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700423 c.watchedChannels.Store(key, channels)
424 }
425
Abhay Kumar40252eb2025-10-13 13:25:53 +0000426 return channels.([]map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700427}
428
Abhay Kumar40252eb2025-10-13 13:25:53 +0000429func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]clientv3.Watcher, bool) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700430 var channels interface{}
431 var exists bool
432
433 channels, exists = c.watchedChannels.Load(key)
434
435 if channels == nil {
436 return nil, exists
437 }
438
Abhay Kumar40252eb2025-10-13 13:25:53 +0000439 return channels.([]map[chan *Event]clientv3.Watcher), exists
Scott Baker2c1c4822019-10-16 11:02:41 -0700440}
441
442// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
443// may be multiple listeners on the same key. The previously created channel serves as a key
Neha Sharma94f16a92020-06-26 04:17:55 +0000444func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700445 // Get the array of channels mapping
Abhay Kumar40252eb2025-10-13 13:25:53 +0000446 var watchedChannels []map[chan *Event]clientv3.Watcher
Scott Baker2c1c4822019-10-16 11:02:41 -0700447 var ok bool
Scott Baker2c1c4822019-10-16 11:02:41 -0700448
449 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000450 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700451 return
452 }
453 // Look for the channels
454 var pos = -1
455 for i, chMap := range watchedChannels {
456 if t, ok := chMap[ch]; ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000457 logger.Debug(ctx, "channel-found")
Scott Baker2c1c4822019-10-16 11:02:41 -0700458 // Close the etcd watcher before the client channel. This should close the etcd channel as well
459 if err := t.Close(); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000460 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700461 }
462 pos = i
463 break
464 }
465 }
466
467 channelMaps, _ := c.getChannelMaps(key)
468 // Remove that entry if present
469 if pos >= 0 {
470 channelMaps = c.removeChannelMap(key, pos)
471 }
khenaidoo6f415b22021-06-22 18:08:53 -0400472
473 // If we don't have any keys being watched then return the Etcd client to the pool
474 if len(channelMaps) == 0 {
475 c.watchedClientsLock.Lock()
476 // Sanity
477 if client, ok := c.watchedClients[key]; ok {
478 c.pool.Put(client)
479 delete(c.watchedClients, key)
480 }
481 c.watchedClientsLock.Unlock()
482 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000483 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
Scott Baker2c1c4822019-10-16 11:02:41 -0700484}
485
Abhay Kumar40252eb2025-10-13 13:25:53 +0000486func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel clientv3.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
Neha Sharma94f16a92020-06-26 04:17:55 +0000487 logger.Debug(ctx, "start-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700488 defer cancel()
489 defer close(ch)
490 for resp := range channel {
491 for _, ev := range resp.Events {
492 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
493 }
494 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000495 logger.Debug(ctx, "stop-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700496}
497
Abhay Kumar40252eb2025-10-13 13:25:53 +0000498func getEventType(event *clientv3.Event) int {
Scott Baker2c1c4822019-10-16 11:02:41 -0700499 switch event.Type {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000500 case clientv3.EventTypePut:
Scott Baker2c1c4822019-10-16 11:02:41 -0700501 return PUT
Abhay Kumar40252eb2025-10-13 13:25:53 +0000502 case clientv3.EventTypeDelete:
Scott Baker2c1c4822019-10-16 11:02:41 -0700503 return DELETE
504 }
505 return UNKNOWN
506}
507
khenaidoo6f415b22021-06-22 18:08:53 -0400508// Close closes all the connection in the pool store client
Neha Sharma94f16a92020-06-26 04:17:55 +0000509func (c *EtcdClient) Close(ctx context.Context) {
khenaidoo6f415b22021-06-22 18:08:53 -0400510 logger.Debug(ctx, "closing-etcd-pool")
511 c.pool.Close(ctx)
Scott Baker2c1c4822019-10-16 11:02:41 -0700512}
513
khenaidoo6f415b22021-06-22 18:08:53 -0400514// The APIs below are not used
515var errUnimplemented = errors.New("deprecated")
516
517// Reserve is deprecated
518func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
519 return nil, errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700520}
521
khenaidoo6f415b22021-06-22 18:08:53 -0400522// ReleaseAllReservations is deprecated
523func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
524 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700525}
526
khenaidoo6f415b22021-06-22 18:08:53 -0400527// ReleaseReservation is deprecated
528func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
529 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700530}
531
khenaidoo6f415b22021-06-22 18:08:53 -0400532// RenewReservation is deprecated
533func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
534 return errUnimplemented
535}
536
537// AcquireLock is deprecated
Neha Sharma130ac6d2020-04-08 08:46:32 +0000538func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400539 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700540}
541
khenaidoo6f415b22021-06-22 18:08:53 -0400542// ReleaseLock is deprecated
Scott Baker2c1c4822019-10-16 11:02:41 -0700543func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400544 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700545}