key.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. "context"
  17. "fmt"
  18. v3 "github.com/coreos/etcd/clientv3"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "github.com/coreos/etcd/mvcc/mvccpb"
  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 matching the prefix and no greater
  43. // than the create revision.
  44. func waitDeletes(ctx context.Context, client *v3.Client, pfx string, maxCreateRev int64) (*pb.ResponseHeader, error) {
  45. getOpts := append(v3.WithLastCreate(), v3.WithMaxCreateRev(maxCreateRev))
  46. for {
  47. resp, err := client.Get(ctx, pfx, getOpts...)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if len(resp.Kvs) == 0 {
  52. return resp.Header, nil
  53. }
  54. lastKey := string(resp.Kvs[0].Key)
  55. if err = waitDelete(ctx, client, lastKey, resp.Header.Revision); err != nil {
  56. return nil, err
  57. }
  58. }
  59. }