v3_grpc_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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. "math/rand"
  19. "reflect"
  20. "sort"
  21. "sync"
  22. "testing"
  23. "time"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  25. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  26. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/storage/storagepb"
  28. )
  29. type clusterV3 struct {
  30. *cluster
  31. conns []*grpc.ClientConn
  32. }
  33. // newClusterGRPC returns a launched cluster with a grpc client connection
  34. // for each cluster member.
  35. func newClusterGRPC(t *testing.T, cfg *clusterConfig) *clusterV3 {
  36. cfg.useV3 = true
  37. cfg.useGRPC = true
  38. clus := &clusterV3{cluster: NewClusterByConfig(t, cfg)}
  39. for _, m := range clus.Members {
  40. conn, err := NewGRPCClient(m)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. clus.conns = append(clus.conns, conn)
  45. }
  46. clus.Launch(t)
  47. return clus
  48. }
  49. func (c *clusterV3) Terminate(t *testing.T) {
  50. for _, conn := range c.conns {
  51. if err := conn.Close(); err != nil {
  52. t.Error(err)
  53. }
  54. }
  55. c.cluster.Terminate(t)
  56. }
  57. func (c *clusterV3) RandConn() *grpc.ClientConn {
  58. return c.conns[rand.Intn(len(c.conns))]
  59. }
  60. // TestV3PutOverwrite puts a key with the v3 api to a random cluster member,
  61. // overwrites it, then checks that the change was applied.
  62. func TestV3PutOverwrite(t *testing.T) {
  63. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  64. defer clus.Terminate(t)
  65. kvc := pb.NewKVClient(clus.RandConn())
  66. key := []byte("foo")
  67. reqput := &pb.PutRequest{Key: key, Value: []byte("bar")}
  68. respput, err := kvc.Put(context.TODO(), reqput)
  69. if err != nil {
  70. t.Fatalf("couldn't put key (%v)", err)
  71. }
  72. // overwrite
  73. reqput.Value = []byte("baz")
  74. respput2, err := kvc.Put(context.TODO(), reqput)
  75. if err != nil {
  76. t.Fatalf("couldn't put key (%v)", err)
  77. }
  78. if respput2.Header.Revision <= respput.Header.Revision {
  79. t.Fatalf("expected newer revision on overwrite, got %v <= %v",
  80. respput2.Header.Revision, respput.Header.Revision)
  81. }
  82. reqrange := &pb.RangeRequest{Key: key}
  83. resprange, err := kvc.Range(context.TODO(), reqrange)
  84. if err != nil {
  85. t.Fatalf("couldn't get key (%v)", err)
  86. }
  87. if len(resprange.Kvs) != 1 {
  88. t.Fatalf("expected 1 key, got %v", len(resprange.Kvs))
  89. }
  90. kv := resprange.Kvs[0]
  91. if kv.ModRevision <= kv.CreateRevision {
  92. t.Errorf("expected modRev > createRev, got %d <= %d",
  93. kv.ModRevision, kv.CreateRevision)
  94. }
  95. if !reflect.DeepEqual(reqput.Value, kv.Value) {
  96. t.Errorf("expected value %v, got %v", reqput.Value, kv.Value)
  97. }
  98. }
  99. // TestV3DeleteRange tests various edge cases in the DeleteRange API.
  100. func TestV3DeleteRange(t *testing.T) {
  101. tests := []struct {
  102. keySet []string
  103. begin string
  104. end string
  105. wantSet [][]byte
  106. }{
  107. // delete middle
  108. {
  109. []string{"foo", "foo/abc", "fop"},
  110. "foo/", "fop",
  111. [][]byte{[]byte("foo"), []byte("fop")},
  112. },
  113. // no delete
  114. {
  115. []string{"foo", "foo/abc", "fop"},
  116. "foo/", "foo/",
  117. [][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")},
  118. },
  119. // delete first
  120. {
  121. []string{"foo", "foo/abc", "fop"},
  122. "fo", "fop",
  123. [][]byte{[]byte("fop")},
  124. },
  125. // delete tail
  126. {
  127. []string{"foo", "foo/abc", "fop"},
  128. "foo/", "fos",
  129. [][]byte{[]byte("foo")},
  130. },
  131. // delete exact
  132. {
  133. []string{"foo", "foo/abc", "fop"},
  134. "foo/abc", "",
  135. [][]byte{[]byte("foo"), []byte("fop")},
  136. },
  137. // delete none, [x,x)
  138. {
  139. []string{"foo"},
  140. "foo", "foo",
  141. [][]byte{[]byte("foo")},
  142. },
  143. }
  144. for i, tt := range tests {
  145. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  146. kvc := pb.NewKVClient(clus.RandConn())
  147. ks := tt.keySet
  148. for j := range ks {
  149. reqput := &pb.PutRequest{Key: []byte(ks[j]), Value: []byte{}}
  150. _, err := kvc.Put(context.TODO(), reqput)
  151. if err != nil {
  152. t.Fatalf("couldn't put key (%v)", err)
  153. }
  154. }
  155. dreq := &pb.DeleteRangeRequest{
  156. Key: []byte(tt.begin),
  157. RangeEnd: []byte(tt.end)}
  158. dresp, err := kvc.DeleteRange(context.TODO(), dreq)
  159. if err != nil {
  160. t.Fatalf("couldn't delete range on test %d (%v)", i, err)
  161. }
  162. rreq := &pb.RangeRequest{Key: []byte{0x0}, RangeEnd: []byte{0xff}}
  163. rresp, err := kvc.Range(context.TODO(), rreq)
  164. if err != nil {
  165. t.Errorf("couldn't get range on test %v (%v)", i, err)
  166. }
  167. if dresp.Header.Revision != rresp.Header.Revision {
  168. t.Errorf("expected revision %v, got %v",
  169. dresp.Header.Revision, rresp.Header.Revision)
  170. }
  171. keys := [][]byte{}
  172. for j := range rresp.Kvs {
  173. keys = append(keys, rresp.Kvs[j].Key)
  174. }
  175. if reflect.DeepEqual(tt.wantSet, keys) == false {
  176. t.Errorf("expected %v on test %v, got %v", tt.wantSet, i, keys)
  177. }
  178. // can't defer because tcp ports will be in use
  179. clus.Terminate(t)
  180. }
  181. }
  182. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  183. func TestV3WatchFromCurrentRevision(t *testing.T) {
  184. tests := []struct {
  185. putKeys []string
  186. watchRequest *pb.WatchRequest
  187. wresps []*pb.WatchResponse
  188. }{
  189. // watch the key, matching
  190. {
  191. []string{"foo"},
  192. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")}},
  193. []*pb.WatchResponse{
  194. {
  195. Header: &pb.ResponseHeader{Revision: 1},
  196. Created: true,
  197. },
  198. {
  199. Header: &pb.ResponseHeader{Revision: 2},
  200. Created: false,
  201. Events: []*storagepb.Event{
  202. {
  203. Type: storagepb.PUT,
  204. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  205. },
  206. },
  207. },
  208. },
  209. },
  210. // watch the key, non-matching
  211. {
  212. []string{"foo"},
  213. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("helloworld")}},
  214. []*pb.WatchResponse{
  215. {
  216. Header: &pb.ResponseHeader{Revision: 1},
  217. Created: true,
  218. },
  219. },
  220. },
  221. // watch the prefix, matching
  222. {
  223. []string{"fooLong"},
  224. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Prefix: []byte("foo")}},
  225. []*pb.WatchResponse{
  226. {
  227. Header: &pb.ResponseHeader{Revision: 1},
  228. Created: true,
  229. },
  230. {
  231. Header: &pb.ResponseHeader{Revision: 2},
  232. Created: false,
  233. Events: []*storagepb.Event{
  234. {
  235. Type: storagepb.PUT,
  236. Kv: &storagepb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  237. },
  238. },
  239. },
  240. },
  241. },
  242. // watch the prefix, non-matching
  243. {
  244. []string{"foo"},
  245. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Prefix: []byte("helloworld")}},
  246. []*pb.WatchResponse{
  247. {
  248. Header: &pb.ResponseHeader{Revision: 1},
  249. Created: true,
  250. },
  251. },
  252. },
  253. // multiple puts, one watcher with matching key
  254. {
  255. []string{"foo", "foo", "foo"},
  256. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")}},
  257. []*pb.WatchResponse{
  258. {
  259. Header: &pb.ResponseHeader{Revision: 1},
  260. Created: true,
  261. },
  262. {
  263. Header: &pb.ResponseHeader{Revision: 2},
  264. Created: false,
  265. Events: []*storagepb.Event{
  266. {
  267. Type: storagepb.PUT,
  268. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  269. },
  270. },
  271. },
  272. {
  273. Header: &pb.ResponseHeader{Revision: 3},
  274. Created: false,
  275. Events: []*storagepb.Event{
  276. {
  277. Type: storagepb.PUT,
  278. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  279. },
  280. },
  281. },
  282. {
  283. Header: &pb.ResponseHeader{Revision: 4},
  284. Created: false,
  285. Events: []*storagepb.Event{
  286. {
  287. Type: storagepb.PUT,
  288. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  289. },
  290. },
  291. },
  292. },
  293. },
  294. // multiple puts, one watcher with matching prefix
  295. {
  296. []string{"foo", "foo", "foo"},
  297. &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Prefix: []byte("foo")}},
  298. []*pb.WatchResponse{
  299. {
  300. Header: &pb.ResponseHeader{Revision: 1},
  301. Created: true,
  302. },
  303. {
  304. Header: &pb.ResponseHeader{Revision: 2},
  305. Created: false,
  306. Events: []*storagepb.Event{
  307. {
  308. Type: storagepb.PUT,
  309. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  310. },
  311. },
  312. },
  313. {
  314. Header: &pb.ResponseHeader{Revision: 3},
  315. Created: false,
  316. Events: []*storagepb.Event{
  317. {
  318. Type: storagepb.PUT,
  319. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  320. },
  321. },
  322. },
  323. {
  324. Header: &pb.ResponseHeader{Revision: 4},
  325. Created: false,
  326. Events: []*storagepb.Event{
  327. {
  328. Type: storagepb.PUT,
  329. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  330. },
  331. },
  332. },
  333. },
  334. },
  335. // TODO: watch and receive multiple-events from synced (need Txn)
  336. }
  337. for i, tt := range tests {
  338. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  339. wAPI := pb.NewWatchClient(clus.RandConn())
  340. wStream, err := wAPI.Watch(context.TODO())
  341. if err != nil {
  342. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  343. }
  344. if err := wStream.Send(tt.watchRequest); err != nil {
  345. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  346. }
  347. go func() {
  348. for _, k := range tt.putKeys {
  349. kvc := pb.NewKVClient(clus.RandConn())
  350. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  351. if _, err := kvc.Put(context.TODO(), req); err != nil {
  352. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  353. }
  354. }
  355. }()
  356. var createdWatchId int64
  357. for j, wresp := range tt.wresps {
  358. resp, err := wStream.Recv()
  359. if err != nil {
  360. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  361. }
  362. if resp.Header == nil {
  363. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  364. }
  365. if resp.Header.Revision != wresp.Header.Revision {
  366. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  367. }
  368. if wresp.Created != resp.Created {
  369. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  370. }
  371. if resp.Created {
  372. createdWatchId = resp.WatchId
  373. }
  374. if resp.WatchId != createdWatchId {
  375. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  376. }
  377. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  378. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  379. }
  380. }
  381. rok, nr := WaitResponse(wStream, 1*time.Second)
  382. if !rok {
  383. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  384. }
  385. // can't defer because tcp ports will be in use
  386. clus.Terminate(t)
  387. }
  388. }
  389. // TestV3WatchCancel tests Watch APIs cancellation.
  390. func TestV3WatchCancel(t *testing.T) {
  391. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  392. wAPI := pb.NewWatchClient(clus.RandConn())
  393. wStream, errW := wAPI.Watch(context.TODO())
  394. if errW != nil {
  395. t.Fatalf("wAPI.Watch error: %v", errW)
  396. }
  397. if err := wStream.Send(&pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")}}); err != nil {
  398. t.Fatalf("wStream.Send error: %v", err)
  399. }
  400. wresp, errR := wStream.Recv()
  401. if errR != nil {
  402. t.Errorf("wStream.Recv error: %v", errR)
  403. }
  404. if !wresp.Created {
  405. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  406. }
  407. if err := wStream.Send(&pb.WatchRequest{CancelRequest: &pb.WatchCancelRequest{WatchId: wresp.WatchId}}); err != nil {
  408. t.Fatalf("wStream.Send error: %v", err)
  409. }
  410. cresp, err := wStream.Recv()
  411. if err != nil {
  412. t.Errorf("wStream.Recv error: %v", err)
  413. }
  414. if !cresp.Canceled {
  415. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  416. }
  417. kvc := pb.NewKVClient(clus.RandConn())
  418. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  419. t.Errorf("couldn't put key (%v)", err)
  420. }
  421. // watch got canceled, so this should block
  422. rok, nr := WaitResponse(wStream, 1*time.Second)
  423. if !rok {
  424. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  425. }
  426. clus.Terminate(t)
  427. }
  428. // TestV3WatchMultiple tests multiple watchers on the same key
  429. // and one watcher with matching prefix. It first puts the key
  430. // that matches all watchers, and another key that matches only
  431. // one watcher to test if it receives expected events.
  432. func TestV3WatchMultiple(t *testing.T) {
  433. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  434. wAPI := pb.NewWatchClient(clus.RandConn())
  435. kvc := pb.NewKVClient(clus.RandConn())
  436. wStream, errW := wAPI.Watch(context.TODO())
  437. if errW != nil {
  438. t.Fatalf("wAPI.Watch error: %v", errW)
  439. }
  440. watchKeyN := 4
  441. for i := 0; i < watchKeyN+1; i++ {
  442. var wreq *pb.WatchRequest
  443. if i < watchKeyN {
  444. wreq = &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")}}
  445. } else {
  446. wreq = &pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Prefix: []byte("fo")}}
  447. }
  448. if err := wStream.Send(wreq); err != nil {
  449. t.Fatalf("wStream.Send error: %v", err)
  450. }
  451. }
  452. ids := make(map[int64]struct{})
  453. for i := 0; i < watchKeyN+1; i++ {
  454. wresp, err := wStream.Recv()
  455. if err != nil {
  456. t.Fatalf("wStream.Recv error: %v", err)
  457. }
  458. if !wresp.Created {
  459. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  460. }
  461. ids[wresp.WatchId] = struct{}{}
  462. }
  463. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  464. t.Fatalf("couldn't put key (%v)", err)
  465. }
  466. for i := 0; i < watchKeyN+1; i++ {
  467. wresp, err := wStream.Recv()
  468. if err != nil {
  469. t.Fatalf("wStream.Recv error: %v", err)
  470. }
  471. if _, ok := ids[wresp.WatchId]; !ok {
  472. t.Errorf("watchId %d is not created!", wresp.WatchId)
  473. } else {
  474. delete(ids, wresp.WatchId)
  475. }
  476. if len(wresp.Events) == 0 {
  477. t.Errorf("#%d: no events received", i)
  478. }
  479. for _, ev := range wresp.Events {
  480. if string(ev.Kv.Key) != "foo" {
  481. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  482. }
  483. if string(ev.Kv.Value) != "bar" {
  484. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  485. }
  486. }
  487. }
  488. // now put one key that has only one matching watcher
  489. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  490. t.Fatalf("couldn't put key (%v)", err)
  491. }
  492. wresp, err := wStream.Recv()
  493. if err != nil {
  494. t.Errorf("wStream.Recv error: %v", err)
  495. }
  496. if len(wresp.Events) != 1 {
  497. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  498. }
  499. if string(wresp.Events[0].Kv.Key) != "fo" {
  500. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  501. }
  502. // now Recv should block because there is no more events coming
  503. rok, nr := WaitResponse(wStream, 1*time.Second)
  504. if !rok {
  505. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  506. }
  507. clus.Terminate(t)
  508. }
  509. // TestV3WatchMultipleEventsFromCurrentRevision tests Watch APIs from current revision
  510. // in cases it receives multiple events.
  511. func TestV3WatchMultipleEventsFromCurrentRevision(t *testing.T) {
  512. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  513. wAPI := pb.NewWatchClient(clus.RandConn())
  514. wStream, wErr := wAPI.Watch(context.TODO())
  515. if wErr != nil {
  516. t.Fatalf("wAPI.Watch error: %v", wErr)
  517. }
  518. if err := wStream.Send(&pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Prefix: []byte("foo")}}); err != nil {
  519. t.Fatalf("wStream.Send error: %v", err)
  520. }
  521. kvc := pb.NewKVClient(clus.RandConn())
  522. txn := pb.TxnRequest{}
  523. for i := 0; i < 3; i++ {
  524. ru := &pb.RequestUnion{}
  525. ru.RequestPut = &pb.PutRequest{Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}
  526. txn.Success = append(txn.Success, ru)
  527. }
  528. tresp, err := kvc.Txn(context.Background(), &txn)
  529. if err != nil {
  530. t.Fatalf("kvc.Txn error: %v", err)
  531. }
  532. if !tresp.Succeeded {
  533. t.Fatalf("kvc.Txn failed: %+v", tresp)
  534. }
  535. events := []*storagepb.Event{}
  536. for len(events) < 3 {
  537. resp, err := wStream.Recv()
  538. if err != nil {
  539. t.Errorf("wStream.Recv error: %v", err)
  540. }
  541. if resp.Created {
  542. continue
  543. }
  544. events = append(events, resp.Events...)
  545. }
  546. sort.Sort(eventsSortByKey(events))
  547. wevents := []*storagepb.Event{
  548. {
  549. Type: storagepb.PUT,
  550. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  551. },
  552. {
  553. Type: storagepb.PUT,
  554. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  555. },
  556. {
  557. Type: storagepb.PUT,
  558. Kv: &storagepb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  559. },
  560. }
  561. if !reflect.DeepEqual(events, wevents) {
  562. t.Errorf("events got = %+v, want = %+v", events, wevents)
  563. }
  564. rok, nr := WaitResponse(wStream, 1*time.Second)
  565. if !rok {
  566. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  567. }
  568. // can't defer because tcp ports will be in use
  569. clus.Terminate(t)
  570. }
  571. type eventsSortByKey []*storagepb.Event
  572. func (evs eventsSortByKey) Len() int { return len(evs) }
  573. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  574. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  575. // TestV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  576. func TestV3WatchMultipleStreams(t *testing.T) {
  577. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  578. wAPI := pb.NewWatchClient(clus.RandConn())
  579. kvc := pb.NewKVClient(clus.RandConn())
  580. streams := make([]pb.Watch_WatchClient, 5)
  581. for i := range streams {
  582. wStream, errW := wAPI.Watch(context.TODO())
  583. if errW != nil {
  584. t.Fatalf("wAPI.Watch error: %v", errW)
  585. }
  586. if err := wStream.Send(&pb.WatchRequest{CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")}}); err != nil {
  587. t.Fatalf("wStream.Send error: %v", err)
  588. }
  589. streams[i] = wStream
  590. }
  591. for _, wStream := range streams {
  592. wresp, err := wStream.Recv()
  593. if err != nil {
  594. t.Fatalf("wStream.Recv error: %v", err)
  595. }
  596. if !wresp.Created {
  597. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  598. }
  599. }
  600. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  601. t.Fatalf("couldn't put key (%v)", err)
  602. }
  603. var wg sync.WaitGroup
  604. wg.Add(len(streams))
  605. wevents := []*storagepb.Event{
  606. {
  607. Type: storagepb.PUT,
  608. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  609. },
  610. }
  611. for i := range streams {
  612. go func(i int) {
  613. defer wg.Done()
  614. wStream := streams[i]
  615. wresp, err := wStream.Recv()
  616. if err != nil {
  617. t.Fatalf("wStream.Recv error: %v", err)
  618. }
  619. if wresp.WatchId != 0 {
  620. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  621. }
  622. if !reflect.DeepEqual(wresp.Events, wevents) {
  623. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  624. }
  625. // now Recv should block because there is no more events coming
  626. rok, nr := WaitResponse(wStream, 1*time.Second)
  627. if !rok {
  628. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  629. }
  630. }(i)
  631. }
  632. wg.Wait()
  633. clus.Terminate(t)
  634. }
  635. // WaitResponse waits on the given stream for given duration.
  636. // If there is no more events, true and a nil response will be
  637. // returned closing the WatchClient stream. Or the response will
  638. // be returned.
  639. func WaitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  640. rCh := make(chan *pb.WatchResponse)
  641. go func() {
  642. resp, _ := wc.Recv()
  643. rCh <- resp
  644. }()
  645. select {
  646. case nr := <-rCh:
  647. return false, nr
  648. case <-time.After(timeout):
  649. }
  650. wc.CloseSend()
  651. rv, ok := <-rCh
  652. if rv != nil || !ok {
  653. return false, rv
  654. }
  655. return true, nil
  656. }
  657. func TestV3RangeRequest(t *testing.T) {
  658. tests := []struct {
  659. putKeys []string
  660. reqs []pb.RangeRequest
  661. wresps [][]string
  662. wmores []bool
  663. }{
  664. // single key
  665. {
  666. []string{"foo", "bar"},
  667. []pb.RangeRequest{
  668. // exists
  669. {Key: []byte("foo")},
  670. // doesn't exist
  671. {Key: []byte("baz")},
  672. },
  673. [][]string{
  674. {"foo"},
  675. {},
  676. },
  677. []bool{false, false},
  678. },
  679. // multi-key
  680. {
  681. []string{"a", "b", "c", "d", "e"},
  682. []pb.RangeRequest{
  683. // all in range
  684. {Key: []byte("a"), RangeEnd: []byte("z")},
  685. // [b, d)
  686. {Key: []byte("b"), RangeEnd: []byte("d")},
  687. // out of range
  688. {Key: []byte("f"), RangeEnd: []byte("z")},
  689. // [c,c) = empty
  690. {Key: []byte("c"), RangeEnd: []byte("c")},
  691. // [d, b) = empty
  692. {Key: []byte("d"), RangeEnd: []byte("b")},
  693. },
  694. [][]string{
  695. {"a", "b", "c", "d", "e"},
  696. {"b", "c"},
  697. {},
  698. {},
  699. {},
  700. },
  701. []bool{false, false, false, false, false},
  702. },
  703. // revision
  704. {
  705. []string{"a", "b", "c", "d", "e"},
  706. []pb.RangeRequest{
  707. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 0},
  708. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 1},
  709. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 2},
  710. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 3},
  711. },
  712. [][]string{
  713. {"a", "b", "c", "d", "e"},
  714. {},
  715. {"a"},
  716. {"a", "b"},
  717. },
  718. []bool{false, false, false, false},
  719. },
  720. // limit
  721. {
  722. []string{"foo", "bar"},
  723. []pb.RangeRequest{
  724. // more
  725. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 1},
  726. // no more
  727. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 2},
  728. },
  729. [][]string{
  730. {"bar"},
  731. {"bar", "foo"},
  732. },
  733. []bool{true, false},
  734. },
  735. // sort
  736. {
  737. []string{"b", "a", "c", "d", "c"},
  738. []pb.RangeRequest{
  739. {
  740. Key: []byte("a"), RangeEnd: []byte("z"),
  741. Limit: 1,
  742. SortOrder: pb.RangeRequest_ASCEND,
  743. SortTarget: pb.RangeRequest_KEY,
  744. },
  745. {
  746. Key: []byte("a"), RangeEnd: []byte("z"),
  747. Limit: 1,
  748. SortOrder: pb.RangeRequest_DESCEND,
  749. SortTarget: pb.RangeRequest_KEY,
  750. },
  751. {
  752. Key: []byte("a"), RangeEnd: []byte("z"),
  753. Limit: 1,
  754. SortOrder: pb.RangeRequest_ASCEND,
  755. SortTarget: pb.RangeRequest_CREATE,
  756. },
  757. {
  758. Key: []byte("a"), RangeEnd: []byte("z"),
  759. Limit: 1,
  760. SortOrder: pb.RangeRequest_DESCEND,
  761. SortTarget: pb.RangeRequest_MOD,
  762. },
  763. {
  764. Key: []byte("z"), RangeEnd: []byte("z"),
  765. Limit: 1,
  766. SortOrder: pb.RangeRequest_DESCEND,
  767. SortTarget: pb.RangeRequest_CREATE,
  768. },
  769. },
  770. [][]string{
  771. {"a"},
  772. {"d"},
  773. {"b"},
  774. {"c"},
  775. {},
  776. },
  777. []bool{true, true, true, true, false},
  778. },
  779. }
  780. for i, tt := range tests {
  781. clus := newClusterGRPC(t, &clusterConfig{size: 3})
  782. for _, k := range tt.putKeys {
  783. kvc := pb.NewKVClient(clus.RandConn())
  784. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  785. if _, err := kvc.Put(context.TODO(), req); err != nil {
  786. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  787. }
  788. }
  789. for j, req := range tt.reqs {
  790. kvc := pb.NewKVClient(clus.RandConn())
  791. resp, err := kvc.Range(context.TODO(), &req)
  792. if err != nil {
  793. t.Errorf("#%d.%d: Range error: %v", i, j, err)
  794. continue
  795. }
  796. if len(resp.Kvs) != len(tt.wresps[j]) {
  797. t.Errorf("#%d.%d: bad len(resp.Kvs). got = %d, want = %d, ", i, j, len(resp.Kvs), len(tt.wresps[j]))
  798. continue
  799. }
  800. for k, wKey := range tt.wresps[j] {
  801. respKey := string(resp.Kvs[k].Key)
  802. if respKey != wKey {
  803. t.Errorf("#%d.%d: key[%d]. got = %v, want = %v, ", i, j, k, respKey, wKey)
  804. }
  805. }
  806. if resp.More != tt.wmores[j] {
  807. t.Errorf("#%d.%d: bad more. got = %v, want = %v, ", i, j, resp.More, tt.wmores[j])
  808. }
  809. wrev := req.Revision
  810. if wrev == 0 {
  811. wrev = int64(len(tt.putKeys) + 1)
  812. }
  813. if resp.Header.Revision != wrev {
  814. t.Errorf("#%d.%d: bad header revision. got = %d. want = %d", i, j, resp.Header.Revision, wrev)
  815. }
  816. }
  817. clus.Terminate(t)
  818. }
  819. }