Skip to content

Instantly share code, notes, and snippets.

@liuchang0812
Last active November 18, 2019 09:06
Show Gist options
  • Save liuchang0812/0f453b3976de5d927eed083ee93bc0cc to your computer and use it in GitHub Desktop.
Save liuchang0812/0f453b3976de5d927eed083ee93bc0cc to your computer and use it in GitHub Desktop.
etcd clientv3 election
const prefix = "/resume-election/"
cli, _ := clientv3.New(clientv3.Config{Endpoints: endpoints})
defer cli.Close()
var s *concurrency.Session
s, _ = concurrency.NewSession(cli)
defer s.Close()
e := concurrency.NewElection(s, prefix)
if err = e.Campaign(context.TODO(), "candidate1"); err != nil {
t.Fatalf("Campaign() returned non nil err: %s", err)
}
// waitDeletes efficiently waits until all keys matching the prefix and no greater
// than the create revision.
func waitDeletes(ctx context.Context, client *v3.Client, pfx string, maxCreateRev int64) (*pb.ResponseHeader, error) {
getOpts := append(v3.WithLastCreate(), v3.WithMaxCreateRev(maxCreateRev))
for {
resp, err := client.Get(ctx, pfx, getOpts...)
if err != nil {
return nil, err
}
if len(resp.Kvs) == 0 {
return resp.Header, nil
}
lastKey := string(resp.Kvs[0].Key)
if err = waitDelete(ctx, client, lastKey, resp.Header.Revision); err != nil {
return nil, err
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment