watchable_store.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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) (*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) (*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. }
  166. s.store.mu.Lock()
  167. synced := startRev > s.store.currentRev.main || startRev == 0
  168. if synced {
  169. wa.minRev = s.store.currentRev.main + 1
  170. if startRev > wa.minRev {
  171. wa.minRev = startRev
  172. }
  173. }
  174. s.store.mu.Unlock()
  175. if synced {
  176. s.synced.add(wa)
  177. } else {
  178. slowWatcherGauge.Inc()
  179. s.unsynced.add(wa)
  180. }
  181. watcherGauge.Inc()
  182. return wa, func() { s.cancelWatcher(wa) }
  183. }
  184. // cancelWatcher removes references of the watcher from the watchableStore
  185. func (s *watchableStore) cancelWatcher(wa *watcher) {
  186. for {
  187. s.mu.Lock()
  188. if s.unsynced.delete(wa) {
  189. slowWatcherGauge.Dec()
  190. break
  191. } else if s.synced.delete(wa) {
  192. break
  193. } else if wa.compacted {
  194. break
  195. }
  196. if !wa.victim {
  197. panic("watcher not victim but not in watch groups")
  198. }
  199. var victimBatch watcherBatch
  200. for _, wb := range s.victims {
  201. if wb[wa] != nil {
  202. victimBatch = wb
  203. break
  204. }
  205. }
  206. if victimBatch != nil {
  207. slowWatcherGauge.Dec()
  208. delete(victimBatch, wa)
  209. break
  210. }
  211. // victim being processed so not accessible; retry
  212. s.mu.Unlock()
  213. time.Sleep(time.Millisecond)
  214. }
  215. watcherGauge.Dec()
  216. s.mu.Unlock()
  217. }
  218. // syncWatchersLoop syncs the watcher in the unsynced map every 100ms.
  219. func (s *watchableStore) syncWatchersLoop() {
  220. defer s.wg.Done()
  221. for {
  222. s.mu.Lock()
  223. st := time.Now()
  224. lastUnsyncedWatchers := s.unsynced.size()
  225. s.syncWatchers()
  226. unsyncedWatchers := s.unsynced.size()
  227. s.mu.Unlock()
  228. syncDuration := time.Since(st)
  229. waitDuration := 100 * time.Millisecond
  230. // more work pending?
  231. if unsyncedWatchers != 0 && lastUnsyncedWatchers > unsyncedWatchers {
  232. // be fair to other store operations by yielding time taken
  233. waitDuration = syncDuration
  234. }
  235. select {
  236. case <-time.After(waitDuration):
  237. case <-s.stopc:
  238. return
  239. }
  240. }
  241. }
  242. // syncVictimsLoop tries to write precomputed watcher responses to
  243. // watchers that had a blocked watcher channel
  244. func (s *watchableStore) syncVictimsLoop() {
  245. defer s.wg.Done()
  246. for {
  247. for s.moveVictims() != 0 {
  248. // try to update all victim watchers
  249. }
  250. s.mu.Lock()
  251. isEmpty := len(s.victims) == 0
  252. s.mu.Unlock()
  253. var tickc <-chan time.Time
  254. if !isEmpty {
  255. tickc = time.After(10 * time.Millisecond)
  256. }
  257. select {
  258. case <-tickc:
  259. case <-s.victimc:
  260. case <-s.stopc:
  261. return
  262. }
  263. }
  264. }
  265. // moveVictims tries to update watches with already pending event data
  266. func (s *watchableStore) moveVictims() (moved int) {
  267. s.mu.Lock()
  268. victims := s.victims
  269. s.victims = nil
  270. s.mu.Unlock()
  271. var newVictim watcherBatch
  272. for _, wb := range victims {
  273. // try to send responses again
  274. for w, eb := range wb {
  275. // watcher has observed the store up to, but not including, w.minRev
  276. rev := w.minRev - 1
  277. select {
  278. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}:
  279. pendingEventsGauge.Add(float64(len(eb.evs)))
  280. default:
  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. select {
  361. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: curRev}:
  362. pendingEventsGauge.Add(float64(len(eb.evs)))
  363. default:
  364. if victims == nil {
  365. victims = make(watcherBatch)
  366. }
  367. w.victim = true
  368. }
  369. if w.victim {
  370. victims[w] = eb
  371. } else {
  372. if eb.moreRev != 0 {
  373. // stay unsynced; more to read
  374. continue
  375. }
  376. s.synced.add(w)
  377. }
  378. s.unsynced.delete(w)
  379. }
  380. s.addVictim(victims)
  381. vsz := 0
  382. for _, v := range s.victims {
  383. vsz += len(v)
  384. }
  385. slowWatcherGauge.Set(float64(s.unsynced.size() + vsz))
  386. }
  387. // kvsToEvents gets all events for the watchers from all key-value pairs
  388. func kvsToEvents(wg *watcherGroup, revs, vals [][]byte) (evs []mvccpb.Event) {
  389. for i, v := range vals {
  390. var kv mvccpb.KeyValue
  391. if err := kv.Unmarshal(v); err != nil {
  392. plog.Panicf("cannot unmarshal event: %v", err)
  393. }
  394. if !wg.contains(string(kv.Key)) {
  395. continue
  396. }
  397. ty := mvccpb.PUT
  398. if isTombstone(revs[i]) {
  399. ty = mvccpb.DELETE
  400. // patch in mod revision so watchers won't skip
  401. kv.ModRevision = bytesToRev(revs[i]).main
  402. }
  403. evs = append(evs, mvccpb.Event{Kv: &kv, Type: ty})
  404. }
  405. return evs
  406. }
  407. // notify notifies the fact that given event at the given rev just happened to
  408. // watchers that watch on the key of the event.
  409. func (s *watchableStore) notify(rev int64, evs []mvccpb.Event) {
  410. var victim watcherBatch
  411. for w, eb := range newWatcherBatch(&s.synced, evs) {
  412. if eb.revs != 1 {
  413. plog.Panicf("unexpected multiple revisions in notification")
  414. }
  415. select {
  416. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: rev}:
  417. pendingEventsGauge.Add(float64(len(eb.evs)))
  418. default:
  419. // move slow watcher to victims
  420. w.minRev = rev + 1
  421. if victim == nil {
  422. victim = make(watcherBatch)
  423. }
  424. w.victim = true
  425. victim[w] = eb
  426. s.synced.delete(w)
  427. slowWatcherGauge.Inc()
  428. }
  429. }
  430. s.addVictim(victim)
  431. }
  432. func (s *watchableStore) addVictim(victim watcherBatch) {
  433. if victim == nil {
  434. return
  435. }
  436. s.victims = append(s.victims, victim)
  437. select {
  438. case s.victimc <- struct{}{}:
  439. default:
  440. }
  441. }
  442. func (s *watchableStore) rev() int64 { return s.store.Rev() }
  443. func (s *watchableStore) progress(w *watcher) {
  444. s.mu.Lock()
  445. defer s.mu.Unlock()
  446. if _, ok := s.synced.watchers[w]; ok {
  447. select {
  448. case w.ch <- WatchResponse{WatchID: w.id, Revision: s.rev()}:
  449. default:
  450. // If the ch is full, this watcher is receiving events.
  451. // We do not need to send progress at all.
  452. }
  453. }
  454. }
  455. type watcher struct {
  456. // the watcher key
  457. key []byte
  458. // end indicates the end of the range to watch.
  459. // If end is set, the watcher is on a range.
  460. end []byte
  461. // victim is set when ch is blocked and undergoing victim processing
  462. victim bool
  463. // compacted is set when the watcher is removed because of compaction
  464. compacted bool
  465. // minRev is the minimum revision update the watcher will accept
  466. minRev int64
  467. id WatchID
  468. // a chan to send out the watch response.
  469. // The chan might be shared with other watchers.
  470. ch chan<- WatchResponse
  471. }