watcher_hub.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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, storeIndex uint64) (Watcher, *etcdErr.Error) {
  37. event, err := wh.EventHistory.scan(key, recursive, index)
  38. if err != nil {
  39. err.Index = storeIndex
  40. return nil, err
  41. }
  42. w := &watcher{
  43. eventChan: make(chan *Event, 100), // use a buffered channel
  44. recursive: recursive,
  45. stream: stream,
  46. sinceIndex: index,
  47. startIndex: storeIndex,
  48. hub: wh,
  49. }
  50. // If the event exists in the known history, append the EtcdIndex and return immediately
  51. if event != nil {
  52. event.EtcdIndex = storeIndex
  53. w.eventChan <- event
  54. return w, nil
  55. }
  56. wh.mutex.Lock()
  57. defer wh.mutex.Unlock()
  58. l, ok := wh.watchers[key]
  59. var elem *list.Element
  60. if ok { // add the new watcher to the back of the list
  61. elem = l.PushBack(w)
  62. } else { // create a new list and add the new watcher
  63. l = list.New()
  64. elem = l.PushBack(w)
  65. wh.watchers[key] = l
  66. }
  67. w.remove = func() {
  68. if w.removed { // avoid removing it twice
  69. return
  70. }
  71. w.removed = true
  72. l.Remove(elem)
  73. atomic.AddInt64(&wh.count, -1)
  74. if l.Len() == 0 {
  75. delete(wh.watchers, key)
  76. }
  77. }
  78. atomic.AddInt64(&wh.count, 1)
  79. return w, nil
  80. }
  81. // notify function accepts an event and notify to the watchers.
  82. func (wh *watcherHub) notify(e *Event) {
  83. e = wh.EventHistory.addEvent(e) // add event into the eventHistory
  84. segments := strings.Split(e.Node.Key, "/")
  85. currPath := "/"
  86. // walk through all the segments of the path and notify the watchers
  87. // if the path is "/foo/bar", it will notify watchers with path "/",
  88. // "/foo" and "/foo/bar"
  89. for _, segment := range segments {
  90. currPath = path.Join(currPath, segment)
  91. // notify the watchers who interests in the changes of current path
  92. wh.notifyWatchers(e, currPath, false)
  93. }
  94. }
  95. func (wh *watcherHub) notifyWatchers(e *Event, nodePath string, deleted bool) {
  96. wh.mutex.Lock()
  97. defer wh.mutex.Unlock()
  98. l, ok := wh.watchers[nodePath]
  99. if ok {
  100. curr := l.Front()
  101. for curr != nil {
  102. next := curr.Next() // save reference to the next one in the list
  103. w, _ := curr.Value.(*watcher)
  104. originalPath := (e.Node.Key == nodePath)
  105. if (originalPath || !isHidden(nodePath, e.Node.Key)) && w.notify(e, originalPath, deleted) {
  106. if !w.stream { // do not remove the stream watcher
  107. // if we successfully notify a watcher
  108. // we need to remove the watcher from the list
  109. // and decrease the counter
  110. l.Remove(curr)
  111. atomic.AddInt64(&wh.count, -1)
  112. }
  113. }
  114. curr = next // update current to the next element in the list
  115. }
  116. if l.Len() == 0 {
  117. // if we have notified all watcher in the list
  118. // we can delete the list
  119. delete(wh.watchers, nodePath)
  120. }
  121. }
  122. }
  123. // clone function clones the watcherHub and return the cloned one.
  124. // only clone the static content. do not clone the current watchers.
  125. func (wh *watcherHub) clone() *watcherHub {
  126. clonedHistory := wh.EventHistory.clone()
  127. return &watcherHub{
  128. EventHistory: clonedHistory,
  129. }
  130. }
  131. // isHidden checks to see if key path is considered hidden to watch path i.e. the
  132. // last element is hidden or it's within a hidden directory
  133. func isHidden(watchPath, keyPath string) bool {
  134. // When deleting a directory, watchPath might be deeper than the actual keyPath
  135. // For example, when deleting /foo we also need to notify watchers on /foo/bar.
  136. if len(watchPath) > len(keyPath) {
  137. return false
  138. }
  139. // if watch path is just a "/", after path will start without "/"
  140. // add a "/" to deal with the special case when watchPath is "/"
  141. afterPath := path.Clean("/" + keyPath[len(watchPath):])
  142. return strings.Contains(afterPath, "/_")
  143. }