watcher.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. // The returned `id` is the ID of this watching. It appears as WatchID
  26. // in events that are sent to this watching.
  27. Watch(key []byte, prefix bool, startRev int64) (id int64, cancel CancelFunc)
  28. // Chan returns a chan. All watched events will be sent to the returned chan.
  29. Chan() <-chan storagepb.Event
  30. // Close closes the WatchChan and release all related resources.
  31. Close()
  32. }
  33. // watcher contains a collection of watching that share
  34. // one chan to send out watched events and other control events.
  35. type watcher struct {
  36. watchable watchable
  37. ch chan storagepb.Event
  38. mu sync.Mutex // guards fields below it
  39. nextID int64 // nextID is the ID allocated for next new watching
  40. closed bool
  41. cancels []CancelFunc
  42. }
  43. // TODO: return error if ws is closed?
  44. func (ws *watcher) Watch(key []byte, prefix bool, startRev int64) (id int64, cancel CancelFunc) {
  45. ws.mu.Lock()
  46. defer ws.mu.Unlock()
  47. if ws.closed {
  48. return -1, nil
  49. }
  50. id = ws.nextID
  51. ws.nextID++
  52. _, c := ws.watchable.watch(key, prefix, startRev, id, ws.ch)
  53. // TODO: cancelFunc needs to be removed from the cancels when it is called.
  54. ws.cancels = append(ws.cancels, c)
  55. return id, c
  56. }
  57. func (ws *watcher) Chan() <-chan storagepb.Event {
  58. return ws.ch
  59. }
  60. func (ws *watcher) Close() {
  61. ws.mu.Lock()
  62. defer ws.mu.Unlock()
  63. for _, cancel := range ws.cancels {
  64. cancel()
  65. }
  66. ws.closed = true
  67. close(ws.ch)
  68. watcherGauge.Dec()
  69. }