blob: b1080efe6350afd6cfae07de926053ba5f18a9db [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 (
Abhay Kumar222b61b2025-10-29 20:32:42 +000039 defaultMaxPoolCapacity = 1000 // Default size of an Etcd Client pool
40 defaultMaxPoolUsage = 100 // Maximum concurrent request an Etcd Client is allowed to process
41 defaultMaxAttempts = 10 // Default number of attempts to retry an operation
42 defaultOperationContextTimeout = 3 * time.Second // Default context timeout for operations
Scott Baker2c1c4822019-10-16 11:02:41 -070043)
44
45// EtcdClient represents the Etcd KV store client
46type EtcdClient struct {
khenaidoo6f415b22021-06-22 18:08:53 -040047 pool EtcdClientAllocator
48 watchedChannels sync.Map
Abhay Kumar40252eb2025-10-13 13:25:53 +000049 watchedClients map[string]*clientv3.Client
khenaidoo6f415b22021-06-22 18:08:53 -040050 watchedClientsLock sync.RWMutex
Scott Baker2c1c4822019-10-16 11:02:41 -070051}
52
David K. Bainbridgebc381072021-03-19 20:56:04 +000053// NewEtcdCustomClient returns a new client for the Etcd KV store allowing
54// the called to specify etcd client configuration
khenaidoo6f415b22021-06-22 18:08:53 -040055func NewEtcdCustomClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
56 // Get the capacity and max usage from the environment
57 capacity := defaultMaxPoolCapacity
58 maxUsage := defaultMaxPoolUsage
59 if capacityStr, present := os.LookupEnv(poolCapacityEnvName); present {
60 if val, err := strconv.Atoi(capacityStr); err == nil {
61 capacity = val
62 logger.Infow(ctx, "env-variable-set", log.Fields{"pool-capacity": capacity})
63 } else {
64 logger.Warnw(ctx, "invalid-capacity-value", log.Fields{"error": err, "capacity": capacityStr})
65 }
66 }
67 if maxUsageStr, present := os.LookupEnv(maxUsageEnvName); present {
68 if val, err := strconv.Atoi(maxUsageStr); err == nil {
69 maxUsage = val
70 logger.Infow(ctx, "env-variable-set", log.Fields{"max-usage": maxUsage})
71 } else {
72 logger.Warnw(ctx, "invalid-max-usage-value", log.Fields{"error": err, "max-usage": maxUsageStr})
73 }
Scott Baker2c1c4822019-10-16 11:02:41 -070074 }
75
khenaidoo6f415b22021-06-22 18:08:53 -040076 var err error
Scott Baker2c1c4822019-10-16 11:02:41 -070077
khenaidoo6f415b22021-06-22 18:08:53 -040078 pool, err := NewRoundRobinEtcdClientAllocator([]string{addr}, timeout, capacity, maxUsage, level)
79 if err != nil {
80 logger.Errorw(ctx, "failed-to-create-rr-client", log.Fields{
81 "error": err,
82 })
83 }
84
85 logger.Infow(ctx, "etcd-pool-created", log.Fields{"capacity": capacity, "max-usage": maxUsage})
86
87 return &EtcdClient{pool: pool,
Abhay Kumar40252eb2025-10-13 13:25:53 +000088 watchedClients: make(map[string]*clientv3.Client),
khenaidoo6f415b22021-06-22 18:08:53 -040089 }, nil
Scott Baker2c1c4822019-10-16 11:02:41 -070090}
91
David K. Bainbridgebc381072021-03-19 20:56:04 +000092// NewEtcdClient returns a new client for the Etcd KV store
93func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) {
khenaidoo6f415b22021-06-22 18:08:53 -040094 return NewEtcdCustomClient(ctx, addr, timeout, level)
David K. Bainbridgebc381072021-03-19 20:56:04 +000095}
96
Scott Baker2c1c4822019-10-16 11:02:41 -070097// IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then
98// it is assumed the connection is down or unreachable.
npujar5bf737f2020-01-16 19:35:25 +053099func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool {
Scott Baker2c1c4822019-10-16 11:02:41 -0700100 // 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 +0530101 if _, err := c.Get(ctx, "non-existent-key"); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700102 return false
103 }
104 return true
105}
106
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530107// KeyExists returns boolean value based on the existence of the key in kv-store. Timeout defines how long the function will
108// wait for a response
109func (c *EtcdClient) KeyExists(ctx context.Context, key string) (bool, error) {
110 client, err := c.pool.Get(ctx)
111 if err != nil {
112 return false, err
113 }
114 defer c.pool.Put(client)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000115 resp, err := client.Get(ctx, key, clientv3.WithKeysOnly(), clientv3.WithCountOnly())
Sridhar Ravindra037d7cd2025-10-23 12:52:50 +0530116 if err != nil {
117 logger.Error(ctx, err)
118 return false, err
119 }
120 if resp.Count > 0 {
121 return true, nil
122 }
123 return false, nil
124}
125
Scott Baker2c1c4822019-10-16 11:02:41 -0700126// List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will
127// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530128func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400129 client, err := c.pool.Get(ctx)
130 if err != nil {
131 return nil, err
132 }
133 defer c.pool.Put(client)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000134 resp, err := client.Get(ctx, key, clientv3.WithPrefix())
khenaidoo6f415b22021-06-22 18:08:53 -0400135
Scott Baker2c1c4822019-10-16 11:02:41 -0700136 if err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000137 logger.Error(ctx, err)
Scott Baker2c1c4822019-10-16 11:02:41 -0700138 return nil, err
139 }
140 m := make(map[string]*KVPair)
141 for _, ev := range resp.Kvs {
142 m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
143 }
144 return m, nil
145}
146
147// Get returns a key-value pair for a given key. Timeout defines how long the function will
148// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530149func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) {
khenaidoo6f415b22021-06-22 18:08:53 -0400150 client, err := c.pool.Get(ctx)
151 if err != nil {
152 return nil, err
153 }
154 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700155
Girish Gowdra248971a2021-06-01 15:14:15 -0700156 attempt := 0
157startLoop:
158 for {
Abhay Kumar222b61b2025-10-29 20:32:42 +0000159 retryCtx, cancel := context.WithTimeout(ctx, defaultOperationContextTimeout)
160 resp, err := client.Get(retryCtx, key)
161 cancel()
162 if attempt >= defaultMaxAttempts {
163 logger.Warnw(ctx, "get-retries-exceeded", log.Fields{"key": key, "error": err, "attempt": attempt})
164 return nil, err
165 }
Girish Gowdra248971a2021-06-01 15:14:15 -0700166 if err != nil {
167 switch err {
168 case context.Canceled:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000169 // Check if the parent context was cancelled, if so don't retry
170 if ctx.Err() != nil {
171 logger.Warnw(ctx, "parent-context-cancelled", log.Fields{"error": err})
172 return nil, err
173 }
174 // Otherwise retry
Girish Gowdra248971a2021-06-01 15:14:15 -0700175 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
176 case context.DeadlineExceeded:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000177 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "attempt": attempt})
Girish Gowdra248971a2021-06-01 15:14:15 -0700178 case v3rpcTypes.ErrEmptyKey:
179 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000180 return nil, err
Girish Gowdra248971a2021-06-01 15:14:15 -0700181 case v3rpcTypes.ErrLeaderChanged,
182 v3rpcTypes.ErrGRPCNoLeader,
183 v3rpcTypes.ErrTimeout,
184 v3rpcTypes.ErrTimeoutDueToLeaderFail,
185 v3rpcTypes.ErrTimeoutDueToConnectionLost:
186 // Retry for these server errors
Girish Gowdra248971a2021-06-01 15:14:15 -0700187 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000188 default:
189 logger.Warnw(ctx, "etcd-unknown-error", log.Fields{"error": err})
Girish Gowdra248971a2021-06-01 15:14:15 -0700190 }
Abhay Kumar222b61b2025-10-29 20:32:42 +0000191
192 // Common retry logic for all error cases
193 attempt++
194 if er := backoff(ctx, attempt); er != nil {
195 logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
196 return nil, err
197 }
198 logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt})
199 goto startLoop
Girish Gowdra248971a2021-06-01 15:14:15 -0700200 }
npujar5bf737f2020-01-16 19:35:25 +0530201
Girish Gowdra248971a2021-06-01 15:14:15 -0700202 for _, ev := range resp.Kvs {
203 // Only one value is returned
204 return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil
205 }
206 return nil, nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700207 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700208}
209
pnalmas37560752025-01-11 22:05:35 +0530210// GetWithPrefix fetches all key-value pairs with the specified prefix from etcd.
211// Returns a map of key-value pairs or an error if the operation fails.
212func (c *EtcdClient) GetWithPrefix(ctx context.Context, prefixKey string) (map[string]*KVPair, error) {
213 // Acquire a client from the pool
214 client, err := c.pool.Get(ctx)
215 if err != nil {
216 return nil, fmt.Errorf("failed to get client from pool: %w", err)
217 }
218 defer c.pool.Put(client)
219
220 // Fetch keys with the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000221 resp, err := client.Get(ctx, prefixKey, clientv3.WithPrefix())
pnalmas37560752025-01-11 22:05:35 +0530222 if err != nil {
223 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
224 }
225
226 // Initialize the result map
227 result := make(map[string]*KVPair)
228
229 // Iterate through the fetched key-value pairs and populate the map
230 for _, ev := range resp.Kvs {
231 result[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version)
232 }
233
234 return result, nil
235}
236
237// GetWithPrefixKeysOnly retrieves only the keys that match a given prefix.
238func (c *EtcdClient) GetWithPrefixKeysOnly(ctx context.Context, prefixKey string) ([]string, error) {
239 // Acquire a client from the pool
240 client, err := c.pool.Get(ctx)
241 if err != nil {
242 return nil, fmt.Errorf("failed to get client from pool: %w", err)
243 }
244 defer c.pool.Put(client)
245
246 // Fetch keys with the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000247 resp, err := client.Get(ctx, prefixKey, clientv3.WithPrefix(), clientv3.WithKeysOnly())
pnalmas37560752025-01-11 22:05:35 +0530248 if err != nil {
249 return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err)
250 }
251
252 // Extract keys from the response
253 keys := []string{}
254 for _, kv := range resp.Kvs {
255 keys = append(keys, string(kv.Key))
256 }
257
258 return keys, nil
259}
260
Scott Baker2c1c4822019-10-16 11:02:41 -0700261// Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API
262// accepts only a string as a value for a put operation. Timeout defines how long the function will
263// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530264func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error {
Scott Baker2c1c4822019-10-16 11:02:41 -0700265 // Validate that we can convert value to a string as etcd API expects a string
266 var val string
khenaidoo6f415b22021-06-22 18:08:53 -0400267 var err error
268 if val, err = ToString(value); err != nil {
Scott Baker2c1c4822019-10-16 11:02:41 -0700269 return fmt.Errorf("unexpected-type-%T", value)
270 }
271
khenaidoo6f415b22021-06-22 18:08:53 -0400272 client, err := c.pool.Get(ctx)
273 if err != nil {
274 return err
275 }
276 defer c.pool.Put(client)
277
Girish Gowdra248971a2021-06-01 15:14:15 -0700278 attempt := 0
279startLoop:
280 for {
Abhay Kumar222b61b2025-10-29 20:32:42 +0000281 retryCtx, cancel := context.WithTimeout(ctx, defaultOperationContextTimeout)
282 _, err = client.Put(retryCtx, key, val)
283 cancel()
284 if attempt >= defaultMaxAttempts {
285 logger.Warnw(ctx, "put-retries-exceeded", log.Fields{"key": key, "error": err, "attempt": attempt})
286 return err
287 }
Girish Gowdra248971a2021-06-01 15:14:15 -0700288 if err != nil {
289 switch err {
290 case context.Canceled:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000291 // Check if the parent context was cancelled, if so don't retry
292 if ctx.Err() != nil {
293 logger.Warnw(ctx, "parent-context-cancelled", log.Fields{"error": err})
294 return err
295 }
296 // Otherwise retry
Girish Gowdra248971a2021-06-01 15:14:15 -0700297 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
298 case context.DeadlineExceeded:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000299 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "attempt": attempt})
Girish Gowdra248971a2021-06-01 15:14:15 -0700300 case v3rpcTypes.ErrEmptyKey:
301 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000302 return err
Girish Gowdra248971a2021-06-01 15:14:15 -0700303 case v3rpcTypes.ErrLeaderChanged,
304 v3rpcTypes.ErrGRPCNoLeader,
305 v3rpcTypes.ErrTimeout,
306 v3rpcTypes.ErrTimeoutDueToLeaderFail,
307 v3rpcTypes.ErrTimeoutDueToConnectionLost:
308 // Retry for these server errors
Girish Gowdra248971a2021-06-01 15:14:15 -0700309 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000310 default:
311 logger.Warnw(ctx, "etcd-unknown-error", log.Fields{"error": err})
Girish Gowdra248971a2021-06-01 15:14:15 -0700312 }
Abhay Kumar222b61b2025-10-29 20:32:42 +0000313
314 // Common retry logic for all error cases
315 attempt++
316 if er := backoff(ctx, attempt); er != nil {
317 logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
318 return err
319 }
320 logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt})
321 goto startLoop
Girish Gowdra248971a2021-06-01 15:14:15 -0700322 }
323 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700324 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700325}
326
327// Delete removes a key from the KV store. Timeout defines how long the function will
328// wait for a response
npujar5bf737f2020-01-16 19:35:25 +0530329func (c *EtcdClient) Delete(ctx context.Context, key string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400330 client, err := c.pool.Get(ctx)
331 if err != nil {
332 return err
333 }
334 defer c.pool.Put(client)
Scott Baker2c1c4822019-10-16 11:02:41 -0700335
Girish Gowdra248971a2021-06-01 15:14:15 -0700336 attempt := 0
337startLoop:
338 for {
Abhay Kumar222b61b2025-10-29 20:32:42 +0000339 retryCtx, cancel := context.WithTimeout(ctx, defaultOperationContextTimeout)
340 _, err = client.Delete(retryCtx, key)
341 cancel()
342 if attempt >= defaultMaxAttempts {
343 logger.Warnw(ctx, "delete-retries-exceeded", log.Fields{"key": key, "error": err, "attempt": attempt})
344 return err
345 }
Girish Gowdra248971a2021-06-01 15:14:15 -0700346 if err != nil {
347 switch err {
348 case context.Canceled:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000349 // Check if the parent context was cancelled, if so don't retry
350 if ctx.Err() != nil {
351 logger.Warnw(ctx, "parent-context-cancelled", log.Fields{"error": err})
352 return err
353 }
354 // Otherwise retry
Girish Gowdra248971a2021-06-01 15:14:15 -0700355 logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err})
356 case context.DeadlineExceeded:
Abhay Kumar222b61b2025-10-29 20:32:42 +0000357 logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "attempt": attempt})
Girish Gowdra248971a2021-06-01 15:14:15 -0700358 case v3rpcTypes.ErrEmptyKey:
359 logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000360 return err
Girish Gowdra248971a2021-06-01 15:14:15 -0700361 case v3rpcTypes.ErrLeaderChanged,
362 v3rpcTypes.ErrGRPCNoLeader,
363 v3rpcTypes.ErrTimeout,
364 v3rpcTypes.ErrTimeoutDueToLeaderFail,
365 v3rpcTypes.ErrTimeoutDueToConnectionLost:
366 // Retry for these server errors
Girish Gowdra248971a2021-06-01 15:14:15 -0700367 logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err})
Abhay Kumar222b61b2025-10-29 20:32:42 +0000368 default:
369 logger.Warnw(ctx, "etcd-unknown-error", log.Fields{"error": err})
Girish Gowdra248971a2021-06-01 15:14:15 -0700370 }
Abhay Kumar222b61b2025-10-29 20:32:42 +0000371
372 // Common retry logic for all error cases
373 attempt++
374 if er := backoff(ctx, attempt); er != nil {
375 logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt})
376 return err
377 }
378 logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt})
379 goto startLoop
Girish Gowdra248971a2021-06-01 15:14:15 -0700380 }
381 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key})
382 return nil
Scott Baker2c1c4822019-10-16 11:02:41 -0700383 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700384}
385
Serkant Uluderya198de902020-11-16 20:29:17 +0300386func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error {
387
khenaidoo6f415b22021-06-22 18:08:53 -0400388 client, err := c.pool.Get(ctx)
389 if err != nil {
390 return err
391 }
392 defer c.pool.Put(client)
393
Serkant Uluderya198de902020-11-16 20:29:17 +0300394 //delete the prefix
Abhay Kumar40252eb2025-10-13 13:25:53 +0000395 if _, err := client.Delete(ctx, prefixKey, clientv3.WithPrefix()); err != nil {
Serkant Uluderya198de902020-11-16 20:29:17 +0300396 logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err})
397 return err
398 }
399 logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey})
400 return nil
401}
402
Scott Baker2c1c4822019-10-16 11:02:41 -0700403// Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to
404// listen to receive Events.
divyadesai8bf96862020-02-07 12:24:26 +0000405func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event {
khenaidoo6f415b22021-06-22 18:08:53 -0400406 var err error
407 // Reuse the Etcd client when multiple callees are watching the same key.
408 c.watchedClientsLock.Lock()
409 client, exist := c.watchedClients[key]
410 if !exist {
411 client, err = c.pool.Get(ctx)
412 if err != nil {
413 logger.Errorw(ctx, "failed-to-an-etcd-client", log.Fields{"key": key, "error": err})
414 c.watchedClientsLock.Unlock()
415 return nil
416 }
417 c.watchedClients[key] = client
418 }
419 c.watchedClientsLock.Unlock()
420
Abhay Kumar40252eb2025-10-13 13:25:53 +0000421 w := clientv3.NewWatcher(client)
npujar5bf737f2020-01-16 19:35:25 +0530422 ctx, cancel := context.WithCancel(ctx)
Abhay Kumar40252eb2025-10-13 13:25:53 +0000423 var channel clientv3.WatchChan
divyadesai8bf96862020-02-07 12:24:26 +0000424 if withPrefix {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000425 channel = w.Watch(ctx, key, clientv3.WithPrefix())
divyadesai8bf96862020-02-07 12:24:26 +0000426 } else {
427 channel = w.Watch(ctx, key)
428 }
Scott Baker2c1c4822019-10-16 11:02:41 -0700429
430 // Create a new channel
431 ch := make(chan *Event, maxClientChannelBufferSize)
432
433 // Keep track of the created channels so they can be closed when required
Abhay Kumar40252eb2025-10-13 13:25:53 +0000434 channelMap := make(map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700435 channelMap[ch] = w
Scott Baker2c1c4822019-10-16 11:02:41 -0700436 channelMaps := c.addChannelMap(key, channelMap)
437
438 // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a
439 // json format.
Neha Sharma94f16a92020-06-26 04:17:55 +0000440 logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)})
Scott Baker2c1c4822019-10-16 11:02:41 -0700441 // Launch a go routine to listen for updates
Neha Sharma94f16a92020-06-26 04:17:55 +0000442 go c.listenForKeyChange(ctx, channel, ch, cancel)
Scott Baker2c1c4822019-10-16 11:02:41 -0700443
444 return ch
445
446}
447
Abhay Kumar40252eb2025-10-13 13:25:53 +0000448func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]clientv3.Watcher) []map[chan *Event]clientv3.Watcher {
Scott Baker2c1c4822019-10-16 11:02:41 -0700449 var channels interface{}
450 var exists bool
451
452 if channels, exists = c.watchedChannels.Load(key); exists {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000453 channels = append(channels.([]map[chan *Event]clientv3.Watcher), channelMap)
Scott Baker2c1c4822019-10-16 11:02:41 -0700454 } else {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000455 channels = []map[chan *Event]clientv3.Watcher{channelMap}
Scott Baker2c1c4822019-10-16 11:02:41 -0700456 }
457 c.watchedChannels.Store(key, channels)
458
Abhay Kumar40252eb2025-10-13 13:25:53 +0000459 return channels.([]map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700460}
461
Abhay Kumar40252eb2025-10-13 13:25:53 +0000462func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]clientv3.Watcher {
Scott Baker2c1c4822019-10-16 11:02:41 -0700463 var channels interface{}
464 var exists bool
465
466 if channels, exists = c.watchedChannels.Load(key); exists {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000467 channels = append(channels.([]map[chan *Event]clientv3.Watcher)[:pos], channels.([]map[chan *Event]clientv3.Watcher)[pos+1:]...)
Scott Baker2c1c4822019-10-16 11:02:41 -0700468 c.watchedChannels.Store(key, channels)
469 }
470
Abhay Kumar40252eb2025-10-13 13:25:53 +0000471 return channels.([]map[chan *Event]clientv3.Watcher)
Scott Baker2c1c4822019-10-16 11:02:41 -0700472}
473
Abhay Kumar40252eb2025-10-13 13:25:53 +0000474func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]clientv3.Watcher, bool) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700475 var channels interface{}
476 var exists bool
477
478 channels, exists = c.watchedChannels.Load(key)
479
480 if channels == nil {
481 return nil, exists
482 }
483
Abhay Kumar40252eb2025-10-13 13:25:53 +0000484 return channels.([]map[chan *Event]clientv3.Watcher), exists
Scott Baker2c1c4822019-10-16 11:02:41 -0700485}
486
487// CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there
488// may be multiple listeners on the same key. The previously created channel serves as a key
Neha Sharma94f16a92020-06-26 04:17:55 +0000489func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) {
Scott Baker2c1c4822019-10-16 11:02:41 -0700490 // Get the array of channels mapping
Abhay Kumar40252eb2025-10-13 13:25:53 +0000491 var watchedChannels []map[chan *Event]clientv3.Watcher
Scott Baker2c1c4822019-10-16 11:02:41 -0700492 var ok bool
Scott Baker2c1c4822019-10-16 11:02:41 -0700493
494 if watchedChannels, ok = c.getChannelMaps(key); !ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000495 logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key})
Scott Baker2c1c4822019-10-16 11:02:41 -0700496 return
497 }
498 // Look for the channels
499 var pos = -1
500 for i, chMap := range watchedChannels {
501 if t, ok := chMap[ch]; ok {
Neha Sharma94f16a92020-06-26 04:17:55 +0000502 logger.Debug(ctx, "channel-found")
Scott Baker2c1c4822019-10-16 11:02:41 -0700503 // Close the etcd watcher before the client channel. This should close the etcd channel as well
504 if err := t.Close(); err != nil {
Neha Sharma94f16a92020-06-26 04:17:55 +0000505 logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err})
Scott Baker2c1c4822019-10-16 11:02:41 -0700506 }
507 pos = i
508 break
509 }
510 }
511
512 channelMaps, _ := c.getChannelMaps(key)
513 // Remove that entry if present
514 if pos >= 0 {
515 channelMaps = c.removeChannelMap(key, pos)
516 }
khenaidoo6f415b22021-06-22 18:08:53 -0400517
518 // If we don't have any keys being watched then return the Etcd client to the pool
519 if len(channelMaps) == 0 {
520 c.watchedClientsLock.Lock()
521 // Sanity
522 if client, ok := c.watchedClients[key]; ok {
523 c.pool.Put(client)
524 delete(c.watchedClients, key)
525 }
526 c.watchedClientsLock.Unlock()
527 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000528 logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps})
Scott Baker2c1c4822019-10-16 11:02:41 -0700529}
530
Abhay Kumar40252eb2025-10-13 13:25:53 +0000531func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel clientv3.WatchChan, ch chan<- *Event, cancel context.CancelFunc) {
Neha Sharma94f16a92020-06-26 04:17:55 +0000532 logger.Debug(ctx, "start-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700533 defer cancel()
534 defer close(ch)
535 for resp := range channel {
536 for _, ev := range resp.Events {
537 ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version)
538 }
539 }
Neha Sharma94f16a92020-06-26 04:17:55 +0000540 logger.Debug(ctx, "stop-listening-on-channel ...")
Scott Baker2c1c4822019-10-16 11:02:41 -0700541}
542
Abhay Kumar40252eb2025-10-13 13:25:53 +0000543func getEventType(event *clientv3.Event) int {
Scott Baker2c1c4822019-10-16 11:02:41 -0700544 switch event.Type {
Abhay Kumar40252eb2025-10-13 13:25:53 +0000545 case clientv3.EventTypePut:
Scott Baker2c1c4822019-10-16 11:02:41 -0700546 return PUT
Abhay Kumar40252eb2025-10-13 13:25:53 +0000547 case clientv3.EventTypeDelete:
Scott Baker2c1c4822019-10-16 11:02:41 -0700548 return DELETE
549 }
550 return UNKNOWN
551}
552
khenaidoo6f415b22021-06-22 18:08:53 -0400553// Close closes all the connection in the pool store client
Neha Sharma94f16a92020-06-26 04:17:55 +0000554func (c *EtcdClient) Close(ctx context.Context) {
khenaidoo6f415b22021-06-22 18:08:53 -0400555 logger.Debug(ctx, "closing-etcd-pool")
556 c.pool.Close(ctx)
Scott Baker2c1c4822019-10-16 11:02:41 -0700557}
558
khenaidoo6f415b22021-06-22 18:08:53 -0400559// The APIs below are not used
560var errUnimplemented = errors.New("deprecated")
561
562// Reserve is deprecated
563func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) {
564 return nil, errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700565}
566
khenaidoo6f415b22021-06-22 18:08:53 -0400567// ReleaseAllReservations is deprecated
568func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error {
569 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700570}
571
khenaidoo6f415b22021-06-22 18:08:53 -0400572// ReleaseReservation is deprecated
573func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error {
574 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700575}
576
khenaidoo6f415b22021-06-22 18:08:53 -0400577// RenewReservation is deprecated
578func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error {
579 return errUnimplemented
580}
581
582// AcquireLock is deprecated
Neha Sharma130ac6d2020-04-08 08:46:32 +0000583func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400584 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700585}
586
khenaidoo6f415b22021-06-22 18:08:53 -0400587// ReleaseLock is deprecated
Scott Baker2c1c4822019-10-16 11:02:41 -0700588func (c *EtcdClient) ReleaseLock(lockName string) error {
khenaidoo6f415b22021-06-22 18:08:53 -0400589 return errUnimplemented
Scott Baker2c1c4822019-10-16 11:02:41 -0700590}