v3_watch_test.go 27 KB

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