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 | 89c985b | 2020-10-14 15:02:09 -0700 | [diff] [blame] | 25 | "github.com/opencord/voltha-lib-go/v4/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 | |
| 102 | resp, err := c.ectdAPI.Get(ctx, key) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 103 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 104 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 105 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 106 | return nil, err |
| 107 | } |
| 108 | for _, ev := range resp.Kvs { |
| 109 | // Only one value is returned |
| 110 | return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil |
| 111 | } |
| 112 | return nil, nil |
| 113 | } |
| 114 | |
| 115 | // Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API |
| 116 | // accepts only a string as a value for a put operation. Timeout defines how long the function will |
| 117 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 118 | func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 119 | |
| 120 | // Validate that we can convert value to a string as etcd API expects a string |
| 121 | var val string |
| 122 | var er error |
| 123 | if val, er = ToString(value); er != nil { |
| 124 | return fmt.Errorf("unexpected-type-%T", value) |
| 125 | } |
| 126 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 127 | var err error |
| 128 | // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make |
| 129 | // 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] | 130 | c.keyReservationsLock.RLock() |
| 131 | leaseID, ok := c.keyReservations[key] |
| 132 | c.keyReservationsLock.RUnlock() |
| 133 | if ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 134 | _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID)) |
| 135 | } else { |
| 136 | _, err = c.ectdAPI.Put(ctx, key, val) |
| 137 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 138 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 139 | if err != nil { |
| 140 | switch err { |
| 141 | case context.Canceled: |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 142 | logger.Warnw(ctx, "context-cancelled", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 143 | case context.DeadlineExceeded: |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 144 | logger.Warnw(ctx, "context-deadline-exceeded", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 145 | case v3rpcTypes.ErrEmptyKey: |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 146 | logger.Warnw(ctx, "etcd-client-error", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 147 | default: |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 148 | logger.Warnw(ctx, "bad-endpoints", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 149 | } |
| 150 | return err |
| 151 | } |
| 152 | return nil |
| 153 | } |
| 154 | |
| 155 | // Delete removes a key from the KV store. Timeout defines how long the function will |
| 156 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 157 | func (c *EtcdClient) Delete(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 158 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 159 | // delete the key |
| 160 | if _, err := c.ectdAPI.Delete(ctx, key); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 161 | logger.Errorw(ctx, "failed-to-delete-key", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 162 | return err |
| 163 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 164 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 165 | return nil |
| 166 | } |
| 167 | |
Serkant Uluderya | 198de90 | 2020-11-16 20:29:17 +0300 | [diff] [blame] | 168 | func (c *EtcdClient) DeleteWithPrefix(ctx context.Context, prefixKey string) error { |
| 169 | |
| 170 | //delete the prefix |
| 171 | if _, err := c.ectdAPI.Delete(ctx, prefixKey, v3Client.WithPrefix()); err != nil { |
| 172 | logger.Errorw(ctx, "failed-to-delete-prefix-key", log.Fields{"key": prefixKey, "error": err}) |
| 173 | return err |
| 174 | } |
| 175 | logger.Debugw(ctx, "key(s)-deleted", log.Fields{"key": prefixKey}) |
| 176 | return nil |
| 177 | } |
| 178 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 179 | // Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since |
| 180 | // the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL |
| 181 | // defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself. |
| 182 | // If the key is acquired then the value returned will be the value passed in. If the key is already acquired |
| 183 | // then the value assigned to that key will be returned. |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 184 | 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] | 185 | // Validate that we can convert value to a string as etcd API expects a string |
| 186 | var val string |
| 187 | var er error |
| 188 | if val, er = ToString(value); er != nil { |
| 189 | return nil, fmt.Errorf("unexpected-type%T", value) |
| 190 | } |
| 191 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 192 | resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds())) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 193 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 194 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 195 | return nil, err |
| 196 | } |
| 197 | // Register the lease id |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 198 | c.keyReservationsLock.Lock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 199 | c.keyReservations[key] = &resp.ID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 200 | c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 201 | |
| 202 | // Revoke lease if reservation is not successful |
| 203 | reservationSuccessful := false |
| 204 | defer func() { |
| 205 | if !reservationSuccessful { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 206 | if err = c.ReleaseReservation(context.Background(), key); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 207 | logger.Error(ctx, "cannot-release-lease") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 208 | } |
| 209 | } |
| 210 | }() |
| 211 | |
| 212 | // Try to grap the Key with the above lease |
| 213 | c.ectdAPI.Txn(context.Background()) |
| 214 | txn := c.ectdAPI.Txn(context.Background()) |
| 215 | txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0)) |
| 216 | txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID))) |
| 217 | txn = txn.Else(v3Client.OpGet(key)) |
| 218 | result, er := txn.Commit() |
| 219 | if er != nil { |
| 220 | return nil, er |
| 221 | } |
| 222 | |
| 223 | if !result.Succeeded { |
| 224 | // Verify whether we are already the owner of that Key |
| 225 | if len(result.Responses) > 0 && |
| 226 | len(result.Responses[0].GetResponseRange().Kvs) > 0 { |
| 227 | kv := result.Responses[0].GetResponseRange().Kvs[0] |
| 228 | if string(kv.Value) == val { |
| 229 | reservationSuccessful = true |
| 230 | return value, nil |
| 231 | } |
| 232 | return kv.Value, nil |
| 233 | } |
| 234 | } else { |
| 235 | // Read the Key to ensure this is our Key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 236 | m, err := c.Get(ctx, key) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 237 | if err != nil { |
| 238 | return nil, err |
| 239 | } |
| 240 | if m != nil { |
| 241 | if m.Key == key && isEqual(m.Value, value) { |
| 242 | // My reservation is successful - register it. For now, support is only for 1 reservation per key |
| 243 | // per session. |
| 244 | reservationSuccessful = true |
| 245 | return value, nil |
| 246 | } |
| 247 | // My reservation has failed. Return the owner of that key |
| 248 | return m.Value, nil |
| 249 | } |
| 250 | } |
| 251 | return nil, nil |
| 252 | } |
| 253 | |
| 254 | // ReleaseAllReservations releases all key reservations previously made (using Reserve API) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 255 | func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error { |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 256 | c.keyReservationsLock.Lock() |
| 257 | defer c.keyReservationsLock.Unlock() |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 258 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 259 | for key, leaseID := range c.keyReservations { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 260 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
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.Errorw(ctx, "cannot-release-reservation", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 263 | return err |
| 264 | } |
| 265 | delete(c.keyReservations, key) |
| 266 | } |
| 267 | return nil |
| 268 | } |
| 269 | |
| 270 | // ReleaseReservation releases reservation for a specific key. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 271 | func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 272 | // Get the leaseid using the key |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 273 | logger.Debugw(ctx, "Release-reservation", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 274 | var ok bool |
| 275 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 276 | c.keyReservationsLock.Lock() |
| 277 | defer c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 278 | if leaseID, ok = c.keyReservations[key]; !ok { |
| 279 | return nil |
| 280 | } |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 281 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 282 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 283 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 284 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 285 | logger.Error(ctx, err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 286 | return err |
| 287 | } |
| 288 | delete(c.keyReservations, key) |
| 289 | } |
| 290 | return nil |
| 291 | } |
| 292 | |
| 293 | // RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live) |
| 294 | // period specified when reserving the key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 295 | func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 296 | // Get the leaseid using the key |
| 297 | var ok bool |
| 298 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 299 | c.keyReservationsLock.RLock() |
| 300 | leaseID, ok = c.keyReservations[key] |
| 301 | c.keyReservationsLock.RUnlock() |
| 302 | |
| 303 | if !ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 304 | return errors.New("key-not-reserved") |
| 305 | } |
| 306 | |
| 307 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 308 | _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 309 | if err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 310 | logger.Errorw(ctx, "lease-may-have-expired", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 311 | return err |
| 312 | } |
| 313 | } else { |
| 314 | return errors.New("lease-expired") |
| 315 | } |
| 316 | return nil |
| 317 | } |
| 318 | |
| 319 | // Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to |
| 320 | // listen to receive Events. |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 321 | 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] | 322 | w := v3Client.NewWatcher(c.ectdAPI) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 323 | ctx, cancel := context.WithCancel(ctx) |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 324 | var channel v3Client.WatchChan |
| 325 | if withPrefix { |
| 326 | channel = w.Watch(ctx, key, v3Client.WithPrefix()) |
| 327 | } else { |
| 328 | channel = w.Watch(ctx, key) |
| 329 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 330 | |
| 331 | // Create a new channel |
| 332 | ch := make(chan *Event, maxClientChannelBufferSize) |
| 333 | |
| 334 | // Keep track of the created channels so they can be closed when required |
| 335 | channelMap := make(map[chan *Event]v3Client.Watcher) |
| 336 | channelMap[ch] = w |
| 337 | |
| 338 | channelMaps := c.addChannelMap(key, channelMap) |
| 339 | |
| 340 | // Changing the log field (from channelMaps) as the underlying logger cannot format the map of channels into a |
| 341 | // json format. |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 342 | logger.Debugw(ctx, "watched-channels", log.Fields{"len": len(channelMaps)}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 343 | // Launch a go routine to listen for updates |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 344 | go c.listenForKeyChange(ctx, channel, ch, cancel) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 345 | |
| 346 | return ch |
| 347 | |
| 348 | } |
| 349 | |
| 350 | func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher { |
| 351 | var channels interface{} |
| 352 | var exists bool |
| 353 | |
| 354 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 355 | channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap) |
| 356 | } else { |
| 357 | channels = []map[chan *Event]v3Client.Watcher{channelMap} |
| 358 | } |
| 359 | c.watchedChannels.Store(key, channels) |
| 360 | |
| 361 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 362 | } |
| 363 | |
| 364 | func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher { |
| 365 | var channels interface{} |
| 366 | var exists bool |
| 367 | |
| 368 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 369 | channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...) |
| 370 | c.watchedChannels.Store(key, channels) |
| 371 | } |
| 372 | |
| 373 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 374 | } |
| 375 | |
| 376 | func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) { |
| 377 | var channels interface{} |
| 378 | var exists bool |
| 379 | |
| 380 | channels, exists = c.watchedChannels.Load(key) |
| 381 | |
| 382 | if channels == nil { |
| 383 | return nil, exists |
| 384 | } |
| 385 | |
| 386 | return channels.([]map[chan *Event]v3Client.Watcher), exists |
| 387 | } |
| 388 | |
| 389 | // CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there |
| 390 | // 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] | 391 | func (c *EtcdClient) CloseWatch(ctx context.Context, key string, ch chan *Event) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 392 | // Get the array of channels mapping |
| 393 | var watchedChannels []map[chan *Event]v3Client.Watcher |
| 394 | var ok bool |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 395 | |
| 396 | if watchedChannels, ok = c.getChannelMaps(key); !ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 397 | logger.Warnw(ctx, "key-has-no-watched-channels", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 398 | return |
| 399 | } |
| 400 | // Look for the channels |
| 401 | var pos = -1 |
| 402 | for i, chMap := range watchedChannels { |
| 403 | if t, ok := chMap[ch]; ok { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 404 | logger.Debug(ctx, "channel-found") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 405 | // Close the etcd watcher before the client channel. This should close the etcd channel as well |
| 406 | if err := t.Close(); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 407 | 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] | 408 | } |
| 409 | pos = i |
| 410 | break |
| 411 | } |
| 412 | } |
| 413 | |
| 414 | channelMaps, _ := c.getChannelMaps(key) |
| 415 | // Remove that entry if present |
| 416 | if pos >= 0 { |
| 417 | channelMaps = c.removeChannelMap(key, pos) |
| 418 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 419 | logger.Infow(ctx, "watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 420 | } |
| 421 | |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 422 | func (c *EtcdClient) listenForKeyChange(ctx context.Context, channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) { |
| 423 | logger.Debug(ctx, "start-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 424 | defer cancel() |
| 425 | defer close(ch) |
| 426 | for resp := range channel { |
| 427 | for _, ev := range resp.Events { |
| 428 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version) |
| 429 | } |
| 430 | } |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 431 | logger.Debug(ctx, "stop-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 432 | } |
| 433 | |
| 434 | func getEventType(event *v3Client.Event) int { |
| 435 | switch event.Type { |
| 436 | case v3Client.EventTypePut: |
| 437 | return PUT |
| 438 | case v3Client.EventTypeDelete: |
| 439 | return DELETE |
| 440 | } |
| 441 | return UNKNOWN |
| 442 | } |
| 443 | |
| 444 | // Close closes the KV store client |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 445 | func (c *EtcdClient) Close(ctx context.Context) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 446 | if err := c.ectdAPI.Close(); err != nil { |
Neha Sharma | 94f16a9 | 2020-06-26 04:17:55 +0000 | [diff] [blame] | 447 | logger.Errorw(ctx, "error-closing-client", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 448 | } |
| 449 | } |
| 450 | |
| 451 | func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) { |
| 452 | c.lockToMutexLock.Lock() |
| 453 | defer c.lockToMutexLock.Unlock() |
| 454 | c.lockToMutexMap[lockName] = lock |
| 455 | c.lockToSessionMap[lockName] = session |
| 456 | } |
| 457 | |
| 458 | func (c *EtcdClient) deleteLockName(lockName string) { |
| 459 | c.lockToMutexLock.Lock() |
| 460 | defer c.lockToMutexLock.Unlock() |
| 461 | delete(c.lockToMutexMap, lockName) |
| 462 | delete(c.lockToSessionMap, lockName) |
| 463 | } |
| 464 | |
| 465 | func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) { |
| 466 | c.lockToMutexLock.Lock() |
| 467 | defer c.lockToMutexLock.Unlock() |
| 468 | var lock *v3Concurrency.Mutex |
| 469 | var session *v3Concurrency.Session |
| 470 | if l, exist := c.lockToMutexMap[lockName]; exist { |
| 471 | lock = l |
| 472 | } |
| 473 | if s, exist := c.lockToSessionMap[lockName]; exist { |
| 474 | session = s |
| 475 | } |
| 476 | return lock, session |
| 477 | } |
| 478 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 479 | 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] | 480 | session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx)) |
| 481 | mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName) |
| 482 | if err := mu.Lock(context.Background()); err != nil { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 483 | //cancel() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 484 | return err |
| 485 | } |
| 486 | c.addLockName(lockName, mu, session) |
| 487 | return nil |
| 488 | } |
| 489 | |
| 490 | func (c *EtcdClient) ReleaseLock(lockName string) error { |
| 491 | lock, session := c.getLock(lockName) |
| 492 | var err error |
| 493 | if lock != nil { |
| 494 | if e := lock.Unlock(context.Background()); e != nil { |
| 495 | err = e |
| 496 | } |
| 497 | } |
| 498 | if session != nil { |
| 499 | if e := session.Close(); e != nil { |
| 500 | err = e |
| 501 | } |
| 502 | } |
| 503 | c.deleteLockName(lockName) |
| 504 | |
| 505 | return err |
| 506 | } |