watcher_hub.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package store
  2. import (
  3. "container/list"
  4. "path"
  5. "strings"
  6. "sync"
  7. "sync/atomic"
  8. etcdErr "github.com/coreos/etcd/error"
  9. )
  10. // A watcherHub contains all subscribed watchers
  11. // watchers is a map with watched path as key and watcher as value
  12. // EventHistory keeps the old events for watcherHub. It is used to help
  13. // watcher to get a continuous event history. Or a watcher might miss the
  14. // event happens between the end of the first watch command and the start
  15. // of the second command.
  16. type watcherHub struct {
  17. mutex sync.Mutex // protect the hash map
  18. watchers map[string]*list.List
  19. count int64 // current number of watchers.
  20. EventHistory *EventHistory
  21. }
  22. // newWatchHub creates a watchHub. The capacity determines how many events we will
  23. // keep in the eventHistory.
  24. // Typically, we only need to keep a small size of history[smaller than 20K].
  25. // Ideally, it should smaller than 20K/s[max throughput] * 2 * 50ms[RTT] = 2000
  26. func newWatchHub(capacity int) *watcherHub {
  27. return &watcherHub{
  28. watchers: make(map[string]*list.List),
  29. EventHistory: newEventHistory(capacity),
  30. }
  31. }
  32. // Watch function returns a watcher.
  33. // If recursive is true, the first change after index under key will be sent to the event channel of the watcher.
  34. // If recursive is false, the first change after index at key will be sent to the event channel of the watcher.
  35. // If index is zero, watch will start from the current index + 1.
  36. func (wh *watcherHub) watch(key string, recursive, stream bool, index uint64) (*Watcher, *etcdErr.Error) {
  37. event, err := wh.EventHistory.scan(key, recursive, index)
  38. if err != nil {
  39. return nil, err
  40. }
  41. w := &Watcher{
  42. EventChan: make(chan *Event, 1), // use a buffered channel
  43. recursive: recursive,
  44. stream: stream,
  45. sinceIndex: index,
  46. hub: wh,
  47. }
  48. if event != nil {
  49. w.EventChan <- event
  50. return w, nil
  51. }
  52. wh.mutex.Lock()
  53. defer wh.mutex.Unlock()
  54. l, ok := wh.watchers[key]
  55. var elem *list.Element
  56. if ok { // add the new watcher to the back of the list
  57. elem = l.PushBack(w)
  58. } else { // create a new list and add the new watcher
  59. l = list.New()
  60. elem = l.PushBack(w)
  61. wh.watchers[key] = l
  62. }
  63. w.remove = func() {
  64. if w.removed { // avoid remove it twice
  65. return
  66. }
  67. w.removed = true
  68. l.Remove(elem)
  69. atomic.AddInt64(&wh.count, -1)
  70. if l.Len() == 0 {
  71. delete(wh.watchers, key)
  72. }
  73. }
  74. atomic.AddInt64(&wh.count, 1)
  75. return w, nil
  76. }
  77. // notify function accepts an event and notify to the watchers.
  78. func (wh *watcherHub) notify(e *Event) {
  79. e = wh.EventHistory.addEvent(e) // add event into the eventHistory
  80. segments := strings.Split(e.Node.Key, "/")
  81. currPath := "/"
  82. // walk through all the segments of the path and notify the watchers
  83. // if the path is "/foo/bar", it will notify watchers with path "/",
  84. // "/foo" and "/foo/bar"
  85. for _, segment := range segments {
  86. currPath = path.Join(currPath, segment)
  87. // notify the watchers who interests in the changes of current path
  88. wh.notifyWatchers(e, currPath, false)
  89. }
  90. }
  91. func (wh *watcherHub) notifyWatchers(e *Event, nodePath string, deleted bool) {
  92. wh.mutex.Lock()
  93. defer wh.mutex.Unlock()
  94. l, ok := wh.watchers[nodePath]
  95. if ok {
  96. curr := l.Front()
  97. for curr != nil {
  98. next := curr.Next() // save reference to the next one in the list
  99. w, _ := curr.Value.(*Watcher)
  100. originalPath := (e.Node.Key == nodePath)
  101. if (originalPath || !isHidden(nodePath, e.Node.Key)) && w.notify(e, originalPath, deleted) {
  102. if !w.stream { // do not remove the stream watcher
  103. // if we successfully notify a watcher
  104. // we need to remove the watcher from the list
  105. // and decrease the counter
  106. l.Remove(curr)
  107. atomic.AddInt64(&wh.count, -1)
  108. }
  109. }
  110. curr = next // update current to the next element in the list
  111. }
  112. if l.Len() == 0 {
  113. // if we have notified all watcher in the list
  114. // we can delete the list
  115. delete(wh.watchers, nodePath)
  116. }
  117. }
  118. }
  119. // clone function clones the watcherHub and return the cloned one.
  120. // only clone the static content. do not clone the current watchers.
  121. func (wh *watcherHub) clone() *watcherHub {
  122. clonedHistory := wh.EventHistory.clone()
  123. return &watcherHub{
  124. EventHistory: clonedHistory,
  125. }
  126. }
  127. // isHidden checks to see if key path is considered hidden to watch path i.e. the
  128. // last element is hidden or it's within a hidden directory
  129. func isHidden(watchPath, keyPath string) bool {
  130. // When deleting a directory, watchPath might be deeper than the actual keyPath
  131. // For example, when deleting /foo we also need to notify watchers on /foo/bar.
  132. if len(watchPath) > len(keyPath) {
  133. return false
  134. }
  135. // if watch path is just a "/", after path will start without "/"
  136. // add a "/" to deal with the special case when watchPath is "/"
  137. afterPath := path.Clean("/" + keyPath[len(watchPath):])
  138. return strings.Contains(afterPath, "/_")
  139. }