key.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package concurrency
  15. import (
  16. "fmt"
  17. "math"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. "github.com/coreos/etcd/mvcc/mvccpb"
  20. "golang.org/x/net/context"
  21. )
  22. func waitDelete(ctx context.Context, client *v3.Client, key string, rev int64) error {
  23. cctx, cancel := context.WithCancel(ctx)
  24. defer cancel()
  25. wch := client.Watch(cctx, key, v3.WithRev(rev))
  26. for wr := range wch {
  27. for _, ev := range wr.Events {
  28. if ev.Type == mvccpb.DELETE {
  29. return nil
  30. }
  31. }
  32. }
  33. if err := ctx.Err(); err != nil {
  34. return err
  35. }
  36. return fmt.Errorf("lost watcher waiting for delete")
  37. }
  38. // waitDeletes efficiently waits until all keys matched by Get(key, opts...) are deleted
  39. func waitDeletes(ctx context.Context, client *v3.Client, key string, opts ...v3.OpOption) error {
  40. getOpts := []v3.OpOption{v3.WithSort(v3.SortByCreateRevision, v3.SortAscend)}
  41. getOpts = append(getOpts, opts...)
  42. resp, err := client.Get(ctx, key, getOpts...)
  43. maxRev := int64(math.MaxInt64)
  44. getOpts = append(getOpts, v3.WithRev(0))
  45. for err == nil {
  46. for len(resp.Kvs) > 0 {
  47. i := len(resp.Kvs) - 1
  48. if resp.Kvs[i].CreateRevision <= maxRev {
  49. break
  50. }
  51. resp.Kvs = resp.Kvs[:i]
  52. }
  53. if len(resp.Kvs) == 0 {
  54. break
  55. }
  56. lastKV := resp.Kvs[len(resp.Kvs)-1]
  57. maxRev = lastKV.CreateRevision
  58. err = waitDelete(ctx, client, string(lastKV.Key), maxRev)
  59. if err != nil || len(resp.Kvs) == 1 {
  60. break
  61. }
  62. getOpts = append(getOpts, v3.WithLimit(int64(len(resp.Kvs)-1)))
  63. resp, err = client.Get(ctx, key, getOpts...)
  64. }
  65. return err
  66. }