watcher_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. // Copyright 2015 The etcd Authors
  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 mvcc
  15. import (
  16. "bytes"
  17. "fmt"
  18. "os"
  19. "reflect"
  20. "testing"
  21. "time"
  22. "github.com/coreos/etcd/internal/mvcc/backend"
  23. "github.com/coreos/etcd/internal/mvcc/mvccpb"
  24. "github.com/coreos/etcd/lease"
  25. )
  26. // TestWatcherWatchID tests that each watcher provides unique watchID,
  27. // and the watched event attaches the correct watchID.
  28. func TestWatcherWatchID(t *testing.T) {
  29. b, tmpPath := backend.NewDefaultTmpBackend()
  30. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  31. defer cleanup(s, b, tmpPath)
  32. w := s.NewWatchStream()
  33. defer w.Close()
  34. idm := make(map[WatchID]struct{})
  35. for i := 0; i < 10; i++ {
  36. id, _ := w.Watch(0, []byte("foo"), nil, 0)
  37. if _, ok := idm[id]; ok {
  38. t.Errorf("#%d: id %d exists", i, id)
  39. }
  40. idm[id] = struct{}{}
  41. s.Put([]byte("foo"), []byte("bar"), lease.NoLease)
  42. resp := <-w.Chan()
  43. if resp.WatchID != id {
  44. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  45. }
  46. if err := w.Cancel(id); err != nil {
  47. t.Error(err)
  48. }
  49. }
  50. s.Put([]byte("foo2"), []byte("bar"), lease.NoLease)
  51. // unsynced watchers
  52. for i := 10; i < 20; i++ {
  53. id, _ := w.Watch(0, []byte("foo2"), nil, 1)
  54. if _, ok := idm[id]; ok {
  55. t.Errorf("#%d: id %d exists", i, id)
  56. }
  57. idm[id] = struct{}{}
  58. resp := <-w.Chan()
  59. if resp.WatchID != id {
  60. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  61. }
  62. if err := w.Cancel(id); err != nil {
  63. t.Error(err)
  64. }
  65. }
  66. }
  67. func TestWatcherRequestsCustomID(t *testing.T) {
  68. b, tmpPath := backend.NewDefaultTmpBackend()
  69. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  70. defer cleanup(s, b, tmpPath)
  71. w := s.NewWatchStream()
  72. defer w.Close()
  73. // - Request specifically ID #1
  74. // - Try to duplicate it, get an error
  75. // - Make sure the auto-assignment skips over things we manually assigned
  76. tt := []struct {
  77. givenID WatchID
  78. expectedID WatchID
  79. expectedErr error
  80. }{
  81. {1, 1, nil},
  82. {1, 0, ErrWatcherDuplicateID},
  83. {0, 0, nil},
  84. {0, 2, nil},
  85. }
  86. for i, tcase := range tt {
  87. id, err := w.Watch(tcase.givenID, []byte("foo"), nil, 0)
  88. if tcase.expectedErr != nil || err != nil {
  89. if err != tcase.expectedErr {
  90. t.Errorf("expected get error %q in test case %q, got %q", tcase.expectedErr, i, err)
  91. }
  92. } else if tcase.expectedID != id {
  93. t.Errorf("expected to create ID %d, got %d in test case %d", tcase.expectedID, id, i)
  94. }
  95. }
  96. }
  97. // TestWatcherWatchPrefix tests if Watch operation correctly watches
  98. // and returns events with matching prefixes.
  99. func TestWatcherWatchPrefix(t *testing.T) {
  100. b, tmpPath := backend.NewDefaultTmpBackend()
  101. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  102. defer cleanup(s, b, tmpPath)
  103. w := s.NewWatchStream()
  104. defer w.Close()
  105. idm := make(map[WatchID]struct{})
  106. val := []byte("bar")
  107. keyWatch, keyEnd, keyPut := []byte("foo"), []byte("fop"), []byte("foobar")
  108. for i := 0; i < 10; i++ {
  109. id, _ := w.Watch(0, keyWatch, keyEnd, 0)
  110. if _, ok := idm[id]; ok {
  111. t.Errorf("#%d: unexpected duplicated id %x", i, id)
  112. }
  113. idm[id] = struct{}{}
  114. s.Put(keyPut, val, lease.NoLease)
  115. resp := <-w.Chan()
  116. if resp.WatchID != id {
  117. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  118. }
  119. if err := w.Cancel(id); err != nil {
  120. t.Errorf("#%d: unexpected cancel error %v", i, err)
  121. }
  122. if len(resp.Events) != 1 {
  123. t.Errorf("#%d: len(resp.Events) got = %d, want = 1", i, len(resp.Events))
  124. }
  125. if len(resp.Events) == 1 {
  126. if !bytes.Equal(resp.Events[0].Kv.Key, keyPut) {
  127. t.Errorf("#%d: resp.Events got = %s, want = %s", i, resp.Events[0].Kv.Key, keyPut)
  128. }
  129. }
  130. }
  131. keyWatch1, keyEnd1, keyPut1 := []byte("foo1"), []byte("foo2"), []byte("foo1bar")
  132. s.Put(keyPut1, val, lease.NoLease)
  133. // unsynced watchers
  134. for i := 10; i < 15; i++ {
  135. id, _ := w.Watch(0, keyWatch1, keyEnd1, 1)
  136. if _, ok := idm[id]; ok {
  137. t.Errorf("#%d: id %d exists", i, id)
  138. }
  139. idm[id] = struct{}{}
  140. resp := <-w.Chan()
  141. if resp.WatchID != id {
  142. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  143. }
  144. if err := w.Cancel(id); err != nil {
  145. t.Error(err)
  146. }
  147. if len(resp.Events) != 1 {
  148. t.Errorf("#%d: len(resp.Events) got = %d, want = 1", i, len(resp.Events))
  149. }
  150. if len(resp.Events) == 1 {
  151. if !bytes.Equal(resp.Events[0].Kv.Key, keyPut1) {
  152. t.Errorf("#%d: resp.Events got = %s, want = %s", i, resp.Events[0].Kv.Key, keyPut1)
  153. }
  154. }
  155. }
  156. }
  157. // TestWatcherWatchWrongRange ensures that watcher with wrong 'end' range
  158. // does not create watcher, which panics when canceling in range tree.
  159. func TestWatcherWatchWrongRange(t *testing.T) {
  160. b, tmpPath := backend.NewDefaultTmpBackend()
  161. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  162. defer cleanup(s, b, tmpPath)
  163. w := s.NewWatchStream()
  164. defer w.Close()
  165. if _, err := w.Watch(0, []byte("foa"), []byte("foa"), 1); err != ErrEmptyWatcherRange {
  166. t.Fatalf("key == end range given; expected ErrEmptyWatcherRange, got %+v", err)
  167. }
  168. if _, err := w.Watch(0, []byte("fob"), []byte("foa"), 1); err != ErrEmptyWatcherRange {
  169. t.Fatalf("key > end range given; expected ErrEmptyWatcherRange, got %+v", err)
  170. }
  171. // watch request with 'WithFromKey' has empty-byte range end
  172. if id, _ := w.Watch(0, []byte("foo"), []byte{}, 1); id != 0 {
  173. t.Fatalf("\x00 is range given; id expected 0, got %d", id)
  174. }
  175. }
  176. func TestWatchDeleteRange(t *testing.T) {
  177. b, tmpPath := backend.NewDefaultTmpBackend()
  178. s := newWatchableStore(b, &lease.FakeLessor{}, nil)
  179. defer func() {
  180. s.store.Close()
  181. os.Remove(tmpPath)
  182. }()
  183. testKeyPrefix := []byte("foo")
  184. for i := 0; i < 3; i++ {
  185. s.Put([]byte(fmt.Sprintf("%s_%d", testKeyPrefix, i)), []byte("bar"), lease.NoLease)
  186. }
  187. w := s.NewWatchStream()
  188. from, to := []byte(testKeyPrefix), []byte(fmt.Sprintf("%s_%d", testKeyPrefix, 99))
  189. w.Watch(0, from, to, 0)
  190. s.DeleteRange(from, to)
  191. we := []mvccpb.Event{
  192. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_0"), ModRevision: 5}},
  193. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_1"), ModRevision: 5}},
  194. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_2"), ModRevision: 5}},
  195. }
  196. select {
  197. case r := <-w.Chan():
  198. if !reflect.DeepEqual(r.Events, we) {
  199. t.Errorf("event = %v, want %v", r.Events, we)
  200. }
  201. case <-time.After(10 * time.Second):
  202. t.Fatal("failed to receive event after 10 seconds!")
  203. }
  204. }
  205. // TestWatchStreamCancelWatcherByID ensures cancel calls the cancel func of the watcher
  206. // with given id inside watchStream.
  207. func TestWatchStreamCancelWatcherByID(t *testing.T) {
  208. b, tmpPath := backend.NewDefaultTmpBackend()
  209. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  210. defer cleanup(s, b, tmpPath)
  211. w := s.NewWatchStream()
  212. defer w.Close()
  213. id, _ := w.Watch(0, []byte("foo"), nil, 0)
  214. tests := []struct {
  215. cancelID WatchID
  216. werr error
  217. }{
  218. // no error should be returned when cancel the created watcher.
  219. {id, nil},
  220. // not exist error should be returned when cancel again.
  221. {id, ErrWatcherNotExist},
  222. // not exist error should be returned when cancel a bad id.
  223. {id + 1, ErrWatcherNotExist},
  224. }
  225. for i, tt := range tests {
  226. gerr := w.Cancel(tt.cancelID)
  227. if gerr != tt.werr {
  228. t.Errorf("#%d: err = %v, want %v", i, gerr, tt.werr)
  229. }
  230. }
  231. if l := len(w.(*watchStream).cancels); l != 0 {
  232. t.Errorf("cancels = %d, want 0", l)
  233. }
  234. }
  235. // TestWatcherRequestProgress ensures synced watcher can correctly
  236. // report its correct progress.
  237. func TestWatcherRequestProgress(t *testing.T) {
  238. b, tmpPath := backend.NewDefaultTmpBackend()
  239. // manually create watchableStore instead of newWatchableStore
  240. // because newWatchableStore automatically calls syncWatchers
  241. // method to sync watchers in unsynced map. We want to keep watchers
  242. // in unsynced to test if syncWatchers works as expected.
  243. s := &watchableStore{
  244. store: NewStore(b, &lease.FakeLessor{}, nil),
  245. unsynced: newWatcherGroup(),
  246. synced: newWatcherGroup(),
  247. }
  248. defer func() {
  249. s.store.Close()
  250. os.Remove(tmpPath)
  251. }()
  252. testKey := []byte("foo")
  253. notTestKey := []byte("bad")
  254. testValue := []byte("bar")
  255. s.Put(testKey, testValue, lease.NoLease)
  256. w := s.NewWatchStream()
  257. badID := WatchID(1000)
  258. w.RequestProgress(badID)
  259. select {
  260. case resp := <-w.Chan():
  261. t.Fatalf("unexpected %+v", resp)
  262. default:
  263. }
  264. id, _ := w.Watch(0, notTestKey, nil, 1)
  265. w.RequestProgress(id)
  266. select {
  267. case resp := <-w.Chan():
  268. t.Fatalf("unexpected %+v", resp)
  269. default:
  270. }
  271. s.syncWatchers()
  272. w.RequestProgress(id)
  273. wrs := WatchResponse{WatchID: id, Revision: 2}
  274. select {
  275. case resp := <-w.Chan():
  276. if !reflect.DeepEqual(resp, wrs) {
  277. t.Fatalf("got %+v, expect %+v", resp, wrs)
  278. }
  279. case <-time.After(time.Second):
  280. t.Fatal("failed to receive progress")
  281. }
  282. }
  283. func TestWatcherWatchWithFilter(t *testing.T) {
  284. b, tmpPath := backend.NewDefaultTmpBackend()
  285. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  286. defer cleanup(s, b, tmpPath)
  287. w := s.NewWatchStream()
  288. defer w.Close()
  289. filterPut := func(e mvccpb.Event) bool {
  290. return e.Type == mvccpb.PUT
  291. }
  292. w.Watch(0, []byte("foo"), nil, 0, filterPut)
  293. done := make(chan struct{})
  294. go func() {
  295. <-w.Chan()
  296. done <- struct{}{}
  297. }()
  298. s.Put([]byte("foo"), []byte("bar"), 0)
  299. select {
  300. case <-done:
  301. t.Fatal("failed to filter put request")
  302. case <-time.After(100 * time.Millisecond):
  303. }
  304. s.DeleteRange([]byte("foo"), nil)
  305. select {
  306. case <-done:
  307. case <-time.After(100 * time.Millisecond):
  308. t.Fatal("failed to receive delete request")
  309. }
  310. }