watcher.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2013 CoreOS Inc.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package store
  14. type Watcher struct {
  15. EventChan chan *Event
  16. stream bool
  17. recursive bool
  18. sinceIndex uint64
  19. hub *watcherHub
  20. removed bool
  21. remove func()
  22. }
  23. // notify function notifies the watcher. If the watcher interests in the given path,
  24. // the function will return true.
  25. func (w *Watcher) notify(e *Event, originalPath bool, deleted bool) bool {
  26. // watcher is interested the path in three cases and under one condition
  27. // the condition is that the event happens after the watcher's sinceIndex
  28. // 1. the path at which the event happens is the path the watcher is watching at.
  29. // For example if the watcher is watching at "/foo" and the event happens at "/foo",
  30. // the watcher must be interested in that event.
  31. // 2. the watcher is a recursive watcher, it interests in the event happens after
  32. // its watching path. For example if watcher A watches at "/foo" and it is a recursive
  33. // one, it will interest in the event happens at "/foo/bar".
  34. // 3. when we delete a directory, we need to force notify all the watchers who watches
  35. // at the file we need to delete.
  36. // For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher
  37. // should get notified even if "/foo" is not the path it is watching.
  38. if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex {
  39. // We cannot block here if the EventChan capacity is full, otherwise
  40. // etcd will hang. EventChan capacity is full when the rate of
  41. // notifications are higher than our send rate.
  42. // If this happens, we close the channel.
  43. select {
  44. case w.EventChan <- e:
  45. default:
  46. // We have missed a notification. Remove the watcher.
  47. // Removing the watcher also closes the EventChan.
  48. w.remove()
  49. }
  50. return true
  51. }
  52. return false
  53. }
  54. // Remove removes the watcher from watcherHub
  55. // The actual remove function is guaranteed to only be executed once
  56. func (w *Watcher) Remove() {
  57. w.hub.mutex.Lock()
  58. defer w.hub.mutex.Unlock()
  59. close(w.EventChan)
  60. w.remove()
  61. }