watchable_store.go 13 KB

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