watchable_store.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. "fmt"
  17. "log"
  18. "math"
  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 watchable interface {
  33. watch(key []byte, prefix bool, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc)
  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 map[*watcher]struct{}
  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 map[string]map[*watcher]struct{}
  43. tx *ongoingTx
  44. stopc chan struct{}
  45. wg sync.WaitGroup
  46. }
  47. // cancelFunc updates unsynced and synced maps when running
  48. // cancel operations.
  49. type cancelFunc func()
  50. func newWatchableStore(b backend.Backend) *watchableStore {
  51. s := &watchableStore{
  52. store: NewStore(b),
  53. unsynced: make(map[*watcher]struct{}),
  54. synced: make(map[string]map[*watcher]struct{}),
  55. stopc: make(chan struct{}),
  56. }
  57. s.wg.Add(1)
  58. go s.syncWatchersLoop()
  59. return s
  60. }
  61. func (s *watchableStore) Put(key, value []byte, lease lease.LeaseID) (rev int64) {
  62. s.mu.Lock()
  63. defer s.mu.Unlock()
  64. rev = s.store.Put(key, value, lease)
  65. // TODO: avoid this range
  66. kvs, _, err := s.store.Range(key, nil, 0, rev)
  67. if err != nil {
  68. log.Panicf("unexpected range error (%v)", err)
  69. }
  70. ev := storagepb.Event{
  71. Type: storagepb.PUT,
  72. Kv: &kvs[0],
  73. }
  74. s.handle(rev, []storagepb.Event{ev})
  75. return rev
  76. }
  77. func (s *watchableStore) DeleteRange(key, end []byte) (n, rev int64) {
  78. s.mu.Lock()
  79. defer s.mu.Unlock()
  80. // TODO: avoid this range
  81. kvs, _, err := s.store.Range(key, end, 0, 0)
  82. if err != nil {
  83. log.Panicf("unexpected range error (%v)", err)
  84. }
  85. n, rev = s.store.DeleteRange(key, end)
  86. evs := make([]storagepb.Event, len(kvs))
  87. for i, kv := range kvs {
  88. evs[i] = storagepb.Event{
  89. Type: storagepb.DELETE,
  90. Kv: &storagepb.KeyValue{
  91. Key: kv.Key,
  92. }}
  93. }
  94. s.handle(rev, evs)
  95. return n, rev
  96. }
  97. func (s *watchableStore) TxnBegin() int64 {
  98. s.mu.Lock()
  99. s.tx = newOngoingTx()
  100. return s.store.TxnBegin()
  101. }
  102. func (s *watchableStore) TxnPut(txnID int64, key, value []byte, lease lease.LeaseID) (rev int64, err error) {
  103. rev, err = s.store.TxnPut(txnID, key, value, lease)
  104. if err == nil {
  105. s.tx.put(string(key))
  106. }
  107. return rev, err
  108. }
  109. func (s *watchableStore) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  110. kvs, _, err := s.store.TxnRange(txnID, key, end, 0, 0)
  111. if err != nil {
  112. log.Panicf("unexpected range error (%v)", err)
  113. }
  114. n, rev, err = s.store.TxnDeleteRange(txnID, key, end)
  115. if err == nil {
  116. for _, kv := range kvs {
  117. s.tx.del(string(kv.Key))
  118. }
  119. }
  120. return n, rev, err
  121. }
  122. func (s *watchableStore) TxnEnd(txnID int64) error {
  123. err := s.store.TxnEnd(txnID)
  124. if err != nil {
  125. return err
  126. }
  127. _, rev, _ := s.store.Range(nil, nil, 0, 0)
  128. evs := []storagepb.Event{}
  129. for k := range s.tx.putm {
  130. kvs, _, err := s.store.Range([]byte(k), nil, 0, 0)
  131. if err != nil {
  132. log.Panicf("unexpected range error (%v)", err)
  133. }
  134. ev := storagepb.Event{
  135. Type: storagepb.PUT,
  136. Kv: &kvs[0],
  137. }
  138. evs = append(evs, ev)
  139. }
  140. for k := range s.tx.delm {
  141. ev := storagepb.Event{
  142. Type: storagepb.DELETE,
  143. Kv: &storagepb.KeyValue{
  144. Key: []byte(k),
  145. },
  146. }
  147. evs = append(evs, ev)
  148. }
  149. s.handle(rev, evs)
  150. s.mu.Unlock()
  151. return nil
  152. }
  153. func (s *watchableStore) Close() error {
  154. close(s.stopc)
  155. s.wg.Wait()
  156. return s.store.Close()
  157. }
  158. func (s *watchableStore) NewWatchStream() WatchStream {
  159. watchStreamGauge.Inc()
  160. return &watchStream{
  161. watchable: s,
  162. ch: make(chan WatchResponse, chanBufLen),
  163. cancels: make(map[WatchID]cancelFunc),
  164. }
  165. }
  166. func (s *watchableStore) watch(key []byte, prefix bool, startRev int64, id WatchID, ch chan<- WatchResponse) (*watcher, cancelFunc) {
  167. s.mu.Lock()
  168. defer s.mu.Unlock()
  169. wa := &watcher{
  170. key: key,
  171. prefix: prefix,
  172. cur: startRev,
  173. id: id,
  174. ch: ch,
  175. }
  176. k := string(key)
  177. if startRev == 0 {
  178. if err := unsafeAddWatcher(&s.synced, k, wa); err != nil {
  179. log.Panicf("error unsafeAddWatcher (%v) for key %s", err, k)
  180. }
  181. } else {
  182. slowWatcherGauge.Inc()
  183. s.unsynced[wa] = struct{}{}
  184. }
  185. watcherGauge.Inc()
  186. cancel := cancelFunc(func() {
  187. s.mu.Lock()
  188. defer s.mu.Unlock()
  189. // remove global references of the watcher
  190. if _, ok := s.unsynced[wa]; ok {
  191. delete(s.unsynced, wa)
  192. slowWatcherGauge.Dec()
  193. watcherGauge.Dec()
  194. return
  195. }
  196. if v, ok := s.synced[k]; ok {
  197. if _, ok := v[wa]; ok {
  198. delete(v, wa)
  199. // if there is nothing in s.synced[k],
  200. // remove the key from the synced
  201. if len(v) == 0 {
  202. delete(s.synced, k)
  203. }
  204. watcherGauge.Dec()
  205. }
  206. }
  207. // If we cannot find it, it should have finished watch.
  208. })
  209. return wa, cancel
  210. }
  211. // syncWatchersLoop syncs the watcher in the unsyncd map every 100ms.
  212. func (s *watchableStore) syncWatchersLoop() {
  213. defer s.wg.Done()
  214. for {
  215. s.mu.Lock()
  216. s.syncWatchers()
  217. s.mu.Unlock()
  218. select {
  219. case <-time.After(100 * time.Millisecond):
  220. case <-s.stopc:
  221. return
  222. }
  223. }
  224. }
  225. // syncWatchers periodically syncs unsynced watchers by: Iterate all unsynced
  226. // watchers to get the minimum revision within its range, skipping the
  227. // watcher if its current revision is behind the compact revision of the
  228. // store. And use this minimum revision to get all key-value pairs. Then send
  229. // those events to watchers.
  230. func (s *watchableStore) syncWatchers() {
  231. s.store.mu.Lock()
  232. defer s.store.mu.Unlock()
  233. if len(s.unsynced) == 0 {
  234. return
  235. }
  236. // in order to find key-value pairs from unsynced watchers, we need to
  237. // find min revision index, and these revisions can be used to
  238. // query the backend store of key-value pairs
  239. minRev := int64(math.MaxInt64)
  240. curRev := s.store.currentRev.main
  241. compactionRev := s.store.compactMainRev
  242. // TODO: change unsynced struct type same to this
  243. keyToUnsynced := make(map[string]map[*watcher]struct{})
  244. for w := range s.unsynced {
  245. k := string(w.key)
  246. if w.cur > curRev {
  247. panic("watcher current revision should not exceed current revision")
  248. }
  249. if w.cur < compactionRev {
  250. // TODO: return error compacted to that watcher instead of
  251. // just removing it sliently from unsynced.
  252. delete(s.unsynced, w)
  253. continue
  254. }
  255. if minRev >= w.cur {
  256. minRev = w.cur
  257. }
  258. if _, ok := keyToUnsynced[k]; !ok {
  259. keyToUnsynced[k] = make(map[*watcher]struct{})
  260. }
  261. keyToUnsynced[k][w] = struct{}{}
  262. }
  263. minBytes, maxBytes := newRevBytes(), newRevBytes()
  264. revToBytes(revision{main: minRev}, minBytes)
  265. revToBytes(revision{main: curRev + 1}, maxBytes)
  266. // UnsafeRange returns keys and values. And in boltdb, keys are revisions.
  267. // values are actual key-value pairs in backend.
  268. tx := s.store.b.BatchTx()
  269. tx.Lock()
  270. ks, vs := tx.UnsafeRange(keyBucketName, minBytes, maxBytes, 0)
  271. tx.Unlock()
  272. evs := []storagepb.Event{}
  273. // get the list of all events from all key-value pairs
  274. for i, v := range vs {
  275. var kv storagepb.KeyValue
  276. if err := kv.Unmarshal(v); err != nil {
  277. log.Panicf("storage: cannot unmarshal event: %v", err)
  278. }
  279. k := string(kv.Key)
  280. if _, ok := keyToUnsynced[k]; !ok {
  281. continue
  282. }
  283. var ev storagepb.Event
  284. switch {
  285. case isTombstone(ks[i]):
  286. ev.Type = storagepb.DELETE
  287. default:
  288. ev.Type = storagepb.PUT
  289. }
  290. ev.Kv = &kv
  291. evs = append(evs, ev)
  292. }
  293. for w, es := range newWatcherToEventMap(keyToUnsynced, evs) {
  294. wr := WatchResponse{WatchID: w.id, Events: es}
  295. select {
  296. case w.ch <- wr:
  297. pendingEventsGauge.Add(float64(len(es)))
  298. default:
  299. // TODO: handle the full unsynced watchers.
  300. // continue to process other watchers for now, the full ones
  301. // will be processed next time and hopefully it will not be full.
  302. continue
  303. }
  304. k := string(w.key)
  305. if err := unsafeAddWatcher(&s.synced, k, w); err != nil {
  306. log.Panicf("error unsafeAddWatcher (%v) for key %s", err, k)
  307. }
  308. delete(s.unsynced, w)
  309. }
  310. slowWatcherGauge.Set(float64(len(s.unsynced)))
  311. }
  312. // handle handles the change of the happening event on all watchers.
  313. func (s *watchableStore) handle(rev int64, evs []storagepb.Event) {
  314. s.notify(rev, evs)
  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. wr := WatchResponse{WatchID: w.id, Events: es}
  327. select {
  328. case w.ch <- wr:
  329. pendingEventsGauge.Add(float64(len(es)))
  330. default:
  331. // move slow watcher to unsynced
  332. w.cur = rev
  333. s.unsynced[w] = struct{}{}
  334. delete(wm, w)
  335. slowWatcherGauge.Inc()
  336. }
  337. }
  338. }
  339. }
  340. type ongoingTx struct {
  341. // keys put/deleted in the ongoing txn
  342. putm map[string]struct{}
  343. delm map[string]struct{}
  344. }
  345. func newOngoingTx() *ongoingTx {
  346. return &ongoingTx{
  347. putm: make(map[string]struct{}),
  348. delm: make(map[string]struct{}),
  349. }
  350. }
  351. func (tx *ongoingTx) put(k string) {
  352. tx.putm[k] = struct{}{}
  353. if _, ok := tx.delm[k]; ok {
  354. delete(tx.delm, k)
  355. }
  356. }
  357. func (tx *ongoingTx) del(k string) {
  358. tx.delm[k] = struct{}{}
  359. if _, ok := tx.putm[k]; ok {
  360. delete(tx.putm, k)
  361. }
  362. }
  363. type watcher struct {
  364. // the watcher key
  365. key []byte
  366. // prefix indicates if watcher is on a key or a prefix.
  367. // If prefix is true, the watcher is on a prefix.
  368. prefix bool
  369. // cur is the current watcher revision.
  370. // If cur is behind the current revision of the KV,
  371. // watcher is unsynced and needs to catch up.
  372. cur int64
  373. id WatchID
  374. // a chan to send out the watch response.
  375. // The chan might be shared with other watchers.
  376. ch chan<- WatchResponse
  377. }
  378. // unsafeAddWatcher puts watcher with key k into watchableStore's synced.
  379. // Make sure to this is thread-safe using mutex before and after.
  380. func unsafeAddWatcher(synced *map[string]map[*watcher]struct{}, k string, wa *watcher) error {
  381. if wa == nil {
  382. return fmt.Errorf("nil watcher received")
  383. }
  384. mp := *synced
  385. if v, ok := mp[k]; ok {
  386. if _, ok := v[wa]; ok {
  387. return fmt.Errorf("put the same watcher twice: %+v", wa)
  388. } else {
  389. v[wa] = struct{}{}
  390. }
  391. return nil
  392. }
  393. mp[k] = make(map[*watcher]struct{})
  394. mp[k][wa] = struct{}{}
  395. return nil
  396. }
  397. // newWatcherToEventMap creates a map that has watcher as key and events as
  398. // value. It enables quick events look up by watcher.
  399. func newWatcherToEventMap(sm map[string]map[*watcher]struct{}, evs []storagepb.Event) map[*watcher][]storagepb.Event {
  400. watcherToEvents := make(map[*watcher][]storagepb.Event)
  401. for _, ev := range evs {
  402. key := string(ev.Kv.Key)
  403. // check all prefixes of the key to notify all corresponded watchers
  404. for i := 0; i <= len(key); i++ {
  405. k := string(key[:i])
  406. wm, ok := sm[k]
  407. if !ok {
  408. continue
  409. }
  410. for w := range wm {
  411. // the watcher needs to be notified when either it watches prefix or
  412. // the key is exactly matched.
  413. if !w.prefix && i != len(ev.Kv.Key) {
  414. continue
  415. }
  416. if _, ok := watcherToEvents[w]; !ok {
  417. watcherToEvents[w] = []storagepb.Event{}
  418. }
  419. watcherToEvents[w] = append(watcherToEvents[w], ev)
  420. }
  421. }
  422. }
  423. return watcherToEvents
  424. }