key.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. var wr v3.WatchResponse
  26. wch := client.Watch(cctx, key, v3.WithRev(rev))
  27. for wr = range wch {
  28. for _, ev := range wr.Events {
  29. if ev.Type == mvccpb.DELETE {
  30. return nil
  31. }
  32. }
  33. }
  34. if err := wr.Err(); err != nil {
  35. return err
  36. }
  37. if err := ctx.Err(); err != nil {
  38. return err
  39. }
  40. return fmt.Errorf("lost watcher waiting for delete")
  41. }
  42. // waitDeletes efficiently waits until all keys matched by Get(key, opts...) are deleted
  43. func waitDeletes(ctx context.Context, client *v3.Client, key string, opts ...v3.OpOption) error {
  44. getOpts := []v3.OpOption{v3.WithSort(v3.SortByCreateRevision, v3.SortAscend)}
  45. getOpts = append(getOpts, opts...)
  46. resp, err := client.Get(ctx, key, getOpts...)
  47. maxRev := int64(math.MaxInt64)
  48. getOpts = append(getOpts, v3.WithRev(0))
  49. for err == nil {
  50. for len(resp.Kvs) > 0 {
  51. i := len(resp.Kvs) - 1
  52. if resp.Kvs[i].CreateRevision <= maxRev {
  53. break
  54. }
  55. resp.Kvs = resp.Kvs[:i]
  56. }
  57. if len(resp.Kvs) == 0 {
  58. break
  59. }
  60. lastKV := resp.Kvs[len(resp.Kvs)-1]
  61. maxRev = lastKV.CreateRevision
  62. err = waitDelete(ctx, client, string(lastKV.Key), maxRev)
  63. if err != nil || len(resp.Kvs) == 1 {
  64. break
  65. }
  66. getOpts = append(getOpts, v3.WithLimit(int64(len(resp.Kvs)-1)))
  67. resp, err = client.Get(ctx, key, getOpts...)
  68. }
  69. return err
  70. }