watch.go 1.7 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 recipe
  15. import (
  16. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  17. "github.com/coreos/etcd/clientv3"
  18. "github.com/coreos/etcd/storage/storagepb"
  19. )
  20. // WaitEvents waits on a key until it observes the given events and returns the final one.
  21. func WaitEvents(c *clientv3.Client, key string, rev int64, evs []storagepb.Event_EventType) (*storagepb.Event, error) {
  22. w := clientv3.NewWatcher(c)
  23. wc := w.Watch(context.Background(), key, rev)
  24. if wc == nil {
  25. w.Close()
  26. return nil, ErrNoWatcher
  27. }
  28. return waitEvents(wc, evs), w.Close()
  29. }
  30. func WaitPrefixEvents(c *clientv3.Client, prefix string, rev int64, evs []storagepb.Event_EventType) (*storagepb.Event, error) {
  31. w := clientv3.NewWatcher(c)
  32. wc := w.WatchPrefix(context.Background(), prefix, rev)
  33. if wc == nil {
  34. w.Close()
  35. return nil, ErrNoWatcher
  36. }
  37. return waitEvents(wc, evs), w.Close()
  38. }
  39. func waitEvents(wc clientv3.WatchChan, evs []storagepb.Event_EventType) *storagepb.Event {
  40. i := 0
  41. for wresp := range wc {
  42. for _, ev := range wresp.Events {
  43. if ev.Type == evs[i] {
  44. i++
  45. if i == len(evs) {
  46. return ev
  47. }
  48. }
  49. }
  50. }
  51. return nil
  52. }