key.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2016 CoreOS, Inc.
  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. "time"
  18. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  19. v3 "github.com/coreos/etcd/clientv3"
  20. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  21. )
  22. // NewUniqueKey creates a new key from a given prefix.
  23. func NewUniqueKey(ctx context.Context, kv v3.KV, pfx string, opts ...v3.OpOption) (string, int64, error) {
  24. for {
  25. newKey := fmt.Sprintf("%s/%v", pfx, time.Now().UnixNano())
  26. put := v3.OpPut(newKey, "", opts...)
  27. cmp := v3.Compare(v3.ModifiedRevision(newKey), "=", 0)
  28. resp, err := kv.Txn(ctx).If(cmp).Then(put).Commit()
  29. if err != nil {
  30. return "", 0, err
  31. }
  32. if !resp.Succeeded {
  33. continue
  34. }
  35. return newKey, resp.Header.Revision, nil
  36. }
  37. }
  38. func waitUpdate(ctx context.Context, client *v3.Client, key string, opts ...v3.OpOption) error {
  39. w := v3.NewWatcher(client)
  40. defer w.Close()
  41. wc := w.Watch(ctx, key, opts...)
  42. if wc == nil {
  43. return ctx.Err()
  44. }
  45. wresp, ok := <-wc
  46. if !ok {
  47. return ctx.Err()
  48. }
  49. if len(wresp.Events) == 0 {
  50. return v3rpc.ErrCompacted
  51. }
  52. return nil
  53. }