watch_test.go 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. // ensure the channel is closed
  466. if wresp, ok = <-wch; ok {
  467. t.Fatalf("expected closed channel, but got %v", wresp)
  468. }
  469. }
  470. func TestWatchWithProgressNotify(t *testing.T) { testWatchWithProgressNotify(t, true) }
  471. func TestWatchWithProgressNotifyNoEvent(t *testing.T) { testWatchWithProgressNotify(t, false) }
  472. func testWatchWithProgressNotify(t *testing.T, watchOnPut bool) {
  473. defer testutil.AfterTest(t)
  474. // accelerate report interval so test terminates quickly
  475. oldpi := v3rpc.GetProgressReportInterval()
  476. // using atomics to avoid race warnings
  477. v3rpc.SetProgressReportInterval(3 * time.Second)
  478. pi := 3 * time.Second
  479. defer func() { v3rpc.SetProgressReportInterval(oldpi) }()
  480. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  481. defer clus.Terminate(t)
  482. wc := clus.RandClient()
  483. opts := []clientv3.OpOption{clientv3.WithProgressNotify()}
  484. if watchOnPut {
  485. opts = append(opts, clientv3.WithPrefix())
  486. }
  487. rch := wc.Watch(context.Background(), "foo", opts...)
  488. select {
  489. case resp := <-rch: // wait for notification
  490. if len(resp.Events) != 0 {
  491. t.Fatalf("resp.Events expected none, got %+v", resp.Events)
  492. }
  493. case <-time.After(2 * pi):
  494. t.Fatalf("watch response expected in %v, but timed out", pi)
  495. }
  496. kvc := clus.RandClient()
  497. if _, err := kvc.Put(context.TODO(), "foox", "bar"); err != nil {
  498. t.Fatal(err)
  499. }
  500. select {
  501. case resp := <-rch:
  502. if resp.Header.Revision != 2 {
  503. t.Fatalf("resp.Header.Revision expected 2, got %d", resp.Header.Revision)
  504. }
  505. if watchOnPut { // wait for put if watch on the put key
  506. ev := []*clientv3.Event{{Type: clientv3.EventTypePut,
  507. Kv: &mvccpb.KeyValue{Key: []byte("foox"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1}}}
  508. if !reflect.DeepEqual(ev, resp.Events) {
  509. t.Fatalf("expected %+v, got %+v", ev, resp.Events)
  510. }
  511. } else if len(resp.Events) != 0 { // wait for notification otherwise
  512. t.Fatalf("expected no events, but got %+v", resp.Events)
  513. }
  514. case <-time.After(time.Duration(1.5 * float64(pi))):
  515. t.Fatalf("watch response expected in %v, but timed out", pi)
  516. }
  517. }
  518. func TestWatchEventType(t *testing.T) {
  519. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  520. defer cluster.Terminate(t)
  521. client := cluster.RandClient()
  522. ctx := context.Background()
  523. watchChan := client.Watch(ctx, "/", clientv3.WithPrefix())
  524. if _, err := client.Put(ctx, "/toDelete", "foo"); err != nil {
  525. t.Fatalf("Put failed: %v", err)
  526. }
  527. if _, err := client.Put(ctx, "/toDelete", "bar"); err != nil {
  528. t.Fatalf("Put failed: %v", err)
  529. }
  530. if _, err := client.Delete(ctx, "/toDelete"); err != nil {
  531. t.Fatalf("Delete failed: %v", err)
  532. }
  533. lcr, err := client.Lease.Grant(ctx, 1)
  534. if err != nil {
  535. t.Fatalf("lease create failed: %v", err)
  536. }
  537. if _, err := client.Put(ctx, "/toExpire", "foo", clientv3.WithLease(lcr.ID)); err != nil {
  538. t.Fatalf("Put failed: %v", err)
  539. }
  540. tests := []struct {
  541. et mvccpb.Event_EventType
  542. isCreate bool
  543. isModify bool
  544. }{{
  545. et: clientv3.EventTypePut,
  546. isCreate: true,
  547. }, {
  548. et: clientv3.EventTypePut,
  549. isModify: true,
  550. }, {
  551. et: clientv3.EventTypeDelete,
  552. }, {
  553. et: clientv3.EventTypePut,
  554. isCreate: true,
  555. }, {
  556. et: clientv3.EventTypeDelete,
  557. }}
  558. var res []*clientv3.Event
  559. for {
  560. select {
  561. case wres := <-watchChan:
  562. res = append(res, wres.Events...)
  563. case <-time.After(10 * time.Second):
  564. t.Fatalf("Should receive %d events and then break out loop", len(tests))
  565. }
  566. if len(res) == len(tests) {
  567. break
  568. }
  569. }
  570. for i, tt := range tests {
  571. ev := res[i]
  572. if tt.et != ev.Type {
  573. t.Errorf("#%d: event type want=%s, get=%s", i, tt.et, ev.Type)
  574. }
  575. if tt.isCreate && !ev.IsCreate() {
  576. t.Errorf("#%d: event should be CreateEvent", i)
  577. }
  578. if tt.isModify && !ev.IsModify() {
  579. t.Errorf("#%d: event should be ModifyEvent", i)
  580. }
  581. }
  582. }
  583. func TestWatchErrConnClosed(t *testing.T) {
  584. defer testutil.AfterTest(t)
  585. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  586. defer clus.Terminate(t)
  587. cli := clus.Client(0)
  588. donec := make(chan struct{})
  589. go func() {
  590. defer close(donec)
  591. ch := cli.Watch(context.TODO(), "foo")
  592. if wr := <-ch; grpc.ErrorDesc(wr.Err()) != grpc.ErrClientConnClosing.Error() {
  593. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, grpc.ErrorDesc(wr.Err()))
  594. }
  595. }()
  596. if err := cli.ActiveConnection().Close(); err != nil {
  597. t.Fatal(err)
  598. }
  599. clus.TakeClient(0)
  600. select {
  601. case <-time.After(3 * time.Second):
  602. t.Fatal("wc.Watch took too long")
  603. case <-donec:
  604. }
  605. }
  606. func TestWatchAfterClose(t *testing.T) {
  607. defer testutil.AfterTest(t)
  608. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  609. defer clus.Terminate(t)
  610. cli := clus.Client(0)
  611. clus.TakeClient(0)
  612. if err := cli.Close(); err != nil {
  613. t.Fatal(err)
  614. }
  615. donec := make(chan struct{})
  616. go func() {
  617. cli.Watch(context.TODO(), "foo")
  618. if err := cli.Close(); err != nil && err != grpc.ErrClientConnClosing {
  619. t.Fatalf("expected %v, got %v", grpc.ErrClientConnClosing, err)
  620. }
  621. close(donec)
  622. }()
  623. select {
  624. case <-time.After(3 * time.Second):
  625. t.Fatal("wc.Watch took too long")
  626. case <-donec:
  627. }
  628. }
  629. // TestWatchWithRequireLeader checks the watch channel closes when no leader.
  630. func TestWatchWithRequireLeader(t *testing.T) {
  631. defer testutil.AfterTest(t)
  632. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 3})
  633. defer clus.Terminate(t)
  634. // Put a key for the non-require leader watch to read as an event.
  635. // The watchers will be on member[0]; put key through member[0] to
  636. // ensure that it receives the update so watching after killing quorum
  637. // is guaranteed to have the key.
  638. liveClient := clus.Client(0)
  639. if _, err := liveClient.Put(context.TODO(), "foo", "bar"); err != nil {
  640. t.Fatal(err)
  641. }
  642. clus.Members[1].Stop(t)
  643. clus.Members[2].Stop(t)
  644. clus.Client(1).Close()
  645. clus.Client(2).Close()
  646. clus.TakeClient(1)
  647. clus.TakeClient(2)
  648. // wait for election timeout, then member[0] will not have a leader.
  649. tickDuration := 10 * time.Millisecond
  650. // existing streams need three elections before they're torn down; wait until 5 elections cycle
  651. // so proxy tests receive a leader loss event on its existing watch before creating a new watch.
  652. time.Sleep(time.Duration(5*clus.Members[0].ElectionTicks) * tickDuration)
  653. chLeader := liveClient.Watch(clientv3.WithRequireLeader(context.TODO()), "foo", clientv3.WithRev(1))
  654. chNoLeader := liveClient.Watch(context.TODO(), "foo", clientv3.WithRev(1))
  655. select {
  656. case resp, ok := <-chLeader:
  657. if !ok {
  658. t.Fatalf("expected %v watch channel, got closed channel", rpctypes.ErrNoLeader)
  659. }
  660. if resp.Err() != rpctypes.ErrNoLeader {
  661. t.Fatalf("expected %v watch response error, got %+v", rpctypes.ErrNoLeader, resp)
  662. }
  663. case <-time.After(3 * time.Second):
  664. t.Fatal("watch without leader took too long to close")
  665. }
  666. select {
  667. case resp, ok := <-chLeader:
  668. if ok {
  669. t.Fatalf("expected closed channel, got response %v", resp)
  670. }
  671. case <-time.After(3 * time.Second):
  672. t.Fatal("waited too long for channel to close")
  673. }
  674. if _, ok := <-chNoLeader; !ok {
  675. t.Fatalf("expected response, got closed channel")
  676. }
  677. }
  678. // TestWatchWithFilter checks that watch filtering works.
  679. func TestWatchWithFilter(t *testing.T) {
  680. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  681. defer cluster.Terminate(t)
  682. client := cluster.RandClient()
  683. ctx := context.Background()
  684. wcNoPut := client.Watch(ctx, "a", clientv3.WithFilterPut())
  685. wcNoDel := client.Watch(ctx, "a", clientv3.WithFilterDelete())
  686. if _, err := client.Put(ctx, "a", "abc"); err != nil {
  687. t.Fatal(err)
  688. }
  689. if _, err := client.Delete(ctx, "a"); err != nil {
  690. t.Fatal(err)
  691. }
  692. npResp := <-wcNoPut
  693. if len(npResp.Events) != 1 || npResp.Events[0].Type != clientv3.EventTypeDelete {
  694. t.Fatalf("expected delete event, got %+v", npResp.Events)
  695. }
  696. ndResp := <-wcNoDel
  697. if len(ndResp.Events) != 1 || ndResp.Events[0].Type != clientv3.EventTypePut {
  698. t.Fatalf("expected put event, got %+v", ndResp.Events)
  699. }
  700. select {
  701. case resp := <-wcNoPut:
  702. t.Fatalf("unexpected event on filtered put (%+v)", resp)
  703. case resp := <-wcNoDel:
  704. t.Fatalf("unexpected event on filtered delete (%+v)", resp)
  705. case <-time.After(100 * time.Millisecond):
  706. }
  707. }
  708. // TestWatchWithCreatedNotification checks that createdNotification works.
  709. func TestWatchWithCreatedNotification(t *testing.T) {
  710. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  711. defer cluster.Terminate(t)
  712. client := cluster.RandClient()
  713. ctx := context.Background()
  714. createC := client.Watch(ctx, "a", clientv3.WithCreatedNotify())
  715. resp := <-createC
  716. if !resp.Created {
  717. t.Fatalf("expected created event, got %v", resp)
  718. }
  719. }
  720. // TestWatchWithCreatedNotificationDropConn ensures that
  721. // a watcher with created notify does not post duplicate
  722. // created events from disconnect.
  723. func TestWatchWithCreatedNotificationDropConn(t *testing.T) {
  724. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  725. defer cluster.Terminate(t)
  726. client := cluster.RandClient()
  727. wch := client.Watch(context.Background(), "a", clientv3.WithCreatedNotify())
  728. resp := <-wch
  729. if !resp.Created {
  730. t.Fatalf("expected created event, got %v", resp)
  731. }
  732. cluster.Members[0].DropConnections()
  733. // try to receive from watch channel again
  734. // ensure it doesn't post another createNotify
  735. select {
  736. case wresp := <-wch:
  737. t.Fatalf("got unexpected watch response: %+v\n", wresp)
  738. case <-time.After(time.Second):
  739. // watcher may not reconnect by the time it hits the select,
  740. // so it wouldn't have a chance to filter out the second create event
  741. }
  742. }
  743. // TestWatchCancelOnServer ensures client watcher cancels propagate back to the server.
  744. func TestWatchCancelOnServer(t *testing.T) {
  745. cluster := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  746. defer cluster.Terminate(t)
  747. client := cluster.RandClient()
  748. numWatches := 10
  749. cancels := make([]context.CancelFunc, numWatches)
  750. for i := 0; i < numWatches; i++ {
  751. // use WithTimeout to force separate streams in client
  752. ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  753. cancels[i] = cancel
  754. w := client.Watch(ctx, fmt.Sprintf("%d", i), clientv3.WithCreatedNotify())
  755. <-w
  756. }
  757. // get max watches; proxy tests have leadership watches, so total may be >numWatches
  758. maxWatches, _ := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  759. // cancel all and wait for cancels to propagate to etcd server
  760. for i := 0; i < numWatches; i++ {
  761. cancels[i]()
  762. }
  763. time.Sleep(time.Second)
  764. minWatches, err := cluster.Members[0].Metric("etcd_debugging_mvcc_watcher_total")
  765. if err != nil {
  766. t.Fatal(err)
  767. }
  768. maxWatchV, minWatchV := 0, 0
  769. n, serr := fmt.Sscanf(maxWatches+" "+minWatches, "%d %d", &maxWatchV, &minWatchV)
  770. if n != 2 || serr != nil {
  771. t.Fatalf("expected n=2 and err=nil, got n=%d and err=%v", n, serr)
  772. }
  773. if maxWatchV-minWatchV != numWatches {
  774. t.Fatalf("expected %d canceled watchers, got %d", numWatches, maxWatchV-minWatchV)
  775. }
  776. }
  777. // TestWatchOverlapContextCancel stresses the watcher stream teardown path by
  778. // creating/canceling watchers to ensure that new watchers are not taken down
  779. // by a torn down watch stream. The sort of race that's being detected:
  780. // 1. create w1 using a cancelable ctx with %v as "ctx"
  781. // 2. cancel ctx
  782. // 3. watcher client begins tearing down watcher grpc stream since no more watchers
  783. // 3. start creating watcher w2 using a new "ctx" (not canceled), attaches to old grpc stream
  784. // 4. watcher client finishes tearing down stream on "ctx"
  785. // 5. w2 comes back canceled
  786. func TestWatchOverlapContextCancel(t *testing.T) {
  787. f := func(clus *integration.ClusterV3) {}
  788. testWatchOverlapContextCancel(t, f)
  789. }
  790. func TestWatchOverlapDropConnContextCancel(t *testing.T) {
  791. f := func(clus *integration.ClusterV3) {
  792. clus.Members[0].DropConnections()
  793. }
  794. testWatchOverlapContextCancel(t, f)
  795. }
  796. func testWatchOverlapContextCancel(t *testing.T, f func(*integration.ClusterV3)) {
  797. defer testutil.AfterTest(t)
  798. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  799. defer clus.Terminate(t)
  800. // each unique context "%v" has a unique grpc stream
  801. n := 100
  802. ctxs, ctxc := make([]context.Context, 5), make([]chan struct{}, 5)
  803. for i := range ctxs {
  804. // make "%v" unique
  805. ctxs[i] = context.WithValue(context.TODO(), "key", i)
  806. // limits the maximum number of outstanding watchers per stream
  807. ctxc[i] = make(chan struct{}, 2)
  808. }
  809. // issue concurrent watches on "abc" with cancel
  810. cli := clus.RandClient()
  811. if _, err := cli.Put(context.TODO(), "abc", "def"); err != nil {
  812. t.Fatal(err)
  813. }
  814. ch := make(chan struct{}, n)
  815. for i := 0; i < n; i++ {
  816. go func() {
  817. defer func() { ch <- struct{}{} }()
  818. idx := rand.Intn(len(ctxs))
  819. ctx, cancel := context.WithCancel(ctxs[idx])
  820. ctxc[idx] <- struct{}{}
  821. wch := cli.Watch(ctx, "abc", clientv3.WithRev(1))
  822. f(clus)
  823. select {
  824. case _, ok := <-wch:
  825. if !ok {
  826. t.Fatalf("unexpected closed channel %p", wch)
  827. }
  828. // may take a second or two to reestablish a watcher because of
  829. // grpc backoff policies for disconnects
  830. case <-time.After(5 * time.Second):
  831. t.Errorf("timed out waiting for watch on %p", wch)
  832. }
  833. // randomize how cancel overlaps with watch creation
  834. if rand.Intn(2) == 0 {
  835. <-ctxc[idx]
  836. cancel()
  837. } else {
  838. cancel()
  839. <-ctxc[idx]
  840. }
  841. }()
  842. }
  843. // join on watches
  844. for i := 0; i < n; i++ {
  845. select {
  846. case <-ch:
  847. case <-time.After(5 * time.Second):
  848. t.Fatalf("timed out waiting for completed watch")
  849. }
  850. }
  851. }
  852. // TestWatchCanelAndCloseClient ensures that canceling a watcher then immediately
  853. // closing the client does not return a client closing error.
  854. func TestWatchCancelAndCloseClient(t *testing.T) {
  855. defer testutil.AfterTest(t)
  856. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  857. defer clus.Terminate(t)
  858. cli := clus.Client(0)
  859. ctx, cancel := context.WithCancel(context.Background())
  860. wch := cli.Watch(ctx, "abc")
  861. donec := make(chan struct{})
  862. go func() {
  863. defer close(donec)
  864. select {
  865. case wr, ok := <-wch:
  866. if ok {
  867. t.Fatalf("expected closed watch after cancel(), got resp=%+v err=%v", wr, wr.Err())
  868. }
  869. case <-time.After(5 * time.Second):
  870. t.Fatal("timed out waiting for closed channel")
  871. }
  872. }()
  873. cancel()
  874. if err := cli.Close(); err != nil {
  875. t.Fatal(err)
  876. }
  877. <-donec
  878. clus.TakeClient(0)
  879. }
  880. // TestWatchStressResumeClose establishes a bunch of watchers, disconnects
  881. // to put them in resuming mode, cancels them so some resumes by cancel fail,
  882. // then closes the watcher interface to ensure correct clean up.
  883. func TestWatchStressResumeClose(t *testing.T) {
  884. defer testutil.AfterTest(t)
  885. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  886. defer clus.Terminate(t)
  887. cli := clus.Client(0)
  888. ctx, cancel := context.WithCancel(context.Background())
  889. // add more watches than can be resumed before the cancel
  890. wchs := make([]clientv3.WatchChan, 2000)
  891. for i := range wchs {
  892. wchs[i] = cli.Watch(ctx, "abc")
  893. }
  894. clus.Members[0].DropConnections()
  895. cancel()
  896. if err := cli.Close(); err != nil {
  897. t.Fatal(err)
  898. }
  899. clus.TakeClient(0)
  900. }
  901. // TestWatchCancelDisconnected ensures canceling a watcher works when
  902. // its grpc stream is disconnected / reconnecting.
  903. func TestWatchCancelDisconnected(t *testing.T) {
  904. defer testutil.AfterTest(t)
  905. clus := integration.NewClusterV3(t, &integration.ClusterConfig{Size: 1})
  906. defer clus.Terminate(t)
  907. cli := clus.Client(0)
  908. ctx, cancel := context.WithCancel(context.Background())
  909. // add more watches than can be resumed before the cancel
  910. wch := cli.Watch(ctx, "abc")
  911. clus.Members[0].Stop(t)
  912. cancel()
  913. select {
  914. case <-wch:
  915. case <-time.After(time.Second):
  916. t.Fatal("took too long to cancel disconnected watcher")
  917. }
  918. }