watch_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. // Copyright 2016 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 integration
  15. import (
  16. "fmt"
  17. "reflect"
  18. "sort"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  22. "github.com/coreos/etcd/clientv3"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  24. "github.com/coreos/etcd/integration"
  25. "github.com/coreos/etcd/pkg/testutil"
  26. storagepb "github.com/coreos/etcd/storage/storagepb"
  27. )
  28. type watcherTest func(*testing.T, *watchctx)
  29. type watchctx struct {
  30. clus *integration.ClusterV3
  31. w clientv3.Watcher
  32. wclient *clientv3.Client
  33. kv clientv3.KV
  34. ch clientv3.WatchChan
  35. }
  36. func runWatchTest(t *testing.T, f watcherTest) {
  37. defer testutil.AfterTest(t)
  38. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  39. defer clus.Terminate(t)
  40. wclient := clus.RandClient()
  41. w := clientv3.NewWatcher(wclient)
  42. defer w.Close()
  43. // select a different client from wclient so puts succeed if
  44. // a test knocks out the watcher client
  45. kvclient := clus.RandClient()
  46. for kvclient == wclient {
  47. kvclient = clus.RandClient()
  48. }
  49. kv := clientv3.NewKV(kvclient)
  50. wctx := &watchctx{clus, w, wclient, kv, nil}
  51. f(t, wctx)
  52. }
  53. // TestWatchMultiWatcher modifies multiple keys and observes the changes.
  54. func TestWatchMultiWatcher(t *testing.T) {
  55. runWatchTest(t, testWatchMultiWatcher)
  56. }
  57. func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
  58. numKeyUpdates := 4
  59. keys := []string{"foo", "bar", "baz"}
  60. donec := make(chan struct{})
  61. readyc := make(chan struct{})
  62. for _, k := range keys {
  63. // key watcher
  64. go func(key string) {
  65. ch := wctx.w.Watch(context.TODO(), key)
  66. if ch == nil {
  67. t.Fatalf("expected watcher channel, got nil")
  68. }
  69. readyc <- struct{}{}
  70. for i := 0; i < numKeyUpdates; i++ {
  71. resp, ok := <-ch
  72. if !ok {
  73. t.Fatalf("watcher unexpectedly closed")
  74. }
  75. v := fmt.Sprintf("%s-%d", key, i)
  76. gotv := string(resp.Events[0].Kv.Value)
  77. if gotv != v {
  78. t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
  79. }
  80. }
  81. donec <- struct{}{}
  82. }(k)
  83. }
  84. // prefix watcher on "b" (bar and baz)
  85. go func() {
  86. prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
  87. if prefixc == nil {
  88. t.Fatalf("expected watcher channel, got nil")
  89. }
  90. readyc <- struct{}{}
  91. evs := []*storagepb.Event{}
  92. for i := 0; i < numKeyUpdates*2; i++ {
  93. resp, ok := <-prefixc
  94. if !ok {
  95. t.Fatalf("watcher unexpectedly closed")
  96. }
  97. evs = append(evs, resp.Events...)
  98. }
  99. // check response
  100. expected := []string{}
  101. bkeys := []string{"bar", "baz"}
  102. for _, k := range bkeys {
  103. for i := 0; i < numKeyUpdates; i++ {
  104. expected = append(expected, fmt.Sprintf("%s-%d", k, i))
  105. }
  106. }
  107. got := []string{}
  108. for _, ev := range evs {
  109. got = append(got, string(ev.Kv.Value))
  110. }
  111. sort.Strings(got)
  112. if reflect.DeepEqual(expected, got) == false {
  113. t.Errorf("got %v, expected %v", got, expected)
  114. }
  115. // ensure no extra data
  116. select {
  117. case resp, ok := <-prefixc:
  118. if !ok {
  119. t.Fatalf("watcher unexpectedly closed")
  120. }
  121. t.Fatalf("unexpected event %+v", resp)
  122. case <-time.After(time.Second):
  123. }
  124. donec <- struct{}{}
  125. }()
  126. // wait for watcher bring up
  127. for i := 0; i < len(keys)+1; i++ {
  128. <-readyc
  129. }
  130. // generate events
  131. ctx := context.TODO()
  132. for i := 0; i < numKeyUpdates; i++ {
  133. for _, k := range keys {
  134. v := fmt.Sprintf("%s-%d", k, i)
  135. if _, err := wctx.kv.Put(ctx, k, v); err != nil {
  136. t.Fatal(err)
  137. }
  138. }
  139. }
  140. // wait for watcher shutdown
  141. for i := 0; i < len(keys)+1; i++ {
  142. <-donec
  143. }
  144. }
  145. // TestWatchRange tests watcher creates ranges
  146. func TestWatchRange(t *testing.T) {
  147. runWatchTest(t, testWatchReconnInit)
  148. }
  149. func testWatchRange(t *testing.T, wctx *watchctx) {
  150. if wctx.ch = wctx.w.Watch(context.TODO(), "a", clientv3.WithRange("c")); wctx.ch == nil {
  151. t.Fatalf("expected non-nil channel")
  152. }
  153. putAndWatch(t, wctx, "a", "a")
  154. putAndWatch(t, wctx, "b", "b")
  155. putAndWatch(t, wctx, "bar", "bar")
  156. }
  157. // TestWatchReconnRequest tests the send failure path when requesting a watcher.
  158. func TestWatchReconnRequest(t *testing.T) {
  159. runWatchTest(t, testWatchReconnRequest)
  160. }
  161. func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
  162. donec, stopc := make(chan struct{}), make(chan struct{}, 1)
  163. go func() {
  164. timer := time.After(2 * time.Second)
  165. defer close(donec)
  166. // take down watcher connection
  167. for {
  168. wctx.wclient.ActiveConnection().Close()
  169. select {
  170. case <-timer:
  171. // spinning on close may live lock reconnection
  172. return
  173. case <-stopc:
  174. return
  175. default:
  176. }
  177. }
  178. }()
  179. // should reconnect when requesting watch
  180. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  181. t.Fatalf("expected non-nil channel")
  182. }
  183. // wait for disconnections to stop
  184. stopc <- struct{}{}
  185. <-donec
  186. // ensure watcher works
  187. putAndWatch(t, wctx, "a", "a")
  188. }
  189. // TestWatchReconnInit tests watcher resumes correctly if connection lost
  190. // before any data was sent.
  191. func TestWatchReconnInit(t *testing.T) {
  192. runWatchTest(t, testWatchReconnInit)
  193. }
  194. func testWatchReconnInit(t *testing.T, wctx *watchctx) {
  195. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  196. t.Fatalf("expected non-nil channel")
  197. }
  198. // take down watcher connection
  199. wctx.wclient.ActiveConnection().Close()
  200. // watcher should recover
  201. putAndWatch(t, wctx, "a", "a")
  202. }
  203. // TestWatchReconnRunning tests watcher resumes correctly if connection lost
  204. // after data was sent.
  205. func TestWatchReconnRunning(t *testing.T) {
  206. runWatchTest(t, testWatchReconnRunning)
  207. }
  208. func testWatchReconnRunning(t *testing.T, wctx *watchctx) {
  209. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  210. t.Fatalf("expected non-nil channel")
  211. }
  212. putAndWatch(t, wctx, "a", "a")
  213. // take down watcher connection
  214. wctx.wclient.ActiveConnection().Close()
  215. // watcher should recover
  216. putAndWatch(t, wctx, "a", "b")
  217. }
  218. // TestWatchCancelImmediate ensures a closed channel is returned
  219. // if the context is cancelled.
  220. func TestWatchCancelImmediate(t *testing.T) {
  221. runWatchTest(t, testWatchCancelImmediate)
  222. }
  223. func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
  224. ctx, cancel := context.WithCancel(context.Background())
  225. cancel()
  226. wch := wctx.w.Watch(ctx, "a")
  227. select {
  228. case wresp, ok := <-wch:
  229. if ok {
  230. t.Fatalf("read wch got %v; expected closed channel", wresp)
  231. }
  232. default:
  233. t.Fatalf("closed watcher channel should not block")
  234. }
  235. }
  236. // TestWatchCancelInit tests watcher closes correctly after no events.
  237. func TestWatchCancelInit(t *testing.T) {
  238. runWatchTest(t, testWatchCancelInit)
  239. }
  240. func testWatchCancelInit(t *testing.T, wctx *watchctx) {
  241. ctx, cancel := context.WithCancel(context.Background())
  242. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  243. t.Fatalf("expected non-nil watcher channel")
  244. }
  245. cancel()
  246. select {
  247. case <-time.After(time.Second):
  248. t.Fatalf("took too long to cancel")
  249. case _, ok := <-wctx.ch:
  250. if ok {
  251. t.Fatalf("expected watcher channel to close")
  252. }
  253. }
  254. }
  255. // TestWatchCancelRunning tests watcher closes correctly after events.
  256. func TestWatchCancelRunning(t *testing.T) {
  257. runWatchTest(t, testWatchCancelRunning)
  258. }
  259. func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
  260. ctx, cancel := context.WithCancel(context.Background())
  261. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  262. t.Fatalf("expected non-nil watcher channel")
  263. }
  264. if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
  265. t.Fatal(err)
  266. }
  267. cancel()
  268. select {
  269. case <-time.After(time.Second):
  270. t.Fatalf("took too long to cancel")
  271. case v, ok := <-wctx.ch:
  272. if !ok {
  273. // closed before getting put; OK
  274. break
  275. }
  276. // got the PUT; should close next
  277. select {
  278. case <-time.After(time.Second):
  279. t.Fatalf("took too long to close")
  280. case v, ok = <-wctx.ch:
  281. if ok {
  282. t.Fatalf("expected watcher channel to close, got %v", v)
  283. }
  284. }
  285. }
  286. }
  287. func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
  288. if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
  289. t.Fatal(err)
  290. }
  291. select {
  292. case <-time.After(5 * time.Second):
  293. t.Fatalf("watch timed out")
  294. case v, ok := <-wctx.ch:
  295. if !ok {
  296. t.Fatalf("unexpected watch close")
  297. }
  298. if string(v.Events[0].Kv.Value) != val {
  299. t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
  300. }
  301. }
  302. }
  303. func TestWatchInvalidFutureRevision(t *testing.T) {
  304. defer testutil.AfterTest(t)
  305. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  306. defer clus.Terminate(t)
  307. w := clientv3.NewWatcher(clus.RandClient())
  308. defer w.Close()
  309. rch := w.Watch(context.Background(), "foo", clientv3.WithRev(100))
  310. wresp, ok := <-rch // WatchResponse from canceled one
  311. if !ok {
  312. t.Fatalf("expected wresp 'open'(ok true), but got ok %v", ok)
  313. }
  314. if wresp.Err() != v3rpc.ErrFutureRev {
  315. t.Fatalf("wresp.Err() expected ErrFutureRev, but got %v", wresp.Err())
  316. }
  317. _, ok = <-rch // ensure the channel is closed
  318. if ok != false {
  319. t.Fatalf("expected wresp 'closed'(ok false), but got ok %v", ok)
  320. }
  321. }
  322. // TestWatchCompactRevision ensures the CompactRevision error is given on a
  323. // compaction event ahead of a watcher.
  324. func TestWatchCompactRevision(t *testing.T) {
  325. defer testutil.AfterTest(t)
  326. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  327. defer clus.Terminate(t)
  328. // set some keys
  329. kv := clientv3.NewKV(clus.RandClient())
  330. for i := 0; i < 5; i++ {
  331. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  332. t.Fatal(err)
  333. }
  334. }
  335. w := clientv3.NewWatcher(clus.RandClient())
  336. defer w.Close()
  337. if err := kv.Compact(context.TODO(), 4); err != nil {
  338. t.Fatal(err)
  339. }
  340. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(2))
  341. // get compacted error message
  342. wresp, ok := <-wch
  343. if !ok {
  344. t.Fatalf("expected wresp, but got closed channel")
  345. }
  346. if wresp.Err() != v3rpc.ErrCompacted {
  347. t.Fatalf("wresp.Err() expected ErrCompacteed, but got %v", wresp.Err())
  348. }
  349. // ensure the channel is closed
  350. if wresp, ok = <-wch; ok {
  351. t.Fatalf("expected closed channel, but got %v", wresp)
  352. }
  353. }
  354. func TestWatchWithProgressNotify(t *testing.T) { testWatchWithProgressNotify(t, true) }
  355. func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }
  356. func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
  357. defer testutil.AfterTest(t)
  358. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  359. defer clus.Terminate(t)
  360. wc := clientv3.NewWatcher(clus.RandClient())
  361. defer wc.Close()
  362. testInterval := 3 * time.Second
  363. pi := v3rpc.ProgressReportInterval
  364. v3rpc.ProgressReportInterval = testInterval
  365. defer func() { v3rpc.ProgressReportInterval = pi }()
  366. opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
  367. if watchOnPut {
  368. opts = append(opts, clientv3.WithPrefix())
  369. }
  370. rch := wc.Watch(context.Background(), "foo", opts...)
  371. select {
  372. case resp := <-rch: // wait for notification
  373. if len(resp.Events) != 0 {
  374. t.Fatalf("resp.Events expected none, got %+v", resp.Events)
  375. }
  376. case <-time.After(2 * pi):
  377. t.Fatalf("watch response expected in %v, but timed out", pi)
  378. }
  379. kvc := clientv3.NewKV(clus.RandClient())
  380. if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
  381. t.Fatal(err)
  382. }
  383. select {
  384. case resp := <-rch:
  385. if resp.Header.Revision != 2 {
  386. t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
  387. }
  388. if watchOnPut { // wait for put if watch on the put key
  389. ev := []*storagepb.Event{{Type: storagepb.PUT,
  390. Kv: &storagepb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
  391. if !reflect.DeepEqual(ev, resp.Events) {
  392. t.Fatalf("expected %+v, got %+v", ev, resp.Events)
  393. }
  394. } else if len(resp.Events) != 0 { // wait for notification otherwise
  395. t.Fatalf("expected no events, but got %+v", resp.Events)
  396. }
  397. case <-time.After(2 * pi):
  398. t.Fatalf("watch response expected in %v, but timed out", pi)
  399. }
  400. }