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