watchable_store.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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. "math"
  18. "strings"
  19. "sync"
  20. "time"
  21. "github.com/coreos/etcd/lease"
  22. "github.com/coreos/etcd/storage/backend"
  23. "github.com/coreos/etcd/storage/storagepb"
  24. )
  25. const (
  26. // chanBufLen is the length of the buffered chan
  27. // for sending out watched events.
  28. // TODO: find a good buf value. 1024 is just a random one that
  29. // seems to be reasonable.
  30. chanBufLen = 1024
  31. )
  32. type (
  33. watcherSetByKey map[string]watcherSet
  34. watcherSet map[*watcher]struct{}
  35. )
  36. func (w watcherSet) add(wa *watcher) {
  37. if _, ok := w[wa]; ok {
  38. panic("add watcher twice!")
  39. }
  40. w[wa] = struct{}{}
  41. }
  42. func (w watcherSetByKey) add(wa *watcher) {
  43. set := w[string(wa.key)]
  44. if set == nil {
  45. set = make(watcherSet)
  46. w[string(wa.key)] = set
  47. }
  48. set.add(wa)
  49. }
  50. func (w watcherSetByKey) getSetByKey(key string) (watcherSet, bool) {
  51. set, ok := w[key]
  52. return set, ok
  53. }
  54. func (w watcherSetByKey) delete(wa *watcher) bool {
  55. k := string(wa.key)
  56. if v, ok := w[k]; ok {
  57. if _, ok := v[wa]; ok {
  58. delete(v, wa)
  59. // if there is nothing in the set,
  60. // remove the set
  61. if len(v) == 0 {
  62. delete(w, k)
  63. }
  64. return true
  65. }
  66. }
  67. return false
  68. }
  69. type watchable interface {
  70. watch(key []byte, prefix bool, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc)
  71. rev() int64
  72. }
  73. type watchableStore struct {
  74. mu sync.Mutex
  75. *store
  76. // contains all unsynced watchers that needs to sync with events that have happened
  77. unsynced watcherSetByKey
  78. // contains all synced watchers that are in sync with the progress of the store.
  79. // The key of the map is the key that the watcher watches on.
  80. synced watcherSetByKey
  81. stopc chan struct{}
  82. wg sync.WaitGroup
  83. }
  84. // cancelFunc updates unsynced and synced maps when running
  85. // cancel operations.
  86. type cancelFunc func()
  87. func newWatchableStore(b backend.Backend, le lease.Lessor) *watchableStore {
  88. s := &watchableStore{
  89. store: NewStore(b, le),
  90. unsynced: make(watcherSetByKey),
  91. synced: make(watcherSetByKey),
  92. stopc: make(chan struct{}),
  93. }
  94. if s.le != nil {
  95. // use this store as the deleter so revokes trigger watch events
  96. s.le.SetRangeDeleter(s)
  97. }
  98. s.wg.Add(1)
  99. go s.syncWatchersLoop()
  100. return s
  101. }
  102. func (s *watchableStore) Put(key, value []byte, lease lease.LeaseID) (rev int64) {
  103. s.mu.Lock()
  104. defer s.mu.Unlock()
  105. rev = s.store.Put(key, value, lease)
  106. changes := s.store.getChanges()
  107. if len(changes) != 1 {
  108. log.Panicf("unexpected len(changes) != 1 after put")
  109. }
  110. ev := storagepb.Event{
  111. Type: storagepb.PUT,
  112. Kv: &changes[0],
  113. }
  114. s.notify(rev, []storagepb.Event{ev})
  115. return rev
  116. }
  117. func (s *watchableStore) DeleteRange(key, end []byte) (n, rev int64) {
  118. s.mu.Lock()
  119. defer s.mu.Unlock()
  120. n, rev = s.store.DeleteRange(key, end)
  121. changes := s.store.getChanges()
  122. if len(changes) != int(n) {
  123. log.Panicf("unexpected len(changes) != n after deleteRange")
  124. }
  125. if n == 0 {
  126. return n, rev
  127. }
  128. evs := make([]storagepb.Event, n)
  129. for i, change := range changes {
  130. evs[i] = storagepb.Event{
  131. Type: storagepb.DELETE,
  132. Kv: &change}
  133. }
  134. s.notify(rev, evs)
  135. return n, rev
  136. }
  137. func (s *watchableStore) TxnBegin() int64 {
  138. s.mu.Lock()
  139. return s.store.TxnBegin()
  140. }
  141. func (s *watchableStore) TxnEnd(txnID int64) error {
  142. err := s.store.TxnEnd(txnID)
  143. if err != nil {
  144. return err
  145. }
  146. changes := s.getChanges()
  147. if len(changes) == 0 {
  148. s.mu.Unlock()
  149. return nil
  150. }
  151. evs := make([]storagepb.Event, len(changes))
  152. for i, change := range changes {
  153. switch change.Value {
  154. case nil:
  155. evs[i] = storagepb.Event{
  156. Type: storagepb.DELETE,
  157. Kv: &changes[i]}
  158. default:
  159. evs[i] = storagepb.Event{
  160. Type: storagepb.PUT,
  161. Kv: &changes[i]}
  162. }
  163. }
  164. s.notify(s.store.Rev(), evs)
  165. s.mu.Unlock()
  166. return nil
  167. }
  168. func (s *watchableStore) Close() error {
  169. close(s.stopc)
  170. s.wg.Wait()
  171. return s.store.Close()
  172. }
  173. func (s *watchableStore) NewWatchStream() WatchStream {
  174. watchStreamGauge.Inc()
  175. return &watchStream{
  176. watchable: s,
  177. ch: make(chan WatchResponse, chanBufLen),
  178. cancels: make(map[WatchID]cancelFunc),
  179. }
  180. }
  181. func (s *watchableStore) watch(key []byte, prefix bool, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc) {
  182. s.mu.Lock()
  183. defer s.mu.Unlock()
  184. wa := &watcher{
  185. key: key,
  186. prefix: prefix,
  187. cur: startRev,
  188. id: id,
  189. ch: ch,
  190. }
  191. if startRev == 0 {
  192. s.synced.add(wa)
  193. } else {
  194. slowWatcherGauge.Inc()
  195. s.unsynced.add(wa)
  196. }
  197. watcherGauge.Inc()
  198. cancel := cancelFunc(func() {
  199. s.mu.Lock()
  200. defer s.mu.Unlock()
  201. // remove references of the watcher
  202. if s.unsynced.delete(wa) {
  203. slowWatcherGauge.Dec()
  204. watcherGauge.Dec()
  205. return
  206. }
  207. if s.synced.delete(wa) {
  208. watcherGauge.Dec()
  209. }
  210. // If we cannot find it, it should have finished watch.
  211. })
  212. return wa, cancel
  213. }
  214. // syncWatchersLoop syncs the watcher in the unsynced map every 100ms.
  215. func (s *watchableStore) syncWatchersLoop() {
  216. defer s.wg.Done()
  217. for {
  218. s.mu.Lock()
  219. s.syncWatchers()
  220. s.mu.Unlock()
  221. select {
  222. case <-time.After(100 * time.Millisecond):
  223. case <-s.stopc:
  224. return
  225. }
  226. }
  227. }
  228. // syncWatchers periodically syncs unsynced watchers by: Iterate all unsynced
  229. // watchers to get the minimum revision within its range, skipping the
  230. // watcher if its current revision is behind the compact revision of the
  231. // store. And use this minimum revision to get all key-value pairs. Then send
  232. // those events to watchers.
  233. func (s *watchableStore) syncWatchers() {
  234. s.store.mu.Lock()
  235. defer s.store.mu.Unlock()
  236. if len(s.unsynced) == 0 {
  237. return
  238. }
  239. // in order to find key-value pairs from unsynced watchers, we need to
  240. // find min revision index, and these revisions can be used to
  241. // query the backend store of key-value pairs
  242. minRev := int64(math.MaxInt64)
  243. curRev := s.store.currentRev.main
  244. compactionRev := s.store.compactMainRev
  245. prefixes := make(map[string]struct{})
  246. for _, set := range s.unsynced {
  247. for w := range set {
  248. k := string(w.key)
  249. if w.cur > curRev {
  250. panic("watcher current revision should not exceed current revision")
  251. }
  252. if w.cur < compactionRev {
  253. select {
  254. case w.ch <- WatchResponse{WatchID: w.id, Compacted: true}:
  255. s.unsynced.delete(w)
  256. default:
  257. // retry next time
  258. }
  259. continue
  260. }
  261. if minRev >= w.cur {
  262. minRev = w.cur
  263. }
  264. if w.prefix {
  265. prefixes[k] = struct{}{}
  266. }
  267. }
  268. }
  269. minBytes, maxBytes := newRevBytes(), newRevBytes()
  270. revToBytes(revision{main: minRev}, minBytes)
  271. revToBytes(revision{main: curRev + 1}, maxBytes)
  272. // UnsafeRange returns keys and values. And in boltdb, keys are revisions.
  273. // values are actual key-value pairs in backend.
  274. tx := s.store.b.BatchTx()
  275. tx.Lock()
  276. ks, vs := tx.UnsafeRange(keyBucketName, minBytes, maxBytes, 0)
  277. evs := []storagepb.Event{}
  278. // get the list of all events from all key-value pairs
  279. for i, v := range vs {
  280. var kv storagepb.KeyValue
  281. if err := kv.Unmarshal(v); err != nil {
  282. log.Panicf("storage: cannot unmarshal event: %v", err)
  283. }
  284. k := string(kv.Key)
  285. if _, ok := s.unsynced.getSetByKey(k); !ok && !matchPrefix(k, prefixes) {
  286. continue
  287. }
  288. var ev storagepb.Event
  289. switch {
  290. case isTombstone(ks[i]):
  291. ev.Type = storagepb.DELETE
  292. default:
  293. ev.Type = storagepb.PUT
  294. }
  295. ev.Kv = &kv
  296. evs = append(evs, ev)
  297. }
  298. tx.Unlock()
  299. for w, es := range newWatcherToEventMap(s.unsynced, evs) {
  300. select {
  301. // s.store.Rev also uses Lock, so just return directly
  302. case w.ch <- WatchResponse{WatchID: w.id, Events: es, Revision: s.store.currentRev.main}:
  303. pendingEventsGauge.Add(float64(len(es)))
  304. default:
  305. // TODO: handle the full unsynced watchers.
  306. // continue to process other watchers for now, the full ones
  307. // will be processed next time and hopefully it will not be full.
  308. continue
  309. }
  310. w.cur = curRev
  311. s.synced.add(w)
  312. s.unsynced.delete(w)
  313. }
  314. slowWatcherGauge.Set(float64(len(s.unsynced)))
  315. }
  316. // notify notifies the fact that given event at the given rev just happened to
  317. // watchers that watch on the key of the event.
  318. func (s *watchableStore) notify(rev int64, evs []storagepb.Event) {
  319. we := newWatcherToEventMap(s.synced, evs)
  320. for _, wm := range s.synced {
  321. for w := range wm {
  322. es, ok := we[w]
  323. if !ok {
  324. continue
  325. }
  326. select {
  327. case w.ch <- WatchResponse{WatchID: w.id, Events: es, Revision: s.Rev()}:
  328. pendingEventsGauge.Add(float64(len(es)))
  329. default:
  330. // move slow watcher to unsynced
  331. w.cur = rev
  332. s.unsynced.add(w)
  333. delete(wm, w)
  334. slowWatcherGauge.Inc()
  335. }
  336. }
  337. }
  338. }
  339. func (s *watchableStore) rev() int64 { return s.store.Rev() }
  340. type watcher struct {
  341. // the watcher key
  342. key []byte
  343. // prefix indicates if watcher is on a key or a prefix.
  344. // If prefix is true, the watcher is on a prefix.
  345. prefix bool
  346. // cur is the current watcher revision.
  347. // If cur is behind the current revision of the KV,
  348. // watcher is unsynced and needs to catch up.
  349. cur int64
  350. id WatchID
  351. // a chan to send out the watch response.
  352. // The chan might be shared with other watchers.
  353. ch chan<- WatchResponse
  354. }
  355. // newWatcherToEventMap creates a map that has watcher as key and events as
  356. // value. It enables quick events look up by watcher.
  357. func newWatcherToEventMap(sm watcherSetByKey, evs []storagepb.Event) map[*watcher][]storagepb.Event {
  358. watcherToEvents := make(map[*watcher][]storagepb.Event)
  359. for _, ev := range evs {
  360. key := string(ev.Kv.Key)
  361. // check all prefixes of the key to notify all corresponded watchers
  362. for i := 0; i <= len(key); i++ {
  363. k := string(key[:i])
  364. wm, ok := sm[k]
  365. if !ok {
  366. continue
  367. }
  368. for w := range wm {
  369. // the watcher needs to be notified when either it watches prefix or
  370. // the key is exactly matched.
  371. if !w.prefix && i != len(ev.Kv.Key) {
  372. continue
  373. }
  374. if _, ok := watcherToEvents[w]; !ok {
  375. watcherToEvents[w] = []storagepb.Event{}
  376. }
  377. watcherToEvents[w] = append(watcherToEvents[w], ev)
  378. }
  379. }
  380. }
  381. return watcherToEvents
  382. }
  383. // matchPrefix returns true if key has any matching prefix
  384. // from prefixes map.
  385. func matchPrefix(key string, prefixes map[string]struct{}) bool {
  386. for p := range prefixes {
  387. if strings.HasPrefix(key, p) {
  388. return true
  389. }
  390. }
  391. return false
  392. }