watch_test.go 18 KB

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