watchable_store_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. "bytes"
  17. "os"
  18. "reflect"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/lease"
  22. "github.com/coreos/etcd/storage/backend"
  23. "github.com/coreos/etcd/storage/storagepb"
  24. )
  25. func TestWatch(t *testing.T) {
  26. b, tmpPath := backend.NewDefaultTmpBackend()
  27. s := newWatchableStore(b, &lease.FakeLessor{})
  28. defer func() {
  29. s.store.Close()
  30. os.Remove(tmpPath)
  31. }()
  32. testKey := []byte("foo")
  33. testValue := []byte("bar")
  34. s.Put(testKey, testValue, lease.NoLease)
  35. w := s.NewWatchStream()
  36. w.Watch(testKey, true, 0)
  37. if _, ok := s.synced[string(testKey)]; !ok {
  38. // the key must have had an entry in synced
  39. t.Errorf("existence = %v, want true", ok)
  40. }
  41. }
  42. func TestNewWatcherCancel(t *testing.T) {
  43. b, tmpPath := backend.NewDefaultTmpBackend()
  44. s := newWatchableStore(b, &lease.FakeLessor{})
  45. defer func() {
  46. s.store.Close()
  47. os.Remove(tmpPath)
  48. }()
  49. testKey := []byte("foo")
  50. testValue := []byte("bar")
  51. s.Put(testKey, testValue, lease.NoLease)
  52. w := s.NewWatchStream()
  53. wt := w.Watch(testKey, true, 0)
  54. if err := w.Cancel(wt); err != nil {
  55. t.Error(err)
  56. }
  57. if _, ok := s.synced[string(testKey)]; ok {
  58. // the key shoud have been deleted
  59. t.Errorf("existence = %v, want false", ok)
  60. }
  61. }
  62. // TestCancelUnsynced tests if running CancelFunc removes watchers from unsynced.
  63. func TestCancelUnsynced(t *testing.T) {
  64. b, tmpPath := backend.NewDefaultTmpBackend()
  65. // manually create watchableStore instead of newWatchableStore
  66. // because newWatchableStore automatically calls syncWatchers
  67. // method to sync watchers in unsynced map. We want to keep watchers
  68. // in unsynced to test if syncWatchers works as expected.
  69. s := &watchableStore{
  70. store: NewStore(b, &lease.FakeLessor{}),
  71. unsynced: make(watcherSetByKey),
  72. // to make the test not crash from assigning to nil map.
  73. // 'synced' doesn't get populated in this test.
  74. synced: make(watcherSetByKey),
  75. }
  76. defer func() {
  77. s.store.Close()
  78. os.Remove(tmpPath)
  79. }()
  80. // Put a key so that we can spawn watchers on that key.
  81. // (testKey in this test). This increases the rev to 1,
  82. // and later we can we set the watcher's startRev to 1,
  83. // and force watchers to be in unsynced.
  84. testKey := []byte("foo")
  85. testValue := []byte("bar")
  86. s.Put(testKey, testValue, lease.NoLease)
  87. w := s.NewWatchStream()
  88. // arbitrary number for watchers
  89. watcherN := 100
  90. // create watcherN of watch ids to cancel
  91. watchIDs := make([]WatchID, watcherN)
  92. for i := 0; i < watcherN; i++ {
  93. // use 1 to keep watchers in unsynced
  94. watchIDs[i] = w.Watch(testKey, true, 1)
  95. }
  96. for _, idx := range watchIDs {
  97. if err := w.Cancel(idx); err != nil {
  98. t.Error(err)
  99. }
  100. }
  101. // After running CancelFunc
  102. //
  103. // unsynced should be empty
  104. // because cancel removes watcher from unsynced
  105. if len(s.unsynced) != 0 {
  106. t.Errorf("unsynced size = %d, want 0", len(s.unsynced))
  107. }
  108. }
  109. // TestSyncWatchers populates unsynced watcher map and tests syncWatchers
  110. // method to see if it correctly sends events to channel of unsynced watchers
  111. // and moves these watchers to synced.
  112. func TestSyncWatchers(t *testing.T) {
  113. b, tmpPath := backend.NewDefaultTmpBackend()
  114. s := &watchableStore{
  115. store: NewStore(b, &lease.FakeLessor{}),
  116. unsynced: make(watcherSetByKey),
  117. synced: make(watcherSetByKey),
  118. }
  119. defer func() {
  120. s.store.Close()
  121. os.Remove(tmpPath)
  122. }()
  123. testKey := []byte("foo")
  124. testValue := []byte("bar")
  125. s.Put(testKey, testValue, lease.NoLease)
  126. w := s.NewWatchStream()
  127. // arbitrary number for watchers
  128. watcherN := 100
  129. for i := 0; i < watcherN; i++ {
  130. // specify rev as 1 to keep watchers in unsynced
  131. w.Watch(testKey, true, 1)
  132. }
  133. // Before running s.syncWatchers() synced should be empty because we manually
  134. // populate unsynced only
  135. sws, _ := s.synced.getSetByKey(string(testKey))
  136. uws, _ := s.unsynced.getSetByKey(string(testKey))
  137. if len(sws) != 0 {
  138. t.Fatalf("synced[string(testKey)] size = %d, want 0", len(sws))
  139. }
  140. // unsynced should not be empty because we manually populated unsynced only
  141. if len(uws) != watcherN {
  142. t.Errorf("unsynced size = %d, want %d", len(uws), watcherN)
  143. }
  144. // this should move all unsynced watchers to synced ones
  145. s.syncWatchers()
  146. sws, _ = s.synced.getSetByKey(string(testKey))
  147. uws, _ = s.unsynced.getSetByKey(string(testKey))
  148. // After running s.syncWatchers(), synced should not be empty because syncwatchers
  149. // populates synced in this test case
  150. if len(sws) != watcherN {
  151. t.Errorf("synced[string(testKey)] size = %d, want %d", len(sws), watcherN)
  152. }
  153. // unsynced should be empty because syncwatchers is expected to move all watchers
  154. // from unsynced to synced in this test case
  155. if len(uws) != 0 {
  156. t.Errorf("unsynced size = %d, want 0", len(uws))
  157. }
  158. for w := range sws {
  159. if w.cur != s.Rev() {
  160. t.Errorf("w.cur = %d, want %d", w.cur, s.Rev())
  161. }
  162. }
  163. if len(w.(*watchStream).ch) != watcherN {
  164. t.Errorf("watched event size = %d, want %d", len(w.(*watchStream).ch), watcherN)
  165. }
  166. evs := (<-w.(*watchStream).ch).Events
  167. if len(evs) != 1 {
  168. t.Errorf("len(evs) got = %d, want = 1", len(evs))
  169. }
  170. if evs[0].Type != storagepb.PUT {
  171. t.Errorf("got = %v, want = %v", evs[0].Type, storagepb.PUT)
  172. }
  173. if !bytes.Equal(evs[0].Kv.Key, testKey) {
  174. t.Errorf("got = %s, want = %s", evs[0].Kv.Key, testKey)
  175. }
  176. if !bytes.Equal(evs[0].Kv.Value, testValue) {
  177. t.Errorf("got = %s, want = %s", evs[0].Kv.Value, testValue)
  178. }
  179. }
  180. // TestWatchCompacted tests a watcher that watches on a compacted revision.
  181. func TestWatchCompacted(t *testing.T) {
  182. b, tmpPath := backend.NewDefaultTmpBackend()
  183. s := newWatchableStore(b, &lease.FakeLessor{})
  184. defer func() {
  185. s.store.Close()
  186. os.Remove(tmpPath)
  187. }()
  188. testKey := []byte("foo")
  189. testValue := []byte("bar")
  190. maxRev := 10
  191. compactRev := int64(5)
  192. for i := 0; i < maxRev; i++ {
  193. s.Put(testKey, testValue, lease.NoLease)
  194. }
  195. err := s.Compact(compactRev)
  196. if err != nil {
  197. t.Fatalf("failed to compact kv (%v)", err)
  198. }
  199. w := s.NewWatchStream()
  200. wt := w.Watch(testKey, true, compactRev-1)
  201. select {
  202. case resp := <-w.Chan():
  203. if resp.WatchID != wt {
  204. t.Errorf("resp.WatchID = %x, want %x", resp.WatchID, wt)
  205. }
  206. if resp.CompactRevision == 0 {
  207. t.Errorf("resp.Compacted = %v, want %v", resp.CompactRevision, compactRev)
  208. }
  209. case <-time.After(1 * time.Second):
  210. t.Fatalf("failed to receive response (timeout)")
  211. }
  212. }
  213. // TestWatchBatchUnsynced tests batching on unsynced watchers
  214. func TestWatchBatchUnsynced(t *testing.T) {
  215. b, tmpPath := backend.NewDefaultTmpBackend()
  216. s := newWatchableStore(b, &lease.FakeLessor{})
  217. oldMaxRevs := watchBatchMaxRevs
  218. defer func() {
  219. watchBatchMaxRevs = oldMaxRevs
  220. s.store.Close()
  221. os.Remove(tmpPath)
  222. }()
  223. batches := 3
  224. watchBatchMaxRevs = 4
  225. v := []byte("foo")
  226. for i := 0; i < watchBatchMaxRevs*batches; i++ {
  227. s.Put(v, v, lease.NoLease)
  228. }
  229. w := s.NewWatchStream()
  230. w.Watch(v, false, 1)
  231. for i := 0; i < batches; i++ {
  232. if resp := <-w.Chan(); len(resp.Events) != watchBatchMaxRevs {
  233. t.Fatalf("len(events) = %d, want %d", len(resp.Events), watchBatchMaxRevs)
  234. }
  235. }
  236. s.store.mu.Lock()
  237. defer s.store.mu.Unlock()
  238. if len(s.synced) != 1 {
  239. t.Errorf("synced size = %d, want 1", len(s.synced))
  240. }
  241. }
  242. func TestNewMapwatcherToEventMap(t *testing.T) {
  243. k0, k1, k2 := []byte("foo0"), []byte("foo1"), []byte("foo2")
  244. v0, v1, v2 := []byte("bar0"), []byte("bar1"), []byte("bar2")
  245. ws := []*watcher{{key: k0}, {key: k1}, {key: k2}}
  246. evs := []storagepb.Event{
  247. {
  248. Type: storagepb.PUT,
  249. Kv: &storagepb.KeyValue{Key: k0, Value: v0},
  250. },
  251. {
  252. Type: storagepb.PUT,
  253. Kv: &storagepb.KeyValue{Key: k1, Value: v1},
  254. },
  255. {
  256. Type: storagepb.PUT,
  257. Kv: &storagepb.KeyValue{Key: k2, Value: v2},
  258. },
  259. }
  260. tests := []struct {
  261. sync watcherSetByKey
  262. evs []storagepb.Event
  263. wwe map[*watcher][]storagepb.Event
  264. }{
  265. // no watcher in sync, some events should return empty wwe
  266. {
  267. watcherSetByKey{},
  268. evs,
  269. map[*watcher][]storagepb.Event{},
  270. },
  271. // one watcher in sync, one event that does not match the key of that
  272. // watcher should return empty wwe
  273. {
  274. watcherSetByKey{
  275. string(k2): {ws[2]: struct{}{}},
  276. },
  277. evs[:1],
  278. map[*watcher][]storagepb.Event{},
  279. },
  280. // one watcher in sync, one event that matches the key of that
  281. // watcher should return wwe with that matching watcher
  282. {
  283. watcherSetByKey{
  284. string(k1): {ws[1]: struct{}{}},
  285. },
  286. evs[1:2],
  287. map[*watcher][]storagepb.Event{
  288. ws[1]: evs[1:2],
  289. },
  290. },
  291. // two watchers in sync that watches two different keys, one event
  292. // that matches the key of only one of the watcher should return wwe
  293. // with the matching watcher
  294. {
  295. watcherSetByKey{
  296. string(k0): {ws[0]: struct{}{}},
  297. string(k2): {ws[2]: struct{}{}},
  298. },
  299. evs[2:],
  300. map[*watcher][]storagepb.Event{
  301. ws[2]: evs[2:],
  302. },
  303. },
  304. // two watchers in sync that watches the same key, two events that
  305. // match the keys should return wwe with those two watchers
  306. {
  307. watcherSetByKey{
  308. string(k0): {ws[0]: struct{}{}},
  309. string(k1): {ws[1]: struct{}{}},
  310. },
  311. evs[:2],
  312. map[*watcher][]storagepb.Event{
  313. ws[0]: evs[:1],
  314. ws[1]: evs[1:2],
  315. },
  316. },
  317. }
  318. for i, tt := range tests {
  319. gwe := newWatcherBatch(tt.sync, tt.evs)
  320. if len(gwe) != len(tt.wwe) {
  321. t.Errorf("#%d: len(gwe) got = %d, want = %d", i, len(gwe), len(tt.wwe))
  322. }
  323. // compare gwe and tt.wwe
  324. for w, eb := range gwe {
  325. if len(eb.evs) != len(tt.wwe[w]) {
  326. t.Errorf("#%d: len(eb.evs) got = %d, want = %d", i, len(eb.evs), len(tt.wwe[w]))
  327. }
  328. if !reflect.DeepEqual(eb.evs, tt.wwe[w]) {
  329. t.Errorf("#%d: reflect.DeepEqual events got = %v, want = true", i, false)
  330. }
  331. }
  332. }
  333. }