watch_test.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  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. kv clientv3.KV
  36. wclientMember int
  37. kvMember int
  38. ch clientv3.WatchChan
  39. }
  40. func runWatchTest(t *testing.T, f watcherTest) {
  41. defer testutil.AfterTest(t)
  42. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  43. defer clus.Terminate(t)
  44. wclientMember := rand.Intn(3)
  45. w := clus.Client(wclientMember).Watcher
  46. // select a different client from wclient so puts succeed if
  47. // a test knocks out the watcher client
  48. kvMember := rand.Intn(3)
  49. for kvMember == wclientMember {
  50. kvMember = rand.Intn(3)
  51. }
  52. kv := clus.Client(kvMember).KV
  53. wctx := &watchctx{clus, w, kv, wclientMember, kvMember, nil}
  54. f(t, wctx)
  55. }
  56. // TestWatchMultiWatcher modifies multiple keys and observes the changes.
  57. func TestWatchMultiWatcher(t *testing.T) {
  58. runWatchTest(t, testWatchMultiWatcher)
  59. }
  60. func testWatchMultiWatcher(t *testing.T, wctx *watchctx) {
  61. numKeyUpdates := 4
  62. keys := []string{"foo", "bar", "baz"}
  63. donec := make(chan struct{})
  64. readyc := make(chan struct{})
  65. for _, k := range keys {
  66. // key watcher
  67. go func(key string) {
  68. ch := wctx.w.Watch(context.TODO(), key)
  69. if ch == nil {
  70. t.Fatalf("expected watcher channel, got nil")
  71. }
  72. readyc <- struct{}{}
  73. for i := 0; i < numKeyUpdates; i++ {
  74. resp, ok := <-ch
  75. if !ok {
  76. t.Fatalf("watcher unexpectedly closed")
  77. }
  78. v := fmt.Sprintf("%s-%d", key, i)
  79. gotv := string(resp.Events[0].Kv.Value)
  80. if gotv != v {
  81. t.Errorf("#%d: got %s, wanted %s", i, gotv, v)
  82. }
  83. }
  84. donec <- struct{}{}
  85. }(k)
  86. }
  87. // prefix watcher on "b" (bar and baz)
  88. go func() {
  89. prefixc := wctx.w.Watch(context.TODO(), "b", clientv3.WithPrefix())
  90. if prefixc == nil {
  91. t.Fatalf("expected watcher channel, got nil")
  92. }
  93. readyc <- struct{}{}
  94. evs := []*clientv3.Event{}
  95. for i := 0; i < numKeyUpdates*2; i++ {
  96. resp, ok := <-prefixc
  97. if !ok {
  98. t.Fatalf("watcher unexpectedly closed")
  99. }
  100. evs = append(evs, resp.Events...)
  101. }
  102. // check response
  103. expected := []string{}
  104. bkeys := []string{"bar", "baz"}
  105. for _, k := range bkeys {
  106. for i := 0; i < numKeyUpdates; i++ {
  107. expected = append(expected, fmt.Sprintf("%s-%d", k, i))
  108. }
  109. }
  110. got := []string{}
  111. for _, ev := range evs {
  112. got = append(got, string(ev.Kv.Value))
  113. }
  114. sort.Strings(got)
  115. if !reflect.DeepEqual(expected, got) {
  116. t.Errorf("got %v, expected %v", got, expected)
  117. }
  118. // ensure no extra data
  119. select {
  120. case resp, ok := <-prefixc:
  121. if !ok {
  122. t.Fatalf("watcher unexpectedly closed")
  123. }
  124. t.Fatalf("unexpected event %+v", resp)
  125. case <-time.After(time.Second):
  126. }
  127. donec <- struct{}{}
  128. }()
  129. // wait for watcher bring up
  130. for i := 0; i < len(keys)+1; i++ {
  131. <-readyc
  132. }
  133. // generate events
  134. ctx := context.TODO()
  135. for i := 0; i < numKeyUpdates; i++ {
  136. for _, k := range keys {
  137. v := fmt.Sprintf("%s-%d", k, i)
  138. if _, err := wctx.kv.Put(ctx, k, v); err != nil {
  139. t.Fatal(err)
  140. }
  141. }
  142. }
  143. // wait for watcher shutdown
  144. for i := 0; i < len(keys)+1; i++ {
  145. <-donec
  146. }
  147. }
  148. // TestWatchRange tests watcher creates ranges
  149. func TestWatchRange(t *testing.T) {
  150. runWatchTest(t, testWatchRange)
  151. }
  152. func testWatchRange(t *testing.T, wctx *watchctx) {
  153. if wctx.ch = wctx.w.Watch(context.TODO(), "a", clientv3.WithRange("c")); wctx.ch == nil {
  154. t.Fatalf("expected non-nil channel")
  155. }
  156. putAndWatch(t, wctx, "a", "a")
  157. putAndWatch(t, wctx, "b", "b")
  158. putAndWatch(t, wctx, "bar", "bar")
  159. }
  160. // TestWatchReconnRequest tests the send failure path when requesting a watcher.
  161. func TestWatchReconnRequest(t *testing.T) {
  162. runWatchTest(t, testWatchReconnRequest)
  163. }
  164. func testWatchReconnRequest(t *testing.T, wctx *watchctx) {
  165. donec, stopc := make(chan struct{}), make(chan struct{}, 1)
  166. go func() {
  167. timer := time.After(2 * time.Second)
  168. defer close(donec)
  169. // take down watcher connection
  170. for {
  171. wctx.clus.Members[wctx.wclientMember].DropConnections()
  172. select {
  173. case <-timer:
  174. // spinning on close may live lock reconnection
  175. return
  176. case <-stopc:
  177. return
  178. default:
  179. }
  180. }
  181. }()
  182. // should reconnect when requesting watch
  183. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  184. t.Fatalf("expected non-nil channel")
  185. }
  186. // wait for disconnections to stop
  187. stopc <- struct{}{}
  188. <-donec
  189. // spinning on dropping connections may trigger a leader election
  190. // due to resource starvation; l-read to ensure the cluster is stable
  191. ctx, cancel := context.WithTimeout(context.TODO(), 30*time.Second)
  192. if _, err := wctx.kv.Get(ctx, "_"); err != nil {
  193. t.Fatal(err)
  194. }
  195. cancel()
  196. // ensure watcher works
  197. putAndWatch(t, wctx, "a", "a")
  198. }
  199. // TestWatchReconnInit tests watcher resumes correctly if connection lost
  200. // before any data was sent.
  201. func TestWatchReconnInit(t *testing.T) {
  202. runWatchTest(t, testWatchReconnInit)
  203. }
  204. func testWatchReconnInit(t *testing.T, wctx *watchctx) {
  205. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  206. t.Fatalf("expected non-nil channel")
  207. }
  208. wctx.clus.Members[wctx.wclientMember].DropConnections()
  209. // watcher should recover
  210. putAndWatch(t, wctx, "a", "a")
  211. }
  212. // TestWatchReconnRunning tests watcher resumes correctly if connection lost
  213. // after data was sent.
  214. func TestWatchReconnRunning(t *testing.T) {
  215. runWatchTest(t, testWatchReconnRunning)
  216. }
  217. func testWatchReconnRunning(t *testing.T, wctx *watchctx) {
  218. if wctx.ch = wctx.w.Watch(context.TODO(), "a"); wctx.ch == nil {
  219. t.Fatalf("expected non-nil channel")
  220. }
  221. putAndWatch(t, wctx, "a", "a")
  222. // take down watcher connection
  223. wctx.clus.Members[wctx.wclientMember].DropConnections()
  224. // watcher should recover
  225. putAndWatch(t, wctx, "a", "b")
  226. }
  227. // TestWatchCancelImmediate ensures a closed channel is returned
  228. // if the context is cancelled.
  229. func TestWatchCancelImmediate(t *testing.T) {
  230. runWatchTest(t, testWatchCancelImmediate)
  231. }
  232. func testWatchCancelImmediate(t *testing.T, wctx *watchctx) {
  233. ctx, cancel := context.WithCancel(context.Background())
  234. cancel()
  235. wch := wctx.w.Watch(ctx, "a")
  236. select {
  237. case wresp, ok := <-wch:
  238. if ok {
  239. t.Fatalf("read wch got %v; expected closed channel", wresp)
  240. }
  241. default:
  242. t.Fatalf("closed watcher channel should not block")
  243. }
  244. }
  245. // TestWatchCancelInit tests watcher closes correctly after no events.
  246. func TestWatchCancelInit(t *testing.T) {
  247. runWatchTest(t, testWatchCancelInit)
  248. }
  249. func testWatchCancelInit(t *testing.T, wctx *watchctx) {
  250. ctx, cancel := context.WithCancel(context.Background())
  251. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  252. t.Fatalf("expected non-nil watcher channel")
  253. }
  254. cancel()
  255. select {
  256. case <-time.After(time.Second):
  257. t.Fatalf("took too long to cancel")
  258. case _, ok := <-wctx.ch:
  259. if ok {
  260. t.Fatalf("expected watcher channel to close")
  261. }
  262. }
  263. }
  264. // TestWatchCancelRunning tests watcher closes correctly after events.
  265. func TestWatchCancelRunning(t *testing.T) {
  266. runWatchTest(t, testWatchCancelRunning)
  267. }
  268. func testWatchCancelRunning(t *testing.T, wctx *watchctx) {
  269. ctx, cancel := context.WithCancel(context.Background())
  270. if wctx.ch = wctx.w.Watch(ctx, "a"); wctx.ch == nil {
  271. t.Fatalf("expected non-nil watcher channel")
  272. }
  273. if _, err := wctx.kv.Put(ctx, "a", "a"); err != nil {
  274. t.Fatal(err)
  275. }
  276. cancel()
  277. select {
  278. case <-time.After(time.Second):
  279. t.Fatalf("took too long to cancel")
  280. case v, ok := <-wctx.ch:
  281. if !ok {
  282. // closed before getting put; OK
  283. break
  284. }
  285. // got the PUT; should close next
  286. select {
  287. case <-time.After(time.Second):
  288. t.Fatalf("took too long to close")
  289. case v, ok = <-wctx.ch:
  290. if ok {
  291. t.Fatalf("expected watcher channel to close, got %v", v)
  292. }
  293. }
  294. }
  295. }
  296. func putAndWatch(t *testing.T, wctx *watchctx, key, val string) {
  297. if _, err := wctx.kv.Put(context.TODO(), key, val); err != nil {
  298. t.Fatal(err)
  299. }
  300. select {
  301. case <-time.After(5 * time.Second):
  302. t.Fatalf("watch timed out")
  303. case v, ok := <-wctx.ch:
  304. if !ok {
  305. t.Fatalf("unexpected watch close")
  306. }
  307. if string(v.Events[0].Kv.Value) != val {
  308. t.Fatalf("bad value got %v, wanted %v", v.Events[0].Kv.Value, val)
  309. }
  310. }
  311. }
  312. func TestWatchResumeInitRev(t *testing.T) {
  313. defer testutil.AfterTest(t)
  314. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  315. defer clus.Terminate(t)
  316. cli := clus.Client(0)
  317. if _, err := cli.Put(context.TODO(), "b", "2"); err != nil {
  318. t.Fatal(err)
  319. }
  320. if _, err := cli.Put(context.TODO(), "a", "3"); err != nil {
  321. t.Fatal(err)
  322. }
  323. // if resume is broken, it'll pick up this key first instead of a=3
  324. if _, err := cli.Put(context.TODO(), "a", "4"); err != nil {
  325. t.Fatal(err)
  326. }
  327. wch := clus.Client(0).Watch(context.Background(), "a", clientv3.WithRev(1), clientv3.WithCreatedNotify())
  328. if resp, ok := <-wch; !ok || resp.Header.Revision != 4 {
  329. t.Fatalf("got (%v, %v), expected create notification rev=4", resp, ok)
  330. }
  331. // pause wch
  332. clus.Members[0].DropConnections()
  333. clus.Members[0].PauseConnections()
  334. select {
  335. case resp, ok := <-wch:
  336. t.Skipf("wch should block, got (%+v, %v); drop not fast enough", resp, ok)
  337. case <-time.After(100 * time.Millisecond):
  338. }
  339. // resume wch
  340. clus.Members[0].UnpauseConnections()
  341. select {
  342. case resp, ok := <-wch:
  343. if !ok {
  344. t.Fatal("unexpected watch close")
  345. }
  346. if len(resp.Events) == 0 {
  347. t.Fatal("expected event on watch")
  348. }
  349. if string(resp.Events[0].Kv.Value) != "3" {
  350. t.Fatalf("expected value=3, got event %+v", resp.Events[0])
  351. }
  352. case <-time.After(5 * time.Second):
  353. t.Fatal("watch timed out")
  354. }
  355. }
  356. // TestWatchResumeCompacted checks that the watcher gracefully closes in case
  357. // that it tries to resume to a revision that's been compacted out of the store.
  358. // Since the watcher's server restarts with stale data, the watcher will receive
  359. // either a compaction error or all keys by staying in sync before the compaction
  360. // is finally applied.
  361. func TestWatchResumeCompacted(t *testing.T) {
  362. defer testutil.AfterTest(t)
  363. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  364. defer clus.Terminate(t)
  365. // create a waiting watcher at rev 1
  366. w := clus.Client(0)
  367. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(1))
  368. select {
  369. case w := <-wch:
  370. t.Errorf("unexpected message from wch %v", w)
  371. default:
  372. }
  373. clus.Members[0].Stop(t)
  374. ticker := time.After(time.Second * 10)
  375. for clus.WaitLeader(t) <= 0 {
  376. select {
  377. case <-ticker:
  378. t.Fatalf("failed to wait for new leader")
  379. default:
  380. time.Sleep(10 * time.Millisecond)
  381. }
  382. }
  383. // put some data and compact away
  384. numPuts := 5
  385. kv := clus.Client(1)
  386. for i := 0; i < numPuts; i++ {
  387. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  388. t.Fatal(err)
  389. }
  390. }
  391. if _, err := kv.Compact(context.TODO(), 3); err != nil {
  392. t.Fatal(err)
  393. }
  394. clus.Members[0].Restart(t)
  395. // since watch's server isn't guaranteed to be synced with the cluster when
  396. // the watch resumes, there is a window where the watch can stay synced and
  397. // read off all events; if the watcher misses the window, it will go out of
  398. // sync and get a compaction error.
  399. wRev := int64(2)
  400. for int(wRev) <= numPuts+1 {
  401. var wresp clientv3.WatchResponse
  402. var ok bool
  403. select {
  404. case wresp, ok = <-wch:
  405. if !ok {
  406. t.Fatalf("expected wresp, but got closed channel")
  407. }
  408. case <-time.After(5 * time.Second):
  409. t.Fatalf("compacted watch timed out")
  410. }
  411. for _, ev := range wresp.Events {
  412. if ev.Kv.ModRevision != wRev {
  413. t.Fatalf("expected modRev %v, got %+v", wRev, ev)
  414. }
  415. wRev++
  416. }
  417. if wresp.Err() == nil {
  418. continue
  419. }
  420. if wresp.Err() != rpctypes.ErrCompacted {
  421. t.Fatalf("wresp.Err() expected %v, got %+v", rpctypes.ErrCompacted, wresp.Err())
  422. }
  423. break
  424. }
  425. if int(wRev) > numPuts+1 {
  426. // got data faster than the compaction
  427. return
  428. }
  429. // received compaction error; ensure the channel closes
  430. select {
  431. case wresp, ok := <-wch:
  432. if ok {
  433. t.Fatalf("expected closed channel, but got %v", wresp)
  434. }
  435. case <-time.After(5 * time.Second):
  436. t.Fatalf("timed out waiting for channel close")
  437. }
  438. }
  439. // TestWatchCompactRevision ensures the CompactRevision error is given on a
  440. // compaction event ahead of a watcher.
  441. func TestWatchCompactRevision(t *testing.T) {
  442. defer testutil.AfterTest(t)
  443. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  444. defer clus.Terminate(t)
  445. // set some keys
  446. kv := clus.RandClient()
  447. for i := 0; i < 5; i++ {
  448. if _, err := kv.Put(context.TODO(), "foo", "bar"); err != nil {
  449. t.Fatal(err)
  450. }
  451. }
  452. w := clus.RandClient()
  453. if _, err := kv.Compact(context.TODO(), 4); err != nil {
  454. t.Fatal(err)
  455. }
  456. wch := w.Watch(context.Background(), "foo", clientv3.WithRev(2))
  457. // get compacted error message
  458. wresp, ok := <-wch
  459. if !ok {
  460. t.Fatalf("expected wresp, but got closed channel")
  461. }
  462. if wresp.Err() != rpctypes.ErrCompacted {
  463. t.Fatalf("wresp.Err() expected %v, but got %v", rpctypes.ErrCompacted, wresp.Err())
  464. }
  465. if !wresp.Canceled {
  466. t.Fatalf("wresp.Canceled expected true, got %+v", wresp)
  467. }
  468. // ensure the channel is closed
  469. if wresp, ok = <-wch; ok {
  470. t.Fatalf("expected closed channel, but got %v", wresp)
  471. }
  472. }
  473. func TestWatchWithProgressNotify(t *testing.T) { testWatchWithProgressNotify(t, true) }
  474. func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }
  475. func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
  476. defer testutil.AfterTest(t)
  477. // accelerate report interval so test terminates quickly
  478. oldpi := v3rpc.GetProgressReportInterval()
  479. // using atomics to avoid race warnings
  480. v3rpc.SetProgressReportInterval(3 * time.Second)
  481. pi := 3 * time.Second
  482. defer func() { v3rpc.SetProgressReportInterval(oldpi) }()
  483. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  484. defer clus.Terminate(t)
  485. wc := clus.RandClient()
  486. opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
  487. if watchOnPut {
  488. opts = append(opts, clientv3.WithPrefix())
  489. }
  490. rch := wc.Watch(context.Background(), "foo", opts...)
  491. select {
  492. case resp := <-rch: // wait for notification
  493. if len(resp.Events) != 0 {
  494. t.Fatalf("resp.Events expected none, got %+v", resp.Events)
  495. }
  496. case <-time.After(2 * pi):
  497. t.Fatalf("watch response expected in %v, but timed out", pi)
  498. }
  499. kvc := clus.RandClient()
  500. if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
  501. t.Fatal(err)
  502. }
  503. select {
  504. case resp := <-rch:
  505. if resp.Header.Revision != 2 {
  506. t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
  507. }
  508. if watchOnPut { // wait for put if watch on the put key
  509. ev := []*clientv3.Event{{Type: clientv3.EventTypePut,
  510. Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
  511. if !reflect.DeepEqual(ev, resp.Events) {
  512. t.Fatalf("expected %+v, got %+v", ev, resp.Events)
  513. }
  514. } else if len(resp.Events) != 0 { // wait for notification otherwise
  515. t.Fatalf("expected no events, but got %+v", resp.Events)
  516. }
  517. case <-time.After(time.Duration(1.5 * float64(pi))):
  518. t.Fatalf("watch response expected in %v, but timed out", pi)
  519. }
  520. }
  521. func TestWatchEventType(t *testing.T) {
  522. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  523. defer cluster.Terminate(t)
  524. client := cluster.RandClient()
  525. ctx := context.Background()
  526. watchChan := client.Watch(ctx, "/", clientv3.WithPrefix())
  527. if _, err := client.Put(ctx, "/toDelete", "foo"); err != nil {
  528. t.Fatalf("Put failed: %v", err)
  529. }
  530. if _, err := client.Put(ctx, "/toDelete", "bar"); err != nil {
  531. t.Fatalf("Put failed: %v", err)
  532. }
  533. if _, err := client.Delete(ctx, "/toDelete"); err != nil {
  534. t.Fatalf("Delete failed: %v", err)
  535. }
  536. lcr, err := client.Lease.Grant(ctx, 1)
  537. if err != nil {
  538. t.Fatalf("lease create failed: %v", err)
  539. }
  540. if _, err := client.Put(ctx, "/toExpire", "foo", clientv3.WithLease(lcr.ID)); err != nil {
  541. t.Fatalf("Put failed: %v", err)
  542. }
  543. tests := []struct {
  544. et mvccpb.Event_EventType
  545. isCreate bool
  546. isModify bool
  547. }{{
  548. et: clientv3.EventTypePut,
  549. isCreate: true,
  550. }, {
  551. et: clientv3.EventTypePut,
  552. isModify: true,
  553. }, {
  554. et: clientv3.EventTypeDelete,
  555. }, {
  556. et: clientv3.EventTypePut,
  557. isCreate: true,
  558. }, {
  559. et: clientv3.EventTypeDelete,
  560. }}
  561. var res []*clientv3.Event
  562. for {
  563. select {
  564. case wres := <-watchChan:
  565. res = append(res, wres.Events...)
  566. case <-time.After(10 * time.Second):
  567. t.Fatalf("Should receive %d events and then break out loop", len(tests))
  568. }
  569. if len(res) == len(tests) {
  570. break
  571. }
  572. }
  573. for i, tt := range tests {
  574. ev := res[i]
  575. if tt.et != ev.Type {
  576. t.Errorf("#%d: event type want=%s, get=%s", i, tt.et, ev.Type)
  577. }
  578. if tt.isCreate && !ev.IsCreate() {
  579. t.Errorf("#%d: event should be CreateEvent", i)
  580. }
  581. if tt.isModify && !ev.IsModify() {
  582. t.Errorf("#%d: event should be ModifyEvent", i)
  583. }
  584. }
  585. }
  586. func TestWatchErrConnClosed(t *testing.T) {
  587. defer testutil.AfterTest(t)
  588. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  589. defer clus.Terminate(t)
  590. cli := clus.Client(0)
  591. donec := make(chan struct{})
  592. go func() {
  593. defer close(donec)
  594. ch := cli.Watch(context.TODO(), "foo")
  595. if wr := <-ch; grpc.ErrorDesc(wr.Err()) != grpc.ErrClientConnClosing.Error() {
  596. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, grpc.ErrorDesc(wr.Err()))
  597. }
  598. }()
  599. if err := cli.ActiveConnection().Close(); err != nil {
  600. t.Fatal(err)
  601. }
  602. clus.TakeClient(0)
  603. select {
  604. case <-time.After(3 * time.Second):
  605. t.Fatal("wc.Watch took too long")
  606. case <-donec:
  607. }
  608. }
  609. func TestWatchAfterClose(t *testing.T) {
  610. defer testutil.AfterTest(t)
  611. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  612. defer clus.Terminate(t)
  613. cli := clus.Client(0)
  614. clus.TakeClient(0)
  615. if err := cli.Close(); err != nil {
  616. t.Fatal(err)
  617. }
  618. donec := make(chan struct{})
  619. go func() {
  620. cli.Watch(context.TODO(), "foo")
  621. if err := cli.Close(); err != nil && err != grpc.ErrClientConnClosing {
  622. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
  623. }
  624. close(donec)
  625. }()
  626. select {
  627. case <-time.After(3 * time.Second):
  628. t.Fatal("wc.Watch took too long")
  629. case <-donec:
  630. }
  631. }
  632. // TestWatchWithRequireLeader checks the watch channel closes when no leader.
  633. func TestWatchWithRequireLeader(t *testing.T) {
  634. defer testutil.AfterTest(t)
  635. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  636. defer clus.Terminate(t)
  637. // Put a key for the non-require leader watch to read as an event.
  638. // The watchers will be on member[0]; put key through member[0] to
  639. // ensure that it receives the update so watching after killing quorum
  640. // is guaranteed to have the key.
  641. liveClient := clus.Client(0)
  642. if _, err := liveClient.Put(context.TODO(), "foo", "bar"); err != nil {
  643. t.Fatal(err)
  644. }
  645. clus.Members[1].Stop(t)
  646. clus.Members[2].Stop(t)
  647. clus.Client(1).Close()
  648. clus.Client(2).Close()
  649. clus.TakeClient(1)
  650. clus.TakeClient(2)
  651. // wait for election timeout, then member[0] will not have a leader.
  652. tickDuration := 10 * time.Millisecond
  653. // existing streams need three elections before they're torn down; wait until 5 elections cycle
  654. // so proxy tests receive a leader loss event on its existing watch before creating a new watch.
  655. time.Sleep(time.Duration(5*clus.Members[0].ElectionTicks) * tickDuration)
  656. chLeader := liveClient.Watch(clientv3.WithRequireLeader(context.TODO()), "foo", clientv3.WithRev(1))
  657. chNoLeader := liveClient.Watch(context.TODO(), "foo", clientv3.WithRev(1))
  658. select {
  659. case resp, ok := <-chLeader:
  660. if !ok {
  661. t.Fatalf("expected %v watch channel, got closed channel", rpctypes.ErrNoLeader)
  662. }
  663. if resp.Err() != rpctypes.ErrNoLeader {
  664. t.Fatalf("expected %v watch response error, got %+v", rpctypes.ErrNoLeader, resp)
  665. }
  666. case <-time.After(3 * time.Second):
  667. t.Fatal("watch without leader took too long to close")
  668. }
  669. select {
  670. case resp, ok := <-chLeader:
  671. if ok {
  672. t.Fatalf("expected closed channel, got response %v", resp)
  673. }
  674. case <-time.After(3 * time.Second):
  675. t.Fatal("waited too long for channel to close")
  676. }
  677. if _, ok := <-chNoLeader; !ok {
  678. t.Fatalf("expected response, got closed channel")
  679. }
  680. }
  681. // TestWatchWithFilter checks that watch filtering works.
  682. func TestWatchWithFilter(t *testing.T) {
  683. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  684. defer cluster.Terminate(t)
  685. client := cluster.RandClient()
  686. ctx := context.Background()
  687. wcNoPut := client.Watch(ctx, "a", clientv3.WithFilterPut())
  688. wcNoDel := client.Watch(ctx, "a", clientv3.WithFilterDelete())
  689. if _, err := client.Put(ctx, "a", "abc"); err != nil {
  690. t.Fatal(err)
  691. }
  692. if _, err := client.Delete(ctx, "a"); err != nil {
  693. t.Fatal(err)
  694. }
  695. npResp := <-wcNoPut
  696. if len(npResp.Events) != 1 || npResp.Events[0].Type != clientv3.EventTypeDelete {
  697. t.Fatalf("expected delete event, got %+v", npResp.Events)
  698. }
  699. ndResp := <-wcNoDel
  700. if len(ndResp.Events) != 1 || ndResp.Events[0].Type != clientv3.EventTypePut {
  701. t.Fatalf("expected put event, got %+v", ndResp.Events)
  702. }
  703. select {
  704. case resp := <-wcNoPut:
  705. t.Fatalf("unexpected event on filtered put (%+v)", resp)
  706. case resp := <-wcNoDel:
  707. t.Fatalf("unexpected event on filtered delete (%+v)", resp)
  708. case <-time.After(100 * time.Millisecond):
  709. }
  710. }
  711. // TestWatchWithCreatedNotification checks that createdNotification works.
  712. func TestWatchWithCreatedNotification(t *testing.T) {
  713. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  714. defer cluster.Terminate(t)
  715. client := cluster.RandClient()
  716. ctx := context.Background()
  717. createC := client.Watch(ctx, "a", clientv3.WithCreatedNotify())
  718. resp := <-createC
  719. if !resp.Created {
  720. t.Fatalf("expected created event, got %v", resp)
  721. }
  722. }
  723. // TestWatchWithCreatedNotificationDropConn ensures that
  724. // a watcher with created notify does not post duplicate
  725. // created events from disconnect.
  726. func TestWatchWithCreatedNotificationDropConn(t *testing.T) {
  727. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  728. defer cluster.Terminate(t)
  729. client := cluster.RandClient()
  730. wch := client.Watch(context.Background(), "a", clientv3.WithCreatedNotify())
  731. resp := <-wch
  732. if !resp.Created {
  733. t.Fatalf("expected created event, got %v", resp)
  734. }
  735. cluster.Members[0].DropConnections()
  736. // try to receive from watch channel again
  737. // ensure it doesn't post another createNotify
  738. select {
  739. case wresp := <-wch:
  740. t.Fatalf("got unexpected watch response: %+v\n", wresp)
  741. case <-time.After(time.Second):
  742. // watcher may not reconnect by the time it hits the select,
  743. // so it wouldn't have a chance to filter out the second create event
  744. }
  745. }
  746. // TestWatchCancelOnServer ensures client watcher cancels propagate back to the server.
  747. func TestWatchCancelOnServer(t *testing.T) {
  748. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  749. defer cluster.Terminate(t)
  750. client := cluster.RandClient()
  751. numWatches := 10
  752. // grpcproxy starts watches to detect leadership after the proxy server
  753. // returns as started; to avoid racing on the proxy's internal watches, wait
  754. // until require leader watches get create responses to ensure the leadership
  755. // watches have started.
  756. for {
  757. ctx, cancel := context.WithCancel(clientv3.WithRequireLeader(context.TODO()))
  758. ww := client.Watch(ctx, "a", clientv3.WithCreatedNotify())
  759. wresp := <-ww
  760. cancel()
  761. if wresp.Err() == nil {
  762. break
  763. }
  764. }
  765. cancels := make([]context.CancelFunc, numWatches)
  766. for i := 0; i < numWatches; i++ {
  767. // use WithTimeout to force separate streams in client
  768. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  769. cancels[i] = cancel
  770. w := client.Watch(ctx, fmt.Sprintf("%d", i), clientv3.WithCreatedNotify())
  771. <-w
  772. }
  773. // get max watches; proxy tests have leadership watches, so total may be >numWatches
  774. maxWatches, _ := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  775. // cancel all and wait for cancels to propagate to etcd server
  776. for i := 0; i < numWatches; i++ {
  777. cancels[i]()
  778. }
  779. time.Sleep(time.Second)
  780. minWatches, err := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  781. if err != nil {
  782. t.Fatal(err)
  783. }
  784. maxWatchV, minWatchV := 0, 0
  785. n, serr := fmt.Sscanf(maxWatches+" "+minWatches, "%d %d", &maxWatchV, &minWatchV)
  786. if n != 2 || serr != nil {
  787. t.Fatalf("expected n=2 and err=nil, got n=%d and err=%v", n, serr)
  788. }
  789. if maxWatchV-minWatchV < numWatches {
  790. t.Fatalf("expected %d canceled watchers, got %d", numWatches, maxWatchV-minWatchV)
  791. }
  792. }
  793. // TestWatchOverlapContextCancel stresses the watcher stream teardown path by
  794. // creating/canceling watchers to ensure that new watchers are not taken down
  795. // by a torn down watch stream. The sort of race that's being detected:
  796. // 1. create w1 using a cancelable ctx with %v as "ctx"
  797. // 2. cancel ctx
  798. // 3. watcher client begins tearing down watcher grpc stream since no more watchers
  799. // 3. start creating watcher w2 using a new "ctx" (not canceled), attaches to old grpc stream
  800. // 4. watcher client finishes tearing down stream on "ctx"
  801. // 5. w2 comes back canceled
  802. func TestWatchOverlapContextCancel(t *testing.T) {
  803. f := func(clus *integration.ClusterV3) {}
  804. testWatchOverlapContextCancel(t, f)
  805. }
  806. func TestWatchOverlapDropConnContextCancel(t *testing.T) {
  807. f := func(clus *integration.ClusterV3) {
  808. clus.Members[0].DropConnections()
  809. }
  810. testWatchOverlapContextCancel(t, f)
  811. }
  812. func testWatchOverlapContextCancel(t *testing.T, f func(*integration.ClusterV3)) {
  813. defer testutil.AfterTest(t)
  814. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  815. defer clus.Terminate(t)
  816. // each unique context "%v" has a unique grpc stream
  817. n := 100
  818. ctxs, ctxc := make([]context.Context, 5), make([]chan struct{}, 5)
  819. for i := range ctxs {
  820. // make "%v" unique
  821. ctxs[i] = context.WithValue(context.TODO(), "key", i)
  822. // limits the maximum number of outstanding watchers per stream
  823. ctxc[i] = make(chan struct{}, 2)
  824. }
  825. // issue concurrent watches on "abc" with cancel
  826. cli := clus.RandClient()
  827. if _, err := cli.Put(context.TODO(), "abc", "def"); err != nil {
  828. t.Fatal(err)
  829. }
  830. ch := make(chan struct{}, n)
  831. for i := 0; i < n; i++ {
  832. go func() {
  833. defer func() { ch <- struct{}{} }()
  834. idx := rand.Intn(len(ctxs))
  835. ctx, cancel := context.WithCancel(ctxs[idx])
  836. ctxc[idx] <- struct{}{}
  837. wch := cli.Watch(ctx, "abc", clientv3.WithRev(1))
  838. f(clus)
  839. select {
  840. case _, ok := <-wch:
  841. if !ok {
  842. t.Fatalf("unexpected closed channel %p", wch)
  843. }
  844. // may take a second or two to reestablish a watcher because of
  845. // grpc backoff policies for disconnects
  846. case <-time.After(5 * time.Second):
  847. t.Errorf("timed out waiting for watch on %p", wch)
  848. }
  849. // randomize how cancel overlaps with watch creation
  850. if rand.Intn(2) == 0 {
  851. <-ctxc[idx]
  852. cancel()
  853. } else {
  854. cancel()
  855. <-ctxc[idx]
  856. }
  857. }()
  858. }
  859. // join on watches
  860. for i := 0; i < n; i++ {
  861. select {
  862. case <-ch:
  863. case <-time.After(5 * time.Second):
  864. t.Fatalf("timed out waiting for completed watch")
  865. }
  866. }
  867. }
  868. // TestWatchCanelAndCloseClient ensures that canceling a watcher then immediately
  869. // closing the client does not return a client closing error.
  870. func TestWatchCancelAndCloseClient(t *testing.T) {
  871. defer testutil.AfterTest(t)
  872. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  873. defer clus.Terminate(t)
  874. cli := clus.Client(0)
  875. ctx, cancel := context.WithCancel(context.Background())
  876. wch := cli.Watch(ctx, "abc")
  877. donec := make(chan struct{})
  878. go func() {
  879. defer close(donec)
  880. select {
  881. case wr, ok := <-wch:
  882. if ok {
  883. t.Fatalf("expected closed watch after cancel(), got resp=%+v err=%v", wr, wr.Err())
  884. }
  885. case <-time.After(5 * time.Second):
  886. t.Fatal("timed out waiting for closed channel")
  887. }
  888. }()
  889. cancel()
  890. if err := cli.Close(); err != nil {
  891. t.Fatal(err)
  892. }
  893. <-donec
  894. clus.TakeClient(0)
  895. }
  896. // TestWatchStressResumeClose establishes a bunch of watchers, disconnects
  897. // to put them in resuming mode, cancels them so some resumes by cancel fail,
  898. // then closes the watcher interface to ensure correct clean up.
  899. func TestWatchStressResumeClose(t *testing.T) {
  900. defer testutil.AfterTest(t)
  901. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  902. defer clus.Terminate(t)
  903. cli := clus.Client(0)
  904. ctx, cancel := context.WithCancel(context.Background())
  905. // add more watches than can be resumed before the cancel
  906. wchs := make([]clientv3.WatchChan, 2000)
  907. for i := range wchs {
  908. wchs[i] = cli.Watch(ctx, "abc")
  909. }
  910. clus.Members[0].DropConnections()
  911. cancel()
  912. if err := cli.Close(); err != nil {
  913. t.Fatal(err)
  914. }
  915. clus.TakeClient(0)
  916. }
  917. // TestWatchCancelDisconnected ensures canceling a watcher works when
  918. // its grpc stream is disconnected / reconnecting.
  919. func TestWatchCancelDisconnected(t *testing.T) {
  920. defer testutil.AfterTest(t)
  921. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  922. defer clus.Terminate(t)
  923. cli := clus.Client(0)
  924. ctx, cancel := context.WithCancel(context.Background())
  925. // add more watches than can be resumed before the cancel
  926. wch := cli.Watch(ctx, "abc")
  927. clus.Members[0].Stop(t)
  928. cancel()
  929. select {
  930. case <-wch:
  931. case <-time.After(time.Second):
  932. t.Fatal("took too long to cancel disconnected watcher")
  933. }
  934. }