watcher.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. recursive bool
  17. sinceIndex uint64
  18. remove func()
  19. }
  20. // notify function notifies the watcher. If the watcher interests in the given path,
  21. // the function will return true.
  22. func (w *Watcher) notify(e *Event, originalPath bool, deleted bool) bool {
  23. // watcher is interested the path in three cases and under one condition
  24. // the condition is that the event happens after the watcher's sinceIndex
  25. // 1. the path at which the event happens is the path the watcher is watching at.
  26. // For example if the watcher is watching at "/foo" and the event happens at "/foo",
  27. // the watcher must be interested in that event.
  28. // 2. the watcher is a recursive watcher, it interests in the event happens after
  29. // its watching path. For example if watcher A watches at "/foo" and it is a recursive
  30. // one, it will interest in the event happens at "/foo/bar".
  31. // 3. when we delete a directory, we need to force notify all the watchers who watches
  32. // at the file we need to delete.
  33. // For example a watcher is watching at "/foo/bar". And we deletes "/foo". The watcher
  34. // should get notified even if "/foo" is not the path it is watching.
  35. if (w.recursive || originalPath || deleted) && e.Index() >= w.sinceIndex {
  36. w.EventChan <- e
  37. return true
  38. }
  39. return false
  40. }
  41. // Remove removes the watcher from watcherHub
  42. func (w *Watcher) Remove() {
  43. if w.remove != nil {
  44. w.remove()
  45. } else {
  46. // We attached a remove function to watcher
  47. // Other pkg cannot change it, so this should not happen
  48. panic("missing Watcher remove function")
  49. }
  50. }