watcher_test.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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/lease"
  23. "github.com/coreos/etcd/mvcc/backend"
  24. "github.com/coreos/etcd/mvcc/mvccpb"
  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([]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([]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. // TestWatcherWatchPrefix tests if Watch operation correctly watches
  68. // and returns events with matching prefixes.
  69. func TestWatcherWatchPrefix(t *testing.T) {
  70. b, tmpPath := backend.NewDefaultTmpBackend()
  71. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  72. defer cleanup(s, b, tmpPath)
  73. w := s.NewWatchStream()
  74. defer w.Close()
  75. idm := make(map[WatchID]struct{})
  76. val := []byte("bar")
  77. keyWatch, keyEnd, keyPut := []byte("foo"), []byte("fop"), []byte("foobar")
  78. for i := 0; i < 10; i++ {
  79. id := w.Watch(keyWatch, keyEnd, 0)
  80. if _, ok := idm[id]; ok {
  81. t.Errorf("#%d: unexpected duplicated id %x", i, id)
  82. }
  83. idm[id] = struct{}{}
  84. s.Put(keyPut, val, lease.NoLease)
  85. resp := <-w.Chan()
  86. if resp.WatchID != id {
  87. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  88. }
  89. if err := w.Cancel(id); err != nil {
  90. t.Errorf("#%d: unexpected cancel error %v", i, err)
  91. }
  92. if len(resp.Events) != 1 {
  93. t.Errorf("#%d: len(resp.Events) got = %d, want = 1", i, len(resp.Events))
  94. }
  95. if len(resp.Events) == 1 {
  96. if !bytes.Equal(resp.Events[0].Kv.Key, keyPut) {
  97. t.Errorf("#%d: resp.Events got = %s, want = %s", i, resp.Events[0].Kv.Key, keyPut)
  98. }
  99. }
  100. }
  101. keyWatch1, keyEnd1, keyPut1 := []byte("foo1"), []byte("foo2"), []byte("foo1bar")
  102. s.Put(keyPut1, val, lease.NoLease)
  103. // unsynced watchers
  104. for i := 10; i < 15; i++ {
  105. id := w.Watch(keyWatch1, keyEnd1, 1)
  106. if _, ok := idm[id]; ok {
  107. t.Errorf("#%d: id %d exists", i, id)
  108. }
  109. idm[id] = struct{}{}
  110. resp := <-w.Chan()
  111. if resp.WatchID != id {
  112. t.Errorf("#%d: watch id in event = %d, want %d", i, resp.WatchID, id)
  113. }
  114. if err := w.Cancel(id); err != nil {
  115. t.Error(err)
  116. }
  117. if len(resp.Events) != 1 {
  118. t.Errorf("#%d: len(resp.Events) got = %d, want = 1", i, len(resp.Events))
  119. }
  120. if len(resp.Events) == 1 {
  121. if !bytes.Equal(resp.Events[0].Kv.Key, keyPut1) {
  122. t.Errorf("#%d: resp.Events got = %s, want = %s", i, resp.Events[0].Kv.Key, keyPut1)
  123. }
  124. }
  125. }
  126. }
  127. // TestWatcherWatchWrongRange ensures that watcher with wrong 'end' range
  128. // does not create watcher, which panics when canceling in range tree.
  129. func TestWatcherWatchWrongRange(t *testing.T) {
  130. b, tmpPath := backend.NewDefaultTmpBackend()
  131. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  132. defer cleanup(s, b, tmpPath)
  133. w := s.NewWatchStream()
  134. defer w.Close()
  135. if id := w.Watch([]byte("foa"), []byte("foa"), 1); id != -1 {
  136. t.Fatalf("key == end range given; id expected -1, got %d", id)
  137. }
  138. if id := w.Watch([]byte("fob"), []byte("foa"), 1); id != -1 {
  139. t.Fatalf("key > end range given; id expected -1, got %d", id)
  140. }
  141. // watch request with 'WithFromKey' has empty-byte range end
  142. if id := w.Watch([]byte("foo"), []byte{}, 1); id != 0 {
  143. t.Fatalf("\x00 is range given; id expected 0, got %d", id)
  144. }
  145. }
  146. func TestWatchDeleteRange(t *testing.T) {
  147. b, tmpPath := backend.NewDefaultTmpBackend()
  148. s := newWatchableStore(b, &lease.FakeLessor{}, nil)
  149. defer func() {
  150. s.store.Close()
  151. os.Remove(tmpPath)
  152. }()
  153. testKeyPrefix := []byte("foo")
  154. for i := 0; i < 3; i++ {
  155. s.Put([]byte(fmt.Sprintf("%s_%d", testKeyPrefix, i)), []byte("bar"), lease.NoLease)
  156. }
  157. w := s.NewWatchStream()
  158. from, to := []byte(testKeyPrefix), []byte(fmt.Sprintf("%s_%d", testKeyPrefix, 99))
  159. w.Watch(from, to, 0)
  160. s.DeleteRange(from, to)
  161. we := []mvccpb.Event{
  162. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_0"), ModRevision: 5}},
  163. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_1"), ModRevision: 5}},
  164. {Type: mvccpb.DELETE, Kv: &mvccpb.KeyValue{Key: []byte("foo_2"), ModRevision: 5}},
  165. }
  166. select {
  167. case r := <-w.Chan():
  168. if !reflect.DeepEqual(r.Events, we) {
  169. t.Errorf("event = %v, want %v", r.Events, we)
  170. }
  171. case <-time.After(10 * time.Second):
  172. t.Fatal("failed to receive event after 10 seconds!")
  173. }
  174. }
  175. // TestWatchStreamCancelWatcherByID ensures cancel calls the cancel func of the watcher
  176. // with given id inside watchStream.
  177. func TestWatchStreamCancelWatcherByID(t *testing.T) {
  178. b, tmpPath := backend.NewDefaultTmpBackend()
  179. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  180. defer cleanup(s, b, tmpPath)
  181. w := s.NewWatchStream()
  182. defer w.Close()
  183. id := w.Watch([]byte("foo"), nil, 0)
  184. tests := []struct {
  185. cancelID WatchID
  186. werr error
  187. }{
  188. // no error should be returned when cancel the created watcher.
  189. {id, nil},
  190. // not exist error should be returned when cancel again.
  191. {id, ErrWatcherNotExist},
  192. // not exist error should be returned when cancel a bad id.
  193. {id + 1, ErrWatcherNotExist},
  194. }
  195. for i, tt := range tests {
  196. gerr := w.Cancel(tt.cancelID)
  197. if gerr != tt.werr {
  198. t.Errorf("#%d: err = %v, want %v", i, gerr, tt.werr)
  199. }
  200. }
  201. if l := len(w.(*watchStream).cancels); l != 0 {
  202. t.Errorf("cancels = %d, want 0", l)
  203. }
  204. }
  205. // TestWatcherRequestProgress ensures synced watcher can correctly
  206. // report its correct progress.
  207. func TestWatcherRequestProgress(t *testing.T) {
  208. b, tmpPath := backend.NewDefaultTmpBackend()
  209. // manually create watchableStore instead of newWatchableStore
  210. // because newWatchableStore automatically calls syncWatchers
  211. // method to sync watchers in unsynced map. We want to keep watchers
  212. // in unsynced to test if syncWatchers works as expected.
  213. s := &watchableStore{
  214. store: NewStore(b, &lease.FakeLessor{}, nil),
  215. unsynced: newWatcherGroup(),
  216. synced: newWatcherGroup(),
  217. }
  218. defer func() {
  219. s.store.Close()
  220. os.Remove(tmpPath)
  221. }()
  222. testKey := []byte("foo")
  223. notTestKey := []byte("bad")
  224. testValue := []byte("bar")
  225. s.Put(testKey, testValue, lease.NoLease)
  226. w := s.NewWatchStream()
  227. badID := WatchID(1000)
  228. w.RequestProgress(badID)
  229. select {
  230. case resp := <-w.Chan():
  231. t.Fatalf("unexpected %+v", resp)
  232. default:
  233. }
  234. id := w.Watch(notTestKey, nil, 1)
  235. w.RequestProgress(id)
  236. select {
  237. case resp := <-w.Chan():
  238. t.Fatalf("unexpected %+v", resp)
  239. default:
  240. }
  241. s.syncWatchers()
  242. w.RequestProgress(id)
  243. wrs := WatchResponse{WatchID: 0, Revision: 2}
  244. select {
  245. case resp := <-w.Chan():
  246. if !reflect.DeepEqual(resp, wrs) {
  247. t.Fatalf("got %+v, expect %+v", resp, wrs)
  248. }
  249. case <-time.After(time.Second):
  250. t.Fatal("failed to receive progress")
  251. }
  252. }
  253. func TestWatcherWatchWithFilter(t *testing.T) {
  254. b, tmpPath := backend.NewDefaultTmpBackend()
  255. s := WatchableKV(newWatchableStore(b, &lease.FakeLessor{}, nil))
  256. defer cleanup(s, b, tmpPath)
  257. w := s.NewWatchStream()
  258. defer w.Close()
  259. filterPut := func(e mvccpb.Event) bool {
  260. return e.Type == mvccpb.PUT
  261. }
  262. w.Watch([]byte("foo"), nil, 0, filterPut)
  263. done := make(chan struct{})
  264. go func() {
  265. <-w.Chan()
  266. done <- struct{}{}
  267. }()
  268. s.Put([]byte("foo"), []byte("bar"), 0)
  269. select {
  270. case <-done:
  271. t.Fatal("failed to filter put request")
  272. case <-time.After(100 * time.Millisecond):
  273. }
  274. s.DeleteRange([]byte("foo"), nil)
  275. select {
  276. case <-done:
  277. case <-time.After(100 * time.Millisecond):
  278. t.Fatal("failed to receive delete request")
  279. }
  280. }