watcher_hub.go 5.6 KB

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