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