watchable_store.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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/storage/storagepb"
  20. )
  21. type watchableStore struct {
  22. mu sync.Mutex
  23. *store
  24. // contains all unsynced watchers that needs to sync events that have happened
  25. unsynced map[*watcher]struct{}
  26. // contains all synced watchers that are tracking the events that will happen
  27. // The key of the map is the key that the watcher is watching on.
  28. synced map[string][]*watcher
  29. tx *ongoingTx
  30. stopc chan struct{}
  31. wg sync.WaitGroup
  32. }
  33. func newWatchableStore(path string) *watchableStore {
  34. s := &watchableStore{
  35. store: newStore(path),
  36. unsynced: make(map[*watcher]struct{}),
  37. synced: make(map[string][]*watcher),
  38. stopc: make(chan struct{}),
  39. }
  40. s.wg.Add(1)
  41. go s.syncWatchersLoop()
  42. return s
  43. }
  44. func (s *watchableStore) Put(key, value []byte) (rev int64) {
  45. s.mu.Lock()
  46. defer s.mu.Unlock()
  47. rev = s.store.Put(key, value)
  48. // TODO: avoid this range
  49. kvs, _, err := s.store.Range(key, nil, 0, rev)
  50. if err != nil {
  51. log.Panicf("unexpected range error (%v)", err)
  52. }
  53. s.handle(rev, storagepb.Event{
  54. Type: storagepb.PUT,
  55. Kv: &kvs[0],
  56. })
  57. return rev
  58. }
  59. func (s *watchableStore) DeleteRange(key, end []byte) (n, rev int64) {
  60. s.mu.Lock()
  61. defer s.mu.Unlock()
  62. // TODO: avoid this range
  63. kvs, _, err := s.store.Range(key, end, 0, 0)
  64. if err != nil {
  65. log.Panicf("unexpected range error (%v)", err)
  66. }
  67. n, rev = s.store.DeleteRange(key, end)
  68. for _, kv := range kvs {
  69. s.handle(rev, storagepb.Event{
  70. Type: storagepb.DELETE,
  71. Kv: &storagepb.KeyValue{
  72. Key: kv.Key,
  73. },
  74. })
  75. }
  76. return n, rev
  77. }
  78. func (s *watchableStore) TxnBegin() int64 {
  79. s.mu.Lock()
  80. s.tx = newOngoingTx()
  81. return s.store.TxnBegin()
  82. }
  83. func (s *watchableStore) TxnPut(txnID int64, key, value []byte) (rev int64, err error) {
  84. rev, err = s.store.TxnPut(txnID, key, value)
  85. if err == nil {
  86. s.tx.put(string(key))
  87. }
  88. return rev, err
  89. }
  90. func (s *watchableStore) TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error) {
  91. kvs, _, err := s.store.TxnRange(txnID, key, end, 0, 0)
  92. if err != nil {
  93. log.Panicf("unexpected range error (%v)", err)
  94. }
  95. n, rev, err = s.store.TxnDeleteRange(txnID, key, end)
  96. if err == nil {
  97. for _, kv := range kvs {
  98. s.tx.del(string(kv.Key))
  99. }
  100. }
  101. return n, rev, err
  102. }
  103. func (s *watchableStore) TxnEnd(txnID int64) error {
  104. err := s.store.TxnEnd(txnID)
  105. if err != nil {
  106. return err
  107. }
  108. _, rev, _ := s.store.Range(nil, nil, 0, 0)
  109. for k := range s.tx.putm {
  110. kvs, _, err := s.store.Range([]byte(k), nil, 0, 0)
  111. if err != nil {
  112. log.Panicf("unexpected range error (%v)", err)
  113. }
  114. s.handle(rev, storagepb.Event{
  115. Type: storagepb.PUT,
  116. Kv: &kvs[0],
  117. })
  118. }
  119. for k := range s.tx.delm {
  120. s.handle(rev, storagepb.Event{
  121. Type: storagepb.DELETE,
  122. Kv: &storagepb.KeyValue{
  123. Key: []byte(k),
  124. },
  125. })
  126. }
  127. s.mu.Unlock()
  128. return nil
  129. }
  130. func (s *watchableStore) Close() error {
  131. close(s.stopc)
  132. s.wg.Wait()
  133. return s.store.Close()
  134. }
  135. func (s *watchableStore) Watcher(key []byte, prefix bool, startRev int64) (Watcher, CancelFunc) {
  136. s.mu.Lock()
  137. defer s.mu.Unlock()
  138. wa := newWatcher(key, prefix, startRev)
  139. k := string(key)
  140. if startRev == 0 {
  141. s.synced[k] = append(s.synced[k], wa)
  142. } else {
  143. slowWatchersGauge.Inc()
  144. s.unsynced[wa] = struct{}{}
  145. }
  146. watchersGauge.Inc()
  147. cancel := CancelFunc(func() {
  148. s.mu.Lock()
  149. defer s.mu.Unlock()
  150. wa.stopWithError(ErrCanceled)
  151. // remove global references of the watcher
  152. if _, ok := s.unsynced[wa]; ok {
  153. delete(s.unsynced, wa)
  154. slowWatchersGauge.Dec()
  155. watchersGauge.Dec()
  156. return
  157. }
  158. for i, w := range s.synced[k] {
  159. if w == wa {
  160. s.synced[k] = append(s.synced[k][:i], s.synced[k][i+1:]...)
  161. watchersGauge.Dec()
  162. }
  163. }
  164. // If we cannot find it, it should have finished watch.
  165. })
  166. return wa, cancel
  167. }
  168. // keepSyncWatchers syncs the watchers in the unsyncd map every 100ms.
  169. func (s *watchableStore) syncWatchersLoop() {
  170. defer s.wg.Done()
  171. for {
  172. s.mu.Lock()
  173. s.syncWatchers()
  174. s.mu.Unlock()
  175. select {
  176. case <-time.After(100 * time.Millisecond):
  177. case <-s.stopc:
  178. return
  179. }
  180. }
  181. }
  182. // syncWatchers syncs the watchers in the unsyncd map.
  183. func (s *watchableStore) syncWatchers() {
  184. _, curRev, _ := s.store.Range(nil, nil, 0, 0)
  185. for w := range s.unsynced {
  186. var end []byte
  187. if w.prefix {
  188. end = make([]byte, len(w.key))
  189. copy(end, w.key)
  190. end[len(w.key)-1]++
  191. }
  192. limit := cap(w.ch) - len(w.ch)
  193. // the channel is full, try it in the next round
  194. if limit == 0 {
  195. continue
  196. }
  197. evs, nextRev, err := s.store.RangeEvents(w.key, end, int64(limit), w.cur)
  198. if err != nil {
  199. w.stopWithError(err)
  200. delete(s.unsynced, w)
  201. continue
  202. }
  203. // push events to the channel
  204. for _, ev := range evs {
  205. w.ch <- ev
  206. pendingEventsGauge.Inc()
  207. }
  208. // switch to tracking future events if needed
  209. if nextRev > curRev {
  210. s.synced[string(w.key)] = append(s.synced[string(w.key)], w)
  211. delete(s.unsynced, w)
  212. continue
  213. }
  214. // put it back to try it in the next round
  215. w.cur = nextRev
  216. }
  217. slowWatchersGauge.Set(float64(len(s.unsynced)))
  218. }
  219. // handle handles the change of the happening event on all watchers.
  220. func (s *watchableStore) handle(rev int64, ev storagepb.Event) {
  221. s.notify(rev, ev)
  222. }
  223. // notify notifies the fact that given event at the given rev just happened to
  224. // watchers that watch on the key of the event.
  225. func (s *watchableStore) notify(rev int64, ev storagepb.Event) {
  226. // check all prefixes of the key to notify all corresponded watchers
  227. for i := 0; i <= len(ev.Kv.Key); i++ {
  228. ws := s.synced[string(ev.Kv.Key[:i])]
  229. nws := ws[:0]
  230. for _, w := range ws {
  231. // the watcher needs to be notified when either it watches prefix or
  232. // the key is exactly matched.
  233. if !w.prefix && i != len(ev.Kv.Key) {
  234. continue
  235. }
  236. select {
  237. case w.ch <- ev:
  238. pendingEventsGauge.Inc()
  239. nws = append(nws, w)
  240. default:
  241. w.cur = rev
  242. s.unsynced[w] = struct{}{}
  243. slowWatchersGauge.Inc()
  244. }
  245. }
  246. s.synced[string(ev.Kv.Key[:i])] = nws
  247. }
  248. }
  249. type ongoingTx struct {
  250. // keys put/deleted in the ongoing txn
  251. putm map[string]bool
  252. delm map[string]bool
  253. }
  254. func newOngoingTx() *ongoingTx {
  255. return &ongoingTx{
  256. putm: make(map[string]bool),
  257. delm: make(map[string]bool),
  258. }
  259. }
  260. func (tx *ongoingTx) put(k string) {
  261. tx.putm[k] = true
  262. tx.delm[k] = false
  263. }
  264. func (tx *ongoingTx) del(k string) {
  265. tx.delm[k] = true
  266. tx.putm[k] = false
  267. }