watchable_store.go 12 KB

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