v3_watch_test.go 24 KB

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