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