watchable_store.go 12 KB

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