v3_watch_test.go 22 KB

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