watchable_store.go 13 KB

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