watchable_store.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. // Copyright 2015 CoreOS, Inc.
  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 storage
  15. import (
  16. "log"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/lease"
  20. "github.com/coreos/etcd/storage/backend"
  21. "github.com/coreos/etcd/storage/storagepb"
  22. )
  23. const (
  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. )
  30. type watchable interface {
  31. watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc)
  32. progress(w *watcher)
  33. rev() int64
  34. }
  35. type watchableStore struct {
  36. mu sync.Mutex
  37. *store
  38. // contains all unsynced watchers that needs to sync with events that have happened
  39. unsynced watcherGroup
  40. // contains all synced watchers that are in sync with the progress of the store.
  41. // The key of the map is the key that the watcher watches on.
  42. synced watcherGroup
  43. stopc chan struct{}
  44. wg sync.WaitGroup
  45. }
  46. // cancelFunc updates unsynced and synced maps when running
  47. // cancel operations.
  48. type cancelFunc func()
  49. func newWatchableStore(b backend.Backend, le lease.Lessor) *watchableStore {
  50. s := &watchableStore{
  51. store: NewStore(b, le),
  52. unsynced: newWatcherGroup(),
  53. synced: newWatcherGroup(),
  54. stopc: make(chan struct{}),
  55. }
  56. if s.le != nil {
  57. // use this store as the deleter so revokes trigger watch events
  58. s.le.SetRangeDeleter(s)
  59. }
  60. s.wg.Add(1)
  61. go s.syncWatchersLoop()
  62. return s
  63. }
  64. func (s *watchableStore) Put(key, value []byte, lease lease.LeaseID) (rev int64) {
  65. s.mu.Lock()
  66. defer s.mu.Unlock()
  67. rev = s.store.Put(key, value, lease)
  68. changes := s.store.getChanges()
  69. if len(changes) != 1 {
  70. log.Panicf("unexpected len(changes) != 1 after put")
  71. }
  72. ev := storagepb.Event{
  73. Type: storagepb.PUT,
  74. Kv: &changes[0],
  75. }
  76. s.notify(rev, []storagepb.Event{ev})
  77. return rev
  78. }
  79. func (s *watchableStore) DeleteRange(key, end []byte) (n, rev int64) {
  80. s.mu.Lock()
  81. defer s.mu.Unlock()
  82. n, rev = s.store.DeleteRange(key, end)
  83. changes := s.store.getChanges()
  84. if len(changes) != int(n) {
  85. log.Panicf("unexpected len(changes) != n after deleteRange")
  86. }
  87. if n == 0 {
  88. return n, rev
  89. }
  90. evs := make([]storagepb.Event, n)
  91. for i, change := range changes {
  92. evs[i] = storagepb.Event{
  93. Type: storagepb.DELETE,
  94. Kv: &change}
  95. evs[i].Kv.ModRevision = rev
  96. }
  97. s.notify(rev, evs)
  98. return n, rev
  99. }
  100. func (s *watchableStore) TxnBegin() int64 {
  101. s.mu.Lock()
  102. return s.store.TxnBegin()
  103. }
  104. func (s *watchableStore) TxnEnd(txnID int64) error {
  105. err := s.store.TxnEnd(txnID)
  106. if err != nil {
  107. return err
  108. }
  109. changes := s.getChanges()
  110. if len(changes) == 0 {
  111. s.mu.Unlock()
  112. return nil
  113. }
  114. rev := s.store.Rev()
  115. evs := make([]storagepb.Event, len(changes))
  116. for i, change := range changes {
  117. switch change.CreateRevision {
  118. case 0:
  119. evs[i] = storagepb.Event{
  120. Type: storagepb.DELETE,
  121. Kv: &changes[i]}
  122. evs[i].Kv.ModRevision = rev
  123. default:
  124. evs[i] = storagepb.Event{
  125. Type: storagepb.PUT,
  126. Kv: &changes[i]}
  127. }
  128. }
  129. s.notify(rev, evs)
  130. s.mu.Unlock()
  131. return nil
  132. }
  133. func (s *watchableStore) Close() error {
  134. close(s.stopc)
  135. s.wg.Wait()
  136. return s.store.Close()
  137. }
  138. func (s *watchableStore) NewWatchStream() WatchStream {
  139. watchStreamGauge.Inc()
  140. return &watchStream{
  141. watchable: s,
  142. ch: make(chan WatchResponse, chanBufLen),
  143. cancels: make(map[WatchID]cancelFunc),
  144. watchers: make(map[WatchID]*watcher),
  145. }
  146. }
  147. func (s *watchableStore) watch(key, end []byte, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc) {
  148. s.mu.Lock()
  149. defer s.mu.Unlock()
  150. wa := &watcher{
  151. key: key,
  152. end: end,
  153. cur: startRev,
  154. id: id,
  155. ch: ch,
  156. }
  157. s.store.mu.Lock()
  158. synced := startRev > s.store.currentRev.main || startRev == 0
  159. if synced {
  160. wa.cur = s.store.currentRev.main + 1
  161. if startRev > wa.cur {
  162. wa.cur = startRev
  163. }
  164. }
  165. s.store.mu.Unlock()
  166. if synced {
  167. s.synced.add(wa)
  168. } else {
  169. slowWatcherGauge.Inc()
  170. s.unsynced.add(wa)
  171. }
  172. watcherGauge.Inc()
  173. cancel := cancelFunc(func() {
  174. s.mu.Lock()
  175. defer s.mu.Unlock()
  176. // remove references of the watcher
  177. if s.unsynced.delete(wa) {
  178. slowWatcherGauge.Dec()
  179. watcherGauge.Dec()
  180. return
  181. }
  182. if s.synced.delete(wa) {
  183. watcherGauge.Dec()
  184. }
  185. // If we cannot find it, it should have finished watch.
  186. })
  187. return wa, cancel
  188. }
  189. // syncWatchersLoop syncs the watcher in the unsynced map every 100ms.
  190. func (s *watchableStore) syncWatchersLoop() {
  191. defer s.wg.Done()
  192. for {
  193. s.mu.Lock()
  194. s.syncWatchers()
  195. s.mu.Unlock()
  196. select {
  197. case <-time.After(100 * time.Millisecond):
  198. case <-s.stopc:
  199. return
  200. }
  201. }
  202. }
  203. // syncWatchers periodically syncs unsynced watchers by: Iterate all unsynced
  204. // watchers to get the minimum revision within its range, skipping the
  205. // watcher if its current revision is behind the compact revision of the
  206. // store. And use this minimum revision to get all key-value pairs. Then send
  207. // those events to watchers.
  208. func (s *watchableStore) syncWatchers() {
  209. s.store.mu.Lock()
  210. defer s.store.mu.Unlock()
  211. if s.unsynced.size() == 0 {
  212. return
  213. }
  214. // in order to find key-value pairs from unsynced watchers, we need to
  215. // find min revision index, and these revisions can be used to
  216. // query the backend store of key-value pairs
  217. curRev := s.store.currentRev.main
  218. compactionRev := s.store.compactMainRev
  219. minRev := s.unsynced.scanMinRev(curRev, compactionRev)
  220. minBytes, maxBytes := newRevBytes(), newRevBytes()
  221. revToBytes(revision{main: minRev}, minBytes)
  222. revToBytes(revision{main: curRev + 1}, maxBytes)
  223. // UnsafeRange returns keys and values. And in boltdb, keys are revisions.
  224. // values are actual key-value pairs in backend.
  225. tx := s.store.b.BatchTx()
  226. tx.Lock()
  227. revs, vs := tx.UnsafeRange(keyBucketName, minBytes, maxBytes, 0)
  228. evs := kvsToEvents(&s.unsynced, revs, vs)
  229. tx.Unlock()
  230. wb := newWatcherBatch(&s.unsynced, evs)
  231. for w, eb := range wb {
  232. select {
  233. // s.store.Rev also uses Lock, so just return directly
  234. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: s.store.currentRev.main}:
  235. pendingEventsGauge.Add(float64(len(eb.evs)))
  236. default:
  237. // TODO: handle the full unsynced watchers.
  238. // continue to process other watchers for now, the full ones
  239. // will be processed next time and hopefully it will not be full.
  240. continue
  241. }
  242. if eb.moreRev != 0 {
  243. w.cur = eb.moreRev
  244. continue
  245. }
  246. w.cur = curRev
  247. s.synced.add(w)
  248. s.unsynced.delete(w)
  249. }
  250. // bring all un-notified watchers to synced.
  251. for w := range s.unsynced.watchers {
  252. if !wb.contains(w) {
  253. w.cur = curRev
  254. s.synced.add(w)
  255. s.unsynced.delete(w)
  256. }
  257. }
  258. slowWatcherGauge.Set(float64(s.unsynced.size()))
  259. }
  260. // kvsToEvents gets all events for the watchers from all key-value pairs
  261. func kvsToEvents(wg *watcherGroup, revs, vals [][]byte) (evs []storagepb.Event) {
  262. for i, v := range vals {
  263. var kv storagepb.KeyValue
  264. if err := kv.Unmarshal(v); err != nil {
  265. log.Panicf("storage: cannot unmarshal event: %v", err)
  266. }
  267. if !wg.contains(string(kv.Key)) {
  268. continue
  269. }
  270. ty := storagepb.PUT
  271. if isTombstone(revs[i]) {
  272. ty = storagepb.DELETE
  273. // patch in mod revision so watchers won't skip
  274. kv.ModRevision = bytesToRev(revs[i]).main
  275. }
  276. evs = append(evs, storagepb.Event{Kv: &kv, Type: ty})
  277. }
  278. return evs
  279. }
  280. // notify notifies the fact that given event at the given rev just happened to
  281. // watchers that watch on the key of the event.
  282. func (s *watchableStore) notify(rev int64, evs []storagepb.Event) {
  283. for w, eb := range newWatcherBatch(&s.synced, evs) {
  284. if eb.revs != 1 {
  285. panic("unexpected multiple revisions in notification")
  286. }
  287. select {
  288. case w.ch <- WatchResponse{WatchID: w.id, Events: eb.evs, Revision: s.Rev()}:
  289. pendingEventsGauge.Add(float64(len(eb.evs)))
  290. default:
  291. // move slow watcher to unsynced
  292. w.cur = rev
  293. s.unsynced.add(w)
  294. s.synced.delete(w)
  295. slowWatcherGauge.Inc()
  296. }
  297. }
  298. }
  299. func (s *watchableStore) rev() int64 { return s.store.Rev() }
  300. func (s *watchableStore) progress(w *watcher) {
  301. s.mu.Lock()
  302. defer s.mu.Unlock()
  303. if _, ok := s.synced.watchers[w]; ok {
  304. select {
  305. case w.ch <- WatchResponse{WatchID: w.id, Revision: s.rev()}:
  306. default:
  307. // If the ch is full, this watcher is receiving events.
  308. // We do not need to send progress at all.
  309. }
  310. }
  311. }
  312. type watcher struct {
  313. // the watcher key
  314. key []byte
  315. // end indicates the end of the range to watch.
  316. // If end is set, the watcher is on a range.
  317. end []byte
  318. // cur is the current watcher revision of a unsynced watcher.
  319. // cur will be updated for unsynced watcher while it is catching up.
  320. // cur is startRev of a synced watcher.
  321. // cur will not be updated for synced watcher.
  322. cur int64
  323. id WatchID
  324. // a chan to send out the watch response.
  325. // The chan might be shared with other watchers.
  326. ch chan<- WatchResponse
  327. }