watchable_store.go 12 KB

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