watchable_store.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. // Copyright 2015 The etcd Authors
  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 mvcc
  15. import (
  16. "sync"
  17. "time"
  18. "github.com/coreos/etcd/lease"
  19. "github.com/coreos/etcd/mvcc/backend"
  20. "github.com/coreos/etcd/mvcc/mvccpb"
  21. )
  22. const (
  23. // chanBufLen is the length of the buffered chan
  24. // for sending out watched events.
  25. // TODO: find a good buf value. 1024 is just a random one that
  26. // seems to be reasonable.
  27. chanBufLen = 1024
  28. // maxWatchersPerSync is the number of watchers to sync in a single batch
  29. maxWatchersPerSync = 512
  30. )
  31. type watchable interface {
  32. watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse, fcs ...FilterFunc) (*watcher, cancelFunc)
  33. progress(w *watcher)
  34. rev() int64
  35. }
  36. type watchableStore struct {
  37. *store
  38. // mu protects watcher groups and batches. It should never be locked
  39. // before locking store.mu to avoid deadlock.
  40. mu sync.RWMutex
  41. // victims are watcher batches that were blocked on the watch channel
  42. victims []watcherBatch
  43. victimc chan struct{}
  44. // contains all unsynced watchers that needs to sync with events that have happened
  45. unsynced watcherGroup
  46. // contains all synced watchers that are in sync with the progress of the store.
  47. // The key of the map is the key that the watcher watches on.
  48. synced watcherGroup
  49. stopc chan struct{}
  50. wg sync.WaitGroup
  51. }
  52. // cancelFunc updates unsynced and synced maps when running
  53. // cancel operations.
  54. type cancelFunc func()
  55. func New(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) ConsistentWatchableKV {
  56. return newWatchableStore(b, le, ig)
  57. }
  58. func newWatchableStore(b backend.Backend, le lease.Lessor, ig ConsistentIndexGetter) *watchableStore {
  59. s := &watchableStore{
  60. store: NewStore(b, le, ig),
  61. victimc: make(chan struct{}, 1),
  62. unsynced: newWatcherGroup(),
  63. synced: newWatcherGroup(),
  64. stopc: make(chan struct{}),
  65. }
  66. s.store.ReadView = &readView{s}
  67. s.store.WriteView = &writeView{s}
  68. if s.le != nil {
  69. // use this store as the deleter so revokes trigger watch events
  70. s.le.SetRangeDeleter(func() lease.TxnDelete { return s.Write() })
  71. }
  72. s.wg.Add(2)
  73. go s.syncWatchersLoop()
  74. go s.syncVictimsLoop()
  75. return s
  76. }
  77. func (s *watchableStore) Close() error {
  78. close(s.stopc)
  79. s.wg.Wait()
  80. return s.store.Close()
  81. }
  82. func (s *watchableStore) NewWatchStream() WatchStream {
  83. watchStreamGauge.Inc()
  84. return &watchStream{
  85. watchable: s,
  86. ch: make(chan WatchResponse, chanBufLen),
  87. cancels: make(map[WatchID]cancelFunc),
  88. watchers: make(map[WatchID]*watcher),
  89. }
  90. }
  91. func (s *watchableStore) watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse, fcs ...FilterFunc) (*watcher, cancelFunc) {
  92. wa := &watcher{
  93. key: key,
  94. end: end,
  95. minRev: startRev,
  96. id: id,
  97. ch: ch,
  98. fcs: fcs,
  99. }
  100. s.mu.Lock()
  101. s.revMu.RLock()
  102. synced := startRev > s.store.currentRev || startRev == 0
  103. if synced {
  104. wa.minRev = s.store.currentRev + 1
  105. if startRev > wa.minRev {
  106. wa.minRev = startRev
  107. }
  108. }
  109. if synced {
  110. s.synced.add(wa)
  111. } else {
  112. slowWatcherGauge.Inc()
  113. s.unsynced.add(wa)
  114. }
  115. s.revMu.RUnlock()
  116. s.mu.Unlock()
  117. watcherGauge.Inc()
  118. return wa, func() { s.cancelWatcher(wa) }
  119. }
  120. // cancelWatcher removes references of the watcher from the watchableStore
  121. func (s *watchableStore) cancelWatcher(wa *watcher) {
  122. for {
  123. s.mu.Lock()
  124. if s.unsynced.delete(wa) {
  125. slowWatcherGauge.Dec()
  126. break
  127. } else if s.synced.delete(wa) {
  128. break
  129. } else if wa.compacted {
  130. break
  131. }
  132. if !wa.victim {
  133. panic("watcher not victim but not in watch groups")
  134. }
  135. var victimBatch watcherBatch
  136. for _, wb := range s.victims {
  137. if wb[wa] != nil {
  138. victimBatch = wb
  139. break
  140. }
  141. }
  142. if victimBatch != nil {
  143. slowWatcherGauge.Dec()
  144. delete(victimBatch, wa)
  145. break
  146. }
  147. // victim being processed so not accessible; retry
  148. s.mu.Unlock()
  149. time.Sleep(time.Millisecond)
  150. }
  151. watcherGauge.Dec()
  152. s.mu.Unlock()
  153. }
  154. // syncWatchersLoop syncs the watcher in the unsynced map every 100ms.
  155. func (s *watchableStore) syncWatchersLoop() {
  156. defer s.wg.Done()
  157. for {
  158. s.mu.RLock()
  159. st := time.Now()
  160. lastUnsyncedWatchers := s.unsynced.size()
  161. s.mu.RUnlock()
  162. unsyncedWatchers := 0
  163. if lastUnsyncedWatchers > 0 {
  164. unsyncedWatchers = s.syncWatchers()
  165. }
  166. syncDuration := time.Since(st)
  167. waitDuration := 100 * time.Millisecond
  168. // more work pending?
  169. if unsyncedWatchers != 0 && lastUnsyncedWatchers > unsyncedWatchers {
  170. // be fair to other store operations by yielding time taken
  171. waitDuration = syncDuration
  172. }
  173. select {
  174. case <-time.After(waitDuration):
  175. case <-s.stopc:
  176. return
  177. }
  178. }
  179. }
  180. // syncVictimsLoop tries to write precomputed watcher responses to
  181. // watchers that had a blocked watcher channel
  182. func (s *watchableStore) syncVictimsLoop() {
  183. defer s.wg.Done()
  184. for {
  185. for s.moveVictims() != 0 {
  186. // try to update all victim watchers
  187. }
  188. s.mu.RLock()
  189. isEmpty := len(s.victims) == 0
  190. s.mu.RUnlock()
  191. var tickc <-chan time.Time
  192. if !isEmpty {
  193. tickc = time.After(10 * time.Millisecond)
  194. }
  195. select {
  196. case <-tickc:
  197. case <-s.victimc:
  198. case <-s.stopc:
  199. return
  200. }
  201. }
  202. }
  203. // moveVictims tries to update watches with already pending event data
  204. func (s *watchableStore) moveVictims() (moved int) {
  205. s.mu.Lock()
  206. victims := s.victims
  207. s.victims = nil
  208. s.mu.Unlock()
  209. var newVictim watcherBatch
  210. for _, wb := range victims {
  211. // try to send responses again
  212. for w, eb := range wb {
  213. // watcher has observed the store up to, but not including, w.minRev
  214. rev := w.minRev - 1
  215. if w.send(WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}) {
  216. pendingEventsGauge.Add(float64(len(eb.evs)))
  217. } else {
  218. if newVictim == nil {
  219. newVictim = make(watcherBatch)
  220. }
  221. newVictim[w] = eb
  222. continue
  223. }
  224. moved++
  225. }
  226. // assign completed victim watchers to unsync/sync
  227. s.mu.Lock()
  228. s.store.revMu.RLock()
  229. curRev := s.store.currentRev
  230. for w, eb := range wb {
  231. if newVictim != nil && newVictim[w] != nil {
  232. // couldn't send watch response; stays victim
  233. continue
  234. }
  235. w.victim = false
  236. if eb.moreRev != 0 {
  237. w.minRev = eb.moreRev
  238. }
  239. if w.minRev <= curRev {
  240. s.unsynced.add(w)
  241. } else {
  242. slowWatcherGauge.Dec()
  243. s.synced.add(w)
  244. }
  245. }
  246. s.store.revMu.RUnlock()
  247. s.mu.Unlock()
  248. }
  249. if len(newVictim) > 0 {
  250. s.mu.Lock()
  251. s.victims = append(s.victims, newVictim)
  252. s.mu.Unlock()
  253. }
  254. return moved
  255. }
  256. // syncWatchers syncs unsynced watchers by:
  257. // 1. choose a set of watchers from the unsynced watcher group
  258. // 2. iterate over the set to get the minimum revision and remove compacted watchers
  259. // 3. use minimum revision to get all key-value pairs and send those events to watchers
  260. // 4. remove synced watchers in set from unsynced group and move to synced group
  261. func (s *watchableStore) syncWatchers() int {
  262. s.mu.Lock()
  263. defer s.mu.Unlock()
  264. if s.unsynced.size() == 0 {
  265. return 0
  266. }
  267. s.store.revMu.RLock()
  268. defer s.store.revMu.RUnlock()
  269. // in order to find key-value pairs from unsynced watchers, we need to
  270. // find min revision index, and these revisions can be used to
  271. // query the backend store of key-value pairs
  272. curRev := s.store.currentRev
  273. compactionRev := s.store.compactMainRev
  274. wg, minRev := s.unsynced.choose(maxWatchersPerSync, curRev, compactionRev)
  275. minBytes, maxBytes := newRevBytes(), newRevBytes()
  276. revToBytes(revision{main: minRev}, minBytes)
  277. revToBytes(revision{main: curRev + 1}, maxBytes)
  278. // UnsafeRange returns keys and values. And in boltdb, keys are revisions.
  279. // values are actual key-value pairs in backend.
  280. tx := s.store.b.ReadTx()
  281. tx.Lock()
  282. revs, vs := tx.UnsafeRange(keyBucketName, minBytes, maxBytes, 0)
  283. evs := kvsToEvents(wg, revs, vs)
  284. tx.Unlock()
  285. var victims watcherBatch
  286. wb := newWatcherBatch(wg, evs)
  287. for w := range wg.watchers {
  288. w.minRev = curRev + 1
  289. eb, ok := wb[w]
  290. if !ok {
  291. // bring un-notified watcher to synced
  292. s.synced.add(w)
  293. s.unsynced.delete(w)
  294. continue
  295. }
  296. if eb.moreRev != 0 {
  297. w.minRev = eb.moreRev
  298. }
  299. if w.send(WatchResponse{WatchID: w.id, Events: eb.evs, Revision: curRev}) {
  300. pendingEventsGauge.Add(float64(len(eb.evs)))
  301. } else {
  302. if victims == nil {
  303. victims = make(watcherBatch)
  304. }
  305. w.victim = true
  306. }
  307. if w.victim {
  308. victims[w] = eb
  309. } else {
  310. if eb.moreRev != 0 {
  311. // stay unsynced; more to read
  312. continue
  313. }
  314. s.synced.add(w)
  315. }
  316. s.unsynced.delete(w)
  317. }
  318. s.addVictim(victims)
  319. vsz := 0
  320. for _, v := range s.victims {
  321. vsz += len(v)
  322. }
  323. slowWatcherGauge.Set(float64(s.unsynced.size() + vsz))
  324. return s.unsynced.size()
  325. }
  326. // kvsToEvents gets all events for the watchers from all key-value pairs
  327. func kvsToEvents(wg *watcherGroup, revs, vals [][]byte) (evs []mvccpb.Event) {
  328. for i, v := range vals {
  329. var kv mvccpb.KeyValue
  330. if err := kv.Unmarshal(v); err != nil {
  331. plog.Panicf("cannot unmarshal event: %v", err)
  332. }
  333. if !wg.contains(string(kv.Key)) {
  334. continue
  335. }
  336. ty := mvccpb.PUT
  337. if isTombstone(revs[i]) {
  338. ty = mvccpb.DELETE
  339. // patch in mod revision so watchers won't skip
  340. kv.ModRevision = bytesToRev(revs[i]).main
  341. }
  342. evs = append(evs, mvccpb.Event{Kv: &kv, Type: ty})
  343. }
  344. return evs
  345. }
  346. // notify notifies the fact that given event at the given rev just happened to
  347. // watchers that watch on the key of the event.
  348. func (s *watchableStore) notify(rev int64, evs []mvccpb.Event) {
  349. var victim watcherBatch
  350. for w, eb := range newWatcherBatch(&s.synced, evs) {
  351. if eb.revs != 1 {
  352. plog.Panicf("unexpected multiple revisions in notification")
  353. }
  354. if w.send(WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}) {
  355. pendingEventsGauge.Add(float64(len(eb.evs)))
  356. } else {
  357. // move slow watcher to victims
  358. w.minRev = rev + 1
  359. if victim == nil {
  360. victim = make(watcherBatch)
  361. }
  362. w.victim = true
  363. victim[w] = eb
  364. s.synced.delete(w)
  365. slowWatcherGauge.Inc()
  366. }
  367. }
  368. s.addVictim(victim)
  369. }
  370. func (s *watchableStore) addVictim(victim watcherBatch) {
  371. if victim == nil {
  372. return
  373. }
  374. s.victims = append(s.victims, victim)
  375. select {
  376. case s.victimc <- struct{}{}:
  377. default:
  378. }
  379. }
  380. func (s *watchableStore) rev() int64 { return s.store.Rev() }
  381. func (s *watchableStore) progress(w *watcher) {
  382. s.mu.RLock()
  383. defer s.mu.RUnlock()
  384. if _, ok := s.synced.watchers[w]; ok {
  385. w.send(WatchResponse{WatchID: w.id, Revision: s.rev()})
  386. // If the ch is full, this watcher is receiving events.
  387. // We do not need to send progress at all.
  388. }
  389. }
  390. type watcher struct {
  391. // the watcher key
  392. key []byte
  393. // end indicates the end of the range to watch.
  394. // If end is set, the watcher is on a range.
  395. end []byte
  396. // victim is set when ch is blocked and undergoing victim processing
  397. victim bool
  398. // compacted is set when the watcher is removed because of compaction
  399. compacted bool
  400. // minRev is the minimum revision update the watcher will accept
  401. minRev int64
  402. id WatchID
  403. fcs []FilterFunc
  404. // a chan to send out the watch response.
  405. // The chan might be shared with other watchers.
  406. ch chan<- WatchResponse
  407. }
  408. func (w *watcher) send(wr WatchResponse) bool {
  409. progressEvent := len(wr.Events) == 0
  410. if len(w.fcs) != 0 {
  411. ne := make([]mvccpb.Event, 0, len(wr.Events))
  412. for i := range wr.Events {
  413. filtered := false
  414. for _, filter := range w.fcs {
  415. if filter(wr.Events[i]) {
  416. filtered = true
  417. break
  418. }
  419. }
  420. if !filtered {
  421. ne = append(ne, wr.Events[i])
  422. }
  423. }
  424. wr.Events = ne
  425. }
  426. // if all events are filtered out, we should send nothing.
  427. if !progressEvent && len(wr.Events) == 0 {
  428. return true
  429. }
  430. select {
  431. case w.ch <- wr:
  432. return true
  433. default:
  434. return false
  435. }
  436. }