watchable_store_test.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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.Compacted != true {
  207. t.Errorf("resp.Compacted = %v, want %v", resp.Compacted, true)
  208. }
  209. case <-time.After(1 * time.Second):
  210. t.Fatalf("failed to receive response (timeout)")
  211. }
  212. }
  213. func TestNewMapwatcherToEventMap(t *testing.T) {
  214. k0, k1, k2 := []byte("foo0"), []byte("foo1"), []byte("foo2")
  215. v0, v1, v2 := []byte("bar0"), []byte("bar1"), []byte("bar2")
  216. ws := []*watcher{{key: k0}, {key: k1}, {key: k2}}
  217. evs := []storagepb.Event{
  218. {
  219. Type: storagepb.PUT,
  220. Kv: &storagepb.KeyValue{Key: k0, Value: v0},
  221. },
  222. {
  223. Type: storagepb.PUT,
  224. Kv: &storagepb.KeyValue{Key: k1, Value: v1},
  225. },
  226. {
  227. Type: storagepb.PUT,
  228. Kv: &storagepb.KeyValue{Key: k2, Value: v2},
  229. },
  230. }
  231. tests := []struct {
  232. sync watcherSetByKey
  233. evs []storagepb.Event
  234. wwe map[*watcher][]storagepb.Event
  235. }{
  236. // no watcher in sync, some events should return empty wwe
  237. {
  238. watcherSetByKey{},
  239. evs,
  240. map[*watcher][]storagepb.Event{},
  241. },
  242. // one watcher in sync, one event that does not match the key of that
  243. // watcher should return empty wwe
  244. {
  245. watcherSetByKey{
  246. string(k2): {ws[2]: struct{}{}},
  247. },
  248. evs[:1],
  249. map[*watcher][]storagepb.Event{},
  250. },
  251. // one watcher in sync, one event that matches the key of that
  252. // watcher should return wwe with that matching watcher
  253. {
  254. watcherSetByKey{
  255. string(k1): {ws[1]: struct{}{}},
  256. },
  257. evs[1:2],
  258. map[*watcher][]storagepb.Event{
  259. ws[1]: evs[1:2],
  260. },
  261. },
  262. // two watchers in sync that watches two different keys, one event
  263. // that matches the key of only one of the watcher should return wwe
  264. // with the matching watcher
  265. {
  266. watcherSetByKey{
  267. string(k0): {ws[0]: struct{}{}},
  268. string(k2): {ws[2]: struct{}{}},
  269. },
  270. evs[2:],
  271. map[*watcher][]storagepb.Event{
  272. ws[2]: evs[2:],
  273. },
  274. },
  275. // two watchers in sync that watches the same key, two events that
  276. // match the keys should return wwe with those two watchers
  277. {
  278. watcherSetByKey{
  279. string(k0): {ws[0]: struct{}{}},
  280. string(k1): {ws[1]: struct{}{}},
  281. },
  282. evs[:2],
  283. map[*watcher][]storagepb.Event{
  284. ws[0]: evs[:1],
  285. ws[1]: evs[1:2],
  286. },
  287. },
  288. }
  289. for i, tt := range tests {
  290. gwe := newWatcherToEventMap(tt.sync, tt.evs)
  291. if len(gwe) != len(tt.wwe) {
  292. t.Errorf("#%d: len(gwe) got = %d, want = %d", i, len(gwe), len(tt.wwe))
  293. }
  294. // compare gwe and tt.wwe
  295. for w, mevs := range gwe {
  296. if len(mevs) != len(tt.wwe[w]) {
  297. t.Errorf("#%d: len(mevs) got = %d, want = %d", i, len(mevs), len(tt.wwe[w]))
  298. }
  299. if !reflect.DeepEqual(mevs, tt.wwe[w]) {
  300. t.Errorf("#%d: reflect.DeepEqual events got = %v, want = true", i, false)
  301. }
  302. }
  303. }
  304. }