watcher.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2015 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 storage
  15. import (
  16. "sync"
  17. "github.com/coreos/etcd/storage/storagepb"
  18. )
  19. type Watcher interface {
  20. // Watch watches the events happening or happened on the given key
  21. // or key prefix from the given startRev.
  22. // The whole event history can be watched unless compacted.
  23. // If `prefix` is true, watch observes all events whose key prefix could be the given `key`.
  24. // If `startRev` <=0, watch observes events after currentRev.
  25. Watch(key []byte, prefix bool, startRev int64) CancelFunc
  26. // Chan returns a chan. All watched events will be sent to the returned chan.
  27. Chan() <-chan storagepb.Event
  28. // Close closes the WatchChan and release all related resources.
  29. Close()
  30. }
  31. // watcher contains a collection of watching that share
  32. // one chan to send out watched events and other control events.
  33. type watcher struct {
  34. watchable watchable
  35. ch chan storagepb.Event
  36. mu sync.Mutex // guards fields below it
  37. closed bool
  38. cancels []CancelFunc
  39. }
  40. // TODO: return error if ws is closed?
  41. func (ws *watcher) Watch(key []byte, prefix bool, startRev int64) CancelFunc {
  42. _, c := ws.watchable.watch(key, prefix, startRev, ws.ch)
  43. ws.mu.Lock()
  44. defer ws.mu.Unlock()
  45. if ws.closed {
  46. return nil
  47. }
  48. // TODO: cancelFunc needs to be removed from the cancels when it is called.
  49. ws.cancels = append(ws.cancels, c)
  50. return c
  51. }
  52. func (ws *watcher) Chan() <-chan storagepb.Event {
  53. return ws.ch
  54. }
  55. func (ws *watcher) Close() {
  56. ws.mu.Lock()
  57. defer ws.mu.Unlock()
  58. for _, cancel := range ws.cancels {
  59. cancel()
  60. }
  61. ws.closed = true
  62. close(ws.ch)
  63. }