watcher_test.go 10 KB

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