v3_grpc_test.go 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406
  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. func TestV3TooLargeRequest(t *testing.T) {
  373. defer testutil.AfterTest(t)
  374. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  375. defer clus.Terminate(t)
  376. kvc := clus.RandClient().KV
  377. // 2MB request value
  378. largeV := make([]byte, 2*1024*1024)
  379. preq := &pb.PutRequest{Key: []byte("foo"), Value: largeV}
  380. _, err := kvc.Put(context.Background(), preq)
  381. if err != v3rpc.ErrRequestTooLarge {
  382. t.Errorf("err = %v, want %v", err, v3rpc.ErrRequestTooLarge)
  383. }
  384. }
  385. // TestV3Hash tests hash.
  386. func TestV3Hash(t *testing.T) {
  387. defer testutil.AfterTest(t)
  388. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  389. defer clus.Terminate(t)
  390. kvc := clus.RandClient().KV
  391. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  392. for i := 0; i < 3; i++ {
  393. _, err := kvc.Put(context.Background(), preq)
  394. if err != nil {
  395. t.Fatalf("couldn't put key (%v)", err)
  396. }
  397. }
  398. resp, err := kvc.Hash(context.Background(), &pb.HashRequest{})
  399. if err != nil || resp.Hash == 0 {
  400. t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
  401. }
  402. }
  403. // TestV3WatchFromCurrentRevision tests Watch APIs from current revision.
  404. func TestV3WatchFromCurrentRevision(t *testing.T) {
  405. defer testutil.AfterTest(t)
  406. tests := []struct {
  407. putKeys []string
  408. watchRequest *pb.WatchRequest
  409. wresps []*pb.WatchResponse
  410. }{
  411. // watch the key, matching
  412. {
  413. []string{"foo"},
  414. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  415. CreateRequest: &pb.WatchCreateRequest{
  416. Key: []byte("foo")}}},
  417. []*pb.WatchResponse{
  418. {
  419. Header: &pb.ResponseHeader{Revision: 1},
  420. Created: true,
  421. },
  422. {
  423. Header: &pb.ResponseHeader{Revision: 2},
  424. Created: false,
  425. Events: []*storagepb.Event{
  426. {
  427. Type: storagepb.PUT,
  428. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  429. },
  430. },
  431. },
  432. },
  433. },
  434. // watch the key, non-matching
  435. {
  436. []string{"foo"},
  437. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  438. CreateRequest: &pb.WatchCreateRequest{
  439. Key: []byte("helloworld")}}},
  440. []*pb.WatchResponse{
  441. {
  442. Header: &pb.ResponseHeader{Revision: 1},
  443. Created: true,
  444. },
  445. },
  446. },
  447. // watch the prefix, matching
  448. {
  449. []string{"fooLong"},
  450. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  451. CreateRequest: &pb.WatchCreateRequest{
  452. Prefix: []byte("foo")}}},
  453. []*pb.WatchResponse{
  454. {
  455. Header: &pb.ResponseHeader{Revision: 1},
  456. Created: true,
  457. },
  458. {
  459. Header: &pb.ResponseHeader{Revision: 2},
  460. Created: false,
  461. Events: []*storagepb.Event{
  462. {
  463. Type: storagepb.PUT,
  464. Kv: &storagepb.KeyValue{Key: []byte("fooLong"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  465. },
  466. },
  467. },
  468. },
  469. },
  470. // watch the prefix, non-matching
  471. {
  472. []string{"foo"},
  473. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  474. CreateRequest: &pb.WatchCreateRequest{
  475. Prefix: []byte("helloworld")}}},
  476. []*pb.WatchResponse{
  477. {
  478. Header: &pb.ResponseHeader{Revision: 1},
  479. Created: true,
  480. },
  481. },
  482. },
  483. // multiple puts, one watcher with matching key
  484. {
  485. []string{"foo", "foo", "foo"},
  486. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  487. CreateRequest: &pb.WatchCreateRequest{
  488. Key: []byte("foo")}}},
  489. []*pb.WatchResponse{
  490. {
  491. Header: &pb.ResponseHeader{Revision: 1},
  492. Created: true,
  493. },
  494. {
  495. Header: &pb.ResponseHeader{Revision: 2},
  496. Created: false,
  497. Events: []*storagepb.Event{
  498. {
  499. Type: storagepb.PUT,
  500. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  501. },
  502. },
  503. },
  504. {
  505. Header: &pb.ResponseHeader{Revision: 3},
  506. Created: false,
  507. Events: []*storagepb.Event{
  508. {
  509. Type: storagepb.PUT,
  510. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  511. },
  512. },
  513. },
  514. {
  515. Header: &pb.ResponseHeader{Revision: 4},
  516. Created: false,
  517. Events: []*storagepb.Event{
  518. {
  519. Type: storagepb.PUT,
  520. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  521. },
  522. },
  523. },
  524. },
  525. },
  526. // multiple puts, one watcher with matching prefix
  527. {
  528. []string{"foo", "foo", "foo"},
  529. &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  530. CreateRequest: &pb.WatchCreateRequest{
  531. Prefix: []byte("foo")}}},
  532. []*pb.WatchResponse{
  533. {
  534. Header: &pb.ResponseHeader{Revision: 1},
  535. Created: true,
  536. },
  537. {
  538. Header: &pb.ResponseHeader{Revision: 2},
  539. Created: false,
  540. Events: []*storagepb.Event{
  541. {
  542. Type: storagepb.PUT,
  543. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  544. },
  545. },
  546. },
  547. {
  548. Header: &pb.ResponseHeader{Revision: 3},
  549. Created: false,
  550. Events: []*storagepb.Event{
  551. {
  552. Type: storagepb.PUT,
  553. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 3, Version: 2},
  554. },
  555. },
  556. },
  557. {
  558. Header: &pb.ResponseHeader{Revision: 4},
  559. Created: false,
  560. Events: []*storagepb.Event{
  561. {
  562. Type: storagepb.PUT,
  563. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 3},
  564. },
  565. },
  566. },
  567. },
  568. },
  569. }
  570. for i, tt := range tests {
  571. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  572. wAPI := clus.RandClient().Watch
  573. ctx, cancel := context.WithCancel(context.Background())
  574. defer cancel()
  575. wStream, err := wAPI.Watch(ctx)
  576. if err != nil {
  577. t.Fatalf("#%d: wAPI.Watch error: %v", i, err)
  578. }
  579. if err := wStream.Send(tt.watchRequest); err != nil {
  580. t.Fatalf("#%d: wStream.Send error: %v", i, err)
  581. }
  582. go func() {
  583. for _, k := range tt.putKeys {
  584. kvc := clus.RandClient().KV
  585. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  586. if _, err := kvc.Put(context.TODO(), req); err != nil {
  587. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  588. }
  589. }
  590. }()
  591. var createdWatchId int64
  592. for j, wresp := range tt.wresps {
  593. resp, err := wStream.Recv()
  594. if err != nil {
  595. t.Errorf("#%d.%d: wStream.Recv error: %v", i, j, err)
  596. }
  597. if resp.Header == nil {
  598. t.Fatalf("#%d.%d: unexpected nil resp.Header", i, j)
  599. }
  600. if resp.Header.Revision != wresp.Header.Revision {
  601. t.Errorf("#%d.%d: resp.Header.Revision got = %d, want = %d", i, j, resp.Header.Revision, wresp.Header.Revision)
  602. }
  603. if wresp.Created != resp.Created {
  604. t.Errorf("#%d.%d: resp.Created got = %v, want = %v", i, j, resp.Created, wresp.Created)
  605. }
  606. if resp.Created {
  607. createdWatchId = resp.WatchId
  608. }
  609. if resp.WatchId != createdWatchId {
  610. t.Errorf("#%d.%d: resp.WatchId got = %d, want = %d", i, j, resp.WatchId, createdWatchId)
  611. }
  612. if !reflect.DeepEqual(resp.Events, wresp.Events) {
  613. t.Errorf("#%d.%d: resp.Events got = %+v, want = %+v", i, j, resp.Events, wresp.Events)
  614. }
  615. }
  616. rok, nr := WaitResponse(wStream, 1*time.Second)
  617. if !rok {
  618. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  619. }
  620. // can't defer because tcp ports will be in use
  621. clus.Terminate(t)
  622. }
  623. }
  624. // TestV3WatchCancelSynced tests Watch APIs cancellation from synced map.
  625. func TestV3WatchCancelSynced(t *testing.T) {
  626. defer testutil.AfterTest(t)
  627. testV3WatchCancel(t, 0)
  628. }
  629. // TestV3WatchCancelUnsynced tests Watch APIs cancellation from unsynced map.
  630. func TestV3WatchCancelUnsynced(t *testing.T) {
  631. defer testutil.AfterTest(t)
  632. testV3WatchCancel(t, 1)
  633. }
  634. func testV3WatchCancel(t *testing.T, startRev int64) {
  635. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  636. ctx, cancel := context.WithCancel(context.Background())
  637. defer cancel()
  638. wStream, errW := clus.RandClient().Watch.Watch(ctx)
  639. if errW != nil {
  640. t.Fatalf("wAPI.Watch error: %v", errW)
  641. }
  642. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  643. CreateRequest: &pb.WatchCreateRequest{
  644. Key: []byte("foo"), StartRevision: startRev}}}
  645. if err := wStream.Send(wreq); err != nil {
  646. t.Fatalf("wStream.Send error: %v", err)
  647. }
  648. wresp, errR := wStream.Recv()
  649. if errR != nil {
  650. t.Errorf("wStream.Recv error: %v", errR)
  651. }
  652. if !wresp.Created {
  653. t.Errorf("wresp.Created got = %v, want = true", wresp.Created)
  654. }
  655. creq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CancelRequest{
  656. CancelRequest: &pb.WatchCancelRequest{
  657. WatchId: wresp.WatchId}}}
  658. if err := wStream.Send(creq); err != nil {
  659. t.Fatalf("wStream.Send error: %v", err)
  660. }
  661. cresp, err := wStream.Recv()
  662. if err != nil {
  663. t.Errorf("wStream.Recv error: %v", err)
  664. }
  665. if !cresp.Canceled {
  666. t.Errorf("cresp.Canceled got = %v, want = true", cresp.Canceled)
  667. }
  668. kvc := clus.RandClient().KV
  669. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  670. t.Errorf("couldn't put key (%v)", err)
  671. }
  672. // watch got canceled, so this should block
  673. rok, nr := WaitResponse(wStream, 1*time.Second)
  674. if !rok {
  675. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  676. }
  677. clus.Terminate(t)
  678. }
  679. func TestV3WatchMultipleWatchersSynced(t *testing.T) {
  680. defer testutil.AfterTest(t)
  681. testV3WatchMultipleWatchers(t, 0)
  682. }
  683. func TestV3WatchMultipleWatchersUnsynced(t *testing.T) {
  684. defer testutil.AfterTest(t)
  685. testV3WatchMultipleWatchers(t, 1)
  686. }
  687. // testV3WatchMultipleWatchers tests multiple watchers on the same key
  688. // and one watcher with matching prefix. It first puts the key
  689. // that matches all watchers, and another key that matches only
  690. // one watcher to test if it receives expected events.
  691. func testV3WatchMultipleWatchers(t *testing.T, startRev int64) {
  692. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  693. kvc := clus.RandClient().KV
  694. ctx, cancel := context.WithCancel(context.Background())
  695. defer cancel()
  696. wStream, errW := clus.RandClient().Watch.Watch(ctx)
  697. if errW != nil {
  698. t.Fatalf("wAPI.Watch error: %v", errW)
  699. }
  700. watchKeyN := 4
  701. for i := 0; i < watchKeyN+1; i++ {
  702. var wreq *pb.WatchRequest
  703. if i < watchKeyN {
  704. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  705. CreateRequest: &pb.WatchCreateRequest{
  706. Key: []byte("foo"), StartRevision: startRev}}}
  707. } else {
  708. wreq = &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  709. CreateRequest: &pb.WatchCreateRequest{
  710. Prefix: []byte("fo"), StartRevision: startRev}}}
  711. }
  712. if err := wStream.Send(wreq); err != nil {
  713. t.Fatalf("wStream.Send error: %v", err)
  714. }
  715. }
  716. ids := make(map[int64]struct{})
  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 !wresp.Created {
  723. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  724. }
  725. ids[wresp.WatchId] = struct{}{}
  726. }
  727. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  728. t.Fatalf("couldn't put key (%v)", err)
  729. }
  730. for i := 0; i < watchKeyN+1; i++ {
  731. wresp, err := wStream.Recv()
  732. if err != nil {
  733. t.Fatalf("wStream.Recv error: %v", err)
  734. }
  735. if _, ok := ids[wresp.WatchId]; !ok {
  736. t.Errorf("watchId %d is not created!", wresp.WatchId)
  737. } else {
  738. delete(ids, wresp.WatchId)
  739. }
  740. if len(wresp.Events) == 0 {
  741. t.Errorf("#%d: no events received", i)
  742. }
  743. for _, ev := range wresp.Events {
  744. if string(ev.Kv.Key) != "foo" {
  745. t.Errorf("ev.Kv.Key got = %s, want = foo", ev.Kv.Key)
  746. }
  747. if string(ev.Kv.Value) != "bar" {
  748. t.Errorf("ev.Kv.Value got = %s, want = bar", ev.Kv.Value)
  749. }
  750. }
  751. }
  752. // now put one key that has only one matching watcher
  753. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("fo"), Value: []byte("bar")}); err != nil {
  754. t.Fatalf("couldn't put key (%v)", err)
  755. }
  756. wresp, err := wStream.Recv()
  757. if err != nil {
  758. t.Errorf("wStream.Recv error: %v", err)
  759. }
  760. if len(wresp.Events) != 1 {
  761. t.Fatalf("len(wresp.Events) got = %d, want = 1", len(wresp.Events))
  762. }
  763. if string(wresp.Events[0].Kv.Key) != "fo" {
  764. t.Errorf("wresp.Events[0].Kv.Key got = %s, want = fo", wresp.Events[0].Kv.Key)
  765. }
  766. // now Recv should block because there is no more events coming
  767. rok, nr := WaitResponse(wStream, 1*time.Second)
  768. if !rok {
  769. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  770. }
  771. clus.Terminate(t)
  772. }
  773. func TestV3WatchMultipleEventsTxnSynced(t *testing.T) {
  774. defer testutil.AfterTest(t)
  775. testV3WatchMultipleEventsTxn(t, 0)
  776. }
  777. func TestV3WatchMultipleEventsTxnUnsynced(t *testing.T) {
  778. defer testutil.AfterTest(t)
  779. testV3WatchMultipleEventsTxn(t, 1)
  780. }
  781. // testV3WatchMultipleEventsTxn tests Watch APIs when it receives multiple events.
  782. func testV3WatchMultipleEventsTxn(t *testing.T, startRev int64) {
  783. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  784. ctx, cancel := context.WithCancel(context.Background())
  785. defer cancel()
  786. wStream, wErr := clus.RandClient().Watch.Watch(ctx)
  787. if wErr != nil {
  788. t.Fatalf("wAPI.Watch error: %v", wErr)
  789. }
  790. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  791. CreateRequest: &pb.WatchCreateRequest{
  792. Prefix: []byte("foo"), StartRevision: startRev}}}
  793. if err := wStream.Send(wreq); err != nil {
  794. t.Fatalf("wStream.Send error: %v", err)
  795. }
  796. kvc := clus.RandClient().KV
  797. txn := pb.TxnRequest{}
  798. for i := 0; i < 3; i++ {
  799. ru := &pb.RequestUnion{}
  800. ru.Request = &pb.RequestUnion_RequestPut{
  801. RequestPut: &pb.PutRequest{
  802. Key: []byte(fmt.Sprintf("foo%d", i)), Value: []byte("bar")}}
  803. txn.Success = append(txn.Success, ru)
  804. }
  805. tresp, err := kvc.Txn(context.Background(), &txn)
  806. if err != nil {
  807. t.Fatalf("kvc.Txn error: %v", err)
  808. }
  809. if !tresp.Succeeded {
  810. t.Fatalf("kvc.Txn failed: %+v", tresp)
  811. }
  812. events := []*storagepb.Event{}
  813. for len(events) < 3 {
  814. resp, err := wStream.Recv()
  815. if err != nil {
  816. t.Errorf("wStream.Recv error: %v", err)
  817. }
  818. if resp.Created {
  819. continue
  820. }
  821. events = append(events, resp.Events...)
  822. }
  823. sort.Sort(eventsSortByKey(events))
  824. wevents := []*storagepb.Event{
  825. {
  826. Type: storagepb.PUT,
  827. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  828. },
  829. {
  830. Type: storagepb.PUT,
  831. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  832. },
  833. {
  834. Type: storagepb.PUT,
  835. Kv: &storagepb.KeyValue{Key: []byte("foo2"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  836. },
  837. }
  838. if !reflect.DeepEqual(events, wevents) {
  839. t.Errorf("events got = %+v, want = %+v", events, wevents)
  840. }
  841. rok, nr := WaitResponse(wStream, 1*time.Second)
  842. if !rok {
  843. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  844. }
  845. // can't defer because tcp ports will be in use
  846. clus.Terminate(t)
  847. }
  848. type eventsSortByKey []*storagepb.Event
  849. func (evs eventsSortByKey) Len() int { return len(evs) }
  850. func (evs eventsSortByKey) Swap(i, j int) { evs[i], evs[j] = evs[j], evs[i] }
  851. func (evs eventsSortByKey) Less(i, j int) bool { return bytes.Compare(evs[i].Kv.Key, evs[j].Kv.Key) < 0 }
  852. func TestV3WatchMultipleEventsPutUnsynced(t *testing.T) {
  853. defer testutil.AfterTest(t)
  854. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  855. defer clus.Terminate(t)
  856. kvc := clus.RandClient().KV
  857. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  858. t.Fatalf("couldn't put key (%v)", err)
  859. }
  860. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  861. t.Fatalf("couldn't put key (%v)", err)
  862. }
  863. ctx, cancel := context.WithCancel(context.Background())
  864. defer cancel()
  865. wStream, wErr := clus.RandClient().Watch.Watch(ctx)
  866. if wErr != nil {
  867. t.Fatalf("wAPI.Watch error: %v", wErr)
  868. }
  869. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  870. CreateRequest: &pb.WatchCreateRequest{
  871. Prefix: []byte("foo"), StartRevision: 1}}}
  872. if err := wStream.Send(wreq); err != nil {
  873. t.Fatalf("wStream.Send error: %v", err)
  874. }
  875. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo0"), Value: []byte("bar")}); err != nil {
  876. t.Fatalf("couldn't put key (%v)", err)
  877. }
  878. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo1"), Value: []byte("bar")}); err != nil {
  879. t.Fatalf("couldn't put key (%v)", err)
  880. }
  881. allWevents := []*storagepb.Event{
  882. {
  883. Type: storagepb.PUT,
  884. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  885. },
  886. {
  887. Type: storagepb.PUT,
  888. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 3, Version: 1},
  889. },
  890. {
  891. Type: storagepb.PUT,
  892. Kv: &storagepb.KeyValue{Key: []byte("foo0"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 4, Version: 2},
  893. },
  894. {
  895. Type: storagepb.PUT,
  896. Kv: &storagepb.KeyValue{Key: []byte("foo1"), Value: []byte("bar"), CreateRevision: 3, ModRevision: 5, Version: 2},
  897. },
  898. }
  899. events := []*storagepb.Event{}
  900. for len(events) < 4 {
  901. resp, err := wStream.Recv()
  902. if err != nil {
  903. t.Errorf("wStream.Recv error: %v", err)
  904. }
  905. if resp.Created {
  906. continue
  907. }
  908. events = append(events, resp.Events...)
  909. // if PUT requests are committed by now, first receive would return
  910. // multiple events, but if not, it returns a single event. In SSD,
  911. // it should return 4 events at once.
  912. }
  913. if !reflect.DeepEqual(events, allWevents) {
  914. t.Errorf("events got = %+v, want = %+v", events, allWevents)
  915. }
  916. rok, nr := WaitResponse(wStream, 1*time.Second)
  917. if !rok {
  918. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  919. }
  920. }
  921. func TestV3WatchMultipleStreamsSynced(t *testing.T) {
  922. defer testutil.AfterTest(t)
  923. testV3WatchMultipleStreams(t, 0)
  924. }
  925. func TestV3WatchMultipleStreamsUnsynced(t *testing.T) {
  926. defer testutil.AfterTest(t)
  927. testV3WatchMultipleStreams(t, 1)
  928. }
  929. // testV3WatchMultipleStreams tests multiple watchers on the same key on multiple streams.
  930. func testV3WatchMultipleStreams(t *testing.T, startRev int64) {
  931. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  932. wAPI := clus.RandClient().Watch
  933. kvc := clus.RandClient().KV
  934. streams := make([]pb.Watch_WatchClient, 5)
  935. for i := range streams {
  936. ctx, cancel := context.WithCancel(context.Background())
  937. defer cancel()
  938. wStream, errW := wAPI.Watch(ctx)
  939. if errW != nil {
  940. t.Fatalf("wAPI.Watch error: %v", errW)
  941. }
  942. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  943. CreateRequest: &pb.WatchCreateRequest{
  944. Key: []byte("foo"), StartRevision: startRev}}}
  945. if err := wStream.Send(wreq); err != nil {
  946. t.Fatalf("wStream.Send error: %v", err)
  947. }
  948. streams[i] = wStream
  949. }
  950. for _, wStream := range streams {
  951. wresp, err := wStream.Recv()
  952. if err != nil {
  953. t.Fatalf("wStream.Recv error: %v", err)
  954. }
  955. if !wresp.Created {
  956. t.Fatalf("wresp.Created got = %v, want = true", wresp.Created)
  957. }
  958. }
  959. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}); err != nil {
  960. t.Fatalf("couldn't put key (%v)", err)
  961. }
  962. var wg sync.WaitGroup
  963. wg.Add(len(streams))
  964. wevents := []*storagepb.Event{
  965. {
  966. Type: storagepb.PUT,
  967. Kv: &storagepb.KeyValue{Key: []byte("foo"), Value: []byte("bar"), CreateRevision: 2, ModRevision: 2, Version: 1},
  968. },
  969. }
  970. for i := range streams {
  971. go func(i int) {
  972. defer wg.Done()
  973. wStream := streams[i]
  974. wresp, err := wStream.Recv()
  975. if err != nil {
  976. t.Fatalf("wStream.Recv error: %v", err)
  977. }
  978. if wresp.WatchId != 0 {
  979. t.Errorf("watchId got = %d, want = 0", wresp.WatchId)
  980. }
  981. if !reflect.DeepEqual(wresp.Events, wevents) {
  982. t.Errorf("wresp.Events got = %+v, want = %+v", wresp.Events, wevents)
  983. }
  984. // now Recv should block because there is no more events coming
  985. rok, nr := WaitResponse(wStream, 1*time.Second)
  986. if !rok {
  987. t.Errorf("unexpected pb.WatchResponse is received %+v", nr)
  988. }
  989. }(i)
  990. }
  991. wg.Wait()
  992. clus.Terminate(t)
  993. }
  994. // WaitResponse waits on the given stream for given duration.
  995. // If there is no more events, true and a nil response will be
  996. // returned closing the WatchClient stream. Or the response will
  997. // be returned.
  998. func WaitResponse(wc pb.Watch_WatchClient, timeout time.Duration) (bool, *pb.WatchResponse) {
  999. rCh := make(chan *pb.WatchResponse)
  1000. go func() {
  1001. resp, _ := wc.Recv()
  1002. rCh <- resp
  1003. }()
  1004. select {
  1005. case nr := <-rCh:
  1006. return false, nr
  1007. case <-time.After(timeout):
  1008. }
  1009. wc.CloseSend()
  1010. rv, ok := <-rCh
  1011. if rv != nil || !ok {
  1012. return false, rv
  1013. }
  1014. return true, nil
  1015. }
  1016. func TestV3RangeRequest(t *testing.T) {
  1017. defer testutil.AfterTest(t)
  1018. tests := []struct {
  1019. putKeys []string
  1020. reqs []pb.RangeRequest
  1021. wresps [][]string
  1022. wmores []bool
  1023. }{
  1024. // single key
  1025. {
  1026. []string{"foo", "bar"},
  1027. []pb.RangeRequest{
  1028. // exists
  1029. {Key: []byte("foo")},
  1030. // doesn't exist
  1031. {Key: []byte("baz")},
  1032. },
  1033. [][]string{
  1034. {"foo"},
  1035. {},
  1036. },
  1037. []bool{false, false},
  1038. },
  1039. // multi-key
  1040. {
  1041. []string{"a", "b", "c", "d", "e"},
  1042. []pb.RangeRequest{
  1043. // all in range
  1044. {Key: []byte("a"), RangeEnd: []byte("z")},
  1045. // [b, d)
  1046. {Key: []byte("b"), RangeEnd: []byte("d")},
  1047. // out of range
  1048. {Key: []byte("f"), RangeEnd: []byte("z")},
  1049. // [c,c) = empty
  1050. {Key: []byte("c"), RangeEnd: []byte("c")},
  1051. // [d, b) = empty
  1052. {Key: []byte("d"), RangeEnd: []byte("b")},
  1053. },
  1054. [][]string{
  1055. {"a", "b", "c", "d", "e"},
  1056. {"b", "c"},
  1057. {},
  1058. {},
  1059. {},
  1060. },
  1061. []bool{false, false, false, false, false},
  1062. },
  1063. // revision
  1064. {
  1065. []string{"a", "b", "c", "d", "e"},
  1066. []pb.RangeRequest{
  1067. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 0},
  1068. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 1},
  1069. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 2},
  1070. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 3},
  1071. },
  1072. [][]string{
  1073. {"a", "b", "c", "d", "e"},
  1074. {},
  1075. {"a"},
  1076. {"a", "b"},
  1077. },
  1078. []bool{false, false, false, false},
  1079. },
  1080. // limit
  1081. {
  1082. []string{"foo", "bar"},
  1083. []pb.RangeRequest{
  1084. // more
  1085. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 1},
  1086. // no more
  1087. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 2},
  1088. },
  1089. [][]string{
  1090. {"bar"},
  1091. {"bar", "foo"},
  1092. },
  1093. []bool{true, false},
  1094. },
  1095. // sort
  1096. {
  1097. []string{"b", "a", "c", "d", "c"},
  1098. []pb.RangeRequest{
  1099. {
  1100. Key: []byte("a"), RangeEnd: []byte("z"),
  1101. Limit: 1,
  1102. SortOrder: pb.RangeRequest_ASCEND,
  1103. SortTarget: pb.RangeRequest_KEY,
  1104. },
  1105. {
  1106. Key: []byte("a"), RangeEnd: []byte("z"),
  1107. Limit: 1,
  1108. SortOrder: pb.RangeRequest_DESCEND,
  1109. SortTarget: pb.RangeRequest_KEY,
  1110. },
  1111. {
  1112. Key: []byte("a"), RangeEnd: []byte("z"),
  1113. Limit: 1,
  1114. SortOrder: pb.RangeRequest_ASCEND,
  1115. SortTarget: pb.RangeRequest_CREATE,
  1116. },
  1117. {
  1118. Key: []byte("a"), RangeEnd: []byte("z"),
  1119. Limit: 1,
  1120. SortOrder: pb.RangeRequest_DESCEND,
  1121. SortTarget: pb.RangeRequest_MOD,
  1122. },
  1123. {
  1124. Key: []byte("z"), RangeEnd: []byte("z"),
  1125. Limit: 1,
  1126. SortOrder: pb.RangeRequest_DESCEND,
  1127. SortTarget: pb.RangeRequest_CREATE,
  1128. },
  1129. },
  1130. [][]string{
  1131. {"a"},
  1132. {"d"},
  1133. {"b"},
  1134. {"c"},
  1135. {},
  1136. },
  1137. []bool{true, true, true, true, false},
  1138. },
  1139. }
  1140. for i, tt := range tests {
  1141. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  1142. for _, k := range tt.putKeys {
  1143. kvc := clus.RandClient().KV
  1144. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  1145. if _, err := kvc.Put(context.TODO(), req); err != nil {
  1146. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  1147. }
  1148. }
  1149. for j, req := range tt.reqs {
  1150. kvc := clus.RandClient().KV
  1151. resp, err := kvc.Range(context.TODO(), &req)
  1152. if err != nil {
  1153. t.Errorf("#%d.%d: Range error: %v", i, j, err)
  1154. continue
  1155. }
  1156. if len(resp.Kvs) != len(tt.wresps[j]) {
  1157. t.Errorf("#%d.%d: bad len(resp.Kvs). got = %d, want = %d, ", i, j, len(resp.Kvs), len(tt.wresps[j]))
  1158. continue
  1159. }
  1160. for k, wKey := range tt.wresps[j] {
  1161. respKey := string(resp.Kvs[k].Key)
  1162. if respKey != wKey {
  1163. t.Errorf("#%d.%d: key[%d]. got = %v, want = %v, ", i, j, k, respKey, wKey)
  1164. }
  1165. }
  1166. if resp.More != tt.wmores[j] {
  1167. t.Errorf("#%d.%d: bad more. got = %v, want = %v, ", i, j, resp.More, tt.wmores[j])
  1168. }
  1169. wrev := int64(len(tt.putKeys) + 1)
  1170. if resp.Header.Revision != wrev {
  1171. t.Errorf("#%d.%d: bad header revision. got = %d. want = %d", i, j, resp.Header.Revision, wrev)
  1172. }
  1173. }
  1174. clus.Terminate(t)
  1175. }
  1176. }
  1177. func newClusterV3NoClients(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  1178. cfg.UseV3 = true
  1179. cfg.UseGRPC = true
  1180. clus := &ClusterV3{cluster: NewClusterByConfig(t, cfg)}
  1181. clus.Launch(t)
  1182. return clus
  1183. }
  1184. // TestTLSGRPCRejectInsecureClient checks that connection is rejected if server is TLS but not client.
  1185. func TestTLSGRPCRejectInsecureClient(t *testing.T) {
  1186. defer testutil.AfterTest(t)
  1187. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  1188. clus := newClusterV3NoClients(t, &cfg)
  1189. defer clus.Terminate(t)
  1190. // nil out TLS field so client will use an insecure connection
  1191. clus.Members[0].ClientTLSInfo = nil
  1192. client, err := NewClientV3(clus.Members[0])
  1193. if err != nil && err != grpc.ErrClientConnTimeout {
  1194. t.Fatalf("unexpected error (%v)", err)
  1195. } else if client == nil {
  1196. // Ideally, no client would be returned. However, grpc will
  1197. // return a connection without trying to handshake first so
  1198. // the connection appears OK.
  1199. return
  1200. }
  1201. defer client.Close()
  1202. ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  1203. conn := client.ActiveConnection()
  1204. st, err := conn.State()
  1205. if err != nil {
  1206. t.Fatal(err)
  1207. } else if st != grpc.Ready {
  1208. t.Fatalf("expected Ready, got %v", st)
  1209. }
  1210. // rpc will fail to handshake, triggering a connection state change
  1211. donec := make(chan error, 1)
  1212. go func() {
  1213. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  1214. _, perr := client.KV.Put(ctx, reqput)
  1215. donec <- perr
  1216. }()
  1217. st, err = conn.WaitForStateChange(ctx, st)
  1218. if err != nil {
  1219. t.Fatalf("unexpected error waiting for change (%v)", err)
  1220. } else if st != grpc.Connecting && st != grpc.TransientFailure {
  1221. t.Fatalf("expected connecting or transient failure state, got %v", st)
  1222. }
  1223. cancel()
  1224. if perr := <-donec; perr == nil {
  1225. t.Fatalf("expected client error on put")
  1226. }
  1227. }
  1228. // TestTLSGRPCRejectSecureClient checks that connection is rejected if client is TLS but not server.
  1229. func TestTLSGRPCRejectSecureClient(t *testing.T) {
  1230. defer testutil.AfterTest(t)
  1231. cfg := ClusterConfig{Size: 3}
  1232. clus := newClusterV3NoClients(t, &cfg)
  1233. defer clus.Terminate(t)
  1234. clus.Members[0].ClientTLSInfo = &testTLSInfo
  1235. client, err := NewClientV3(clus.Members[0])
  1236. if client != nil || err == nil {
  1237. t.Fatalf("expected no client")
  1238. } else if err != grpc.ErrClientConnTimeout {
  1239. t.Fatalf("unexpected error (%v)", err)
  1240. }
  1241. }
  1242. // TestTLSGRPCAcceptSecureAll checks that connection is accepted if both client and server are TLS
  1243. func TestTLSGRPCAcceptSecureAll(t *testing.T) {
  1244. defer testutil.AfterTest(t)
  1245. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  1246. clus := newClusterV3NoClients(t, &cfg)
  1247. defer clus.Terminate(t)
  1248. client, err := NewClientV3(clus.Members[0])
  1249. if err != nil {
  1250. t.Fatalf("expected tls client (%v)", err)
  1251. }
  1252. defer client.Close()
  1253. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  1254. if _, err := client.KV.Put(context.TODO(), reqput); err != nil {
  1255. t.Fatalf("unexpected error on put over tls (%v)", err)
  1256. }
  1257. }