watch_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. // Copyright 2016 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 integration
  15. import (
  16. "fmt"
  17. "reflect"
  18. "sort"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/clientv3"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  24. "github.com/coreos/etcd/integration"
  25. mvccpb "github.com/coreos/etcd/mvcc/mvccpb"
  26. "github.com/coreos/etcd/pkg/testutil"
  27. "golang.org/x/net/context"
  28. )
  29. type watcherTest func(*testing.T, *watchctx)
  30. type watchctx struct {
  31. clus *integration.ClusterV3
  32. w clientv3.Watcher
  33. wclient *clientv3.Client
  34. kv clientv3.KV
  35. ch clientv3.WatchChan
  36. }
  37. func runWatchTest(t *testing.T, f watcherTest) {
  38. defer testutil.AfterTest(t)
  39. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  40. defer clus.Terminate(t)
  41. wclient := clus.RandClient()
  42. w := clientv3.NewWatcher(wclient)
  43. defer w.Close()
  44. // select a different client from wclient so puts succeed if
  45. // a test knocks out the watcher client
  46. kvclient := clus.RandClient()
  47. for kvclient == wclient {
  48. kvclient = clus.RandClient()
  49. }
  50. kv := clientv3.NewKV(kvclient)
  51. wctx := &watchctx{clus, w, wclient, kv, nil}
  52. f(t, wctx)
  53. }
  54. // TestWatchMultiWatcher modifies multiple keys and observes the changes.
  55. func TestWatchMultiWatcher(t *testing.T) {
  56. runWatchTest(t, testWatchMultiWatcher)
  57. }
  58. func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
  59. numKeyUpdates := 4
  60. keys := []string{"foo", "bar", "baz"}
  61. donec := make(chan struct{})
  62. readyc := make(chan struct{})
  63. for _, k := range keys {
  64. // key watcher
  65. go func(key string) {
  66. ch := wctx.w.Watch(context.TODO(), key)
  67. if ch == nil {
  68. t.Fatalf("expected watcher channel, got nil")
  69. }
  70. readyc <- struct{}{}
  71. for i := 0; i < numKeyUpdates; i++ {
  72. resp, ok := <-ch
  73. if !ok {
  74. t.Fatalf("watcher unexpectedly closed")
  75. }
  76. v := fmt.Sprintf("%s-%d", key, i)
  77. gotv := string(resp.Events[0].Kv.Value)
  78. if gotv != v {
  79. t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
  80. }
  81. }
  82. donec <- struct{}{}
  83. }(k)
  84. }
  85. // prefix watcher on "b" (bar and baz)
  86. go func() {
  87. prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
  88. if prefixc == nil {
  89. t.Fatalf("expected watcher channel, got nil")
  90. }
  91. readyc <- struct{}{}
  92. evs := []*clientv3.Event{}
  93. for i := 0; i < numKeyUpdates*2; i++ {
  94. resp, ok := <-prefixc
  95. if !ok {
  96. t.Fatalf("watcher unexpectedly closed")
  97. }
  98. evs = append(evs, resp.Events...)
  99. }
  100. // check response
  101. expected := []string{}
  102. bkeys := []string{"bar", "baz"}
  103. for _, k := range bkeys {
  104. for i := 0; i < numKeyUpdates; i++ {
  105. expected = append(expected, fmt.Sprintf("%s-%d", k, i))
  106. }
  107. }
  108. got := []string{}
  109. for _, ev := range evs {
  110. got = append(got, string(ev.Kv.Value))
  111. }
  112. sort.Strings(got)
  113. if !reflect.DeepEqual(expected, got) {
  114. t.Errorf("got %v, expected %v", got, expected)
  115. }
  116. // ensure no extra data
  117. select {
  118. case resp, ok := <-prefixc:
  119. if !ok {
  120. t.Fatalf("watcher unexpectedly closed")
  121. }
  122. t.Fatalf("unexpected event %+v", resp)
  123. case <-time.After(time.Second):
  124. }
  125. donec <- struct{}{}
  126. }()
  127. // wait for watcher bring up
  128. for i := 0; i < len(keys)+1; i++ {
  129. <-readyc
  130. }
  131. // generate events
  132. ctx := context.TODO()
  133. for i := 0; i < numKeyUpdates; i++ {
  134. for _, k := range keys {
  135. v := fmt.Sprintf("%s-%d", k, i)
  136. if _, err := wctx.kv.Put(ctx, k, v); err != nil {
  137. t.Fatal(err)
  138. }
  139. }
  140. }
  141. // wait for watcher shutdown
  142. for i := 0; i < len(keys)+1; i++ {
  143. <-donec
  144. }
  145. }
  146. // TestWatchRange tests watcher creates ranges
  147. func TestWatchRange(t *testing.T) {
  148. runWatchTest(t, testWatchRange)
  149. }
  150. func testWatchRange(t *testing.T, wctx *watchctx) {
  151. if wctx.ch = wctx.w.Watch(context.TODO(), "a", clientv3.WithRange("c")); wctx.ch == nil {
  152. t.Fatalf("expected non-nil channel")
  153. }
  154. putAndWatch(t, wctx, "a", "a")
  155. putAndWatch(t, wctx, "b", "b")
  156. putAndWatch(t, wctx, "bar", "bar")
  157. }
  158. // TestWatchReconnRequest tests the send failure path when requesting a watcher.
  159. func TestWatchReconnRequest(t *testing.T) {
  160. runWatchTest(t, testWatchReconnRequest)
  161. }
  162. func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
  163. donec, stopc := make(chan struct{}), make(chan struct{}, 1)
  164. go func() {
  165. timer := time.After(2 * time.Second)
  166. defer close(donec)
  167. // take down watcher connection
  168. for {
  169. wctx.wclient.ActiveConnection().Close()
  170. select {
  171. case <-timer:
  172. // spinning on close may live lock reconnection
  173. return
  174. case <-stopc:
  175. return
  176. default:
  177. }
  178. }
  179. }()
  180. // should reconnect when requesting watch
  181. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  182. t.Fatalf("expected non-nil channel")
  183. }
  184. // wait for disconnections to stop
  185. stopc <- struct{}{}
  186. <-donec
  187. // ensure watcher works
  188. putAndWatch(t, wctx, "a", "a")
  189. }
  190. // TestWatchReconnInit tests watcher resumes correctly if connection lost
  191. // before any data was sent.
  192. func TestWatchReconnInit(t *testing.T) {
  193. runWatchTest(t, testWatchReconnInit)
  194. }
  195. func testWatchReconnInit(t *testing.T, wctx *watchctx) {
  196. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  197. t.Fatalf("expected non-nil channel")
  198. }
  199. // take down watcher connection
  200. wctx.wclient.ActiveConnection().Close()
  201. // watcher should recover
  202. putAndWatch(t, wctx, "a", "a")
  203. }
  204. // TestWatchReconnRunning tests watcher resumes correctly if connection lost
  205. // after data was sent.
  206. func TestWatchReconnRunning(t *testing.T) {
  207. runWatchTest(t, testWatchReconnRunning)
  208. }
  209. func testWatchReconnRunning(t *testing.T, wctx *watchctx) {
  210. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  211. t.Fatalf("expected non-nil channel")
  212. }
  213. putAndWatch(t, wctx, "a", "a")
  214. // take down watcher connection
  215. wctx.wclient.ActiveConnection().Close()
  216. // watcher should recover
  217. putAndWatch(t, wctx, "a", "b")
  218. }
  219. // TestWatchCancelImmediate ensures a closed channel is returned
  220. // if the context is cancelled.
  221. func TestWatchCancelImmediate(t *testing.T) {
  222. runWatchTest(t, testWatchCancelImmediate)
  223. }
  224. func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
  225. ctx, cancel := context.WithCancel(context.Background())
  226. cancel()
  227. wch := wctx.w.Watch(ctx, "a")
  228. select {
  229. case wresp, ok := <-wch:
  230. if ok {
  231. t.Fatalf("read wch got %v; expected closed channel", wresp)
  232. }
  233. default:
  234. t.Fatalf("closed watcher channel should not block")
  235. }
  236. }
  237. // TestWatchCancelInit tests watcher closes correctly after no events.
  238. func TestWatchCancelInit(t *testing.T) {
  239. runWatchTest(t, testWatchCancelInit)
  240. }
  241. func testWatchCancelInit(t *testing.T, wctx *watchctx) {
  242. ctx, cancel := context.WithCancel(context.Background())
  243. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  244. t.Fatalf("expected non-nil watcher channel")
  245. }
  246. cancel()
  247. select {
  248. case <-time.After(time.Second):
  249. t.Fatalf("took too long to cancel")
  250. case _, ok := <-wctx.ch:
  251. if ok {
  252. t.Fatalf("expected watcher channel to close")
  253. }
  254. }
  255. }
  256. // TestWatchCancelRunning tests watcher closes correctly after events.
  257. func TestWatchCancelRunning(t *testing.T) {
  258. runWatchTest(t, testWatchCancelRunning)
  259. }
  260. func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
  261. ctx, cancel := context.WithCancel(context.Background())
  262. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  263. t.Fatalf("expected non-nil watcher channel")
  264. }
  265. if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
  266. t.Fatal(err)
  267. }
  268. cancel()
  269. select {
  270. case <-time.After(time.Second):
  271. t.Fatalf("took too long to cancel")
  272. case v, ok := <-wctx.ch:
  273. if !ok {
  274. // closed before getting put; OK
  275. break
  276. }
  277. // got the PUT; should close next
  278. select {
  279. case <-time.After(time.Second):
  280. t.Fatalf("took too long to close")
  281. case v, ok = <-wctx.ch:
  282. if ok {
  283. t.Fatalf("expected watcher channel to close, got %v", v)
  284. }
  285. }
  286. }
  287. }
  288. func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
  289. if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
  290. t.Fatal(err)
  291. }
  292. select {
  293. case <-time.After(5 * time.Second):
  294. t.Fatalf("watch timed out")
  295. case v, ok := <-wctx.ch:
  296. if !ok {
  297. t.Fatalf("unexpected watch close")
  298. }
  299. if string(v.Events[0].Kv.Value) != val {
  300. t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
  301. }
  302. }
  303. }
  304. // TestWatchResumeComapcted checks that the watcher gracefully closes in case
  305. // that it tries to resume to a revision that's been compacted out of the store.
  306. func TestWatchResumeCompacted(t *testing.T) {
  307. defer testutil.AfterTest(t)
  308. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  309. defer clus.Terminate(t)
  310. // create a waiting watcher at rev 1
  311. w := clientv3.NewWatcher(clus.Client(0))
  312. defer w.Close()
  313. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(1))
  314. select {
  315. case w := <-wch:
  316. t.Errorf("unexpected message from wch %v", w)
  317. default:
  318. }
  319. clus.Members[0].Stop(t)
  320. ticker := time.After(time.Second * 10)
  321. for clus.WaitLeader(t) <= 0 {
  322. select {
  323. case <-ticker:
  324. t.Fatalf("failed to wait for new leader")
  325. default:
  326. time.Sleep(10 * time.Millisecond)
  327. }
  328. }
  329. // put some data and compact away
  330. kv := clientv3.NewKV(clus.Client(1))
  331. for i := 0; i < 5; i++ {
  332. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  333. t.Fatal(err)
  334. }
  335. }
  336. if err := kv.Compact(context.TODO(), 3); err != nil {
  337. t.Fatal(err)
  338. }
  339. clus.Members[0].Restart(t)
  340. // get compacted error message
  341. wresp, ok := <-wch
  342. if !ok {
  343. t.Fatalf("expected wresp, but got closed channel")
  344. }
  345. if wresp.Err() != rpctypes.ErrCompacted {
  346. t.Fatalf("wresp.Err() expected %v, but got %v", rpctypes.ErrCompacted, wresp.Err())
  347. }
  348. // ensure the channel is closed
  349. if wresp, ok = <-wch; ok {
  350. t.Fatalf("expected closed channel, but got %v", wresp)
  351. }
  352. }
  353. // TestWatchCompactRevision ensures the CompactRevision error is given on a
  354. // compaction event ahead of a watcher.
  355. func TestWatchCompactRevision(t *testing.T) {
  356. defer testutil.AfterTest(t)
  357. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  358. defer clus.Terminate(t)
  359. // set some keys
  360. kv := clientv3.NewKV(clus.RandClient())
  361. for i := 0; i < 5; i++ {
  362. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  363. t.Fatal(err)
  364. }
  365. }
  366. w := clientv3.NewWatcher(clus.RandClient())
  367. defer w.Close()
  368. if err := kv.Compact(context.TODO(), 4); err != nil {
  369. t.Fatal(err)
  370. }
  371. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(2))
  372. // get compacted error message
  373. wresp, ok := <-wch
  374. if !ok {
  375. t.Fatalf("expected wresp, but got closed channel")
  376. }
  377. if wresp.Err() != rpctypes.ErrCompacted {
  378. t.Fatalf("wresp.Err() expected %v, but got %v", rpctypes.ErrCompacted, wresp.Err())
  379. }
  380. // ensure the channel is closed
  381. if wresp, ok = <-wch; ok {
  382. t.Fatalf("expected closed channel, but got %v", wresp)
  383. }
  384. }
  385. func TestWatchWithProgressNotify(t *testing.T) { testWatchWithProgressNotify(t, true) }
  386. func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }
  387. func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
  388. defer testutil.AfterTest(t)
  389. // accelerate report interval so test terminates quickly
  390. oldpi := v3rpc.GetProgressReportInterval()
  391. // using atomics to avoid race warnings
  392. v3rpc.SetProgressReportInterval(3 * time.Second)
  393. pi := 3 * time.Second
  394. defer func() { v3rpc.SetProgressReportInterval(oldpi) }()
  395. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  396. defer clus.Terminate(t)
  397. wc := clientv3.NewWatcher(clus.RandClient())
  398. defer wc.Close()
  399. opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
  400. if watchOnPut {
  401. opts = append(opts, clientv3.WithPrefix())
  402. }
  403. rch := wc.Watch(context.Background(), "foo", opts...)
  404. select {
  405. case resp := <-rch: // wait for notification
  406. if len(resp.Events) != 0 {
  407. t.Fatalf("resp.Events expected none, got %+v", resp.Events)
  408. }
  409. case <-time.After(2 * pi):
  410. t.Fatalf("watch response expected in %v, but timed out", pi)
  411. }
  412. kvc := clientv3.NewKV(clus.RandClient())
  413. if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
  414. t.Fatal(err)
  415. }
  416. select {
  417. case resp := <-rch:
  418. if resp.Header.Revision != 2 {
  419. t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
  420. }
  421. if watchOnPut { // wait for put if watch on the put key
  422. ev := []*clientv3.Event{{Type: clientv3.EventTypePut,
  423. Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
  424. if !reflect.DeepEqual(ev, resp.Events) {
  425. t.Fatalf("expected %+v, got %+v", ev, resp.Events)
  426. }
  427. } else if len(resp.Events) != 0 { // wait for notification otherwise
  428. t.Fatalf("expected no events, but got %+v", resp.Events)
  429. }
  430. case <-time.After(2 * pi):
  431. t.Fatalf("watch response expected in %v, but timed out", pi)
  432. }
  433. }
  434. func TestWatchEventType(t *testing.T) {
  435. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  436. defer cluster.Terminate(t)
  437. client := cluster.RandClient()
  438. ctx := context.Background()
  439. watchChan := client.Watch(ctx, "/", clientv3.WithPrefix())
  440. if _, err := client.Put(ctx, "/toDelete", "foo"); err != nil {
  441. t.Fatalf("Put failed: %v", err)
  442. }
  443. if _, err := client.Put(ctx, "/toDelete", "bar"); err != nil {
  444. t.Fatalf("Put failed: %v", err)
  445. }
  446. if _, err := client.Delete(ctx, "/toDelete"); err != nil {
  447. t.Fatalf("Delete failed: %v", err)
  448. }
  449. lcr, err := client.Lease.Grant(ctx, 1)
  450. if err != nil {
  451. t.Fatalf("lease create failed: %v", err)
  452. }
  453. if _, err := client.Put(ctx, "/toExpire", "foo", clientv3.WithLease(lcr.ID)); err != nil {
  454. t.Fatalf("Put failed: %v", err)
  455. }
  456. tests := []struct {
  457. et mvccpb.Event_EventType
  458. isCreate bool
  459. isModify bool
  460. }{{
  461. et: clientv3.EventTypePut,
  462. isCreate: true,
  463. }, {
  464. et: clientv3.EventTypePut,
  465. isModify: true,
  466. }, {
  467. et: clientv3.EventTypeDelete,
  468. }, {
  469. et: clientv3.EventTypePut,
  470. isCreate: true,
  471. }, {
  472. et: clientv3.EventTypeDelete,
  473. }}
  474. var res []*clientv3.Event
  475. for {
  476. select {
  477. case wres := <-watchChan:
  478. res = append(res, wres.Events...)
  479. case <-time.After(10 * time.Second):
  480. t.Fatalf("Should receive %d events and then break out loop", len(tests))
  481. }
  482. if len(res) == len(tests) {
  483. break
  484. }
  485. }
  486. for i, tt := range tests {
  487. ev := res[i]
  488. if tt.et != ev.Type {
  489. t.Errorf("#%d: event type want=%s, get=%s", i, tt.et, ev.Type)
  490. }
  491. if tt.isCreate && !ev.IsCreate() {
  492. t.Errorf("#%d: event should be CreateEvent", i)
  493. }
  494. if tt.isModify && !ev.IsModify() {
  495. t.Errorf("#%d: event should be ModifyEvent", i)
  496. }
  497. }
  498. }