Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 1 | /* |
Joey Armstrong | 9cdee9f | 2024-01-03 04:56:14 -0500 | [diff] [blame] | 2 | * Copyright 2018-2024 Open Networking Foundation (ONF) and the ONF Contributors |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 3 | |
Joey Armstrong | 7f8436c | 2023-07-09 20:23:27 -0400 | [diff] [blame] | 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 |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 7 | |
Joey Armstrong | 7f8436c | 2023-07-09 20:23:27 -0400 | [diff] [blame] | 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 9 | |
Joey Armstrong | 7f8436c | 2023-07-09 20:23:27 -0400 | [diff] [blame] | 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. |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 15 | */ |
| 16 | package kvstore |
| 17 | |
| 18 | import ( |
| 19 | "context" |
| 20 | "errors" |
| 21 | "fmt" |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 22 | "os" |
| 23 | "strconv" |
| 24 | "sync" |
| 25 | "time" |
khenaidoo | 2672188 | 2021-08-11 17:42:52 -0400 | [diff] [blame] | 26 | |
| 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" |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 30 | ) |
| 31 | |
| 32 | const ( |
| 33 | poolCapacityEnvName = "VOLTHA_ETCD_CLIENT_POOL_CAPACITY" |
| 34 | maxUsageEnvName = "VOLTHA_ETCD_CLIENT_MAX_USAGE" |
| 35 | ) |
| 36 | |
| 37 | const ( |
| 38 | defaultMaxPoolCapacity = 1000 // Default size of an Etcd Client pool |
| 39 | defaultMaxPoolUsage = 100 // Maximum concurrent request an Etcd Client is allowed to process |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 40 | ) |
| 41 | |
| 42 | // EtcdClient represents the Etcd KV store client |
| 43 | type EtcdClient struct { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 44 | pool EtcdClientAllocator |
| 45 | watchedChannels sync.Map |
| 46 | watchedClients map[string]*v3Client.Client |
| 47 | watchedClientsLock sync.RWMutex |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 48 | } |
| 49 | |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 50 | // NewEtcdCustomClient returns a new client for the Etcd KV store allowing |
| 51 | // the called to specify etcd client configuration |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 52 | func 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 Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 71 | } |
| 72 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 73 | var err error |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 74 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 75 | 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 Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 87 | } |
| 88 | |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 89 | // NewEtcdClient returns a new client for the Etcd KV store |
| 90 | func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 91 | return NewEtcdCustomClient(ctx, addr, timeout, level) |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 92 | } |
| 93 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 94 | // 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. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 96 | func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 97 | // Let's try to get a non existent key. If the connection is up then there will be no error returned. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 98 | if _, err := c.Get(ctx, "non-existent-key"); err != nil { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 99 | return false |
| 100 | } |
| 101 | return true |
| 102 | } |
| 103 | |
| 104 | // List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will |
| 105 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 106 | func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 107 | client, err := c.pool.Get(ctx) |
| 108 | if err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | defer c.pool.Put(client) |
| 112 | resp, err := client.Get(ctx, key, v3Client.WithPrefix()) |
| 113 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 114 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 115 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 116 | return nil, err |
| 117 | } |
| 118 | m := make(map[string]*KVPair) |
| 119 | for _, ev := range resp.Kvs { |
| 120 | m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version) |
| 121 | } |
| 122 | return m, nil |
| 123 | } |
| 124 | |
| 125 | // Get returns a key-value pair for a given key. Timeout defines how long the function will |
| 126 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 127 | func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 128 | client, err := c.pool.Get(ctx) |
| 129 | if err != nil { |
| 130 | return nil, err |
| 131 | } |
| 132 | defer c.pool.Put(client) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 133 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 134 | attempt := 0 |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 135 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 136 | startLoop: |
| 137 | for { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 138 | resp, err := client.Get(ctx, key) |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 139 | if err != nil { |
| 140 | switch err { |
| 141 | case context.Canceled: |
| 142 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 143 | case context.DeadlineExceeded: |
| 144 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 145 | case v3rpcTypes.ErrEmptyKey: |
| 146 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 147 | case v3rpcTypes.ErrLeaderChanged, |
| 148 | v3rpcTypes.ErrGRPCNoLeader, |
| 149 | v3rpcTypes.ErrTimeout, |
| 150 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 151 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 152 | // Retry for these server errors |
| 153 | attempt += 1 |
| 154 | if er := backoff(ctx, attempt); er != nil { |
| 155 | logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 156 | return nil, err |
| 157 | } |
| 158 | logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 159 | goto startLoop |
| 160 | default: |
| 161 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 162 | } |
| 163 | return nil, err |
| 164 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 165 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 166 | for _, ev := range resp.Kvs { |
| 167 | // Only one value is returned |
| 168 | return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil |
| 169 | } |
| 170 | return nil, nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 171 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 172 | } |
| 173 | |
pnalmas | 3756075 | 2025-01-11 22:05:35 +0530 | [diff] [blame] | 174 | // GetWithPrefix fetches all key-value pairs with the specified prefix from etcd. |
| 175 | // Returns a map of key-value pairs or an error if the operation fails. |
| 176 | func (c *EtcdClient) GetWithPrefix(ctx context.Context, prefixKey string) (map[string]*KVPair, error) { |
| 177 | // Acquire a client from the pool |
| 178 | client, err := c.pool.Get(ctx) |
| 179 | if err != nil { |
| 180 | return nil, fmt.Errorf("failed to get client from pool: %w", err) |
| 181 | } |
| 182 | defer c.pool.Put(client) |
| 183 | |
| 184 | // Fetch keys with the prefix |
| 185 | resp, err := client.Get(ctx, prefixKey, v3Client.WithPrefix()) |
| 186 | if err != nil { |
| 187 | return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err) |
| 188 | } |
| 189 | |
| 190 | // Initialize the result map |
| 191 | result := make(map[string]*KVPair) |
| 192 | |
| 193 | // Iterate through the fetched key-value pairs and populate the map |
| 194 | for _, ev := range resp.Kvs { |
| 195 | result[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version) |
| 196 | } |
| 197 | |
| 198 | return result, nil |
| 199 | } |
| 200 | |
| 201 | // GetWithPrefixKeysOnly retrieves only the keys that match a given prefix. |
| 202 | func (c *EtcdClient) GetWithPrefixKeysOnly(ctx context.Context, prefixKey string) ([]string, error) { |
| 203 | // Acquire a client from the pool |
| 204 | client, err := c.pool.Get(ctx) |
| 205 | if err != nil { |
| 206 | return nil, fmt.Errorf("failed to get client from pool: %w", err) |
| 207 | } |
| 208 | defer c.pool.Put(client) |
| 209 | |
| 210 | // Fetch keys with the prefix |
| 211 | resp, err := client.Get(ctx, prefixKey, v3Client.WithPrefix(), v3Client.WithKeysOnly()) |
| 212 | if err != nil { |
| 213 | return nil, fmt.Errorf("failed to fetch entries for prefix %s: %w", prefixKey, err) |
| 214 | } |
| 215 | |
| 216 | // Extract keys from the response |
| 217 | keys := []string{} |
| 218 | for _, kv := range resp.Kvs { |
| 219 | keys = append(keys, string(kv.Key)) |
| 220 | } |
| 221 | |
| 222 | return keys, nil |
| 223 | } |
| 224 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 225 | // Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API |
| 226 | // accepts only a string as a value for a put operation. Timeout defines how long the function will |
| 227 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 228 | func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 229 | |
| 230 | // Validate that we can convert value to a string as etcd API expects a string |
| 231 | var val string |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 232 | var err error |
| 233 | if val, err = ToString(value); err != nil { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 234 | return fmt.Errorf("unexpected-type-%T", value) |
| 235 | } |
| 236 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 237 | client, err := c.pool.Get(ctx) |
| 238 | if err != nil { |
| 239 | return err |
| 240 | } |
| 241 | defer c.pool.Put(client) |
| 242 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 243 | attempt := 0 |
| 244 | startLoop: |
| 245 | for { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 246 | _, err = client.Put(ctx, key, val) |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 247 | if err != nil { |
| 248 | switch err { |
| 249 | case context.Canceled: |
| 250 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 251 | case context.DeadlineExceeded: |
| 252 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 253 | case v3rpcTypes.ErrEmptyKey: |
| 254 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 255 | case v3rpcTypes.ErrLeaderChanged, |
| 256 | v3rpcTypes.ErrGRPCNoLeader, |
| 257 | v3rpcTypes.ErrTimeout, |
| 258 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 259 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 260 | // Retry for these server errors |
| 261 | attempt += 1 |
| 262 | if er := backoff(ctx, attempt); er != nil { |
| 263 | logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 264 | return err |
| 265 | } |
| 266 | logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 267 | goto startLoop |
| 268 | default: |
| 269 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 270 | } |
| 271 | return err |
| 272 | } |
| 273 | return nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 274 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 275 | } |
| 276 | |
| 277 | // Delete removes a key from the KV store. Timeout defines how long the function will |
| 278 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 279 | func (c *EtcdClient) Delete(ctx context.Context, key string) error { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 280 | client, err := c.pool.Get(ctx) |
| 281 | if err != nil { |
| 282 | return err |
| 283 | } |
| 284 | defer c.pool.Put(client) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 285 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 286 | attempt := 0 |
| 287 | startLoop: |
| 288 | for { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 289 | _, err = client.Delete(ctx, key) |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 290 | if err != nil { |
| 291 | switch err { |
| 292 | case context.Canceled: |
| 293 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 294 | case context.DeadlineExceeded: |
| 295 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 296 | case v3rpcTypes.ErrEmptyKey: |
| 297 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 298 | case v3rpcTypes.ErrLeaderChanged, |
| 299 | v3rpcTypes.ErrGRPCNoLeader, |
| 300 | v3rpcTypes.ErrTimeout, |
| 301 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 302 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 303 | // Retry for these server errors |
| 304 | attempt += 1 |
| 305 | if er := backoff(ctx, attempt); er != nil { |
| 306 | logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 307 | return err |
| 308 | } |
| 309 | logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 310 | goto startLoop |
| 311 | default: |
| 312 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 313 | } |
| 314 | return err |
| 315 | } |
| 316 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key}) |
| 317 | return nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 318 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 319 | } |
| 320 | |
Serkant Uluderya | 198de90 | 2020-11-16 20:29:17 +0300 | [diff] [blame] | 321 | func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error { |
| 322 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 323 | client, err := c.pool.Get(ctx) |
| 324 | if err != nil { |
| 325 | return err |
| 326 | } |
| 327 | defer c.pool.Put(client) |
| 328 | |
Serkant Uluderya | 198de90 | 2020-11-16 20:29:17 +0300 | [diff] [blame] | 329 | //delete the prefix |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 330 | if _, err := client.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil { |
Serkant Uluderya | 198de90 | 2020-11-16 20:29:17 +0300 | [diff] [blame] | 331 | logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err}) |
| 332 | return err |
| 333 | } |
| 334 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey}) |
| 335 | return nil |
| 336 | } |
| 337 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 338 | // Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to |
| 339 | // listen to receive Events. |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 340 | func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 341 | var err error |
| 342 | // Reuse the Etcd client when multiple callees are watching the same key. |
| 343 | c.watchedClientsLock.Lock() |
| 344 | client, exist := c.watchedClients[key] |
| 345 | if !exist { |
| 346 | client, err = c.pool.Get(ctx) |
| 347 | if err != nil { |
| 348 | logger.Errorw(ctx, "failed-to-an-etcd-client", log.Fields{"key": key, "error": err}) |
| 349 | c.watchedClientsLock.Unlock() |
| 350 | return nil |
| 351 | } |
| 352 | c.watchedClients[key] = client |
| 353 | } |
| 354 | c.watchedClientsLock.Unlock() |
| 355 | |
| 356 | w := v3Client.NewWatcher(client) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 357 | ctx, cancel := context.WithCancel(ctx) |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 358 | var channel v3Client.WatchChan |
| 359 | if withPrefix { |
| 360 | channel = w.Watch(ctx, key, v3Client.WithPrefix()) |
| 361 | } else { |
| 362 | channel = w.Watch(ctx, key) |
| 363 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 364 | |
| 365 | // Create a new channel |
| 366 | ch := make(chan *Event, maxClientChannelBufferSize) |
| 367 | |
| 368 | // Keep track of the created channels so they can be closed when required |
| 369 | channelMap := make(map[chan *Event]v3Client.Watcher) |
| 370 | channelMap[ch] = w |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 371 | channelMaps := c.addChannelMap(key, channelMap) |
| 372 | |
| 373 | // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a |
| 374 | // json format. |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 375 | logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 376 | // Launch a go routine to listen for updates |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 377 | go c.listenForKeyChange(ctx, channel, ch, cancel) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 378 | |
| 379 | return ch |
| 380 | |
| 381 | } |
| 382 | |
| 383 | func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher { |
| 384 | var channels interface{} |
| 385 | var exists bool |
| 386 | |
| 387 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 388 | channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap) |
| 389 | } else { |
| 390 | channels = []map[chan *Event]v3Client.Watcher{channelMap} |
| 391 | } |
| 392 | c.watchedChannels.Store(key, channels) |
| 393 | |
| 394 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 395 | } |
| 396 | |
| 397 | func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher { |
| 398 | var channels interface{} |
| 399 | var exists bool |
| 400 | |
| 401 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 402 | channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...) |
| 403 | c.watchedChannels.Store(key, channels) |
| 404 | } |
| 405 | |
| 406 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 407 | } |
| 408 | |
| 409 | func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) { |
| 410 | var channels interface{} |
| 411 | var exists bool |
| 412 | |
| 413 | channels, exists = c.watchedChannels.Load(key) |
| 414 | |
| 415 | if channels == nil { |
| 416 | return nil, exists |
| 417 | } |
| 418 | |
| 419 | return channels.([]map[chan *Event]v3Client.Watcher), exists |
| 420 | } |
| 421 | |
| 422 | // CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there |
| 423 | // may be multiple listeners on the same key. The previously created channel serves as a key |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 424 | func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 425 | // Get the array of channels mapping |
| 426 | var watchedChannels []map[chan *Event]v3Client.Watcher |
| 427 | var ok bool |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 428 | |
| 429 | if watchedChannels, ok = c.getChannelMaps(key); !ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 430 | logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 431 | return |
| 432 | } |
| 433 | // Look for the channels |
| 434 | var pos = -1 |
| 435 | for i, chMap := range watchedChannels { |
| 436 | if t, ok := chMap[ch]; ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 437 | logger.Debug(ctx, "channel-found") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 438 | // Close the etcd watcher before the client channel. This should close the etcd channel as well |
| 439 | if err := t.Close(); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 440 | logger.Errorw(ctx, "watcher-cannot-be-closed", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 441 | } |
| 442 | pos = i |
| 443 | break |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | channelMaps, _ := c.getChannelMaps(key) |
| 448 | // Remove that entry if present |
| 449 | if pos >= 0 { |
| 450 | channelMaps = c.removeChannelMap(key, pos) |
| 451 | } |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 452 | |
| 453 | // If we don't have any keys being watched then return the Etcd client to the pool |
| 454 | if len(channelMaps) == 0 { |
| 455 | c.watchedClientsLock.Lock() |
| 456 | // Sanity |
| 457 | if client, ok := c.watchedClients[key]; ok { |
| 458 | c.pool.Put(client) |
| 459 | delete(c.watchedClients, key) |
| 460 | } |
| 461 | c.watchedClientsLock.Unlock() |
| 462 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 463 | logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 464 | } |
| 465 | |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 466 | func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) { |
| 467 | logger.Debug(ctx, "start-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 468 | defer cancel() |
| 469 | defer close(ch) |
| 470 | for resp := range channel { |
| 471 | for _, ev := range resp.Events { |
| 472 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version) |
| 473 | } |
| 474 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 475 | logger.Debug(ctx, "stop-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 476 | } |
| 477 | |
| 478 | func getEventType(event *v3Client.Event) int { |
| 479 | switch event.Type { |
| 480 | case v3Client.EventTypePut: |
| 481 | return PUT |
| 482 | case v3Client.EventTypeDelete: |
| 483 | return DELETE |
| 484 | } |
| 485 | return UNKNOWN |
| 486 | } |
| 487 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 488 | // Close closes all the connection in the pool store client |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 489 | func (c *EtcdClient) Close(ctx context.Context) { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 490 | logger.Debug(ctx, "closing-etcd-pool") |
| 491 | c.pool.Close(ctx) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 492 | } |
| 493 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 494 | // The APIs below are not used |
| 495 | var errUnimplemented = errors.New("deprecated") |
| 496 | |
| 497 | // Reserve is deprecated |
| 498 | func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) { |
| 499 | return nil, errUnimplemented |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 500 | } |
| 501 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 502 | // ReleaseAllReservations is deprecated |
| 503 | func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error { |
| 504 | return errUnimplemented |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 505 | } |
| 506 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 507 | // ReleaseReservation is deprecated |
| 508 | func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error { |
| 509 | return errUnimplemented |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 510 | } |
| 511 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 512 | // RenewReservation is deprecated |
| 513 | func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error { |
| 514 | return errUnimplemented |
| 515 | } |
| 516 | |
| 517 | // AcquireLock is deprecated |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 518 | func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 519 | return errUnimplemented |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 520 | } |
| 521 | |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 522 | // ReleaseLock is deprecated |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 523 | func (c *EtcdClient) ReleaseLock(lockName string) error { |
khenaidoo | 6f415b2 | 2021-06-22 18:08:53 -0400 | [diff] [blame] | 524 | return errUnimplemented |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 525 | } |