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