watchable_store.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 storage
  15. import (
  16. "log"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/lease"
  20. "github.com/coreos/etcd/storage/backend"
  21. "github.com/coreos/etcd/storage/storagepb"
  22. )
  23. const (
  24. // chanBufLen is the length of the buffered chan
  25. // for sending out watched events.
  26. // TODO: find a good buf value. 1024 is just a random one that
  27. // seems to be reasonable.
  28. chanBufLen = 1024
  29. )
  30. type watchable interface {
  31. watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc)
  32. rev() int64
  33. }
  34. type watchableStore struct {
  35. mu sync.Mutex
  36. *store
  37. // contains all unsynced watchers that needs to sync with events that have happened
  38. unsynced watcherGroup
  39. // contains all synced watchers that are in sync with the progress of the store.
  40. // The key of the map is the key that the watcher watches on.
  41. synced watcherGroup
  42. stopc chan struct{}
  43. wg sync.WaitGroup
  44. }
  45. // cancelFunc updates unsynced and synced maps when running
  46. // cancel operations.
  47. type cancelFunc func()
  48. func newWatchableStore(b backend.Backend, le lease.Lessor) *watchableStore {
  49. s := &watchableStore{
  50. store: NewStore(b, le),
  51. unsynced: newWatcherGroup(),
  52. synced: newWatcherGroup(),
  53. stopc: make(chan struct{}),
  54. }
  55. if s.le != nil {
  56. // use this store as the deleter so revokes trigger watch events
  57. s.le.SetRangeDeleter(s)
  58. }
  59. s.wg.Add(1)
  60. go s.syncWatchersLoop()
  61. return s
  62. }
  63. func (s *watchableStore) Put(key, value []byte, lease lease.LeaseID) (rev int64) {
  64. s.mu.Lock()
  65. defer s.mu.Unlock()
  66. rev = s.store.Put(key, value, lease)
  67. changes := s.store.getChanges()
  68. if len(changes) != 1 {
  69. log.Panicf("unexpected len(changes) != 1 after put")
  70. }
  71. ev := storagepb.Event{
  72. Type: storagepb.PUT,
  73. Kv: &changes[0],
  74. }
  75. s.notify(rev, []storagepb.Event{ev})
  76. return rev
  77. }
  78. func (s *watchableStore) DeleteRange(key, end []byte) (n, rev int64) {
  79. s.mu.Lock()
  80. defer s.mu.Unlock()
  81. n, rev = s.store.DeleteRange(key, end)
  82. changes := s.store.getChanges()
  83. if len(changes) != int(n) {
  84. log.Panicf("unexpected len(changes) != n after deleteRange")
  85. }
  86. if n == 0 {
  87. return n, rev
  88. }
  89. evs := make([]storagepb.Event, n)
  90. for i, change := range changes {
  91. evs[i] = storagepb.Event{
  92. Type: storagepb.DELETE,
  93. Kv: &change}
  94. evs[i].Kv.ModRevision = rev
  95. }
  96. s.notify(rev, evs)
  97. return n, rev
  98. }
  99. func (s *watchableStore) TxnBegin() int64 {
  100. s.mu.Lock()
  101. return s.store.TxnBegin()
  102. }
  103. func (s *watchableStore) TxnEnd(txnID int64) error {
  104. err := s.store.TxnEnd(txnID)
  105. if err != nil {
  106. return err
  107. }
  108. changes := s.getChanges()
  109. if len(changes) == 0 {
  110. s.mu.Unlock()
  111. return nil
  112. }
  113. rev := s.store.Rev()
  114. evs := make([]storagepb.Event, len(changes))
  115. for i, change := range changes {
  116. switch change.Value {
  117. case nil:
  118. evs[i] = storagepb.Event{
  119. Type: storagepb.DELETE,
  120. Kv: &changes[i]}
  121. evs[i].Kv.ModRevision = rev
  122. default:
  123. evs[i] = storagepb.Event{
  124. Type: storagepb.PUT,
  125. Kv: &changes[i]}
  126. }
  127. }
  128. s.notify(rev, evs)
  129. s.mu.Unlock()
  130. return nil
  131. }
  132. func (s *watchableStore) Close() error {
  133. close(s.stopc)
  134. s.wg.Wait()
  135. return s.store.Close()
  136. }
  137. func (s *watchableStore) NewWatchStream() WatchStream {
  138. watchStreamGauge.Inc()
  139. return &watchStream{
  140. watchable: s,
  141. ch: make(chan WatchResponse, chanBufLen),
  142. cancels: make(map[WatchID]cancelFunc),
  143. }
  144. }
  145. func (s *watchableStore) watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc) {
  146. s.mu.Lock()
  147. defer s.mu.Unlock()
  148. wa := &watcher{
  149. key: key,
  150. end: end,
  151. cur: startRev,
  152. id: id,
  153. ch: ch,
  154. }
  155. s.store.mu.Lock()
  156. synced := startRev > s.store.currentRev.main || startRev == 0
  157. if synced {
  158. wa.cur = s.store.currentRev.main + 1
  159. }
  160. s.store.mu.Unlock()
  161. if synced {
  162. if startRev > wa.cur {
  163. panic("can't watch past sync revision")
  164. }
  165. s.synced.add(wa)
  166. } else {
  167. slowWatcherGauge.Inc()
  168. s.unsynced.add(wa)
  169. }
  170. watcherGauge.Inc()
  171. cancel := cancelFunc(func() {
  172. s.mu.Lock()
  173. defer s.mu.Unlock()
  174. // remove references of the watcher
  175. if s.unsynced.delete(wa) {
  176. slowWatcherGauge.Dec()
  177. watcherGauge.Dec()
  178. return
  179. }
  180. if s.synced.delete(wa) {
  181. watcherGauge.Dec()
  182. }
  183. // If we cannot find it, it should have finished watch.
  184. })
  185. return wa, cancel
  186. }
  187. // syncWatchersLoop syncs the watcher in the unsynced map every 100ms.
  188. func (s *watchableStore) syncWatchersLoop() {
  189. defer s.wg.Done()
  190. for {
  191. s.mu.Lock()
  192. s.syncWatchers()
  193. s.mu.Unlock()
  194. select {
  195. case <-time.After(100 * time.Millisecond):
  196. case <-s.stopc:
  197. return
  198. }
  199. }
  200. }
  201. // syncWatchers periodically syncs unsynced watchers by: Iterate all unsynced
  202. // watchers to get the minimum revision within its range, skipping the
  203. // watcher if its current revision is behind the compact revision of the
  204. // store. And use this minimum revision to get all key-value pairs. Then send
  205. // those events to watchers.
  206. func (s *watchableStore) syncWatchers() {
  207. s.store.mu.Lock()
  208. defer s.store.mu.Unlock()
  209. if s.unsynced.size() == 0 {
  210. return
  211. }
  212. // in order to find key-value pairs from unsynced watchers, we need to
  213. // find min revision index, and these revisions can be used to
  214. // query the backend store of key-value pairs
  215. curRev := s.store.currentRev.main
  216. compactionRev := s.store.compactMainRev
  217. minRev := s.unsynced.scanMinRev(curRev, compactionRev)
  218. minBytes, maxBytes := newRevBytes(), newRevBytes()
  219. revToBytes(revision{main: minRev}, minBytes)
  220. revToBytes(revision{main: curRev + 1}, maxBytes)
  221. // UnsafeRange returns keys and values. And in boltdb, keys are revisions.
  222. // values are actual key-value pairs in backend.
  223. tx := s.store.b.BatchTx()
  224. tx.Lock()
  225. revs, vs := tx.UnsafeRange(keyBucketName, minBytes, maxBytes, 0)
  226. evs := kvsToEvents(&s.unsynced, revs, vs)
  227. tx.Unlock()
  228. for w, eb := range newWatcherBatch(&s.unsynced, evs) {
  229. select {
  230. // s.store.Rev also uses Lock, so just return directly
  231. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: s.store.currentRev.main}:
  232. pendingEventsGauge.Add(float64(len(eb.evs)))
  233. default:
  234. // TODO: handle the full unsynced watchers.
  235. // continue to process other watchers for now, the full ones
  236. // will be processed next time and hopefully it will not be full.
  237. continue
  238. }
  239. if eb.moreRev != 0 {
  240. w.cur = eb.moreRev
  241. continue
  242. }
  243. w.cur = curRev
  244. s.synced.add(w)
  245. s.unsynced.delete(w)
  246. }
  247. slowWatcherGauge.Set(float64(s.unsynced.size()))
  248. }
  249. // kvsToEvents gets all events for the watchers from all key-value pairs
  250. func kvsToEvents(wg *watcherGroup, revs, vals [][]byte) (evs []storagepb.Event) {
  251. for i, v := range vals {
  252. var kv storagepb.KeyValue
  253. if err := kv.Unmarshal(v); err != nil {
  254. log.Panicf("storage: cannot unmarshal event: %v", err)
  255. }
  256. if !wg.contains(string(kv.Key)) {
  257. continue
  258. }
  259. ty := storagepb.PUT
  260. if isTombstone(revs[i]) {
  261. ty = storagepb.DELETE
  262. // patch in mod revision so watchers won't skip
  263. kv.ModRevision = bytesToRev(revs[i]).main
  264. }
  265. evs = append(evs, storagepb.Event{Kv: &kv, Type: ty})
  266. }
  267. return evs
  268. }
  269. // notify notifies the fact that given event at the given rev just happened to
  270. // watchers that watch on the key of the event.
  271. func (s *watchableStore) notify(rev int64, evs []storagepb.Event) {
  272. for w, eb := range newWatcherBatch(&s.synced, evs) {
  273. if eb.revs != 1 {
  274. panic("unexpected multiple revisions in notification")
  275. }
  276. select {
  277. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: s.Rev()}:
  278. pendingEventsGauge.Add(float64(len(eb.evs)))
  279. default:
  280. // move slow watcher to unsynced
  281. w.cur = rev
  282. s.unsynced.add(w)
  283. s.synced.delete(w)
  284. slowWatcherGauge.Inc()
  285. }
  286. }
  287. }
  288. func (s *watchableStore) rev() int64 { return s.store.Rev() }
  289. type watcher struct {
  290. // the watcher key
  291. key []byte
  292. // end indicates the end of the range to watch.
  293. // If end is set, the watcher is on a range.
  294. end []byte
  295. // cur is the current watcher revision.
  296. // If cur is behind the current revision of the KV,
  297. // watcher is unsynced and needs to catch up.
  298. cur int64
  299. id WatchID
  300. // a chan to send out the watch response.
  301. // The chan might be shared with other watchers.
  302. ch chan<- WatchResponse
  303. }