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 | |
| 314 | log.Debugw("watched-channels", log.Fields{"channels": channelMaps}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 315 | // Launch a go routine to listen for updates |
| 316 | go c.listenForKeyChange(channel, ch) |
| 317 | |
| 318 | return ch |
| 319 | |
| 320 | } |
| 321 | |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 322 | func (c *EtcdClient) addChannelMap(key string, channelMap map[chan *Event]v3Client.Watcher) []map[chan *Event]v3Client.Watcher { |
| 323 | var channels interface{} |
| 324 | var exists bool |
| 325 | |
| 326 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 327 | channels = append(channels.([]map[chan *Event]v3Client.Watcher), channelMap) |
| 328 | } else { |
| 329 | channels = []map[chan *Event]v3Client.Watcher{channelMap} |
| 330 | } |
| 331 | c.watchedChannels.Store(key, channels) |
| 332 | |
| 333 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 334 | } |
| 335 | |
| 336 | func (c *EtcdClient) removeChannelMap(key string, pos int) []map[chan *Event]v3Client.Watcher { |
| 337 | var channels interface{} |
| 338 | var exists bool |
| 339 | |
| 340 | if channels, exists = c.watchedChannels.Load(key); exists { |
| 341 | channels = append(channels.([]map[chan *Event]v3Client.Watcher)[:pos], channels.([]map[chan *Event]v3Client.Watcher)[pos+1:]...) |
| 342 | c.watchedChannels.Store(key, channels) |
| 343 | } |
| 344 | |
| 345 | return channels.([]map[chan *Event]v3Client.Watcher) |
| 346 | } |
| 347 | |
| 348 | func (c *EtcdClient) getChannelMaps(key string) ([]map[chan *Event]v3Client.Watcher, bool) { |
| 349 | var channels interface{} |
| 350 | var exists bool |
| 351 | |
| 352 | channels, exists = c.watchedChannels.Load(key) |
| 353 | |
khenaidoo | daefa37 | 2019-03-15 14:04:25 -0400 | [diff] [blame] | 354 | if channels == nil { |
| 355 | return nil, exists |
| 356 | } |
| 357 | |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 358 | return channels.([]map[chan *Event]v3Client.Watcher), exists |
| 359 | } |
| 360 | |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 361 | // CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there |
| 362 | // may be multiple listeners on the same key. The previously created channel serves as a key |
| 363 | func (c *EtcdClient) CloseWatch(key string, ch chan *Event) { |
| 364 | // Get the array of channels mapping |
| 365 | var watchedChannels []map[chan *Event]v3Client.Watcher |
| 366 | var ok bool |
| 367 | c.writeLock.Lock() |
| 368 | defer c.writeLock.Unlock() |
| 369 | |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 370 | if watchedChannels, ok = c.getChannelMaps(key); !ok { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 371 | log.Warnw("key-has-no-watched-channels", log.Fields{"key": key}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 372 | return |
| 373 | } |
| 374 | // Look for the channels |
| 375 | var pos = -1 |
| 376 | for i, chMap := range watchedChannels { |
| 377 | if t, ok := chMap[ch]; ok { |
| 378 | log.Debug("channel-found") |
| 379 | // Close the etcd watcher before the client channel. This should close the etcd channel as well |
| 380 | if err := t.Close(); err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 381 | log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 382 | } |
| 383 | close(ch) |
| 384 | pos = i |
| 385 | break |
| 386 | } |
| 387 | } |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 388 | |
| 389 | channelMaps, _ := c.getChannelMaps(key) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 390 | // Remove that entry if present |
| 391 | if pos >= 0 { |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 392 | channelMaps = c.removeChannelMap(key, pos) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 393 | } |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 394 | log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": channelMaps}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 395 | } |
| 396 | |
| 397 | func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event) { |
khenaidoo | 8f47419 | 2019-04-03 17:20:44 -0400 | [diff] [blame] | 398 | log.Debug("start-listening-on-channel ...") |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 399 | for resp := range channel { |
| 400 | for _, ev := range resp.Events { |
| 401 | //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] | 402 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value, ev.Kv.Version) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 403 | } |
| 404 | } |
khenaidoo | 8f47419 | 2019-04-03 17:20:44 -0400 | [diff] [blame] | 405 | log.Debug("stop-listening-on-channel ...") |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 406 | } |
| 407 | |
| 408 | func getEventType(event *v3Client.Event) int { |
| 409 | switch event.Type { |
| 410 | case v3Client.EventTypePut: |
| 411 | return PUT |
| 412 | case v3Client.EventTypeDelete: |
| 413 | return DELETE |
| 414 | } |
| 415 | return UNKNOWN |
| 416 | } |
| 417 | |
| 418 | // Close closes the KV store client |
| 419 | func (c *EtcdClient) Close() { |
| 420 | c.writeLock.Lock() |
| 421 | defer c.writeLock.Unlock() |
| 422 | if err := c.ectdAPI.Close(); err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 423 | log.Errorw("error-closing-client", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 424 | } |
| 425 | } |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 426 | |
| 427 | func (c *EtcdClient) addLockName(lockName string, lock *v3Concurrency.Mutex, session *v3Concurrency.Session) { |
| 428 | c.lockToMutexLock.Lock() |
| 429 | defer c.lockToMutexLock.Unlock() |
| 430 | c.lockToMutexMap[lockName] = lock |
| 431 | c.lockToSessionMap[lockName] = session |
| 432 | } |
| 433 | |
| 434 | func (c *EtcdClient) deleteLockName(lockName string) { |
| 435 | c.lockToMutexLock.Lock() |
| 436 | defer c.lockToMutexLock.Unlock() |
| 437 | delete(c.lockToMutexMap, lockName) |
| 438 | delete(c.lockToSessionMap, lockName) |
| 439 | } |
| 440 | |
| 441 | func (c *EtcdClient) getLock(lockName string) (*v3Concurrency.Mutex, *v3Concurrency.Session) { |
| 442 | c.lockToMutexLock.Lock() |
| 443 | defer c.lockToMutexLock.Unlock() |
| 444 | var lock *v3Concurrency.Mutex |
| 445 | var session *v3Concurrency.Session |
| 446 | if l, exist := c.lockToMutexMap[lockName]; exist { |
| 447 | lock = l |
| 448 | } |
| 449 | if s, exist := c.lockToSessionMap[lockName]; exist { |
| 450 | session = s |
| 451 | } |
| 452 | return lock, session |
| 453 | } |
| 454 | |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 455 | func (c *EtcdClient) AcquireLock(lockName string, timeout int) error { |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 456 | duration := GetDuration(timeout) |
| 457 | ctx, cancel := context.WithTimeout(context.Background(), duration) |
Kent Hagerman | 0ab4cb2 | 2019-04-24 13:13:35 -0400 | [diff] [blame] | 458 | defer cancel() |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 459 | session, _ := v3Concurrency.NewSession(c.ectdAPI, v3Concurrency.WithContext(ctx)) |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 460 | mu := v3Concurrency.NewMutex(session, "/devicelock_"+lockName) |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 461 | if err := mu.Lock(context.Background()); err != nil { |
khenaidoo | 2c6a099 | 2019-04-29 13:46:56 -0400 | [diff] [blame] | 462 | cancel() |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 463 | return err |
| 464 | } |
| 465 | c.addLockName(lockName, mu, session) |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 466 | return nil |
| 467 | } |
| 468 | |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 469 | func (c *EtcdClient) ReleaseLock(lockName string) error { |
khenaidoo | bdcb8e0 | 2019-03-06 16:28:56 -0500 | [diff] [blame] | 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 |
Stephane Barbarie | c53a275 | 2019-03-08 17:50:10 -0500 | [diff] [blame] | 485 | } |