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 | |
serkant.uluderya | b38671c | 2019-11-01 09:35:38 -0700 | [diff] [blame] | 25 | "github.com/opencord/voltha-lib-go/v3/pkg/log" |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 26 | v3Client "go.etcd.io/etcd/clientv3" |
| 27 | v3Concurrency "go.etcd.io/etcd/clientv3/concurrency" |
| 28 | v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes" |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 29 | ) |
| 30 | |
| 31 | // EtcdClient represents the Etcd KV store client |
| 32 | type EtcdClient struct { |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 33 | ectdAPI *v3Client.Client |
| 34 | keyReservations map[string]*v3Client.LeaseID |
| 35 | watchedChannels sync.Map |
| 36 | keyReservationsLock sync.RWMutex |
| 37 | lockToMutexMap map[string]*v3Concurrency.Mutex |
| 38 | lockToSessionMap map[string]*v3Concurrency.Session |
| 39 | lockToMutexLock sync.Mutex |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 40 | } |
| 41 | |
| 42 | // NewEtcdClient returns a new client for the Etcd KV store |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 43 | func NewEtcdClient(addr string, timeout time.Duration, level log.LogLevel) (*EtcdClient, error) { |
Rohan Agrawal | ee87e64 | 2020-04-14 10:22:18 +0000 | [diff] [blame] | 44 | logconfig := log.ConstructZapConfig(log.JSON, level, log.Fields{}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 45 | |
| 46 | c, err := v3Client.New(v3Client.Config{ |
| 47 | Endpoints: []string{addr}, |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 48 | DialTimeout: timeout, |
Rohan Agrawal | ee87e64 | 2020-04-14 10:22:18 +0000 | [diff] [blame] | 49 | LogConfig: &logconfig, |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 50 | }) |
| 51 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 52 | logger.Error(err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 53 | return nil, err |
| 54 | } |
| 55 | |
| 56 | reservations := make(map[string]*v3Client.LeaseID) |
| 57 | lockMutexMap := make(map[string]*v3Concurrency.Mutex) |
| 58 | lockSessionMap := make(map[string]*v3Concurrency.Session) |
| 59 | |
| 60 | return &EtcdClient{ectdAPI: c, keyReservations: reservations, lockToMutexMap: lockMutexMap, |
| 61 | lockToSessionMap: lockSessionMap}, nil |
| 62 | } |
| 63 | |
| 64 | // IsConnectionUp returns whether the connection to the Etcd KV store is up. If a timeout occurs then |
| 65 | // it is assumed the connection is down or unreachable. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 66 | func (c *EtcdClient) IsConnectionUp(ctx context.Context) bool { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 67 | // 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] | 68 | if _, err := c.Get(ctx, "non-existent-key"); err != nil { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 69 | return false |
| 70 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 71 | //cancel() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 72 | return true |
| 73 | } |
| 74 | |
| 75 | // List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will |
| 76 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 77 | 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] | 78 | resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix()) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 79 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 80 | logger.Error(err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 81 | return nil, err |
| 82 | } |
| 83 | m := make(map[string]*KVPair) |
| 84 | for _, ev := range resp.Kvs { |
| 85 | m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version) |
| 86 | } |
| 87 | return m, nil |
| 88 | } |
| 89 | |
| 90 | // Get returns a key-value pair for a given key. Timeout defines how long the function will |
| 91 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 92 | func (c *EtcdClient) Get(ctx context.Context, key string) (*KVPair, error) { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 93 | |
| 94 | resp, err := c.ectdAPI.Get(ctx, key) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 95 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 96 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 97 | logger.Error(err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 98 | return nil, err |
| 99 | } |
| 100 | for _, ev := range resp.Kvs { |
| 101 | // Only one value is returned |
| 102 | return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease, ev.Version), nil |
| 103 | } |
| 104 | return nil, nil |
| 105 | } |
| 106 | |
| 107 | // Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API |
| 108 | // accepts only a string as a value for a put operation. Timeout defines how long the function will |
| 109 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 110 | func (c *EtcdClient) Put(ctx context.Context, key string, value interface{}) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 111 | |
| 112 | // Validate that we can convert value to a string as etcd API expects a string |
| 113 | var val string |
| 114 | var er error |
| 115 | if val, er = ToString(value); er != nil { |
| 116 | return fmt.Errorf("unexpected-type-%T", value) |
| 117 | } |
| 118 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 119 | var err error |
| 120 | // Check if there is already a lease for this key - if there is then use it, otherwise a PUT will make |
| 121 | // 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] | 122 | c.keyReservationsLock.RLock() |
| 123 | leaseID, ok := c.keyReservations[key] |
| 124 | c.keyReservationsLock.RUnlock() |
| 125 | if ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 126 | _, err = c.ectdAPI.Put(ctx, key, val, v3Client.WithLease(*leaseID)) |
| 127 | } else { |
| 128 | _, err = c.ectdAPI.Put(ctx, key, val) |
| 129 | } |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 130 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 131 | if err != nil { |
| 132 | switch err { |
| 133 | case context.Canceled: |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 134 | logger.Warnw("context-cancelled", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 135 | case context.DeadlineExceeded: |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 136 | logger.Warnw("context-deadline-exceeded", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 137 | case v3rpcTypes.ErrEmptyKey: |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 138 | logger.Warnw("etcd-client-error", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 139 | default: |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 140 | logger.Warnw("bad-endpoints", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 141 | } |
| 142 | return err |
| 143 | } |
| 144 | return nil |
| 145 | } |
| 146 | |
| 147 | // Delete removes a key from the KV store. Timeout defines how long the function will |
| 148 | // wait for a response |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 149 | func (c *EtcdClient) Delete(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 150 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 151 | // delete the key |
| 152 | if _, err := c.ectdAPI.Delete(ctx, key); err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 153 | logger.Errorw("failed-to-delete-key", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 154 | return err |
| 155 | } |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 156 | logger.Debugw("key(s)-deleted", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 157 | return nil |
| 158 | } |
| 159 | |
| 160 | // Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since |
| 161 | // the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL |
| 162 | // defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself. |
| 163 | // If the key is acquired then the value returned will be the value passed in. If the key is already acquired |
| 164 | // then the value assigned to that key will be returned. |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 165 | 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] | 166 | // Validate that we can convert value to a string as etcd API expects a string |
| 167 | var val string |
| 168 | var er error |
| 169 | if val, er = ToString(value); er != nil { |
| 170 | return nil, fmt.Errorf("unexpected-type%T", value) |
| 171 | } |
| 172 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 173 | resp, err := c.ectdAPI.Grant(ctx, int64(ttl.Seconds())) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 174 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 175 | logger.Error(err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 176 | return nil, err |
| 177 | } |
| 178 | // Register the lease id |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 179 | c.keyReservationsLock.Lock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 180 | c.keyReservations[key] = &resp.ID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 181 | c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 182 | |
| 183 | // Revoke lease if reservation is not successful |
| 184 | reservationSuccessful := false |
| 185 | defer func() { |
| 186 | if !reservationSuccessful { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 187 | if err = c.ReleaseReservation(context.Background(), key); err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 188 | logger.Error("cannot-release-lease") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 189 | } |
| 190 | } |
| 191 | }() |
| 192 | |
| 193 | // Try to grap the Key with the above lease |
| 194 | c.ectdAPI.Txn(context.Background()) |
| 195 | txn := c.ectdAPI.Txn(context.Background()) |
| 196 | txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0)) |
| 197 | txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID))) |
| 198 | txn = txn.Else(v3Client.OpGet(key)) |
| 199 | result, er := txn.Commit() |
| 200 | if er != nil { |
| 201 | return nil, er |
| 202 | } |
| 203 | |
| 204 | if !result.Succeeded { |
| 205 | // Verify whether we are already the owner of that Key |
| 206 | if len(result.Responses) > 0 && |
| 207 | len(result.Responses[0].GetResponseRange().Kvs) > 0 { |
| 208 | kv := result.Responses[0].GetResponseRange().Kvs[0] |
| 209 | if string(kv.Value) == val { |
| 210 | reservationSuccessful = true |
| 211 | return value, nil |
| 212 | } |
| 213 | return kv.Value, nil |
| 214 | } |
| 215 | } else { |
| 216 | // Read the Key to ensure this is our Key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 217 | m, err := c.Get(ctx, key) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | if m != nil { |
| 222 | if m.Key == key && isEqual(m.Value, value) { |
| 223 | // My reservation is successful - register it. For now, support is only for 1 reservation per key |
| 224 | // per session. |
| 225 | reservationSuccessful = true |
| 226 | return value, nil |
| 227 | } |
| 228 | // My reservation has failed. Return the owner of that key |
| 229 | return m.Value, nil |
| 230 | } |
| 231 | } |
| 232 | return nil, nil |
| 233 | } |
| 234 | |
| 235 | // ReleaseAllReservations releases all key reservations previously made (using Reserve API) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 236 | func (c *EtcdClient) ReleaseAllReservations(ctx context.Context) error { |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 237 | c.keyReservationsLock.Lock() |
| 238 | defer c.keyReservationsLock.Unlock() |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 239 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 240 | for key, leaseID := range c.keyReservations { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 241 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 242 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 243 | logger.Errorw("cannot-release-reservation", log.Fields{"key": key, "error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 244 | return err |
| 245 | } |
| 246 | delete(c.keyReservations, key) |
| 247 | } |
| 248 | return nil |
| 249 | } |
| 250 | |
| 251 | // ReleaseReservation releases reservation for a specific key. |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 252 | func (c *EtcdClient) ReleaseReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 253 | // Get the leaseid using the key |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 254 | logger.Debugw("Release-reservation", log.Fields{"key": key}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 255 | var ok bool |
| 256 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 257 | c.keyReservationsLock.Lock() |
| 258 | defer c.keyReservationsLock.Unlock() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 259 | if leaseID, ok = c.keyReservations[key]; !ok { |
| 260 | return nil |
| 261 | } |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 262 | |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 263 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 264 | _, err := c.ectdAPI.Revoke(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 265 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 266 | logger.Error(err) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 267 | return err |
| 268 | } |
| 269 | delete(c.keyReservations, key) |
| 270 | } |
| 271 | return nil |
| 272 | } |
| 273 | |
| 274 | // RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live) |
| 275 | // period specified when reserving the key |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 276 | func (c *EtcdClient) RenewReservation(ctx context.Context, key string) error { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 277 | // Get the leaseid using the key |
| 278 | var ok bool |
| 279 | var leaseID *v3Client.LeaseID |
Matteo Scandolo | ed12882 | 2020-02-10 15:52:35 -0800 | [diff] [blame] | 280 | c.keyReservationsLock.RLock() |
| 281 | leaseID, ok = c.keyReservations[key] |
| 282 | c.keyReservationsLock.RUnlock() |
| 283 | |
| 284 | if !ok { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 285 | return errors.New("key-not-reserved") |
| 286 | } |
| 287 | |
| 288 | if leaseID != nil { |
Thomas Lee S | 86fc936 | 2019-10-31 11:35:19 +0530 | [diff] [blame] | 289 | _, err := c.ectdAPI.KeepAliveOnce(ctx, *leaseID) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 290 | if err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 291 | logger.Errorw("lease-may-have-expired", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 292 | return err |
| 293 | } |
| 294 | } else { |
| 295 | return errors.New("lease-expired") |
| 296 | } |
| 297 | return nil |
| 298 | } |
| 299 | |
| 300 | // Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to |
| 301 | // listen to receive Events. |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 302 | 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] | 303 | w := v3Client.NewWatcher(c.ectdAPI) |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 304 | ctx, cancel := context.WithCancel(ctx) |
divyadesai | 8bf9686 | 2020-02-07 12:24:26 +0000 | [diff] [blame] | 305 | var channel v3Client.WatchChan |
| 306 | if withPrefix { |
| 307 | channel = w.Watch(ctx, key, v3Client.WithPrefix()) |
| 308 | } else { |
| 309 | channel = w.Watch(ctx, key) |
| 310 | } |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 311 | |
| 312 | // Create a new channel |
| 313 | ch := make(chan *Event, maxClientChannelBufferSize) |
| 314 | |
| 315 | // Keep track of the created channels so they can be closed when required |
| 316 | channelMap := make(map[chan *Event]v3Client.Watcher) |
| 317 | channelMap[ch] = w |
| 318 | |
| 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. |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 323 | logger.Debugw("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 |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 325 | go c.listenForKeyChange(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 |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 372 | func (c *EtcdClient) CloseWatch(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 { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 378 | logger.Warnw("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 { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 385 | logger.Debug("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 { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 388 | logger.Errorw("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 | } |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 400 | logger.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 401 | } |
| 402 | |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 403 | func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event, cancel context.CancelFunc) { |
| 404 | logger.Debug("start-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 405 | defer cancel() |
| 406 | defer close(ch) |
| 407 | for resp := range channel { |
| 408 | for _, ev := range resp.Events { |
| 409 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version) |
| 410 | } |
| 411 | } |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 412 | logger.Debug("stop-listening-on-channel ...") |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 413 | } |
| 414 | |
| 415 | func getEventType(event *v3Client.Event) int { |
| 416 | switch event.Type { |
| 417 | case v3Client.EventTypePut: |
| 418 | return PUT |
| 419 | case v3Client.EventTypeDelete: |
| 420 | return DELETE |
| 421 | } |
| 422 | return UNKNOWN |
| 423 | } |
| 424 | |
| 425 | // Close closes the KV store client |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 426 | func (c *EtcdClient) Close() { |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 427 | if err := c.ectdAPI.Close(); err != nil { |
Scott Baker | e668595 | 2020-06-23 04:05:39 +0000 | [diff] [blame] | 428 | logger.Errorw("error-closing-client", log.Fields{"error": err}) |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 429 | } |
| 430 | } |
| 431 | |
| 432 | func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) { |
| 433 | c.lockToMutexLock.Lock() |
| 434 | defer c.lockToMutexLock.Unlock() |
| 435 | c.lockToMutexMap[lockName] = lock |
| 436 | c.lockToSessionMap[lockName] = session |
| 437 | } |
| 438 | |
| 439 | func (c *EtcdClient) deleteLockName(lockName string) { |
| 440 | c.lockToMutexLock.Lock() |
| 441 | defer c.lockToMutexLock.Unlock() |
| 442 | delete(c.lockToMutexMap, lockName) |
| 443 | delete(c.lockToSessionMap, lockName) |
| 444 | } |
| 445 | |
| 446 | func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) { |
| 447 | c.lockToMutexLock.Lock() |
| 448 | defer c.lockToMutexLock.Unlock() |
| 449 | var lock *v3Concurrency.Mutex |
| 450 | var session *v3Concurrency.Session |
| 451 | if l, exist := c.lockToMutexMap[lockName]; exist { |
| 452 | lock = l |
| 453 | } |
| 454 | if s, exist := c.lockToSessionMap[lockName]; exist { |
| 455 | session = s |
| 456 | } |
| 457 | return lock, session |
| 458 | } |
| 459 | |
Neha Sharma | 130ac6d | 2020-04-08 08:46:32 +0000 | [diff] [blame] | 460 | 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] | 461 | session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx)) |
| 462 | mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName) |
| 463 | if err := mu.Lock(context.Background()); err != nil { |
npujar | 5bf737f | 2020-01-16 19:35:25 +0530 | [diff] [blame] | 464 | //cancel() |
Scott Baker | 2c1c482 | 2019-10-16 11:02:41 -0700 | [diff] [blame] | 465 | return err |
| 466 | } |
| 467 | c.addLockName(lockName, mu, session) |
| 468 | return nil |
| 469 | } |
| 470 | |
| 471 | func (c *EtcdClient) ReleaseLock(lockName string) error { |
| 472 | lock, session := c.getLock(lockName) |
| 473 | var err error |
| 474 | if lock != nil { |
| 475 | if e := lock.Unlock(context.Background()); e != nil { |
| 476 | err = e |
| 477 | } |
| 478 | } |
| 479 | if session != nil { |
| 480 | if e := session.Close(); e != nil { |
| 481 | err = e |
| 482 | } |
| 483 | } |
| 484 | c.deleteLockName(lockName) |
| 485 | |
| 486 | return err |
| 487 | } |