watcher_hub.go 5.5 KB

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