key.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. wc := client.Watch(ctx, key, opts...)
  40. if wc == nil {
  41. return ctx.Err()
  42. }
  43. wresp, ok := <-wc
  44. if !ok {
  45. return ctx.Err()
  46. }
  47. if len(wresp.Events) == 0 {
  48. return v3rpc.ErrCompacted
  49. }
  50. return nil
  51. }