watcher_hub.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 watchHub. 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. event.EtcdIndex = storeIndex
  71. w.eventChan <- event
  72. return w, nil
  73. }
  74. l, ok := wh.watchers[key]
  75. var elem *list.Element
  76. if ok { // add the new watcher to the back of the list
  77. elem = l.PushBack(w)
  78. } else { // create a new list and add the new watcher
  79. l = list.New()
  80. elem = l.PushBack(w)
  81. wh.watchers[key] = l
  82. }
  83. w.remove = func() {
  84. if w.removed { // avoid removing it twice
  85. return
  86. }
  87. w.removed = true
  88. l.Remove(elem)
  89. atomic.AddInt64(&wh.count, -1)
  90. reportWatcherRemoved()
  91. if l.Len() == 0 {
  92. delete(wh.watchers, key)
  93. }
  94. }
  95. atomic.AddInt64(&wh.count, 1)
  96. reportWatcherAdded()
  97. return w, nil
  98. }
  99. // notify function accepts an event and notify to the watchers.
  100. func (wh *watcherHub) notify(e *Event) {
  101. e = wh.EventHistory.addEvent(e) // add event into the eventHistory
  102. segments := strings.Split(e.Node.Key, "/")
  103. currPath := "/"
  104. // walk through all the segments of the path and notify the watchers
  105. // if the path is "/foo/bar", it will notify watchers with path "/",
  106. // "/foo" and "/foo/bar"
  107. for _, segment := range segments {
  108. currPath = path.Join(currPath, segment)
  109. // notify the watchers who interests in the changes of current path
  110. wh.notifyWatchers(e, currPath, false)
  111. }
  112. }
  113. func (wh *watcherHub) notifyWatchers(e *Event, nodePath string, deleted bool) {
  114. wh.mutex.Lock()
  115. defer wh.mutex.Unlock()
  116. l, ok := wh.watchers[nodePath]
  117. if ok {
  118. curr := l.Front()
  119. for curr != nil {
  120. next := curr.Next() // save reference to the next one in the list
  121. w, _ := curr.Value.(*watcher)
  122. originalPath := (e.Node.Key == nodePath)
  123. if (originalPath || !isHidden(nodePath, e.Node.Key)) && w.notify(e, originalPath, deleted) {
  124. if !w.stream { // do not remove the stream watcher
  125. // if we successfully notify a watcher
  126. // we need to remove the watcher from the list
  127. // and decrease the counter
  128. w.removed = true
  129. l.Remove(curr)
  130. atomic.AddInt64(&wh.count, -1)
  131. reportWatcherRemoved()
  132. }
  133. }
  134. curr = next // update current to the next element in the list
  135. }
  136. if l.Len() == 0 {
  137. // if we have notified all watcher in the list
  138. // we can delete the list
  139. delete(wh.watchers, nodePath)
  140. }
  141. }
  142. }
  143. // clone function clones the watcherHub and return the cloned one.
  144. // only clone the static content. do not clone the current watchers.
  145. func (wh *watcherHub) clone() *watcherHub {
  146. clonedHistory := wh.EventHistory.clone()
  147. return &watcherHub{
  148. EventHistory: clonedHistory,
  149. }
  150. }
  151. // isHidden checks to see if key path is considered hidden to watch path i.e. the
  152. // last element is hidden or it's within a hidden directory
  153. func isHidden(watchPath, keyPath string) bool {
  154. // When deleting a directory, watchPath might be deeper than the actual keyPath
  155. // For example, when deleting /foo we also need to notify watchers on /foo/bar.
  156. if len(watchPath) > len(keyPath) {
  157. return false
  158. }
  159. // if watch path is just a "/", after path will start without "/"
  160. // add a "/" to deal with the special case when watchPath is "/"
  161. afterPath := path.Clean("/" + keyPath[len(watchPath):])
  162. return strings.Contains(afterPath, "/_")
  163. }