watcher_hub.go 5.8 KB

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