v3_watch_test.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058
  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. "bytes"
  17. "fmt"
  18. "reflect"
  19. "sort"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  24. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  25. "github.com/coreos/etcd/mvcc/mvccpb"
  26. "github.com/coreos/etcd/pkg/testutil"
  27. "golang.org/x/net/context"
  28. )
  29. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  30. func TestV3WatchFromCurrentRevision(t *testing.T) {
  31. defer testutil.AfterTest(t)
  32. tests := []struct {
  33. putKeys []string
  34. watchRequest *pb.WatchRequest
  35. wresps []*pb.WatchResponse
  36. }{
  37. // watch the key, matching
  38. {
  39. []string{"foo"},
  40. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  41. CreateRequest: &pb.WatchCreateRequest{
  42. Key: []byte("foo")}}},
  43. []*pb.WatchResponse{
  44. {
  45. Header: &pb.ResponseHeader{Revision: 2},
  46. Created: false,
  47. Events: []*mvccpb.Event{
  48. {
  49. Type: mvccpb.PUT,
  50. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  51. },
  52. },
  53. },
  54. },
  55. },
  56. // watch the key, non-matching
  57. {
  58. []string{"foo"},
  59. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  60. CreateRequest: &pb.WatchCreateRequest{
  61. Key: []byte("helloworld")}}},
  62. []*pb.WatchResponse{},
  63. },
  64. // watch the prefix, matching
  65. {
  66. []string{"fooLong"},
  67. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  68. CreateRequest: &pb.WatchCreateRequest{
  69. Key: []byte("foo"),
  70. RangeEnd: []byte("fop")}}},
  71. []*pb.WatchResponse{
  72. {
  73. Header: &pb.ResponseHeader{Revision: 2},
  74. Created: false,
  75. Events: []*mvccpb.Event{
  76. {
  77. Type: mvccpb.PUT,
  78. Kv: &mvccpb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  79. },
  80. },
  81. },
  82. },
  83. },
  84. // watch the prefix, non-matching
  85. {
  86. []string{"foo"},
  87. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  88. CreateRequest: &pb.WatchCreateRequest{
  89. Key: []byte("helloworld"),
  90. RangeEnd: []byte("helloworle")}}},
  91. []*pb.WatchResponse{},
  92. },
  93. // watch full range, matching
  94. {
  95. []string{"fooLong"},
  96. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  97. CreateRequest: &pb.WatchCreateRequest{
  98. Key: []byte(""),
  99. RangeEnd: []byte("\x00")}}},
  100. []*pb.WatchResponse{
  101. {
  102. Header: &pb.ResponseHeader{Revision: 2},
  103. Created: false,
  104. Events: []*mvccpb.Event{
  105. {
  106. Type: mvccpb.PUT,
  107. Kv: &mvccpb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  108. },
  109. },
  110. },
  111. },
  112. },
  113. // multiple puts, one watcher with matching key
  114. {
  115. []string{"foo", "foo", "foo"},
  116. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  117. CreateRequest: &pb.WatchCreateRequest{
  118. Key: []byte("foo")}}},
  119. []*pb.WatchResponse{
  120. {
  121. Header: &pb.ResponseHeader{Revision: 2},
  122. Created: false,
  123. Events: []*mvccpb.Event{
  124. {
  125. Type: mvccpb.PUT,
  126. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  127. },
  128. },
  129. },
  130. {
  131. Header: &pb.ResponseHeader{Revision: 3},
  132. Created: false,
  133. Events: []*mvccpb.Event{
  134. {
  135. Type: mvccpb.PUT,
  136. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  137. },
  138. },
  139. },
  140. {
  141. Header: &pb.ResponseHeader{Revision: 4},
  142. Created: false,
  143. Events: []*mvccpb.Event{
  144. {
  145. Type: mvccpb.PUT,
  146. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  147. },
  148. },
  149. },
  150. },
  151. },
  152. // multiple puts, one watcher with matching prefix
  153. {
  154. []string{"foo", "foo", "foo"},
  155. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  156. CreateRequest: &pb.WatchCreateRequest{
  157. Key: []byte("foo"),
  158. RangeEnd: []byte("fop")}}},
  159. []*pb.WatchResponse{
  160. {
  161. Header: &pb.ResponseHeader{Revision: 2},
  162. Created: false,
  163. Events: []*mvccpb.Event{
  164. {
  165. Type: mvccpb.PUT,
  166. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  167. },
  168. },
  169. },
  170. {
  171. Header: &pb.ResponseHeader{Revision: 3},
  172. Created: false,
  173. Events: []*mvccpb.Event{
  174. {
  175. Type: mvccpb.PUT,
  176. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  177. },
  178. },
  179. },
  180. {
  181. Header: &pb.ResponseHeader{Revision: 4},
  182. Created: false,
  183. Events: []*mvccpb.Event{
  184. {
  185. Type: mvccpb.PUT,
  186. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  187. },
  188. },
  189. },
  190. },
  191. },
  192. }
  193. for i, tt := range tests {
  194. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  195. wAPI := toGRPC(clus.RandClient()).Watch
  196. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  197. defer cancel()
  198. wStream, err := wAPI.Watch(ctx)
  199. if err != nil {
  200. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  201. }
  202. err = wStream.Send(tt.watchRequest)
  203. if err != nil {
  204. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  205. }
  206. // ensure watcher request created a new watcher
  207. cresp, err := wStream.Recv()
  208. if err != nil {
  209. t.Errorf("#%d: wStream.Recv error: %v", i, err)
  210. continue
  211. }
  212. if !cresp.Created {
  213. t.Errorf("#%d: did not create watchid, got %+v", i, cresp)
  214. continue
  215. }
  216. if cresp.Canceled {
  217. t.Errorf("#%d: canceled watcher on create %+v", i, cresp)
  218. continue
  219. }
  220. createdWatchId := cresp.WatchId
  221. if cresp.Header == nil || cresp.Header.Revision != 1 {
  222. t.Errorf("#%d: header revision got +%v, wanted revison 1", i, cresp)
  223. continue
  224. }
  225. // asynchronously create keys
  226. go func() {
  227. for _, k := range tt.putKeys {
  228. kvc := toGRPC(clus.RandClient()).KV
  229. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  230. if _, err := kvc.Put(context.TODO(), req); err != nil {
  231. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  232. }
  233. }
  234. }()
  235. // check stream results
  236. for j, wresp := range tt.wresps {
  237. resp, err := wStream.Recv()
  238. if err != nil {
  239. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  240. }
  241. if resp.Header == nil {
  242. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  243. }
  244. if resp.Header.Revision != wresp.Header.Revision {
  245. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  246. }
  247. if wresp.Created != resp.Created {
  248. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  249. }
  250. if resp.WatchId != createdWatchId {
  251. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  252. }
  253. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  254. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  255. }
  256. }
  257. rok, nr := waitResponse(wStream, 1*time.Second)
  258. if !rok {
  259. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  260. }
  261. // can't defer because tcp ports will be in use
  262. clus.Terminate(t)
  263. }
  264. }
  265. // TestV3WatchFutureRevision tests Watch APIs from a future revision.
  266. func TestV3WatchFutureRevision(t *testing.T) {
  267. defer testutil.AfterTest(t)
  268. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  269. defer clus.Terminate(t)
  270. wAPI := toGRPC(clus.RandClient()).Watch
  271. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  272. defer cancel()
  273. wStream, err := wAPI.Watch(ctx)
  274. if err != nil {
  275. t.Fatalf("wAPI.Watch error: %v", err)
  276. }
  277. wkey := []byte("foo")
  278. wrev := int64(10)
  279. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  280. CreateRequest: &pb.WatchCreateRequest{Key: wkey, StartRevision: wrev}}}
  281. err = wStream.Send(req)
  282. if err != nil {
  283. t.Fatalf("wStream.Send error: %v", err)
  284. }
  285. // ensure watcher request created a new watcher
  286. cresp, err := wStream.Recv()
  287. if err != nil {
  288. t.Fatalf("wStream.Recv error: %v", err)
  289. }
  290. if !cresp.Created {
  291. t.Fatalf("create %v, want %v", cresp.Created, true)
  292. }
  293. kvc := toGRPC(clus.RandClient()).KV
  294. for {
  295. req := &pb.PutRequest{Key: wkey, Value: []byte("bar")}
  296. resp, rerr := kvc.Put(context.TODO(), req)
  297. if rerr != nil {
  298. t.Fatalf("couldn't put key (%v)", rerr)
  299. }
  300. if resp.Header.Revision == wrev {
  301. break
  302. }
  303. }
  304. // ensure watcher request created a new watcher
  305. cresp, err = wStream.Recv()
  306. if err != nil {
  307. t.Fatalf("wStream.Recv error: %v", err)
  308. }
  309. if cresp.Header.Revision != wrev {
  310. t.Fatalf("revision = %d, want %d", cresp.Header.Revision, wrev)
  311. }
  312. if len(cresp.Events) != 1 {
  313. t.Fatalf("failed to receive events")
  314. }
  315. if cresp.Events[0].Kv.ModRevision != wrev {
  316. t.Errorf("mod revision = %d, want %d", cresp.Events[0].Kv.ModRevision, wrev)
  317. }
  318. }
  319. // TestV3WatchWrongRange tests wrong range does not create watchers.
  320. func TestV3WatchWrongRange(t *testing.T) {
  321. defer testutil.AfterTest(t)
  322. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  323. defer clus.Terminate(t)
  324. wAPI := toGRPC(clus.RandClient()).Watch
  325. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  326. defer cancel()
  327. wStream, err := wAPI.Watch(ctx)
  328. if err != nil {
  329. t.Fatalf("wAPI.Watch error: %v", err)
  330. }
  331. tests := []struct {
  332. key []byte
  333. end []byte
  334. canceled bool
  335. }{
  336. {[]byte("a"), []byte("a"), true}, // wrong range end
  337. {[]byte("b"), []byte("a"), true}, // wrong range end
  338. {[]byte("foo"), []byte{0}, false}, // watch request with 'WithFromKey'
  339. }
  340. for i, tt := range tests {
  341. if err := wStream.Send(&pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  342. CreateRequest: &pb.WatchCreateRequest{Key: tt.key, RangeEnd: tt.end, StartRevision: 1}}}); err != nil {
  343. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  344. }
  345. cresp, err := wStream.Recv()
  346. if err != nil {
  347. t.Fatalf("#%d: wStream.Recv error: %v", i, err)
  348. }
  349. if !cresp.Created {
  350. t.Fatalf("#%d: create %v, want %v", i, cresp.Created, true)
  351. }
  352. if cresp.Canceled != tt.canceled {
  353. t.Fatalf("#%d: canceled %v, want %v", i, tt.canceled, cresp.Canceled)
  354. }
  355. if tt.canceled && cresp.WatchId != -1 {
  356. t.Fatalf("#%d: canceled watch ID %d, want -1", i, cresp.WatchId)
  357. }
  358. }
  359. }
  360. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  361. func TestV3WatchCancelSynced(t *testing.T) {
  362. defer testutil.AfterTest(t)
  363. testV3WatchCancel(t, 0)
  364. }
  365. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  366. func TestV3WatchCancelUnsynced(t *testing.T) {
  367. defer testutil.AfterTest(t)
  368. testV3WatchCancel(t, 1)
  369. }
  370. func testV3WatchCancel(t *testing.T, startRev int64) {
  371. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  372. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  373. defer cancel()
  374. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  375. if errW != nil {
  376. t.Fatalf("wAPI.Watch error: %v", errW)
  377. }
  378. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  379. CreateRequest: &pb.WatchCreateRequest{
  380. Key: []byte("foo"), StartRevision: startRev}}}
  381. if err := wStream.Send(wreq); err != nil {
  382. t.Fatalf("wStream.Send error: %v", err)
  383. }
  384. wresp, errR := wStream.Recv()
  385. if errR != nil {
  386. t.Errorf("wStream.Recv error: %v", errR)
  387. }
  388. if !wresp.Created {
  389. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  390. }
  391. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  392. CancelRequest: &pb.WatchCancelRequest{
  393. WatchId: wresp.WatchId}}}
  394. if err := wStream.Send(creq); err != nil {
  395. t.Fatalf("wStream.Send error: %v", err)
  396. }
  397. cresp, err := wStream.Recv()
  398. if err != nil {
  399. t.Errorf("wStream.Recv error: %v", err)
  400. }
  401. if !cresp.Canceled {
  402. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  403. }
  404. kvc := toGRPC(clus.RandClient()).KV
  405. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  406. t.Errorf("couldn't put key (%v)", err)
  407. }
  408. // watch got canceled, so this should block
  409. rok, nr := waitResponse(wStream, 1*time.Second)
  410. if !rok {
  411. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  412. }
  413. clus.Terminate(t)
  414. }
  415. // TestV3WatchCurrentPutOverlap ensures current watchers receive all events with
  416. // overlapping puts.
  417. func TestV3WatchCurrentPutOverlap(t *testing.T) {
  418. defer testutil.AfterTest(t)
  419. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  420. defer clus.Terminate(t)
  421. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  422. defer cancel()
  423. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  424. if wErr != nil {
  425. t.Fatalf("wAPI.Watch error: %v", wErr)
  426. }
  427. // last mod_revision that will be observed
  428. nrRevisions := 32
  429. // first revision already allocated as empty revision
  430. for i := 1; i < nrRevisions; i++ {
  431. go func() {
  432. kvc := toGRPC(clus.RandClient()).KV
  433. req := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  434. if _, err := kvc.Put(context.TODO(), req); err != nil {
  435. t.Fatalf("couldn't put key (%v)", err)
  436. }
  437. }()
  438. }
  439. // maps watcher to current expected revision
  440. progress := make(map[int64]int64)
  441. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  442. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), RangeEnd: []byte("fop")}}}
  443. if err := wStream.Send(wreq); err != nil {
  444. t.Fatalf("first watch request failed (%v)", err)
  445. }
  446. more := true
  447. progress[-1] = 0 // watcher creation pending
  448. for more {
  449. resp, err := wStream.Recv()
  450. if err != nil {
  451. t.Fatalf("wStream.Recv error: %v", err)
  452. }
  453. if resp.Created {
  454. // accept events > header revision
  455. progress[resp.WatchId] = resp.Header.Revision + 1
  456. if resp.Header.Revision == int64(nrRevisions) {
  457. // covered all revisions; create no more watchers
  458. progress[-1] = int64(nrRevisions) + 1
  459. } else if err := wStream.Send(wreq); err != nil {
  460. t.Fatalf("watch request failed (%v)", err)
  461. }
  462. } else if len(resp.Events) == 0 {
  463. t.Fatalf("got events %v, want non-empty", resp.Events)
  464. } else {
  465. wRev, ok := progress[resp.WatchId]
  466. if !ok {
  467. t.Fatalf("got %+v, but watch id shouldn't exist ", resp)
  468. }
  469. if resp.Events[0].Kv.ModRevision != wRev {
  470. t.Fatalf("got %+v, wanted first revision %d", resp, wRev)
  471. }
  472. lastRev := resp.Events[len(resp.Events)-1].Kv.ModRevision
  473. progress[resp.WatchId] = lastRev + 1
  474. }
  475. more = false
  476. for _, v := range progress {
  477. if v <= int64(nrRevisions) {
  478. more = true
  479. break
  480. }
  481. }
  482. }
  483. if rok, nr := waitResponse(wStream, time.Second); !rok {
  484. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  485. }
  486. }
  487. // TestV3WatchEmptyKey ensures synced watchers see empty key PUTs as PUT events
  488. func TestV3WatchEmptyKey(t *testing.T) {
  489. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  490. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  491. defer cancel()
  492. ws, werr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  493. if werr != nil {
  494. t.Fatal(werr)
  495. }
  496. req := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  497. CreateRequest: &pb.WatchCreateRequest{
  498. Key: []byte("foo")}}}
  499. if err := ws.Send(req); err != nil {
  500. t.Fatal(err)
  501. }
  502. if _, err := ws.Recv(); err != nil {
  503. t.Fatal(err)
  504. }
  505. // put a key with empty value
  506. kvc := toGRPC(clus.RandClient()).KV
  507. preq := &pb.PutRequest{Key: []byte("foo")}
  508. if _, err := kvc.Put(context.TODO(), preq); err != nil {
  509. t.Fatal(err)
  510. }
  511. // check received PUT
  512. resp, rerr := ws.Recv()
  513. if rerr != nil {
  514. t.Fatal(rerr)
  515. }
  516. wevs := []*mvccpb.Event{
  517. {
  518. Type: mvccpb.PUT,
  519. Kv: &mvccpb.KeyValue{Key: []byte("foo"), CreateRevision: 2, ModRevision: 2, Version: 1},
  520. },
  521. }
  522. if !reflect.DeepEqual(resp.Events, wevs) {
  523. t.Fatalf("got %v, expected %v", resp.Events, wevs)
  524. }
  525. clus.Terminate(t)
  526. }
  527. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  528. defer testutil.AfterTest(t)
  529. testV3WatchMultipleWatchers(t, 0)
  530. }
  531. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  532. defer testutil.AfterTest(t)
  533. testV3WatchMultipleWatchers(t, 1)
  534. }
  535. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  536. // and one watcher with matching prefix. It first puts the key
  537. // that matches all watchers, and another key that matches only
  538. // one watcher to test if it receives expected events.
  539. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  540. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  541. kvc := toGRPC(clus.RandClient()).KV
  542. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  543. defer cancel()
  544. wStream, errW := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  545. if errW != nil {
  546. t.Fatalf("wAPI.Watch error: %v", errW)
  547. }
  548. watchKeyN := 4
  549. for i := 0; i < watchKeyN+1; i++ {
  550. var wreq *pb.WatchRequest
  551. if i < watchKeyN {
  552. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  553. CreateRequest: &pb.WatchCreateRequest{
  554. Key: []byte("foo"), StartRevision: startRev}}}
  555. } else {
  556. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  557. CreateRequest: &pb.WatchCreateRequest{
  558. Key: []byte("fo"), RangeEnd: []byte("fp"), StartRevision: startRev}}}
  559. }
  560. if err := wStream.Send(wreq); err != nil {
  561. t.Fatalf("wStream.Send error: %v", err)
  562. }
  563. }
  564. ids := make(map[int64]struct{})
  565. for i := 0; i < watchKeyN+1; i++ {
  566. wresp, err := wStream.Recv()
  567. if err != nil {
  568. t.Fatalf("wStream.Recv error: %v", err)
  569. }
  570. if !wresp.Created {
  571. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  572. }
  573. ids[wresp.WatchId] = struct{}{}
  574. }
  575. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  576. t.Fatalf("couldn't put key (%v)", err)
  577. }
  578. for i := 0; i < watchKeyN+1; i++ {
  579. wresp, err := wStream.Recv()
  580. if err != nil {
  581. t.Fatalf("wStream.Recv error: %v", err)
  582. }
  583. if _, ok := ids[wresp.WatchId]; !ok {
  584. t.Errorf("watchId %d is not created!", wresp.WatchId)
  585. } else {
  586. delete(ids, wresp.WatchId)
  587. }
  588. if len(wresp.Events) == 0 {
  589. t.Errorf("#%d: no events received", i)
  590. }
  591. for _, ev := range wresp.Events {
  592. if string(ev.Kv.Key) != "foo" {
  593. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  594. }
  595. if string(ev.Kv.Value) != "bar" {
  596. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  597. }
  598. }
  599. }
  600. // now put one key that has only one matching watcher
  601. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  602. t.Fatalf("couldn't put key (%v)", err)
  603. }
  604. wresp, err := wStream.Recv()
  605. if err != nil {
  606. t.Errorf("wStream.Recv error: %v", err)
  607. }
  608. if len(wresp.Events) != 1 {
  609. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  610. }
  611. if string(wresp.Events[0].Kv.Key) != "fo" {
  612. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  613. }
  614. // now Recv should block because there is no more events coming
  615. rok, nr := waitResponse(wStream, 1*time.Second)
  616. if !rok {
  617. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  618. }
  619. clus.Terminate(t)
  620. }
  621. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  622. defer testutil.AfterTest(t)
  623. testV3WatchMultipleEventsTxn(t, 0)
  624. }
  625. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  626. defer testutil.AfterTest(t)
  627. testV3WatchMultipleEventsTxn(t, 1)
  628. }
  629. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  630. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  631. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  632. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  633. defer cancel()
  634. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  635. if wErr != nil {
  636. t.Fatalf("wAPI.Watch error: %v", wErr)
  637. }
  638. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  639. CreateRequest: &pb.WatchCreateRequest{
  640. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: startRev}}}
  641. if err := wStream.Send(wreq); err != nil {
  642. t.Fatalf("wStream.Send error: %v", err)
  643. }
  644. kvc := toGRPC(clus.RandClient()).KV
  645. txn := pb.TxnRequest{}
  646. for i := 0; i < 3; i++ {
  647. ru := &pb.RequestOp{}
  648. ru.Request = &pb.RequestOp_RequestPut{
  649. RequestPut: &pb.PutRequest{
  650. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  651. txn.Success = append(txn.Success, ru)
  652. }
  653. tresp, err := kvc.Txn(context.Background(), &txn)
  654. if err != nil {
  655. t.Fatalf("kvc.Txn error: %v", err)
  656. }
  657. if !tresp.Succeeded {
  658. t.Fatalf("kvc.Txn failed: %+v", tresp)
  659. }
  660. events := []*mvccpb.Event{}
  661. for len(events) < 3 {
  662. resp, err := wStream.Recv()
  663. if err != nil {
  664. t.Errorf("wStream.Recv error: %v", err)
  665. }
  666. if resp.Created {
  667. continue
  668. }
  669. events = append(events, resp.Events...)
  670. }
  671. sort.Sort(eventsSortByKey(events))
  672. wevents := []*mvccpb.Event{
  673. {
  674. Type: mvccpb.PUT,
  675. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  676. },
  677. {
  678. Type: mvccpb.PUT,
  679. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  680. },
  681. {
  682. Type: mvccpb.PUT,
  683. Kv: &mvccpb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  684. },
  685. }
  686. if !reflect.DeepEqual(events, wevents) {
  687. t.Errorf("events got = %+v, want = %+v", events, wevents)
  688. }
  689. rok, nr := waitResponse(wStream, 1*time.Second)
  690. if !rok {
  691. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  692. }
  693. // can't defer because tcp ports will be in use
  694. clus.Terminate(t)
  695. }
  696. type eventsSortByKey []*mvccpb.Event
  697. func (evs eventsSortByKey) Len() int { return len(evs) }
  698. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  699. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  700. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  701. defer testutil.AfterTest(t)
  702. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  703. defer clus.Terminate(t)
  704. kvc := toGRPC(clus.RandClient()).KV
  705. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  706. t.Fatalf("couldn't put key (%v)", err)
  707. }
  708. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  709. t.Fatalf("couldn't put key (%v)", err)
  710. }
  711. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  712. defer cancel()
  713. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  714. if wErr != nil {
  715. t.Fatalf("wAPI.Watch error: %v", wErr)
  716. }
  717. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  718. CreateRequest: &pb.WatchCreateRequest{
  719. Key: []byte("foo"), RangeEnd: []byte("fop"), StartRevision: 1}}}
  720. if err := wStream.Send(wreq); err != nil {
  721. t.Fatalf("wStream.Send error: %v", err)
  722. }
  723. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  724. t.Fatalf("couldn't put key (%v)", err)
  725. }
  726. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  727. t.Fatalf("couldn't put key (%v)", err)
  728. }
  729. allWevents := []*mvccpb.Event{
  730. {
  731. Type: mvccpb.PUT,
  732. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  733. },
  734. {
  735. Type: mvccpb.PUT,
  736. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  737. },
  738. {
  739. Type: mvccpb.PUT,
  740. Kv: &mvccpb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  741. },
  742. {
  743. Type: mvccpb.PUT,
  744. Kv: &mvccpb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  745. },
  746. }
  747. events := []*mvccpb.Event{}
  748. for len(events) < 4 {
  749. resp, err := wStream.Recv()
  750. if err != nil {
  751. t.Errorf("wStream.Recv error: %v", err)
  752. }
  753. if resp.Created {
  754. continue
  755. }
  756. events = append(events, resp.Events...)
  757. // if PUT requests are committed by now, first receive would return
  758. // multiple events, but if not, it returns a single event. In SSD,
  759. // it should return 4 events at once.
  760. }
  761. if !reflect.DeepEqual(events, allWevents) {
  762. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  763. }
  764. rok, nr := waitResponse(wStream, 1*time.Second)
  765. if !rok {
  766. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  767. }
  768. }
  769. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  770. defer testutil.AfterTest(t)
  771. testV3WatchMultipleStreams(t, 0)
  772. }
  773. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  774. defer testutil.AfterTest(t)
  775. testV3WatchMultipleStreams(t, 1)
  776. }
  777. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  778. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  779. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  780. wAPI := toGRPC(clus.RandClient()).Watch
  781. kvc := toGRPC(clus.RandClient()).KV
  782. streams := make([]pb.Watch_WatchClient, 5)
  783. for i := range streams {
  784. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  785. defer cancel()
  786. wStream, errW := wAPI.Watch(ctx)
  787. if errW != nil {
  788. t.Fatalf("wAPI.Watch error: %v", errW)
  789. }
  790. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  791. CreateRequest: &pb.WatchCreateRequest{
  792. Key: []byte("foo"), StartRevision: startRev}}}
  793. if err := wStream.Send(wreq); err != nil {
  794. t.Fatalf("wStream.Send error: %v", err)
  795. }
  796. streams[i] = wStream
  797. }
  798. for _, wStream := range streams {
  799. wresp, err := wStream.Recv()
  800. if err != nil {
  801. t.Fatalf("wStream.Recv error: %v", err)
  802. }
  803. if !wresp.Created {
  804. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  805. }
  806. }
  807. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  808. t.Fatalf("couldn't put key (%v)", err)
  809. }
  810. var wg sync.WaitGroup
  811. wg.Add(len(streams))
  812. wevents := []*mvccpb.Event{
  813. {
  814. Type: mvccpb.PUT,
  815. Kv: &mvccpb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  816. },
  817. }
  818. for i := range streams {
  819. go func(i int) {
  820. defer wg.Done()
  821. wStream := streams[i]
  822. wresp, err := wStream.Recv()
  823. if err != nil {
  824. t.Fatalf("wStream.Recv error: %v", err)
  825. }
  826. if wresp.WatchId != 0 {
  827. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  828. }
  829. if !reflect.DeepEqual(wresp.Events, wevents) {
  830. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  831. }
  832. // now Recv should block because there is no more events coming
  833. rok, nr := waitResponse(wStream, 1*time.Second)
  834. if !rok {
  835. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  836. }
  837. }(i)
  838. }
  839. wg.Wait()
  840. clus.Terminate(t)
  841. }
  842. // waitResponse waits on the given stream for given duration.
  843. // If there is no more events, true and a nil response will be
  844. // returned closing the WatchClient stream. Or the response will
  845. // be returned.
  846. func waitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  847. rCh := make(chan *pb.WatchResponse)
  848. go func() {
  849. resp, _ := wc.Recv()
  850. rCh <- resp
  851. }()
  852. select {
  853. case nr := <-rCh:
  854. return false, nr
  855. case <-time.After(timeout):
  856. }
  857. wc.CloseSend()
  858. rv, ok := <-rCh
  859. if rv != nil || !ok {
  860. return false, rv
  861. }
  862. return true, nil
  863. }
  864. func TestWatchWithProgressNotify(t *testing.T) {
  865. // accelerate report interval so test terminates quickly
  866. oldpi := v3rpc.GetProgressReportInterval()
  867. // using atomics to avoid race warnings
  868. v3rpc.SetProgressReportInterval(3 * time.Second)
  869. testInterval := 3 * time.Second
  870. defer func() { v3rpc.SetProgressReportInterval(oldpi) }()
  871. defer testutil.AfterTest(t)
  872. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  873. defer clus.Terminate(t)
  874. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  875. defer cancel()
  876. wStream, wErr := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  877. if wErr != nil {
  878. t.Fatalf("wAPI.Watch error: %v", wErr)
  879. }
  880. // create two watchers, one with progressNotify set.
  881. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  882. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1, ProgressNotify: true}}}
  883. if err := wStream.Send(wreq); err != nil {
  884. t.Fatalf("watch request failed (%v)", err)
  885. }
  886. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  887. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo"), StartRevision: 1}}}
  888. if err := wStream.Send(wreq); err != nil {
  889. t.Fatalf("watch request failed (%v)", err)
  890. }
  891. // two creation + one notification
  892. for i := 0; i < 3; i++ {
  893. rok, resp := waitResponse(wStream, testInterval+time.Second)
  894. if resp.Created {
  895. continue
  896. }
  897. if rok {
  898. t.Errorf("failed to receive response from watch stream")
  899. }
  900. if resp.Header.Revision != 1 {
  901. t.Errorf("revision = %d, want 1", resp.Header.Revision)
  902. }
  903. if len(resp.Events) != 0 {
  904. t.Errorf("len(resp.Events) = %d, want 0", len(resp.Events))
  905. }
  906. }
  907. // no more notification
  908. rok, resp := waitResponse(wStream, time.Second)
  909. if !rok {
  910. t.Errorf("unexpected pb.WatchResponse is received %+v", resp)
  911. }
  912. }
  913. // TestV3WatcMultiOpenhClose opens many watchers concurrently on multiple streams.
  914. func TestV3WatchClose(t *testing.T) {
  915. defer testutil.AfterTest(t)
  916. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  917. defer clus.Terminate(t)
  918. c := clus.Client(0)
  919. wapi := toGRPC(c).Watch
  920. var wg sync.WaitGroup
  921. wg.Add(100)
  922. for i := 0; i < 100; i++ {
  923. go func() {
  924. ctx, cancel := context.WithCancel(context.TODO())
  925. defer func() {
  926. wg.Done()
  927. cancel()
  928. }()
  929. ws, err := wapi.Watch(ctx)
  930. if err != nil {
  931. return
  932. }
  933. cr := &pb.WatchCreateRequest{Key: []byte("a")}
  934. req := &pb.WatchRequest{
  935. RequestUnion: &pb.WatchRequest_CreateRequest{
  936. CreateRequest: cr}}
  937. ws.Send(req)
  938. ws.Recv()
  939. }()
  940. }
  941. clus.Members[0].DropConnections()
  942. wg.Wait()
  943. }