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