v3_watch_test.go 23 KB

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