watch_test.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063
  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. "context"
  17. "fmt"
  18. "math/rand"
  19. "reflect"
  20. "sort"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/clientv3"
  24. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  26. "github.com/coreos/etcd/integration"
  27. mvccpb "github.com/coreos/etcd/mvcc/mvccpb"
  28. "github.com/coreos/etcd/pkg/testutil"
  29. "google.golang.org/grpc/metadata"
  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 for KV operations 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 _, 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, ok2 := <-wctx.ch:
  290. if ok2 {
  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; !isCanceled(wr.Err()) {
  596. t.Fatalf("expected context canceled, got %v", 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(integration.RequestWaitTimeout):
  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 != context.Canceled {
  622. t.Fatalf("expected %v, got %v", context.Canceled, err)
  623. }
  624. close(donec)
  625. }()
  626. select {
  627. case <-time.After(integration.RequestWaitTimeout):
  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(integration.RequestWaitTimeout):
  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(integration.RequestWaitTimeout):
  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 WithCreatedNotify returns a
  712. // Created watch response.
  713. func TestWatchWithCreatedNotification(t *testing.T) {
  714. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  715. defer cluster.Terminate(t)
  716. client := cluster.RandClient()
  717. ctx := context.Background()
  718. createC := client.Watch(ctx, "a", clientv3.WithCreatedNotify())
  719. resp := <-createC
  720. if !resp.Created {
  721. t.Fatalf("expected created event, got %v", resp)
  722. }
  723. }
  724. // TestWatchWithCreatedNotificationDropConn ensures that
  725. // a watcher with created notify does not post duplicate
  726. // created events from disconnect.
  727. func TestWatchWithCreatedNotificationDropConn(t *testing.T) {
  728. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  729. defer cluster.Terminate(t)
  730. client := cluster.RandClient()
  731. wch := client.Watch(context.Background(), "a", clientv3.WithCreatedNotify())
  732. resp := <-wch
  733. if !resp.Created {
  734. t.Fatalf("expected created event, got %v", resp)
  735. }
  736. cluster.Members[0].DropConnections()
  737. // check watch channel doesn't post another watch response.
  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. // The grpc proxy 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. // force separate streams in client
  768. md := metadata.Pairs("some-key", fmt.Sprintf("%d", i))
  769. mctx := metadata.NewOutgoingContext(context.Background(), md)
  770. ctx, cancel := context.WithCancel(mctx)
  771. cancels[i] = cancel
  772. w := client.Watch(ctx, fmt.Sprintf("%d", i), clientv3.WithCreatedNotify())
  773. <-w
  774. }
  775. // get max watches; proxy tests have leadership watches, so total may be >numWatches
  776. maxWatches, _ := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  777. // cancel all and wait for cancels to propagate to etcd server
  778. for i := 0; i < numWatches; i++ {
  779. cancels[i]()
  780. }
  781. time.Sleep(time.Second)
  782. minWatches, err := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  783. if err != nil {
  784. t.Fatal(err)
  785. }
  786. maxWatchV, minWatchV := 0, 0
  787. n, serr := fmt.Sscanf(maxWatches+" "+minWatches, "%d %d", &maxWatchV, &minWatchV)
  788. if n != 2 || serr != nil {
  789. t.Fatalf("expected n=2 and err=nil, got n=%d and err=%v", n, serr)
  790. }
  791. if maxWatchV-minWatchV < numWatches {
  792. t.Fatalf("expected %d canceled watchers, got %d", numWatches, maxWatchV-minWatchV)
  793. }
  794. }
  795. // TestWatchOverlapContextCancel stresses the watcher stream teardown path by
  796. // creating/canceling watchers to ensure that new watchers are not taken down
  797. // by a torn down watch stream. The sort of race that's being detected:
  798. // 1. create w1 using a cancelable ctx with %v as "ctx"
  799. // 2. cancel ctx
  800. // 3. watcher client begins tearing down watcher grpc stream since no more watchers
  801. // 3. start creating watcher w2 using a new "ctx" (not canceled), attaches to old grpc stream
  802. // 4. watcher client finishes tearing down stream on "ctx"
  803. // 5. w2 comes back canceled
  804. func TestWatchOverlapContextCancel(t *testing.T) {
  805. f := func(clus *integration.ClusterV3) {}
  806. testWatchOverlapContextCancel(t, f)
  807. }
  808. func TestWatchOverlapDropConnContextCancel(t *testing.T) {
  809. f := func(clus *integration.ClusterV3) {
  810. clus.Members[0].DropConnections()
  811. }
  812. testWatchOverlapContextCancel(t, f)
  813. }
  814. func testWatchOverlapContextCancel(t *testing.T, f func(*integration.ClusterV3)) {
  815. defer testutil.AfterTest(t)
  816. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  817. defer clus.Terminate(t)
  818. n := 100
  819. ctxs, ctxc := make([]context.Context, 5), make([]chan struct{}, 5)
  820. for i := range ctxs {
  821. // make unique stream
  822. md := metadata.Pairs("some-key", fmt.Sprintf("%d", i))
  823. ctxs[i] = metadata.NewOutgoingContext(context.Background(), md)
  824. // limits the maximum number of outstanding watchers per stream
  825. ctxc[i] = make(chan struct{}, 2)
  826. }
  827. // issue concurrent watches on "abc" with cancel
  828. cli := clus.RandClient()
  829. if _, err := cli.Put(context.TODO(), "abc", "def"); err != nil {
  830. t.Fatal(err)
  831. }
  832. ch := make(chan struct{}, n)
  833. for i := 0; i < n; i++ {
  834. go func() {
  835. defer func() { ch <- struct{}{} }()
  836. idx := rand.Intn(len(ctxs))
  837. ctx, cancel := context.WithCancel(ctxs[idx])
  838. ctxc[idx] <- struct{}{}
  839. wch := cli.Watch(ctx, "abc", clientv3.WithRev(1))
  840. f(clus)
  841. select {
  842. case _, ok := <-wch:
  843. if !ok {
  844. t.Fatalf("unexpected closed channel %p", wch)
  845. }
  846. // may take a second or two to reestablish a watcher because of
  847. // grpc back off policies for disconnects
  848. case <-time.After(5 * time.Second):
  849. t.Errorf("timed out waiting for watch on %p", wch)
  850. }
  851. // randomize how cancel overlaps with watch creation
  852. if rand.Intn(2) == 0 {
  853. <-ctxc[idx]
  854. cancel()
  855. } else {
  856. cancel()
  857. <-ctxc[idx]
  858. }
  859. }()
  860. }
  861. // join on watches
  862. for i := 0; i < n; i++ {
  863. select {
  864. case <-ch:
  865. case <-time.After(5 * time.Second):
  866. t.Fatalf("timed out waiting for completed watch")
  867. }
  868. }
  869. }
  870. // TestWatchCancelAndCloseClient ensures that canceling a watcher then immediately
  871. // closing the client does not return a client closing error.
  872. func TestWatchCancelAndCloseClient(t *testing.T) {
  873. defer testutil.AfterTest(t)
  874. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  875. defer clus.Terminate(t)
  876. cli := clus.Client(0)
  877. ctx, cancel := context.WithCancel(context.Background())
  878. wch := cli.Watch(ctx, "abc")
  879. donec := make(chan struct{})
  880. go func() {
  881. defer close(donec)
  882. select {
  883. case wr, ok := <-wch:
  884. if ok {
  885. t.Fatalf("expected closed watch after cancel(), got resp=%+v err=%v", wr, wr.Err())
  886. }
  887. case <-time.After(5 * time.Second):
  888. t.Fatal("timed out waiting for closed channel")
  889. }
  890. }()
  891. cancel()
  892. if err := cli.Close(); err != nil {
  893. t.Fatal(err)
  894. }
  895. <-donec
  896. clus.TakeClient(0)
  897. }
  898. // TestWatchStressResumeClose establishes a bunch of watchers, disconnects
  899. // to put them in resuming mode, cancels them so some resumes by cancel fail,
  900. // then closes the watcher interface to ensure correct clean up.
  901. func TestWatchStressResumeClose(t *testing.T) {
  902. defer testutil.AfterTest(t)
  903. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  904. defer clus.Terminate(t)
  905. cli := clus.Client(0)
  906. ctx, cancel := context.WithCancel(context.Background())
  907. // add more watches than can be resumed before the cancel
  908. wchs := make([]clientv3.WatchChan, 2000)
  909. for i := range wchs {
  910. wchs[i] = cli.Watch(ctx, "abc")
  911. }
  912. clus.Members[0].DropConnections()
  913. cancel()
  914. if err := cli.Close(); err != nil {
  915. t.Fatal(err)
  916. }
  917. clus.TakeClient(0)
  918. }
  919. // TestWatchCancelDisconnected ensures canceling a watcher works when
  920. // its grpc stream is disconnected / reconnecting.
  921. func TestWatchCancelDisconnected(t *testing.T) {
  922. defer testutil.AfterTest(t)
  923. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  924. defer clus.Terminate(t)
  925. cli := clus.Client(0)
  926. ctx, cancel := context.WithCancel(context.Background())
  927. // add more watches than can be resumed before the cancel
  928. wch := cli.Watch(ctx, "abc")
  929. clus.Members[0].Stop(t)
  930. cancel()
  931. select {
  932. case <-wch:
  933. case <-time.After(time.Second):
  934. t.Fatal("took too long to cancel disconnected watcher")
  935. }
  936. }