| 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 |
|
| 15 |
package concurrency |
| 16 |
|
| 17 |
import ( |
| 18 |
"context" |
| 19 |
"fmt" |
| 20 |
|
| 21 |
v3 "github.com/coreos/etcd/clientv3" |
| 22 |
pb "github.com/coreos/etcd/etcdserver/etcdserverpb" |
| 23 |
"github.com/coreos/etcd/mvcc/mvccpb" |
| 24 |
) |
| 25 |
|
| 26 |
func waitDelete(ctx context.Context, client *v3.Client, key string, rev int64) error { |
| 27 |
cctx, cancel := context.WithCancel(ctx) |
| 28 |
defer cancel() |
| 29 |
|
| 30 |
var wr v3.WatchResponse |
| 31 |
wch := client.Watch(cctx, key, v3.WithRev(rev)) |
| 32 |
for wr = range wch { |
| 33 |
for _, ev := range wr.Events { |
| 34 |
if ev.Type == mvccpb.DELETE { |
| 35 |
return nil |
| 36 |
} |
| 37 |
} |
| 38 |
} |
| 39 |
if err := wr.Err(); err != nil { |
| 40 |
return err |
| 41 |
} |
| 42 |
if err := ctx.Err(); err != nil { |
| 43 |
return err |
| 44 |
} |
| 45 |
return fmt.Errorf("lost watcher waiting for delete") |
| 46 |
} |
| 47 |
|
| 48 |
// waitDeletes efficiently waits until all keys matching the prefix and no greater |
| 49 |
// than the create revision. |
| 50 |
func waitDeletes(ctx context.Context, client *v3.Client, pfx string, maxCreateRev int64) (*pb.ResponseHeader, error) { |
| 51 |
getOpts := append(v3.WithLastCreate(), v3.WithMaxCreateRev(maxCreateRev)) |
| 52 |
for { |
| 53 |
resp, err := client.Get(ctx, pfx, getOpts...) |
| 54 |
if err != nil { |
| 55 |
return nil, err |
| 56 |
} |
| 57 |
if len(resp.Kvs) == 0 { |
| 58 |
return resp.Header, nil |
| 59 |
} |
| 60 |
lastKey := string(resp.Kvs[0].Key) |
| 61 |
if err = waitDelete(ctx, client, lastKey, resp.Header.Revision); err != nil { |
| 62 |
return nil, err |
| 63 |
} |
| 64 |
} |
| 65 |
} |