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