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