key.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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. v3 "github.com/coreos/etcd/clientv3"
  18. "github.com/coreos/etcd/mvcc/mvccpb"
  19. "golang.org/x/net/context"
  20. )
  21. func waitDelete(ctx context.Context, client *v3.Client, key string, rev int64) error {
  22. cctx, cancel := context.WithCancel(ctx)
  23. defer cancel()
  24. var wr v3.WatchResponse
  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 := wr.Err(); err != nil {
  34. return err
  35. }
  36. if err := ctx.Err(); err != nil {
  37. return err
  38. }
  39. return fmt.Errorf("lost watcher waiting for delete")
  40. }
  41. // waitDeletes efficiently waits until all keys matching the prefix and no greater
  42. // than the create revision.
  43. func waitDeletes(ctx context.Context, client *v3.Client, pfx string, maxCreateRev int64) error {
  44. getOpts := append(v3.WithLastCreate(), v3.WithMaxCreateRev(maxCreateRev))
  45. for {
  46. resp, err := client.Get(ctx, pfx, getOpts...)
  47. if err != nil {
  48. return err
  49. }
  50. if len(resp.Kvs) == 0 {
  51. return nil
  52. }
  53. lastKey := string(resp.Kvs[0].Key)
  54. if err = waitDelete(ctx, client, lastKey, resp.Header.Revision); err != nil {
  55. return err
  56. }
  57. }
  58. }