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