v3_grpc_test.go 37 KB

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