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" |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 22 | "sync" |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 23 | "time" |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 24 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 25 | "github.com/opencord/voltha-lib-go/v5/pkg/log" |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 26 | v3Client "go.etcd.io/etcd/clientv3" |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 27 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 28 | v3Concurrency "go.etcd.io/etcd/clientv3/concurrency" |
| 29 | v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes" |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 30 | ) |
| 31 | |
| 32 | // EtcdClient represents the Etcd KV store client |
| 33 | type EtcdClient struct { |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 34 | ectdAPI *v3Client.Client |
| 35 | keyReservations map[string]*v3Client.LeaseID |
| 36 | watchedChannels sync.Map |
| 37 | keyReservationsLock sync.RWMutex |
| 38 | lockToMutexMap map[string]*v3Concurrency.Mutex |
| 39 | lockToSessionMap map[string]*v3Concurrency.Session |
| 40 | lockToMutexLock sync.Mutex |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 41 | } |
| 42 | |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 43 | // NewEtcdCustomClient returns a new client for the Etcd KV store allowing |
| 44 | // the called to specify etcd client configuration |
| 45 | func NewEtcdCustomClient(ctx context.Context, config *v3Client.Config) (*EtcdClient, error) { |
| 46 | c, err := v3Client.New(*config) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 47 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 48 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 49 | return nil, err |
| 50 | } |
| 51 | |
| 52 | reservations := make(map[string]*v3Client.LeaseID) |
| 53 | lockMutexMap := make(map[string]*v3Concurrency.Mutex) |
| 54 | lockSessionMap := make(map[string]*v3Concurrency.Session) |
| 55 | |
| 56 | return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap, |
| 57 | lockToSessionMap: lockSessionMap}, nil |
| 58 | } |
| 59 | |
David K. Bainbridge | bc38107 | 2021-03-19 20:56:04 +0000 | [diff] [blame] | 60 | // NewEtcdClient returns a new client for the Etcd KV store |
| 61 | func NewEtcdClient(ctx context.Context, addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) { |
| 62 | logconfig := log.ConstructZapConfig(log.JSON, level, log.Fields{}) |
| 63 | |
| 64 | return NewEtcdCustomClient( |
| 65 | ctx, |
| 66 | &v3Client.Config{ |
| 67 | Endpoints: []string{addr}, |
| 68 | DialTimeout: timeout, |
| 69 | LogConfig: &logconfig}) |
| 70 | } |
| 71 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 72 | // IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then |
| 73 | // it is assumed the connection is down or unreachable. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 74 | func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 75 | // 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] | 76 | if _, err := c.Get(ctx, "non-existent-key"); err != nil { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 77 | return false |
| 78 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 79 | //cancel() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 80 | return true |
| 81 | } |
| 82 | |
| 83 | // List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will |
| 84 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 85 | func (c *EtcdClient) List(ctx context.Context, key string) (map[string]*KVPair, error) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 86 | resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix()) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 87 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 88 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 89 | return nil, err |
| 90 | } |
| 91 | m := make(map[string]*KVPair) |
| 92 | for _, ev := range resp.Kvs { |
| 93 | m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version) |
| 94 | } |
| 95 | return m, nil |
| 96 | } |
| 97 | |
| 98 | // Get returns a key-value pair for a given key. Timeout defines how long the function will |
| 99 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 100 | func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 101 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 102 | attempt := 0 |
| 103 | startLoop: |
| 104 | for { |
| 105 | resp, err := c.ectdAPI.Get(ctx, key) |
| 106 | if err != nil { |
| 107 | switch err { |
| 108 | case context.Canceled: |
| 109 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 110 | case context.DeadlineExceeded: |
| 111 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 112 | case v3rpcTypes.ErrEmptyKey: |
| 113 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 114 | case v3rpcTypes.ErrLeaderChanged, |
| 115 | v3rpcTypes.ErrGRPCNoLeader, |
| 116 | v3rpcTypes.ErrTimeout, |
| 117 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 118 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 119 | // Retry for these server errors |
| 120 | attempt += 1 |
| 121 | if er := backoff(ctx, attempt); er != nil { |
| 122 | logger.Warnw(ctx, "get-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 123 | return nil, err |
| 124 | } |
| 125 | logger.Warnw(ctx, "retrying-get", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 126 | goto startLoop |
| 127 | default: |
| 128 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 129 | } |
| 130 | return nil, err |
| 131 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 132 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 133 | for _, ev := range resp.Kvs { |
| 134 | // Only one value is returned |
| 135 | return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil |
| 136 | } |
| 137 | return nil, nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 138 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | // Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API |
| 142 | // accepts only a string as a value for a put operation. Timeout defines how long the function will |
| 143 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 144 | func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 145 | |
| 146 | // Validate that we can convert value to a string as etcd API expects a string |
| 147 | var val string |
| 148 | var er error |
| 149 | if val, er = ToString(value); er != nil { |
| 150 | return fmt.Errorf("unexpected-type-%T", value) |
| 151 | } |
| 152 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 153 | // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make |
| 154 | // that KV key permanent instead of automatically removing it after a lease expiration |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 155 | c.keyReservationsLock.RLock() |
| 156 | leaseID, ok := c.keyReservations[key] |
| 157 | c.keyReservationsLock.RUnlock() |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 158 | attempt := 0 |
| 159 | startLoop: |
| 160 | for { |
| 161 | var err error |
| 162 | if ok { |
| 163 | _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID)) |
| 164 | } else { |
| 165 | _, err = c.ectdAPI.Put(ctx, key, val) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 166 | } |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 167 | if err != nil { |
| 168 | switch err { |
| 169 | case context.Canceled: |
| 170 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 171 | case context.DeadlineExceeded: |
| 172 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 173 | case v3rpcTypes.ErrEmptyKey: |
| 174 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 175 | case v3rpcTypes.ErrLeaderChanged, |
| 176 | v3rpcTypes.ErrGRPCNoLeader, |
| 177 | v3rpcTypes.ErrTimeout, |
| 178 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 179 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 180 | // Retry for these server errors |
| 181 | attempt += 1 |
| 182 | if er := backoff(ctx, attempt); er != nil { |
| 183 | logger.Warnw(ctx, "put-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 184 | return err |
| 185 | } |
| 186 | logger.Warnw(ctx, "retrying-put", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 187 | goto startLoop |
| 188 | default: |
| 189 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 190 | } |
| 191 | return err |
| 192 | } |
| 193 | return nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 194 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 195 | } |
| 196 | |
| 197 | // Delete removes a key from the KV store. Timeout defines how long the function will |
| 198 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 199 | func (c *EtcdClient) Delete(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 200 | |
Girish Gowdra | 248971a | 2021-06-01 15:14:15 -0700 | [diff] [blame] | 201 | attempt := 0 |
| 202 | startLoop: |
| 203 | for { |
| 204 | _, err := c.ectdAPI.Delete(ctx, key) |
| 205 | if err != nil { |
| 206 | switch err { |
| 207 | case context.Canceled: |
| 208 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
| 209 | case context.DeadlineExceeded: |
| 210 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err, "context": ctx}) |
| 211 | case v3rpcTypes.ErrEmptyKey: |
| 212 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
| 213 | case v3rpcTypes.ErrLeaderChanged, |
| 214 | v3rpcTypes.ErrGRPCNoLeader, |
| 215 | v3rpcTypes.ErrTimeout, |
| 216 | v3rpcTypes.ErrTimeoutDueToLeaderFail, |
| 217 | v3rpcTypes.ErrTimeoutDueToConnectionLost: |
| 218 | // Retry for these server errors |
| 219 | attempt += 1 |
| 220 | if er := backoff(ctx, attempt); er != nil { |
| 221 | logger.Warnw(ctx, "delete-retries-failed", log.Fields{"key": key, "error": er, "attempt": attempt}) |
| 222 | return err |
| 223 | } |
| 224 | logger.Warnw(ctx, "retrying-delete", log.Fields{"key": key, "error": err, "attempt": attempt}) |
| 225 | goto startLoop |
| 226 | default: |
| 227 | logger.Warnw(ctx, "etcd-server-error", log.Fields{"error": err}) |
| 228 | } |
| 229 | return err |
| 230 | } |
| 231 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key}) |
| 232 | return nil |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 233 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 234 | } |
| 235 | |
Serkant Uluderya | 198de90 | 2020-11-16 20:29:17 +0300 | [diff] [blame] | 236 | func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error { |
| 237 | |
| 238 | //delete the prefix |
| 239 | if _, err := c.ectdAPI.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil { |
| 240 | logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err}) |
| 241 | return err |
| 242 | } |
| 243 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey}) |
| 244 | return nil |
| 245 | } |
| 246 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 247 | // Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since |
| 248 | // the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL |
| 249 | // defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself. |
| 250 | // If the key is acquired then the value returned will be the value passed in. If the key is already acquired |
| 251 | // then the value assigned to that key will be returned. |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 252 | func (c *EtcdClient) Reserve(ctx context.Context, key string, value interface{}, ttl time.Duration) (interface{}, error) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 253 | // Validate that we can convert value to a string as etcd API expects a string |
| 254 | var val string |
| 255 | var er error |
| 256 | if val, er = ToString(value); er != nil { |
| 257 | return nil, fmt.Errorf("unexpected-type%T", value) |
| 258 | } |
| 259 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 260 | resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds())) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 261 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 262 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 263 | return nil, err |
| 264 | } |
| 265 | // Register the lease id |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 266 | c.keyReservationsLock.Lock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 267 | c.keyReservations[key] = &resp.ID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 268 | c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 269 | |
| 270 | // Revoke lease if reservation is not successful |
| 271 | reservationSuccessful := false |
| 272 | defer func() { |
| 273 | if !reservationSuccessful { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 274 | if err = c.ReleaseReservation(context.Background(), key); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 275 | logger.Error(ctx, "cannot-release-lease") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 276 | } |
| 277 | } |
| 278 | }() |
| 279 | |
| 280 | // Try to grap the Key with the above lease |
| 281 | c.ectdAPI.Txn(context.Background()) |
| 282 | txn := c.ectdAPI.Txn(context.Background()) |
| 283 | txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0)) |
| 284 | txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID))) |
| 285 | txn = txn.Else(v3Client.OpGet(key)) |
| 286 | result, er := txn.Commit() |
| 287 | if er != nil { |
| 288 | return nil, er |
| 289 | } |
| 290 | |
| 291 | if !result.Succeeded { |
| 292 | // Verify whether we are already the owner of that Key |
| 293 | if len(result.Responses) > 0 && |
| 294 | len(result.Responses[0].GetResponseRange().Kvs) > 0 { |
| 295 | kv := result.Responses[0].GetResponseRange().Kvs[0] |
| 296 | if string(kv.Value) == val { |
| 297 | reservationSuccessful = true |
| 298 | return value, nil |
| 299 | } |
| 300 | return kv.Value, nil |
| 301 | } |
| 302 | } else { |
| 303 | // Read the Key to ensure this is our Key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 304 | m, err := c.Get(ctx, key) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 305 | if err != nil { |
| 306 | return nil, err |
| 307 | } |
| 308 | if m != nil { |
| 309 | if m.Key == key && isEqual(m.Value, value) { |
| 310 | // My reservation is successful - register it. For now, support is only for 1 reservation per key |
| 311 | // per session. |
| 312 | reservationSuccessful = true |
| 313 | return value, nil |
| 314 | } |
| 315 | // My reservation has failed. Return the owner of that key |
| 316 | return m.Value, nil |
| 317 | } |
| 318 | } |
| 319 | return nil, nil |
| 320 | } |
| 321 | |
| 322 | // ReleaseAllReservations releases all key reservations previously made (using Reserve API) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 323 | func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error { |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 324 | c.keyReservationsLock.Lock() |
| 325 | defer c.keyReservationsLock.Unlock() |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 326 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 327 | for key, leaseID := range c.keyReservations { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 328 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 329 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 330 | logger.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 331 | return err |
| 332 | } |
| 333 | delete(c.keyReservations, key) |
| 334 | } |
| 335 | return nil |
| 336 | } |
| 337 | |
| 338 | // ReleaseReservation releases reservation for a specific key. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 339 | func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 340 | // Get the leaseid using the key |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 341 | logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 342 | var ok bool |
| 343 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 344 | c.keyReservationsLock.Lock() |
| 345 | defer c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 346 | if leaseID, ok = c.keyReservations[key]; !ok { |
| 347 | return nil |
| 348 | } |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 349 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 350 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 351 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 352 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 353 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 354 | return err |
| 355 | } |
| 356 | delete(c.keyReservations, key) |
| 357 | } |
| 358 | return nil |
| 359 | } |
| 360 | |
| 361 | // RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live) |
| 362 | // period specified when reserving the key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 363 | func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 364 | // Get the leaseid using the key |
| 365 | var ok bool |
| 366 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 367 | c.keyReservationsLock.RLock() |
| 368 | leaseID, ok = c.keyReservations[key] |
| 369 | c.keyReservationsLock.RUnlock() |
| 370 | |
| 371 | if !ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 372 | return errors.New("key-not-reserved") |
| 373 | } |
| 374 | |
| 375 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 376 | _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 377 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 378 | logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 379 | return err |
| 380 | } |
| 381 | } else { |
| 382 | return errors.New("lease-expired") |
| 383 | } |
| 384 | return nil |
| 385 | } |
| 386 | |
| 387 | // Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to |
| 388 | // listen to receive Events. |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 389 | func (c *EtcdClient) Watch(ctx context.Context, key string, withPrefix bool) chan *Event { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 390 | w := v3Client.NewWatcher(c.ectdAPI) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 391 | ctx, cancel := context.WithCancel(ctx) |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 392 | var channel v3Client.WatchChan |
| 393 | if withPrefix { |
| 394 | channel = w.Watch(ctx, key, v3Client.WithPrefix()) |
| 395 | } else { |
| 396 | channel = w.Watch(ctx, key) |
| 397 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 398 | |
| 399 | // Create a new channel |
| 400 | ch := make(chan *Event, maxClientChannelBufferSize) |
| 401 | |
| 402 | // Keep track of the created channels so they can be closed when required |
| 403 | channelMap := make(map[chan *Event]v3Client.Watcher) |
| 404 | channelMap[ch] = w |
| 405 | |
| 406 | channelMaps := c.addChannelMap(key, channelMap) |
| 407 | |
| 408 | // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a |
| 409 | // json format. |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 410 | logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 411 | // Launch a go routine to listen for updates |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 412 | go c.listenForKeyChange(ctx, channel, ch, cancel) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 413 | |
| 414 | return ch |
| 415 | |
| 416 | } |
| 417 | |
| 418 | func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher { |
| 419 | var channels interface{} |
| 420 | var exists bool |
| 421 | |
| 422 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 423 | channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap) |
| 424 | } else { |
| 425 | channels = []map[chan *Event]v3Client.Watcher{channelMap} |
| 426 | } |
| 427 | c.watchedChannels.Store(key, channels) |
| 428 | |
| 429 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 430 | } |
| 431 | |
| 432 | func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher { |
| 433 | var channels interface{} |
| 434 | var exists bool |
| 435 | |
| 436 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 437 | channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...) |
| 438 | c.watchedChannels.Store(key, channels) |
| 439 | } |
| 440 | |
| 441 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 442 | } |
| 443 | |
| 444 | func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) { |
| 445 | var channels interface{} |
| 446 | var exists bool |
| 447 | |
| 448 | channels, exists = c.watchedChannels.Load(key) |
| 449 | |
| 450 | if channels == nil { |
| 451 | return nil, exists |
| 452 | } |
| 453 | |
| 454 | return channels.([]map[chan *Event]v3Client.Watcher), exists |
| 455 | } |
| 456 | |
| 457 | // CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there |
| 458 | // 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] | 459 | func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 460 | // Get the array of channels mapping |
| 461 | var watchedChannels []map[chan *Event]v3Client.Watcher |
| 462 | var ok bool |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 463 | |
| 464 | if watchedChannels, ok = c.getChannelMaps(key); !ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 465 | logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 466 | return |
| 467 | } |
| 468 | // Look for the channels |
| 469 | var pos = -1 |
| 470 | for i, chMap := range watchedChannels { |
| 471 | if t, ok := chMap[ch]; ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 472 | logger.Debug(ctx, "channel-found") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 473 | // Close the etcd watcher before the client channel. This should close the etcd channel as well |
| 474 | if err := t.Close(); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 475 | 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] | 476 | } |
| 477 | pos = i |
| 478 | break |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | channelMaps, _ := c.getChannelMaps(key) |
| 483 | // Remove that entry if present |
| 484 | if pos >= 0 { |
| 485 | channelMaps = c.removeChannelMap(key, pos) |
| 486 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 487 | logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 488 | } |
| 489 | |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 490 | func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) { |
| 491 | logger.Debug(ctx, "start-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 492 | defer cancel() |
| 493 | defer close(ch) |
| 494 | for resp := range channel { |
| 495 | for _, ev := range resp.Events { |
| 496 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version) |
| 497 | } |
| 498 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 499 | logger.Debug(ctx, "stop-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 500 | } |
| 501 | |
| 502 | func getEventType(event *v3Client.Event) int { |
| 503 | switch event.Type { |
| 504 | case v3Client.EventTypePut: |
| 505 | return PUT |
| 506 | case v3Client.EventTypeDelete: |
| 507 | return DELETE |
| 508 | } |
| 509 | return UNKNOWN |
| 510 | } |
| 511 | |
| 512 | // Close closes the KV store client |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 513 | func (c *EtcdClient) Close(ctx context.Context) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 514 | if err := c.ectdAPI.Close(); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 515 | logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 516 | } |
| 517 | } |
| 518 | |
| 519 | func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) { |
| 520 | c.lockToMutexLock.Lock() |
| 521 | defer c.lockToMutexLock.Unlock() |
| 522 | c.lockToMutexMap[lockName] = lock |
| 523 | c.lockToSessionMap[lockName] = session |
| 524 | } |
| 525 | |
| 526 | func (c *EtcdClient) deleteLockName(lockName string) { |
| 527 | c.lockToMutexLock.Lock() |
| 528 | defer c.lockToMutexLock.Unlock() |
| 529 | delete(c.lockToMutexMap, lockName) |
| 530 | delete(c.lockToSessionMap, lockName) |
| 531 | } |
| 532 | |
| 533 | func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) { |
| 534 | c.lockToMutexLock.Lock() |
| 535 | defer c.lockToMutexLock.Unlock() |
| 536 | var lock *v3Concurrency.Mutex |
| 537 | var session *v3Concurrency.Session |
| 538 | if l, exist := c.lockToMutexMap[lockName]; exist { |
| 539 | lock = l |
| 540 | } |
| 541 | if s, exist := c.lockToSessionMap[lockName]; exist { |
| 542 | session = s |
| 543 | } |
| 544 | return lock, session |
| 545 | } |
| 546 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 547 | func (c *EtcdClient) AcquireLock(ctx context.Context, lockName string, timeout time.Duration) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 548 | session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx)) |
| 549 | mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName) |
| 550 | if err := mu.Lock(context.Background()); err != nil { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 551 | //cancel() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 552 | return err |
| 553 | } |
| 554 | c.addLockName(lockName, mu, session) |
| 555 | return nil |
| 556 | } |
| 557 | |
| 558 | func (c *EtcdClient) ReleaseLock(lockName string) error { |
| 559 | lock, session := c.getLock(lockName) |
| 560 | var err error |
| 561 | if lock != nil { |
| 562 | if e := lock.Unlock(context.Background()); e != nil { |
| 563 | err = e |
| 564 | } |
| 565 | } |
| 566 | if session != nil { |
| 567 | if e := session.Close(); e != nil { |
| 568 | err = e |
| 569 | } |
| 570 | } |
| 571 | c.deleteLockName(lockName) |
| 572 | |
| 573 | return err |
| 574 | } |