v3_grpc_test.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388
  1. // Copyright 2016 CoreOS, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.package recipe
  14. package integration
  15. import (
  16. "bytes"
  17. "fmt"
  18. "reflect"
  19. "sort"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  24. "github.com/coreos/etcd/Godeps/_workspace/src/google.golang.org/grpc"
  25. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  26. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  27. "github.com/coreos/etcd/pkg/testutil"
  28. "github.com/coreos/etcd/storage/storagepb"
  29. )
  30. // TestV3PutOverwrite puts a key with the v3 api to a random cluster member,
  31. // overwrites it, then checks that the change was applied.
  32. func TestV3PutOverwrite(t *testing.T) {
  33. defer testutil.AfterTest(t)
  34. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  35. defer clus.Terminate(t)
  36. kvc := clus.RandClient().KV
  37. key := []byte("foo")
  38. reqput := &pb.PutRequest{Key: key, Value: []byte("bar")}
  39. respput, err := kvc.Put(context.TODO(), reqput)
  40. if err != nil {
  41. t.Fatalf("couldn't put key (%v)", err)
  42. }
  43. // overwrite
  44. reqput.Value = []byte("baz")
  45. respput2, err := kvc.Put(context.TODO(), reqput)
  46. if err != nil {
  47. t.Fatalf("couldn't put key (%v)", err)
  48. }
  49. if respput2.Header.Revision <= respput.Header.Revision {
  50. t.Fatalf("expected newer revision on overwrite, got %v <= %v",
  51. respput2.Header.Revision, respput.Header.Revision)
  52. }
  53. reqrange := &pb.RangeRequest{Key: key}
  54. resprange, err := kvc.Range(context.TODO(), reqrange)
  55. if err != nil {
  56. t.Fatalf("couldn't get key (%v)", err)
  57. }
  58. if len(resprange.Kvs) != 1 {
  59. t.Fatalf("expected 1 key, got %v", len(resprange.Kvs))
  60. }
  61. kv := resprange.Kvs[0]
  62. if kv.ModRevision <= kv.CreateRevision {
  63. t.Errorf("expected modRev > createRev, got %d <= %d",
  64. kv.ModRevision, kv.CreateRevision)
  65. }
  66. if !reflect.DeepEqual(reqput.Value, kv.Value) {
  67. t.Errorf("expected value %v, got %v", reqput.Value, kv.Value)
  68. }
  69. }
  70. func TestV3TxnTooManyOps(t *testing.T) {
  71. defer testutil.AfterTest(t)
  72. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  73. defer clus.Terminate(t)
  74. kvc := clus.RandClient().KV
  75. // unique keys
  76. i := new(int)
  77. keyf := func() []byte {
  78. *i++
  79. return []byte(fmt.Sprintf("key-%d", i))
  80. }
  81. addCompareOps := func(txn *pb.TxnRequest) {
  82. txn.Compare = append(txn.Compare,
  83. &pb.Compare{
  84. Result: pb.Compare_GREATER,
  85. Target: pb.Compare_CREATE,
  86. Key: keyf(),
  87. })
  88. }
  89. addSuccessOps := func(txn *pb.TxnRequest) {
  90. txn.Success = append(txn.Success,
  91. &pb.RequestUnion{
  92. Request: &pb.RequestUnion_RequestPut{
  93. RequestPut: &pb.PutRequest{
  94. Key: keyf(),
  95. Value: []byte("bar"),
  96. },
  97. },
  98. })
  99. }
  100. addFailureOps := func(txn *pb.TxnRequest) {
  101. txn.Failure = append(txn.Failure,
  102. &pb.RequestUnion{
  103. Request: &pb.RequestUnion_RequestPut{
  104. RequestPut: &pb.PutRequest{
  105. Key: keyf(),
  106. Value: []byte("bar"),
  107. },
  108. },
  109. })
  110. }
  111. tests := []func(txn *pb.TxnRequest){
  112. addCompareOps,
  113. addSuccessOps,
  114. addFailureOps,
  115. }
  116. for i, tt := range tests {
  117. txn := &pb.TxnRequest{}
  118. for j := 0; j < v3rpc.MaxOpsPerTxn+1; j++ {
  119. tt(txn)
  120. }
  121. _, err := kvc.Txn(context.Background(), txn)
  122. if err != v3rpc.ErrTooManyOps {
  123. t.Errorf("#%d: err = %v, want %v", i, err, v3rpc.ErrTooManyOps)
  124. }
  125. }
  126. }
  127. func TestV3TxnDuplicateKeys(t *testing.T) {
  128. defer testutil.AfterTest(t)
  129. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  130. defer clus.Terminate(t)
  131. putreq := &pb.RequestUnion{Request: &pb.RequestUnion_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}}}
  132. delKeyReq := &pb.RequestUnion{Request: &pb.RequestUnion_RequestDeleteRange{
  133. RequestDeleteRange: &pb.DeleteRangeRequest{
  134. Key: []byte("abc"),
  135. },
  136. },
  137. }
  138. delInRangeReq := &pb.RequestUnion{Request: &pb.RequestUnion_RequestDeleteRange{
  139. RequestDeleteRange: &pb.DeleteRangeRequest{
  140. Key: []byte("a"), RangeEnd: []byte("b"),
  141. },
  142. },
  143. }
  144. delOutOfRangeReq := &pb.RequestUnion{Request: &pb.RequestUnion_RequestDeleteRange{
  145. RequestDeleteRange: &pb.DeleteRangeRequest{
  146. Key: []byte("abb"), RangeEnd: []byte("abc"),
  147. },
  148. },
  149. }
  150. kvc := clus.RandClient().KV
  151. tests := []struct {
  152. txnSuccess []*pb.RequestUnion
  153. werr error
  154. }{
  155. {
  156. txnSuccess: []*pb.RequestUnion{putreq, putreq},
  157. werr: v3rpc.ErrDuplicateKey,
  158. },
  159. {
  160. txnSuccess: []*pb.RequestUnion{putreq, delKeyReq},
  161. werr: v3rpc.ErrDuplicateKey,
  162. },
  163. {
  164. txnSuccess: []*pb.RequestUnion{putreq, delInRangeReq},
  165. werr: v3rpc.ErrDuplicateKey,
  166. },
  167. {
  168. txnSuccess: []*pb.RequestUnion{delKeyReq, delInRangeReq, delKeyReq, delInRangeReq},
  169. werr: nil,
  170. },
  171. {
  172. txnSuccess: []*pb.RequestUnion{putreq, delOutOfRangeReq},
  173. werr: nil,
  174. },
  175. }
  176. for i, tt := range tests {
  177. txn := &pb.TxnRequest{Success: tt.txnSuccess}
  178. _, err := kvc.Txn(context.Background(), txn)
  179. if err != tt.werr {
  180. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  181. }
  182. }
  183. }
  184. // TestV3PutMissingLease ensures that a Put on a key with a bogus lease fails.
  185. func TestV3PutMissingLease(t *testing.T) {
  186. defer testutil.AfterTest(t)
  187. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  188. defer clus.Terminate(t)
  189. kvc := clus.RandClient().KV
  190. key := []byte("foo")
  191. preq := &pb.PutRequest{Key: key, Lease: 123456}
  192. tests := []func(){
  193. // put case
  194. func() {
  195. if presp, err := kvc.Put(context.TODO(), preq); err == nil {
  196. t.Errorf("succeeded put key. req: %v. resp: %v", preq, presp)
  197. }
  198. },
  199. // txn success case
  200. func() {
  201. txn := &pb.TxnRequest{}
  202. txn.Success = append(txn.Success, &pb.RequestUnion{
  203. Request: &pb.RequestUnion_RequestPut{
  204. RequestPut: preq}})
  205. if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
  206. t.Errorf("succeeded txn success. req: %v. resp: %v", txn, tresp)
  207. }
  208. },
  209. // txn failure case
  210. func() {
  211. txn := &pb.TxnRequest{}
  212. txn.Failure = append(txn.Failure, &pb.RequestUnion{
  213. Request: &pb.RequestUnion_RequestPut{
  214. RequestPut: preq}})
  215. cmp := &pb.Compare{
  216. Result: pb.Compare_GREATER,
  217. Target: pb.Compare_CREATE,
  218. Key: []byte("bar"),
  219. }
  220. txn.Compare = append(txn.Compare, cmp)
  221. if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
  222. t.Errorf("succeeded txn failure. req: %v. resp: %v", txn, tresp)
  223. }
  224. },
  225. // ignore bad lease in failure on success txn
  226. func() {
  227. txn := &pb.TxnRequest{}
  228. rreq := &pb.RangeRequest{Key: []byte("bar")}
  229. txn.Success = append(txn.Success, &pb.RequestUnion{
  230. Request: &pb.RequestUnion_RequestRange{
  231. RequestRange: rreq}})
  232. txn.Failure = append(txn.Failure, &pb.RequestUnion{
  233. Request: &pb.RequestUnion_RequestPut{
  234. RequestPut: preq}})
  235. if tresp, err := kvc.Txn(context.TODO(), txn); err != nil {
  236. t.Errorf("failed good txn. req: %v. resp: %v", txn, tresp)
  237. }
  238. },
  239. }
  240. for i, f := range tests {
  241. f()
  242. // key shouldn't have been stored
  243. rreq := &pb.RangeRequest{Key: key}
  244. rresp, err := kvc.Range(context.TODO(), rreq)
  245. if err != nil {
  246. t.Errorf("#%d. could not rangereq (%v)", i, err)
  247. } else if len(rresp.Kvs) != 0 {
  248. t.Errorf("#%d. expected no keys, got %v", i, rresp)
  249. }
  250. }
  251. }
  252. // TestV3DeleteRange tests various edge cases in the DeleteRange API.
  253. func TestV3DeleteRange(t *testing.T) {
  254. defer testutil.AfterTest(t)
  255. tests := []struct {
  256. keySet []string
  257. begin string
  258. end string
  259. wantSet [][]byte
  260. }{
  261. // delete middle
  262. {
  263. []string{"foo", "foo/abc", "fop"},
  264. "foo/", "fop",
  265. [][]byte{[]byte("foo"), []byte("fop")},
  266. },
  267. // no delete
  268. {
  269. []string{"foo", "foo/abc", "fop"},
  270. "foo/", "foo/",
  271. [][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")},
  272. },
  273. // delete first
  274. {
  275. []string{"foo", "foo/abc", "fop"},
  276. "fo", "fop",
  277. [][]byte{[]byte("fop")},
  278. },
  279. // delete tail
  280. {
  281. []string{"foo", "foo/abc", "fop"},
  282. "foo/", "fos",
  283. [][]byte{[]byte("foo")},
  284. },
  285. // delete exact
  286. {
  287. []string{"foo", "foo/abc", "fop"},
  288. "foo/abc", "",
  289. [][]byte{[]byte("foo"), []byte("fop")},
  290. },
  291. // delete none, [x,x)
  292. {
  293. []string{"foo"},
  294. "foo", "foo",
  295. [][]byte{[]byte("foo")},
  296. },
  297. }
  298. for i, tt := range tests {
  299. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  300. kvc := clus.RandClient().KV
  301. ks := tt.keySet
  302. for j := range ks {
  303. reqput := &pb.PutRequest{Key: []byte(ks[j]), Value: []byte{}}
  304. _, err := kvc.Put(context.TODO(), reqput)
  305. if err != nil {
  306. t.Fatalf("couldn't put key (%v)", err)
  307. }
  308. }
  309. dreq := &pb.DeleteRangeRequest{
  310. Key: []byte(tt.begin),
  311. RangeEnd: []byte(tt.end)}
  312. dresp, err := kvc.DeleteRange(context.TODO(), dreq)
  313. if err != nil {
  314. t.Fatalf("couldn't delete range on test %d (%v)", i, err)
  315. }
  316. rreq := &pb.RangeRequest{Key: []byte{0x0}, RangeEnd: []byte{0xff}}
  317. rresp, err := kvc.Range(context.TODO(), rreq)
  318. if err != nil {
  319. t.Errorf("couldn't get range on test %v (%v)", i, err)
  320. }
  321. if dresp.Header.Revision != rresp.Header.Revision {
  322. t.Errorf("expected revision %v, got %v",
  323. dresp.Header.Revision, rresp.Header.Revision)
  324. }
  325. keys := [][]byte{}
  326. for j := range rresp.Kvs {
  327. keys = append(keys, rresp.Kvs[j].Key)
  328. }
  329. if reflect.DeepEqual(tt.wantSet, keys) == false {
  330. t.Errorf("expected %v on test %v, got %v", tt.wantSet, i, keys)
  331. }
  332. // can't defer because tcp ports will be in use
  333. clus.Terminate(t)
  334. }
  335. }
  336. // TestV3TxnInvaildRange tests txn
  337. func TestV3TxnInvaildRange(t *testing.T) {
  338. defer testutil.AfterTest(t)
  339. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  340. defer clus.Terminate(t)
  341. kvc := clus.RandClient().KV
  342. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  343. for i := 0; i < 3; i++ {
  344. _, err := kvc.Put(context.Background(), preq)
  345. if err != nil {
  346. t.Fatalf("couldn't put key (%v)", err)
  347. }
  348. }
  349. _, err := kvc.Compact(context.Background(), &pb.CompactionRequest{Revision: 2})
  350. if err != nil {
  351. t.Fatalf("couldn't compact kv space (%v)", err)
  352. }
  353. // future rev
  354. txn := &pb.TxnRequest{}
  355. txn.Success = append(txn.Success, &pb.RequestUnion{
  356. Request: &pb.RequestUnion_RequestPut{
  357. RequestPut: preq}})
  358. rreq := &pb.RangeRequest{Key: []byte("foo"), Revision: 100}
  359. txn.Success = append(txn.Success, &pb.RequestUnion{
  360. Request: &pb.RequestUnion_RequestRange{
  361. RequestRange: rreq}})
  362. if _, err := kvc.Txn(context.TODO(), txn); err != v3rpc.ErrFutureRev {
  363. t.Errorf("err = %v, want %v", err, v3rpc.ErrFutureRev)
  364. }
  365. // compacted rev
  366. tv, _ := txn.Success[1].Request.(*pb.RequestUnion_RequestRange)
  367. tv.RequestRange.Revision = 1
  368. if _, err := kvc.Txn(context.TODO(), txn); err != v3rpc.ErrCompacted {
  369. t.Errorf("err = %v, want %v", err, v3rpc.ErrCompacted)
  370. }
  371. }
  372. // TestV3Hash tests hash.
  373. func TestV3Hash(t *testing.T) {
  374. defer testutil.AfterTest(t)
  375. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  376. defer clus.Terminate(t)
  377. kvc := clus.RandClient().KV
  378. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  379. for i := 0; i < 3; i++ {
  380. _, err := kvc.Put(context.Background(), preq)
  381. if err != nil {
  382. t.Fatalf("couldn't put key (%v)", err)
  383. }
  384. }
  385. resp, err := kvc.Hash(context.Background(), &pb.HashRequest{})
  386. if err != nil || resp.Hash == 0 {
  387. t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
  388. }
  389. }
  390. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  391. func TestV3WatchFromCurrentRevision(t *testing.T) {
  392. defer testutil.AfterTest(t)
  393. tests := []struct {
  394. putKeys []string
  395. watchRequest *pb.WatchRequest
  396. wresps []*pb.WatchResponse
  397. }{
  398. // watch the key, matching
  399. {
  400. []string{"foo"},
  401. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  402. CreateRequest: &pb.WatchCreateRequest{
  403. Key: []byte("foo")}}},
  404. []*pb.WatchResponse{
  405. {
  406. Header: &pb.ResponseHeader{Revision: 1},
  407. Created: true,
  408. },
  409. {
  410. Header: &pb.ResponseHeader{Revision: 2},
  411. Created: false,
  412. Events: []*storagepb.Event{
  413. {
  414. Type: storagepb.PUT,
  415. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  416. },
  417. },
  418. },
  419. },
  420. },
  421. // watch the key, non-matching
  422. {
  423. []string{"foo"},
  424. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  425. CreateRequest: &pb.WatchCreateRequest{
  426. Key: []byte("helloworld")}}},
  427. []*pb.WatchResponse{
  428. {
  429. Header: &pb.ResponseHeader{Revision: 1},
  430. Created: true,
  431. },
  432. },
  433. },
  434. // watch the prefix, matching
  435. {
  436. []string{"fooLong"},
  437. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  438. CreateRequest: &pb.WatchCreateRequest{
  439. Prefix: []byte("foo")}}},
  440. []*pb.WatchResponse{
  441. {
  442. Header: &pb.ResponseHeader{Revision: 1},
  443. Created: true,
  444. },
  445. {
  446. Header: &pb.ResponseHeader{Revision: 2},
  447. Created: false,
  448. Events: []*storagepb.Event{
  449. {
  450. Type: storagepb.PUT,
  451. Kv: &storagepb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  452. },
  453. },
  454. },
  455. },
  456. },
  457. // watch the prefix, non-matching
  458. {
  459. []string{"foo"},
  460. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  461. CreateRequest: &pb.WatchCreateRequest{
  462. Prefix: []byte("helloworld")}}},
  463. []*pb.WatchResponse{
  464. {
  465. Header: &pb.ResponseHeader{Revision: 1},
  466. Created: true,
  467. },
  468. },
  469. },
  470. // multiple puts, one watcher with matching key
  471. {
  472. []string{"foo", "foo", "foo"},
  473. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  474. CreateRequest: &pb.WatchCreateRequest{
  475. Key: []byte("foo")}}},
  476. []*pb.WatchResponse{
  477. {
  478. Header: &pb.ResponseHeader{Revision: 1},
  479. Created: true,
  480. },
  481. {
  482. Header: &pb.ResponseHeader{Revision: 2},
  483. Created: false,
  484. Events: []*storagepb.Event{
  485. {
  486. Type: storagepb.PUT,
  487. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  488. },
  489. },
  490. },
  491. {
  492. Header: &pb.ResponseHeader{Revision: 3},
  493. Created: false,
  494. Events: []*storagepb.Event{
  495. {
  496. Type: storagepb.PUT,
  497. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  498. },
  499. },
  500. },
  501. {
  502. Header: &pb.ResponseHeader{Revision: 4},
  503. Created: false,
  504. Events: []*storagepb.Event{
  505. {
  506. Type: storagepb.PUT,
  507. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  508. },
  509. },
  510. },
  511. },
  512. },
  513. // multiple puts, one watcher with matching prefix
  514. {
  515. []string{"foo", "foo", "foo"},
  516. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  517. CreateRequest: &pb.WatchCreateRequest{
  518. Prefix: []byte("foo")}}},
  519. []*pb.WatchResponse{
  520. {
  521. Header: &pb.ResponseHeader{Revision: 1},
  522. Created: true,
  523. },
  524. {
  525. Header: &pb.ResponseHeader{Revision: 2},
  526. Created: false,
  527. Events: []*storagepb.Event{
  528. {
  529. Type: storagepb.PUT,
  530. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  531. },
  532. },
  533. },
  534. {
  535. Header: &pb.ResponseHeader{Revision: 3},
  536. Created: false,
  537. Events: []*storagepb.Event{
  538. {
  539. Type: storagepb.PUT,
  540. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  541. },
  542. },
  543. },
  544. {
  545. Header: &pb.ResponseHeader{Revision: 4},
  546. Created: false,
  547. Events: []*storagepb.Event{
  548. {
  549. Type: storagepb.PUT,
  550. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  551. },
  552. },
  553. },
  554. },
  555. },
  556. }
  557. for i, tt := range tests {
  558. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  559. wAPI := clus.RandClient().Watch
  560. ctx, cancel := context.WithCancel(context.Background())
  561. defer cancel()
  562. wStream, err := wAPI.Watch(ctx)
  563. if err != nil {
  564. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  565. }
  566. if err := wStream.Send(tt.watchRequest); err != nil {
  567. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  568. }
  569. go func() {
  570. for _, k := range tt.putKeys {
  571. kvc := clus.RandClient().KV
  572. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  573. if _, err := kvc.Put(context.TODO(), req); err != nil {
  574. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  575. }
  576. }
  577. }()
  578. var createdWatchId int64
  579. for j, wresp := range tt.wresps {
  580. resp, err := wStream.Recv()
  581. if err != nil {
  582. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  583. }
  584. if resp.Header == nil {
  585. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  586. }
  587. if resp.Header.Revision != wresp.Header.Revision {
  588. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  589. }
  590. if wresp.Created != resp.Created {
  591. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  592. }
  593. if resp.Created {
  594. createdWatchId = resp.WatchId
  595. }
  596. if resp.WatchId != createdWatchId {
  597. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  598. }
  599. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  600. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  601. }
  602. }
  603. rok, nr := WaitResponse(wStream, 1*time.Second)
  604. if !rok {
  605. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  606. }
  607. // can't defer because tcp ports will be in use
  608. clus.Terminate(t)
  609. }
  610. }
  611. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  612. func TestV3WatchCancelSynced(t *testing.T) {
  613. defer testutil.AfterTest(t)
  614. testV3WatchCancel(t, 0)
  615. }
  616. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  617. func TestV3WatchCancelUnsynced(t *testing.T) {
  618. defer testutil.AfterTest(t)
  619. testV3WatchCancel(t, 1)
  620. }
  621. func testV3WatchCancel(t *testing.T, startRev int64) {
  622. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  623. ctx, cancel := context.WithCancel(context.Background())
  624. defer cancel()
  625. wStream, errW := clus.RandClient().Watch.Watch(ctx)
  626. if errW != nil {
  627. t.Fatalf("wAPI.Watch error: %v", errW)
  628. }
  629. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  630. CreateRequest: &pb.WatchCreateRequest{
  631. Key: []byte("foo"), StartRevision: startRev}}}
  632. if err := wStream.Send(wreq); err != nil {
  633. t.Fatalf("wStream.Send error: %v", err)
  634. }
  635. wresp, errR := wStream.Recv()
  636. if errR != nil {
  637. t.Errorf("wStream.Recv error: %v", errR)
  638. }
  639. if !wresp.Created {
  640. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  641. }
  642. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  643. CancelRequest: &pb.WatchCancelRequest{
  644. WatchId: wresp.WatchId}}}
  645. if err := wStream.Send(creq); err != nil {
  646. t.Fatalf("wStream.Send error: %v", err)
  647. }
  648. cresp, err := wStream.Recv()
  649. if err != nil {
  650. t.Errorf("wStream.Recv error: %v", err)
  651. }
  652. if !cresp.Canceled {
  653. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  654. }
  655. kvc := clus.RandClient().KV
  656. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  657. t.Errorf("couldn't put key (%v)", err)
  658. }
  659. // watch got canceled, so this should block
  660. rok, nr := WaitResponse(wStream, 1*time.Second)
  661. if !rok {
  662. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  663. }
  664. clus.Terminate(t)
  665. }
  666. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  667. defer testutil.AfterTest(t)
  668. testV3WatchMultipleWatchers(t, 0)
  669. }
  670. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  671. defer testutil.AfterTest(t)
  672. testV3WatchMultipleWatchers(t, 1)
  673. }
  674. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  675. // and one watcher with matching prefix. It first puts the key
  676. // that matches all watchers, and another key that matches only
  677. // one watcher to test if it receives expected events.
  678. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  679. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  680. kvc := clus.RandClient().KV
  681. ctx, cancel := context.WithCancel(context.Background())
  682. defer cancel()
  683. wStream, errW := clus.RandClient().Watch.Watch(ctx)
  684. if errW != nil {
  685. t.Fatalf("wAPI.Watch error: %v", errW)
  686. }
  687. watchKeyN := 4
  688. for i := 0; i < watchKeyN+1; i++ {
  689. var wreq *pb.WatchRequest
  690. if i < watchKeyN {
  691. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  692. CreateRequest: &pb.WatchCreateRequest{
  693. Key: []byte("foo"), StartRevision: startRev}}}
  694. } else {
  695. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  696. CreateRequest: &pb.WatchCreateRequest{
  697. Prefix: []byte("fo"), StartRevision: startRev}}}
  698. }
  699. if err := wStream.Send(wreq); err != nil {
  700. t.Fatalf("wStream.Send error: %v", err)
  701. }
  702. }
  703. ids := make(map[int64]struct{})
  704. for i := 0; i < watchKeyN+1; i++ {
  705. wresp, err := wStream.Recv()
  706. if err != nil {
  707. t.Fatalf("wStream.Recv error: %v", err)
  708. }
  709. if !wresp.Created {
  710. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  711. }
  712. ids[wresp.WatchId] = struct{}{}
  713. }
  714. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  715. t.Fatalf("couldn't put key (%v)", err)
  716. }
  717. for i := 0; i < watchKeyN+1; i++ {
  718. wresp, err := wStream.Recv()
  719. if err != nil {
  720. t.Fatalf("wStream.Recv error: %v", err)
  721. }
  722. if _, ok := ids[wresp.WatchId]; !ok {
  723. t.Errorf("watchId %d is not created!", wresp.WatchId)
  724. } else {
  725. delete(ids, wresp.WatchId)
  726. }
  727. if len(wresp.Events) == 0 {
  728. t.Errorf("#%d: no events received", i)
  729. }
  730. for _, ev := range wresp.Events {
  731. if string(ev.Kv.Key) != "foo" {
  732. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  733. }
  734. if string(ev.Kv.Value) != "bar" {
  735. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  736. }
  737. }
  738. }
  739. // now put one key that has only one matching watcher
  740. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  741. t.Fatalf("couldn't put key (%v)", err)
  742. }
  743. wresp, err := wStream.Recv()
  744. if err != nil {
  745. t.Errorf("wStream.Recv error: %v", err)
  746. }
  747. if len(wresp.Events) != 1 {
  748. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  749. }
  750. if string(wresp.Events[0].Kv.Key) != "fo" {
  751. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  752. }
  753. // now Recv should block because there is no more events coming
  754. rok, nr := WaitResponse(wStream, 1*time.Second)
  755. if !rok {
  756. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  757. }
  758. clus.Terminate(t)
  759. }
  760. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  761. defer testutil.AfterTest(t)
  762. testV3WatchMultipleEventsTxn(t, 0)
  763. }
  764. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  765. defer testutil.AfterTest(t)
  766. testV3WatchMultipleEventsTxn(t, 1)
  767. }
  768. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  769. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  770. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  771. ctx, cancel := context.WithCancel(context.Background())
  772. defer cancel()
  773. wStream, wErr := clus.RandClient().Watch.Watch(ctx)
  774. if wErr != nil {
  775. t.Fatalf("wAPI.Watch error: %v", wErr)
  776. }
  777. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  778. CreateRequest: &pb.WatchCreateRequest{
  779. Prefix: []byte("foo"), StartRevision: startRev}}}
  780. if err := wStream.Send(wreq); err != nil {
  781. t.Fatalf("wStream.Send error: %v", err)
  782. }
  783. kvc := clus.RandClient().KV
  784. txn := pb.TxnRequest{}
  785. for i := 0; i < 3; i++ {
  786. ru := &pb.RequestUnion{}
  787. ru.Request = &pb.RequestUnion_RequestPut{
  788. RequestPut: &pb.PutRequest{
  789. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  790. txn.Success = append(txn.Success, ru)
  791. }
  792. tresp, err := kvc.Txn(context.Background(), &txn)
  793. if err != nil {
  794. t.Fatalf("kvc.Txn error: %v", err)
  795. }
  796. if !tresp.Succeeded {
  797. t.Fatalf("kvc.Txn failed: %+v", tresp)
  798. }
  799. events := []*storagepb.Event{}
  800. for len(events) < 3 {
  801. resp, err := wStream.Recv()
  802. if err != nil {
  803. t.Errorf("wStream.Recv error: %v", err)
  804. }
  805. if resp.Created {
  806. continue
  807. }
  808. events = append(events, resp.Events...)
  809. }
  810. sort.Sort(eventsSortByKey(events))
  811. wevents := []*storagepb.Event{
  812. {
  813. Type: storagepb.PUT,
  814. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  815. },
  816. {
  817. Type: storagepb.PUT,
  818. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  819. },
  820. {
  821. Type: storagepb.PUT,
  822. Kv: &storagepb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  823. },
  824. }
  825. if !reflect.DeepEqual(events, wevents) {
  826. t.Errorf("events got = %+v, want = %+v", events, wevents)
  827. }
  828. rok, nr := WaitResponse(wStream, 1*time.Second)
  829. if !rok {
  830. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  831. }
  832. // can't defer because tcp ports will be in use
  833. clus.Terminate(t)
  834. }
  835. type eventsSortByKey []*storagepb.Event
  836. func (evs eventsSortByKey) Len() int { return len(evs) }
  837. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  838. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  839. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  840. defer testutil.AfterTest(t)
  841. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  842. defer clus.Terminate(t)
  843. kvc := clus.RandClient().KV
  844. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  845. t.Fatalf("couldn't put key (%v)", err)
  846. }
  847. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  848. t.Fatalf("couldn't put key (%v)", err)
  849. }
  850. ctx, cancel := context.WithCancel(context.Background())
  851. defer cancel()
  852. wStream, wErr := clus.RandClient().Watch.Watch(ctx)
  853. if wErr != nil {
  854. t.Fatalf("wAPI.Watch error: %v", wErr)
  855. }
  856. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  857. CreateRequest: &pb.WatchCreateRequest{
  858. Prefix: []byte("foo"), StartRevision: 1}}}
  859. if err := wStream.Send(wreq); err != nil {
  860. t.Fatalf("wStream.Send error: %v", err)
  861. }
  862. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  863. t.Fatalf("couldn't put key (%v)", err)
  864. }
  865. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  866. t.Fatalf("couldn't put key (%v)", err)
  867. }
  868. allWevents := []*storagepb.Event{
  869. {
  870. Type: storagepb.PUT,
  871. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  872. },
  873. {
  874. Type: storagepb.PUT,
  875. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  876. },
  877. {
  878. Type: storagepb.PUT,
  879. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  880. },
  881. {
  882. Type: storagepb.PUT,
  883. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  884. },
  885. }
  886. events := []*storagepb.Event{}
  887. for len(events) < 4 {
  888. resp, err := wStream.Recv()
  889. if err != nil {
  890. t.Errorf("wStream.Recv error: %v", err)
  891. }
  892. if resp.Created {
  893. continue
  894. }
  895. events = append(events, resp.Events...)
  896. // if PUT requests are committed by now, first receive would return
  897. // multiple events, but if not, it returns a single event. In SSD,
  898. // it should return 4 events at once.
  899. }
  900. if !reflect.DeepEqual(events, allWevents) {
  901. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  902. }
  903. rok, nr := WaitResponse(wStream, 1*time.Second)
  904. if !rok {
  905. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  906. }
  907. }
  908. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  909. defer testutil.AfterTest(t)
  910. testV3WatchMultipleStreams(t, 0)
  911. }
  912. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  913. defer testutil.AfterTest(t)
  914. testV3WatchMultipleStreams(t, 1)
  915. }
  916. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  917. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  918. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  919. wAPI := clus.RandClient().Watch
  920. kvc := clus.RandClient().KV
  921. streams := make([]pb.Watch_WatchClient, 5)
  922. for i := range streams {
  923. ctx, cancel := context.WithCancel(context.Background())
  924. defer cancel()
  925. wStream, errW := wAPI.Watch(ctx)
  926. if errW != nil {
  927. t.Fatalf("wAPI.Watch error: %v", errW)
  928. }
  929. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  930. CreateRequest: &pb.WatchCreateRequest{
  931. Key: []byte("foo"), StartRevision: startRev}}}
  932. if err := wStream.Send(wreq); err != nil {
  933. t.Fatalf("wStream.Send error: %v", err)
  934. }
  935. streams[i] = wStream
  936. }
  937. for _, wStream := range streams {
  938. wresp, err := wStream.Recv()
  939. if err != nil {
  940. t.Fatalf("wStream.Recv error: %v", err)
  941. }
  942. if !wresp.Created {
  943. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  944. }
  945. }
  946. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  947. t.Fatalf("couldn't put key (%v)", err)
  948. }
  949. var wg sync.WaitGroup
  950. wg.Add(len(streams))
  951. wevents := []*storagepb.Event{
  952. {
  953. Type: storagepb.PUT,
  954. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  955. },
  956. }
  957. for i := range streams {
  958. go func(i int) {
  959. defer wg.Done()
  960. wStream := streams[i]
  961. wresp, err := wStream.Recv()
  962. if err != nil {
  963. t.Fatalf("wStream.Recv error: %v", err)
  964. }
  965. if wresp.WatchId != 0 {
  966. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  967. }
  968. if !reflect.DeepEqual(wresp.Events, wevents) {
  969. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  970. }
  971. // now Recv should block because there is no more events coming
  972. rok, nr := WaitResponse(wStream, 1*time.Second)
  973. if !rok {
  974. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  975. }
  976. }(i)
  977. }
  978. wg.Wait()
  979. clus.Terminate(t)
  980. }
  981. // WaitResponse waits on the given stream for given duration.
  982. // If there is no more events, true and a nil response will be
  983. // returned closing the WatchClient stream. Or the response will
  984. // be returned.
  985. func WaitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  986. rCh := make(chan *pb.WatchResponse)
  987. go func() {
  988. resp, _ := wc.Recv()
  989. rCh <- resp
  990. }()
  991. select {
  992. case nr := <-rCh:
  993. return false, nr
  994. case <-time.After(timeout):
  995. }
  996. wc.CloseSend()
  997. rv, ok := <-rCh
  998. if rv != nil || !ok {
  999. return false, rv
  1000. }
  1001. return true, nil
  1002. }
  1003. func TestV3RangeRequest(t *testing.T) {
  1004. defer testutil.AfterTest(t)
  1005. tests := []struct {
  1006. putKeys []string
  1007. reqs []pb.RangeRequest
  1008. wresps [][]string
  1009. wmores []bool
  1010. }{
  1011. // single key
  1012. {
  1013. []string{"foo", "bar"},
  1014. []pb.RangeRequest{
  1015. // exists
  1016. {Key: []byte("foo")},
  1017. // doesn't exist
  1018. {Key: []byte("baz")},
  1019. },
  1020. [][]string{
  1021. {"foo"},
  1022. {},
  1023. },
  1024. []bool{false, false},
  1025. },
  1026. // multi-key
  1027. {
  1028. []string{"a", "b", "c", "d", "e"},
  1029. []pb.RangeRequest{
  1030. // all in range
  1031. {Key: []byte("a"), RangeEnd: []byte("z")},
  1032. // [b, d)
  1033. {Key: []byte("b"), RangeEnd: []byte("d")},
  1034. // out of range
  1035. {Key: []byte("f"), RangeEnd: []byte("z")},
  1036. // [c,c) = empty
  1037. {Key: []byte("c"), RangeEnd: []byte("c")},
  1038. // [d, b) = empty
  1039. {Key: []byte("d"), RangeEnd: []byte("b")},
  1040. },
  1041. [][]string{
  1042. {"a", "b", "c", "d", "e"},
  1043. {"b", "c"},
  1044. {},
  1045. {},
  1046. {},
  1047. },
  1048. []bool{false, false, false, false, false},
  1049. },
  1050. // revision
  1051. {
  1052. []string{"a", "b", "c", "d", "e"},
  1053. []pb.RangeRequest{
  1054. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 0},
  1055. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 1},
  1056. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 2},
  1057. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 3},
  1058. },
  1059. [][]string{
  1060. {"a", "b", "c", "d", "e"},
  1061. {},
  1062. {"a"},
  1063. {"a", "b"},
  1064. },
  1065. []bool{false, false, false, false},
  1066. },
  1067. // limit
  1068. {
  1069. []string{"foo", "bar"},
  1070. []pb.RangeRequest{
  1071. // more
  1072. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 1},
  1073. // no more
  1074. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 2},
  1075. },
  1076. [][]string{
  1077. {"bar"},
  1078. {"bar", "foo"},
  1079. },
  1080. []bool{true, false},
  1081. },
  1082. // sort
  1083. {
  1084. []string{"b", "a", "c", "d", "c"},
  1085. []pb.RangeRequest{
  1086. {
  1087. Key: []byte("a"), RangeEnd: []byte("z"),
  1088. Limit: 1,
  1089. SortOrder: pb.RangeRequest_ASCEND,
  1090. SortTarget: pb.RangeRequest_KEY,
  1091. },
  1092. {
  1093. Key: []byte("a"), RangeEnd: []byte("z"),
  1094. Limit: 1,
  1095. SortOrder: pb.RangeRequest_DESCEND,
  1096. SortTarget: pb.RangeRequest_KEY,
  1097. },
  1098. {
  1099. Key: []byte("a"), RangeEnd: []byte("z"),
  1100. Limit: 1,
  1101. SortOrder: pb.RangeRequest_ASCEND,
  1102. SortTarget: pb.RangeRequest_CREATE,
  1103. },
  1104. {
  1105. Key: []byte("a"), RangeEnd: []byte("z"),
  1106. Limit: 1,
  1107. SortOrder: pb.RangeRequest_DESCEND,
  1108. SortTarget: pb.RangeRequest_MOD,
  1109. },
  1110. {
  1111. Key: []byte("z"), RangeEnd: []byte("z"),
  1112. Limit: 1,
  1113. SortOrder: pb.RangeRequest_DESCEND,
  1114. SortTarget: pb.RangeRequest_CREATE,
  1115. },
  1116. },
  1117. [][]string{
  1118. {"a"},
  1119. {"d"},
  1120. {"b"},
  1121. {"c"},
  1122. {},
  1123. },
  1124. []bool{true, true, true, true, false},
  1125. },
  1126. }
  1127. for i, tt := range tests {
  1128. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  1129. for _, k := range tt.putKeys {
  1130. kvc := clus.RandClient().KV
  1131. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  1132. if _, err := kvc.Put(context.TODO(), req); err != nil {
  1133. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  1134. }
  1135. }
  1136. for j, req := range tt.reqs {
  1137. kvc := clus.RandClient().KV
  1138. resp, err := kvc.Range(context.TODO(), &req)
  1139. if err != nil {
  1140. t.Errorf("#%d.%d: Range error: %v", i, j, err)
  1141. continue
  1142. }
  1143. if len(resp.Kvs) != len(tt.wresps[j]) {
  1144. t.Errorf("#%d.%d: bad len(resp.Kvs). got = %d, want = %d, ", i, j, len(resp.Kvs), len(tt.wresps[j]))
  1145. continue
  1146. }
  1147. for k, wKey := range tt.wresps[j] {
  1148. respKey := string(resp.Kvs[k].Key)
  1149. if respKey != wKey {
  1150. t.Errorf("#%d.%d: key[%d]. got = %v, want = %v, ", i, j, k, respKey, wKey)
  1151. }
  1152. }
  1153. if resp.More != tt.wmores[j] {
  1154. t.Errorf("#%d.%d: bad more. got = %v, want = %v, ", i, j, resp.More, tt.wmores[j])
  1155. }
  1156. wrev := int64(len(tt.putKeys) + 1)
  1157. if resp.Header.Revision != wrev {
  1158. t.Errorf("#%d.%d: bad header revision. got = %d. want = %d", i, j, resp.Header.Revision, wrev)
  1159. }
  1160. }
  1161. clus.Terminate(t)
  1162. }
  1163. }
  1164. func newClusterV3NoClients(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  1165. cfg.UseV3 = true
  1166. cfg.UseGRPC = true
  1167. clus := &ClusterV3{cluster: NewClusterByConfig(t, cfg)}
  1168. clus.Launch(t)
  1169. return clus
  1170. }
  1171. // TestTLSGRPCRejectInsecureClient checks that connection is rejected if server is TLS but not client.
  1172. func TestTLSGRPCRejectInsecureClient(t *testing.T) {
  1173. defer testutil.AfterTest(t)
  1174. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  1175. clus := newClusterV3NoClients(t, &cfg)
  1176. defer clus.Terminate(t)
  1177. // nil out TLS field so client will use an insecure connection
  1178. clus.Members[0].ClientTLSInfo = nil
  1179. client, err := NewClientV3(clus.Members[0])
  1180. if err != nil && err != grpc.ErrClientConnTimeout {
  1181. t.Fatalf("unexpected error (%v)", err)
  1182. } else if client == nil {
  1183. // Ideally, no client would be returned. However, grpc will
  1184. // return a connection without trying to handshake first so
  1185. // the connection appears OK.
  1186. return
  1187. }
  1188. defer client.Close()
  1189. ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  1190. conn := client.ActiveConnection()
  1191. st, err := conn.State()
  1192. if err != nil {
  1193. t.Fatal(err)
  1194. } else if st != grpc.Ready {
  1195. t.Fatalf("expected Ready, got %v", st)
  1196. }
  1197. // rpc will fail to handshake, triggering a connection state change
  1198. donec := make(chan error, 1)
  1199. go func() {
  1200. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  1201. _, perr := client.KV.Put(ctx, reqput)
  1202. donec <- perr
  1203. }()
  1204. st, err = conn.WaitForStateChange(ctx, st)
  1205. if err != nil {
  1206. t.Fatalf("unexpected error waiting for change (%v)", err)
  1207. } else if st != grpc.Connecting && st != grpc.TransientFailure {
  1208. t.Fatalf("expected connecting or transient failure state, got %v", st)
  1209. }
  1210. cancel()
  1211. if perr := <-donec; perr == nil {
  1212. t.Fatalf("expected client error on put")
  1213. }
  1214. }
  1215. // TestTLSGRPCRejectSecureClient checks that connection is rejected if client is TLS but not server.
  1216. func TestTLSGRPCRejectSecureClient(t *testing.T) {
  1217. defer testutil.AfterTest(t)
  1218. cfg := ClusterConfig{Size: 3}
  1219. clus := newClusterV3NoClients(t, &cfg)
  1220. defer clus.Terminate(t)
  1221. clus.Members[0].ClientTLSInfo = &testTLSInfo
  1222. client, err := NewClientV3(clus.Members[0])
  1223. if client != nil || err == nil {
  1224. t.Fatalf("expected no client")
  1225. } else if err != grpc.ErrClientConnTimeout {
  1226. t.Fatalf("unexpected error (%v)", err)
  1227. }
  1228. }
  1229. // TestTLSGRPCAcceptSecureAll checks that connection is accepted if both client and server are TLS
  1230. func TestTLSGRPCAcceptSecureAll(t *testing.T) {
  1231. defer testutil.AfterTest(t)
  1232. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  1233. clus := newClusterV3NoClients(t, &cfg)
  1234. defer clus.Terminate(t)
  1235. client, err := NewClientV3(clus.Members[0])
  1236. if err != nil {
  1237. t.Fatalf("expected tls client (%v)", err)
  1238. }
  1239. defer client.Close()
  1240. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  1241. if _, err := client.KV.Put(context.TODO(), reqput); err != nil {
  1242. t.Fatalf("unexpected error on put over tls (%v)", err)
  1243. }
  1244. }