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 ( |
| 19 | //log "../common" |
| 20 | "context" |
| 21 | "errors" |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 22 | "fmt" |
khenaidoo | b920354 | 2018-09-17 22:56:37 -0400 | [diff] [blame] | 23 | //v3Client "github.com/coreos/etcd/clientv3" |
| 24 | //v3rpcTypes "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes" |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 25 | log "github.com/opencord/voltha-go/common/log" |
khenaidoo | b920354 | 2018-09-17 22:56:37 -0400 | [diff] [blame] | 26 | v3Client "go.etcd.io/etcd/clientv3" |
| 27 | v3rpcTypes "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes" |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 28 | "sync" |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 29 | ) |
| 30 | |
| 31 | // EtcdClient represents the Etcd KV store client |
| 32 | type EtcdClient struct { |
| 33 | ectdAPI *v3Client.Client |
| 34 | leaderRev v3Client.Client |
| 35 | keyReservations map[string]*v3Client.LeaseID |
| 36 | watchedChannels map[string][]map[chan *Event]v3Client.Watcher |
| 37 | writeLock sync.Mutex |
| 38 | } |
| 39 | |
| 40 | // NewEtcdClient returns a new client for the Etcd KV store |
| 41 | func NewEtcdClient(addr string, timeout int) (*EtcdClient, error) { |
| 42 | |
| 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 | } |
| 53 | wc := make(map[string][]map[chan *Event]v3Client.Watcher) |
| 54 | reservations := make(map[string]*v3Client.LeaseID) |
| 55 | return &EtcdClient{ectdAPI: c, watchedChannels: wc, keyReservations: reservations}, nil |
| 56 | } |
| 57 | |
| 58 | // List returns an array of key-value pairs with key as a prefix. Timeout defines how long the function will |
| 59 | // wait for a response |
| 60 | func (c *EtcdClient) List(key string, timeout int) (map[string]*KVPair, error) { |
| 61 | duration := GetDuration(timeout) |
| 62 | |
| 63 | ctx, cancel := context.WithTimeout(context.Background(), duration) |
| 64 | resp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix()) |
| 65 | cancel() |
| 66 | if err != nil { |
| 67 | log.Error(err) |
| 68 | return nil, err |
| 69 | } |
| 70 | m := make(map[string]*KVPair) |
| 71 | for _, ev := range resp.Kvs { |
| 72 | m[string(ev.Key)] = NewKVPair(string(ev.Key), ev.Value, "", ev.Lease) |
| 73 | } |
| 74 | return m, nil |
| 75 | } |
| 76 | |
| 77 | // Get returns a key-value pair for a given key. Timeout defines how long the function will |
| 78 | // wait for a response |
| 79 | func (c *EtcdClient) Get(key string, timeout int) (*KVPair, error) { |
| 80 | duration := GetDuration(timeout) |
| 81 | |
| 82 | ctx, cancel := context.WithTimeout(context.Background(), duration) |
| 83 | resp, err := c.ectdAPI.Get(ctx, key) |
| 84 | cancel() |
| 85 | if err != nil { |
| 86 | log.Error(err) |
| 87 | return nil, err |
| 88 | } |
| 89 | for _, ev := range resp.Kvs { |
| 90 | // Only one value is returned |
| 91 | return NewKVPair(string(ev.Key), ev.Value, "", ev.Lease), nil |
| 92 | } |
| 93 | return nil, nil |
| 94 | } |
| 95 | |
| 96 | // Put writes a key-value pair to the KV store. Value can only be a string or []byte since the etcd API |
| 97 | // accepts only a string as a value for a put operation. Timeout defines how long the function will |
| 98 | // wait for a response |
| 99 | func (c *EtcdClient) Put(key string, value interface{}, timeout int) error { |
| 100 | |
| 101 | // Validate that we can convert value to a string as etcd API expects a string |
| 102 | var val string |
| 103 | var er error |
| 104 | if val, er = ToString(value); er != nil { |
| 105 | return fmt.Errorf("unexpected-type-%T", value) |
| 106 | } |
| 107 | |
| 108 | duration := GetDuration(timeout) |
| 109 | |
| 110 | ctx, cancel := context.WithTimeout(context.Background(), duration) |
| 111 | c.writeLock.Lock() |
| 112 | defer c.writeLock.Unlock() |
| 113 | _, err := c.ectdAPI.Put(ctx, key, val) |
| 114 | cancel() |
| 115 | if err != nil { |
| 116 | switch err { |
| 117 | case context.Canceled: |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 118 | log.Warnw("context-cancelled", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 119 | case context.DeadlineExceeded: |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 120 | log.Warnw("context-deadline-exceeded", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 121 | case v3rpcTypes.ErrEmptyKey: |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 122 | log.Warnw("etcd-client-error", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 123 | default: |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 124 | log.Warnw("bad-endpoints", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 125 | } |
| 126 | return err |
| 127 | } |
| 128 | return nil |
| 129 | } |
| 130 | |
| 131 | // Delete removes a key from the KV store. Timeout defines how long the function will |
| 132 | // wait for a response |
| 133 | func (c *EtcdClient) Delete(key string, timeout int) error { |
| 134 | |
| 135 | duration := GetDuration(timeout) |
| 136 | |
| 137 | ctx, cancel := context.WithTimeout(context.Background(), duration) |
| 138 | defer cancel() |
| 139 | |
| 140 | c.writeLock.Lock() |
| 141 | defer c.writeLock.Unlock() |
| 142 | |
| 143 | // count keys about to be deleted |
| 144 | gresp, err := c.ectdAPI.Get(ctx, key, v3Client.WithPrefix()) |
| 145 | if err != nil { |
| 146 | log.Error(err) |
| 147 | return err |
| 148 | } |
| 149 | |
| 150 | // delete the keys |
| 151 | dresp, err := c.ectdAPI.Delete(ctx, key, v3Client.WithPrefix()) |
| 152 | if err != nil { |
| 153 | log.Error(err) |
| 154 | return err |
| 155 | } |
| 156 | |
| 157 | if dresp == nil || gresp == nil { |
| 158 | log.Debug("nothing-to-delete") |
| 159 | return nil |
| 160 | } |
| 161 | |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 162 | log.Debugw("delete-keys", log.Fields{"all-keys-deleted": int64(len(gresp.Kvs)) == dresp.Deleted}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 163 | if int64(len(gresp.Kvs)) == dresp.Deleted { |
| 164 | log.Debug("All-keys-deleted") |
| 165 | } else { |
| 166 | log.Error("not-all-keys-deleted") |
| 167 | err := errors.New("not-all-keys-deleted") |
| 168 | return err |
| 169 | } |
| 170 | return nil |
| 171 | } |
| 172 | |
| 173 | // Reserve is invoked to acquire a key and set it to a given value. Value can only be a string or []byte since |
| 174 | // the etcd API accepts only a string. Timeout defines how long the function will wait for a response. TTL |
| 175 | // defines how long that reservation is valid. When TTL expires the key is unreserved by the KV store itself. |
| 176 | // If the key is acquired then the value returned will be the value passed in. If the key is already acquired |
| 177 | // then the value assigned to that key will be returned. |
| 178 | func (c *EtcdClient) Reserve(key string, value interface{}, ttl int64) (interface{}, error) { |
| 179 | // Validate that we can convert value to a string as etcd API expects a string |
| 180 | var val string |
| 181 | var er error |
| 182 | if val, er = ToString(value); er != nil { |
| 183 | return nil, fmt.Errorf("unexpected-type%T", value) |
| 184 | } |
| 185 | |
| 186 | // Create a lease |
| 187 | resp, err := c.ectdAPI.Grant(context.Background(), ttl) |
| 188 | if err != nil { |
| 189 | log.Error(err) |
| 190 | return nil, err |
| 191 | } |
| 192 | // Register the lease id |
| 193 | c.writeLock.Lock() |
| 194 | c.keyReservations[key] = &resp.ID |
| 195 | c.writeLock.Unlock() |
| 196 | |
| 197 | // Revoke lease if reservation is not successful |
| 198 | reservationSuccessful := false |
| 199 | defer func() { |
| 200 | if !reservationSuccessful { |
| 201 | if err = c.ReleaseReservation(key); err != nil { |
| 202 | log.Errorf("cannot-release-lease") |
| 203 | } |
| 204 | } |
| 205 | }() |
| 206 | |
| 207 | // Try to grap the Key with the above lease |
| 208 | c.ectdAPI.Txn(context.Background()) |
| 209 | txn := c.ectdAPI.Txn(context.Background()) |
| 210 | txn = txn.If(v3Client.Compare(v3Client.Version(key), "=", 0)) |
| 211 | txn = txn.Then(v3Client.OpPut(key, val, v3Client.WithLease(resp.ID))) |
| 212 | txn = txn.Else(v3Client.OpGet(key)) |
| 213 | result, er := txn.Commit() |
| 214 | if er != nil { |
| 215 | return nil, er |
| 216 | } |
| 217 | |
| 218 | if !result.Succeeded { |
| 219 | // Verify whether we are already the owner of that Key |
| 220 | if len(result.Responses) > 0 && |
| 221 | len(result.Responses[0].GetResponseRange().Kvs) > 0 { |
| 222 | kv := result.Responses[0].GetResponseRange().Kvs[0] |
| 223 | if string(kv.Value) == val { |
| 224 | reservationSuccessful = true |
| 225 | return value, nil |
| 226 | } |
| 227 | return kv.Value, nil |
| 228 | } |
| 229 | } else { |
| 230 | // Read the Key to ensure this is our Key |
| 231 | m, err := c.Get(key, defaultKVGetTimeout) |
| 232 | if err != nil { |
| 233 | return nil, err |
| 234 | } |
| 235 | if m != nil { |
| 236 | if m.Key == key && isEqual(m.Value, value) { |
| 237 | // My reservation is successful - register it. For now, support is only for 1 reservation per key |
| 238 | // per session. |
| 239 | reservationSuccessful = true |
| 240 | return value, nil |
| 241 | } |
| 242 | // My reservation has failed. Return the owner of that key |
| 243 | return m.Value, nil |
| 244 | } |
| 245 | } |
| 246 | return nil, nil |
| 247 | } |
| 248 | |
| 249 | // ReleaseAllReservations releases all key reservations previously made (using Reserve API) |
| 250 | func (c *EtcdClient) ReleaseAllReservations() error { |
| 251 | c.writeLock.Lock() |
| 252 | defer c.writeLock.Unlock() |
| 253 | for key, leaseID := range c.keyReservations { |
| 254 | _, err := c.ectdAPI.Revoke(context.Background(), *leaseID) |
| 255 | if err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 256 | log.Errorw("cannot-release-reservation", log.Fields{"key": key, "error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 257 | return err |
| 258 | } |
| 259 | delete(c.keyReservations, key) |
| 260 | } |
| 261 | return nil |
| 262 | } |
| 263 | |
| 264 | // ReleaseReservation releases reservation for a specific key. |
| 265 | func (c *EtcdClient) ReleaseReservation(key string) error { |
| 266 | // Get the leaseid using the key |
| 267 | var ok bool |
| 268 | var leaseID *v3Client.LeaseID |
| 269 | c.writeLock.Lock() |
| 270 | defer c.writeLock.Unlock() |
| 271 | if leaseID, ok = c.keyReservations[key]; !ok { |
| 272 | return errors.New("key-not-reserved") |
| 273 | } |
| 274 | if leaseID != nil { |
| 275 | _, err := c.ectdAPI.Revoke(context.Background(), *leaseID) |
| 276 | if err != nil { |
| 277 | log.Error(err) |
| 278 | return err |
| 279 | } |
| 280 | delete(c.keyReservations, key) |
| 281 | } |
| 282 | return nil |
| 283 | } |
| 284 | |
| 285 | // RenewReservation renews a reservation. A reservation will go stale after the specified TTL (Time To Live) |
| 286 | // period specified when reserving the key |
| 287 | func (c *EtcdClient) RenewReservation(key string) error { |
| 288 | // Get the leaseid using the key |
| 289 | var ok bool |
| 290 | var leaseID *v3Client.LeaseID |
| 291 | c.writeLock.Lock() |
| 292 | defer c.writeLock.Unlock() |
| 293 | if leaseID, ok = c.keyReservations[key]; !ok { |
| 294 | return errors.New("key-not-reserved") |
| 295 | } |
| 296 | |
| 297 | if leaseID != nil { |
| 298 | _, err := c.ectdAPI.KeepAliveOnce(context.Background(), *leaseID) |
| 299 | if err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 300 | log.Errorw("lease-may-have-expired", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 301 | return err |
| 302 | } |
| 303 | } else { |
| 304 | return errors.New("lease-expired") |
| 305 | } |
| 306 | return nil |
| 307 | } |
| 308 | |
| 309 | // Watch provides the watch capability on a given key. It returns a channel onto which the callee needs to |
| 310 | // listen to receive Events. |
| 311 | func (c *EtcdClient) Watch(key string) chan *Event { |
| 312 | w := v3Client.NewWatcher(c.ectdAPI) |
| 313 | channel := w.Watch(context.Background(), key, v3Client.WithPrefix()) |
| 314 | |
| 315 | // Create a new channel |
| 316 | ch := make(chan *Event, maxClientChannelBufferSize) |
| 317 | |
| 318 | // Keep track of the created channels so they can be closed when required |
| 319 | channelMap := make(map[chan *Event]v3Client.Watcher) |
| 320 | channelMap[ch] = w |
| 321 | //c.writeLock.Lock() |
| 322 | //defer c.writeLock.Unlock() |
| 323 | c.watchedChannels[key] = append(c.watchedChannels[key], channelMap) |
| 324 | |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 325 | log.Debugw("watched-channels", log.Fields{"channels": c.watchedChannels[key]}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 326 | // Launch a go routine to listen for updates |
| 327 | go c.listenForKeyChange(channel, ch) |
| 328 | |
| 329 | return ch |
| 330 | |
| 331 | } |
| 332 | |
| 333 | // CloseWatch closes a specific watch. Both the key and the channel are required when closing a watch as there |
| 334 | // may be multiple listeners on the same key. The previously created channel serves as a key |
| 335 | func (c *EtcdClient) CloseWatch(key string, ch chan *Event) { |
| 336 | // Get the array of channels mapping |
| 337 | var watchedChannels []map[chan *Event]v3Client.Watcher |
| 338 | var ok bool |
| 339 | c.writeLock.Lock() |
| 340 | defer c.writeLock.Unlock() |
| 341 | |
| 342 | if watchedChannels, ok = c.watchedChannels[key]; !ok { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 343 | log.Warnw("key-has-no-watched-channels", log.Fields{"key": key}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 344 | return |
| 345 | } |
| 346 | // Look for the channels |
| 347 | var pos = -1 |
| 348 | for i, chMap := range watchedChannels { |
| 349 | if t, ok := chMap[ch]; ok { |
| 350 | log.Debug("channel-found") |
| 351 | // Close the etcd watcher before the client channel. This should close the etcd channel as well |
| 352 | if err := t.Close(); err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 353 | log.Errorw("watcher-cannot-be-closed", log.Fields{"key": key, "error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 354 | } |
| 355 | close(ch) |
| 356 | pos = i |
| 357 | break |
| 358 | } |
| 359 | } |
| 360 | // Remove that entry if present |
| 361 | if pos >= 0 { |
| 362 | c.watchedChannels[key] = append(c.watchedChannels[key][:pos], c.watchedChannels[key][pos+1:]...) |
| 363 | } |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 364 | log.Infow("watcher-channel-exiting", log.Fields{"key": key, "channel": c.watchedChannels[key]}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 365 | } |
| 366 | |
| 367 | func (c *EtcdClient) listenForKeyChange(channel v3Client.WatchChan, ch chan<- *Event) { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 368 | log.Infow("start-listening-on-channel", log.Fields{"channel": ch}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 369 | for resp := range channel { |
| 370 | for _, ev := range resp.Events { |
| 371 | //log.Debugf("%s %q : %q\n", ev.Type, ev.Kv.Key, ev.Kv.Value) |
| 372 | ch <- NewEvent(getEventType(ev), ev.Kv.Key, ev.Kv.Value) |
| 373 | } |
| 374 | } |
| 375 | log.Info("stop-listening-on-channel") |
| 376 | } |
| 377 | |
| 378 | func getEventType(event *v3Client.Event) int { |
| 379 | switch event.Type { |
| 380 | case v3Client.EventTypePut: |
| 381 | return PUT |
| 382 | case v3Client.EventTypeDelete: |
| 383 | return DELETE |
| 384 | } |
| 385 | return UNKNOWN |
| 386 | } |
| 387 | |
| 388 | // Close closes the KV store client |
| 389 | func (c *EtcdClient) Close() { |
| 390 | c.writeLock.Lock() |
| 391 | defer c.writeLock.Unlock() |
| 392 | if err := c.ectdAPI.Close(); err != nil { |
khenaidoo | 5c11af7 | 2018-07-20 17:21:05 -0400 | [diff] [blame] | 393 | log.Errorw("error-closing-client", log.Fields{"error": err}) |
khenaidoo | cfee5f4 | 2018-07-19 22:47:38 -0400 | [diff] [blame] | 394 | } |
| 395 | } |