v3_grpc_test.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  1. // Copyright 2016 The etcd Authors
  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.
  14. package integration
  15. import (
  16. "fmt"
  17. "math/rand"
  18. "reflect"
  19. "testing"
  20. "time"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  22. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  23. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. "golang.org/x/net/context"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/metadata"
  28. )
  29. // TestV3PutOverwrite puts a key with the v3 api to a random cluster member,
  30. // overwrites it, then checks that the change was applied.
  31. func TestV3PutOverwrite(t *testing.T) {
  32. defer testutil.AfterTest(t)
  33. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  34. defer clus.Terminate(t)
  35. kvc := toGRPC(clus.RandClient()).KV
  36. key := []byte("foo")
  37. reqput := &pb.PutRequest{Key: key, Value: []byte("bar")}
  38. respput, err := kvc.Put(context.TODO(), reqput)
  39. if err != nil {
  40. t.Fatalf("couldn't put key (%v)", err)
  41. }
  42. // overwrite
  43. reqput.Value = []byte("baz")
  44. respput2, err := kvc.Put(context.TODO(), reqput)
  45. if err != nil {
  46. t.Fatalf("couldn't put key (%v)", err)
  47. }
  48. if respput2.Header.Revision <= respput.Header.Revision {
  49. t.Fatalf("expected newer revision on overwrite, got %v <= %v",
  50. respput2.Header.Revision, respput.Header.Revision)
  51. }
  52. reqrange := &pb.RangeRequest{Key: key}
  53. resprange, err := kvc.Range(context.TODO(), reqrange)
  54. if err != nil {
  55. t.Fatalf("couldn't get key (%v)", err)
  56. }
  57. if len(resprange.Kvs) != 1 {
  58. t.Fatalf("expected 1 key, got %v", len(resprange.Kvs))
  59. }
  60. kv := resprange.Kvs[0]
  61. if kv.ModRevision <= kv.CreateRevision {
  62. t.Errorf("expected modRev > createRev, got %d <= %d",
  63. kv.ModRevision, kv.CreateRevision)
  64. }
  65. if !reflect.DeepEqual(reqput.Value, kv.Value) {
  66. t.Errorf("expected value %v, got %v", reqput.Value, kv.Value)
  67. }
  68. }
  69. // TestPutRestart checks if a put after an unrelated member restart succeeds
  70. func TestV3PutRestart(t *testing.T) {
  71. defer testutil.AfterTest(t)
  72. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  73. defer clus.Terminate(t)
  74. kvIdx := rand.Intn(3)
  75. kvc := toGRPC(clus.Client(kvIdx)).KV
  76. stopIdx := kvIdx
  77. for stopIdx == kvIdx {
  78. stopIdx = rand.Intn(3)
  79. }
  80. clus.clients[stopIdx].Close()
  81. clus.Members[stopIdx].Stop(t)
  82. clus.Members[stopIdx].Restart(t)
  83. c, cerr := NewClientV3(clus.Members[stopIdx])
  84. if cerr != nil {
  85. t.Fatalf("cannot create client: %v", cerr)
  86. }
  87. clus.clients[stopIdx] = c
  88. ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
  89. defer cancel()
  90. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  91. _, err := kvc.Put(ctx, reqput)
  92. if err != nil && err == ctx.Err() {
  93. t.Fatalf("expected grpc error, got local ctx error (%v)", err)
  94. }
  95. }
  96. // TestV3CompactCurrentRev ensures keys are present when compacting on current revision.
  97. func TestV3CompactCurrentRev(t *testing.T) {
  98. defer testutil.AfterTest(t)
  99. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  100. defer clus.Terminate(t)
  101. kvc := toGRPC(clus.RandClient()).KV
  102. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  103. for i := 0; i < 3; i++ {
  104. if _, err := kvc.Put(context.Background(), preq); err != nil {
  105. t.Fatalf("couldn't put key (%v)", err)
  106. }
  107. }
  108. // compact on current revision
  109. _, err := kvc.Compact(context.Background(), &pb.CompactionRequest{Revision: 4})
  110. if err != nil {
  111. t.Fatalf("couldn't compact kv space (%v)", err)
  112. }
  113. // key still exists?
  114. _, err = kvc.Range(context.Background(), &pb.RangeRequest{Key: []byte("foo")})
  115. if err != nil {
  116. t.Fatalf("couldn't get key after compaction (%v)", err)
  117. }
  118. }
  119. func TestV3TxnTooManyOps(t *testing.T) {
  120. defer testutil.AfterTest(t)
  121. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  122. defer clus.Terminate(t)
  123. kvc := toGRPC(clus.RandClient()).KV
  124. // unique keys
  125. i := new(int)
  126. keyf := func() []byte {
  127. *i++
  128. return []byte(fmt.Sprintf("key-%d", i))
  129. }
  130. addCompareOps := func(txn *pb.TxnRequest) {
  131. txn.Compare = append(txn.Compare,
  132. &pb.Compare{
  133. Result: pb.Compare_GREATER,
  134. Target: pb.Compare_CREATE,
  135. Key: keyf(),
  136. })
  137. }
  138. addSuccessOps := func(txn *pb.TxnRequest) {
  139. txn.Success = append(txn.Success,
  140. &pb.RequestOp{
  141. Request: &pb.RequestOp_RequestPut{
  142. RequestPut: &pb.PutRequest{
  143. Key: keyf(),
  144. Value: []byte("bar"),
  145. },
  146. },
  147. })
  148. }
  149. addFailureOps := func(txn *pb.TxnRequest) {
  150. txn.Failure = append(txn.Failure,
  151. &pb.RequestOp{
  152. Request: &pb.RequestOp_RequestPut{
  153. RequestPut: &pb.PutRequest{
  154. Key: keyf(),
  155. Value: []byte("bar"),
  156. },
  157. },
  158. })
  159. }
  160. tests := []func(txn *pb.TxnRequest){
  161. addCompareOps,
  162. addSuccessOps,
  163. addFailureOps,
  164. }
  165. for i, tt := range tests {
  166. txn := &pb.TxnRequest{}
  167. for j := 0; j < v3rpc.MaxOpsPerTxn+1; j++ {
  168. tt(txn)
  169. }
  170. _, err := kvc.Txn(context.Background(), txn)
  171. if !eqErrGRPC(err, rpctypes.ErrGRPCTooManyOps) {
  172. t.Errorf("#%d: err = %v, want %v", i, err, rpctypes.ErrGRPCTooManyOps)
  173. }
  174. }
  175. }
  176. func TestV3TxnDuplicateKeys(t *testing.T) {
  177. defer testutil.AfterTest(t)
  178. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  179. defer clus.Terminate(t)
  180. putreq := &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}}}
  181. delKeyReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
  182. RequestDeleteRange: &pb.DeleteRangeRequest{
  183. Key: []byte("abc"),
  184. },
  185. },
  186. }
  187. delInRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
  188. RequestDeleteRange: &pb.DeleteRangeRequest{
  189. Key: []byte("a"), RangeEnd: []byte("b"),
  190. },
  191. },
  192. }
  193. delOutOfRangeReq := &pb.RequestOp{Request: &pb.RequestOp_RequestDeleteRange{
  194. RequestDeleteRange: &pb.DeleteRangeRequest{
  195. Key: []byte("abb"), RangeEnd: []byte("abc"),
  196. },
  197. },
  198. }
  199. kvc := toGRPC(clus.RandClient()).KV
  200. tests := []struct {
  201. txnSuccess []*pb.RequestOp
  202. werr error
  203. }{
  204. {
  205. txnSuccess: []*pb.RequestOp{putreq, putreq},
  206. werr: rpctypes.ErrGRPCDuplicateKey,
  207. },
  208. {
  209. txnSuccess: []*pb.RequestOp{putreq, delKeyReq},
  210. werr: rpctypes.ErrGRPCDuplicateKey,
  211. },
  212. {
  213. txnSuccess: []*pb.RequestOp{putreq, delInRangeReq},
  214. werr: rpctypes.ErrGRPCDuplicateKey,
  215. },
  216. {
  217. txnSuccess: []*pb.RequestOp{delKeyReq, delInRangeReq, delKeyReq, delInRangeReq},
  218. werr: nil,
  219. },
  220. {
  221. txnSuccess: []*pb.RequestOp{putreq, delOutOfRangeReq},
  222. werr: nil,
  223. },
  224. }
  225. for i, tt := range tests {
  226. txn := &pb.TxnRequest{Success: tt.txnSuccess}
  227. _, err := kvc.Txn(context.Background(), txn)
  228. if !eqErrGRPC(err, tt.werr) {
  229. t.Errorf("#%d: err = %v, want %v", i, err, tt.werr)
  230. }
  231. }
  232. }
  233. // Testv3TxnRevision tests that the transaction header revision is set as expected.
  234. func TestV3TxnRevision(t *testing.T) {
  235. defer testutil.AfterTest(t)
  236. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  237. defer clus.Terminate(t)
  238. kvc := toGRPC(clus.RandClient()).KV
  239. pr := &pb.PutRequest{Key: []byte("abc"), Value: []byte("def")}
  240. presp, err := kvc.Put(context.TODO(), pr)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. txnget := &pb.RequestOp{Request: &pb.RequestOp_RequestRange{RequestRange: &pb.RangeRequest{Key: []byte("abc")}}}
  245. txn := &pb.TxnRequest{Success: []*pb.RequestOp{txnget}}
  246. tresp, err := kvc.Txn(context.TODO(), txn)
  247. if err != nil {
  248. t.Fatal(err)
  249. }
  250. // did not update revision
  251. if presp.Header.Revision != tresp.Header.Revision {
  252. t.Fatalf("got rev %d, wanted rev %d", tresp.Header.Revision, presp.Header.Revision)
  253. }
  254. txnput := &pb.RequestOp{Request: &pb.RequestOp_RequestPut{RequestPut: &pb.PutRequest{Key: []byte("abc"), Value: []byte("123")}}}
  255. txn = &pb.TxnRequest{Success: []*pb.RequestOp{txnput}}
  256. tresp, err = kvc.Txn(context.TODO(), txn)
  257. if err != nil {
  258. t.Fatal(err)
  259. }
  260. // updated revision
  261. if tresp.Header.Revision != presp.Header.Revision+1 {
  262. t.Fatalf("got rev %d, wanted rev %d", tresp.Header.Revision, presp.Header.Revision+1)
  263. }
  264. }
  265. // TestV3PutMissingLease ensures that a Put on a key with a bogus lease fails.
  266. func TestV3PutMissingLease(t *testing.T) {
  267. defer testutil.AfterTest(t)
  268. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  269. defer clus.Terminate(t)
  270. kvc := toGRPC(clus.RandClient()).KV
  271. key := []byte("foo")
  272. preq := &pb.PutRequest{Key: key, Lease: 123456}
  273. tests := []func(){
  274. // put case
  275. func() {
  276. if presp, err := kvc.Put(context.TODO(), preq); err == nil {
  277. t.Errorf("succeeded put key. req: %v. resp: %v", preq, presp)
  278. }
  279. },
  280. // txn success case
  281. func() {
  282. txn := &pb.TxnRequest{}
  283. txn.Success = append(txn.Success, &pb.RequestOp{
  284. Request: &pb.RequestOp_RequestPut{
  285. RequestPut: preq}})
  286. if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
  287. t.Errorf("succeeded txn success. req: %v. resp: %v", txn, tresp)
  288. }
  289. },
  290. // txn failure case
  291. func() {
  292. txn := &pb.TxnRequest{}
  293. txn.Failure = append(txn.Failure, &pb.RequestOp{
  294. Request: &pb.RequestOp_RequestPut{
  295. RequestPut: preq}})
  296. cmp := &pb.Compare{
  297. Result: pb.Compare_GREATER,
  298. Target: pb.Compare_CREATE,
  299. Key: []byte("bar"),
  300. }
  301. txn.Compare = append(txn.Compare, cmp)
  302. if tresp, err := kvc.Txn(context.TODO(), txn); err == nil {
  303. t.Errorf("succeeded txn failure. req: %v. resp: %v", txn, tresp)
  304. }
  305. },
  306. // ignore bad lease in failure on success txn
  307. func() {
  308. txn := &pb.TxnRequest{}
  309. rreq := &pb.RangeRequest{Key: []byte("bar")}
  310. txn.Success = append(txn.Success, &pb.RequestOp{
  311. Request: &pb.RequestOp_RequestRange{
  312. RequestRange: rreq}})
  313. txn.Failure = append(txn.Failure, &pb.RequestOp{
  314. Request: &pb.RequestOp_RequestPut{
  315. RequestPut: preq}})
  316. if tresp, err := kvc.Txn(context.TODO(), txn); err != nil {
  317. t.Errorf("failed good txn. req: %v. resp: %v", txn, tresp)
  318. }
  319. },
  320. }
  321. for i, f := range tests {
  322. f()
  323. // key shouldn't have been stored
  324. rreq := &pb.RangeRequest{Key: key}
  325. rresp, err := kvc.Range(context.TODO(), rreq)
  326. if err != nil {
  327. t.Errorf("#%d. could not rangereq (%v)", i, err)
  328. } else if len(rresp.Kvs) != 0 {
  329. t.Errorf("#%d. expected no keys, got %v", i, rresp)
  330. }
  331. }
  332. }
  333. // TestV3DeleteRange tests various edge cases in the DeleteRange API.
  334. func TestV3DeleteRange(t *testing.T) {
  335. defer testutil.AfterTest(t)
  336. tests := []struct {
  337. keySet []string
  338. begin string
  339. end string
  340. prevKV bool
  341. wantSet [][]byte
  342. deleted int64
  343. }{
  344. // delete middle
  345. {
  346. []string{"foo", "foo/abc", "fop"},
  347. "foo/", "fop", false,
  348. [][]byte{[]byte("foo"), []byte("fop")}, 1,
  349. },
  350. // no delete
  351. {
  352. []string{"foo", "foo/abc", "fop"},
  353. "foo/", "foo/", false,
  354. [][]byte{[]byte("foo"), []byte("foo/abc"), []byte("fop")}, 0,
  355. },
  356. // delete first
  357. {
  358. []string{"foo", "foo/abc", "fop"},
  359. "fo", "fop", false,
  360. [][]byte{[]byte("fop")}, 2,
  361. },
  362. // delete tail
  363. {
  364. []string{"foo", "foo/abc", "fop"},
  365. "foo/", "fos", false,
  366. [][]byte{[]byte("foo")}, 2,
  367. },
  368. // delete exact
  369. {
  370. []string{"foo", "foo/abc", "fop"},
  371. "foo/abc", "", false,
  372. [][]byte{[]byte("foo"), []byte("fop")}, 1,
  373. },
  374. // delete none, [x,x)
  375. {
  376. []string{"foo"},
  377. "foo", "foo", false,
  378. [][]byte{[]byte("foo")}, 0,
  379. },
  380. // delete middle with preserveKVs set
  381. {
  382. []string{"foo", "foo/abc", "fop"},
  383. "foo/", "fop", true,
  384. [][]byte{[]byte("foo"), []byte("fop")}, 1,
  385. },
  386. }
  387. for i, tt := range tests {
  388. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  389. kvc := toGRPC(clus.RandClient()).KV
  390. ks := tt.keySet
  391. for j := range ks {
  392. reqput := &pb.PutRequest{Key: []byte(ks[j]), Value: []byte{}}
  393. _, err := kvc.Put(context.TODO(), reqput)
  394. if err != nil {
  395. t.Fatalf("couldn't put key (%v)", err)
  396. }
  397. }
  398. dreq := &pb.DeleteRangeRequest{
  399. Key: []byte(tt.begin),
  400. RangeEnd: []byte(tt.end),
  401. PrevKv: tt.prevKV,
  402. }
  403. dresp, err := kvc.DeleteRange(context.TODO(), dreq)
  404. if err != nil {
  405. t.Fatalf("couldn't delete range on test %d (%v)", i, err)
  406. }
  407. if tt.deleted != dresp.Deleted {
  408. t.Errorf("expected %d on test %v, got %d", tt.deleted, i, dresp.Deleted)
  409. }
  410. if tt.prevKV {
  411. if len(dresp.PrevKvs) != int(dresp.Deleted) {
  412. t.Errorf("preserve %d keys, want %d", len(dresp.PrevKvs), dresp.Deleted)
  413. }
  414. }
  415. rreq := &pb.RangeRequest{Key: []byte{0x0}, RangeEnd: []byte{0xff}}
  416. rresp, err := kvc.Range(context.TODO(), rreq)
  417. if err != nil {
  418. t.Errorf("couldn't get range on test %v (%v)", i, err)
  419. }
  420. if dresp.Header.Revision != rresp.Header.Revision {
  421. t.Errorf("expected revision %v, got %v",
  422. dresp.Header.Revision, rresp.Header.Revision)
  423. }
  424. keys := [][]byte{}
  425. for j := range rresp.Kvs {
  426. keys = append(keys, rresp.Kvs[j].Key)
  427. }
  428. if !reflect.DeepEqual(tt.wantSet, keys) {
  429. t.Errorf("expected %v on test %v, got %v", tt.wantSet, i, keys)
  430. }
  431. // can't defer because tcp ports will be in use
  432. clus.Terminate(t)
  433. }
  434. }
  435. // TestV3TxnInvalidRange tests that invalid ranges are rejected in txns.
  436. func TestV3TxnInvalidRange(t *testing.T) {
  437. defer testutil.AfterTest(t)
  438. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  439. defer clus.Terminate(t)
  440. kvc := toGRPC(clus.RandClient()).KV
  441. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  442. for i := 0; i < 3; i++ {
  443. _, err := kvc.Put(context.Background(), preq)
  444. if err != nil {
  445. t.Fatalf("couldn't put key (%v)", err)
  446. }
  447. }
  448. _, err := kvc.Compact(context.Background(), &pb.CompactionRequest{Revision: 2})
  449. if err != nil {
  450. t.Fatalf("couldn't compact kv space (%v)", err)
  451. }
  452. // future rev
  453. txn := &pb.TxnRequest{}
  454. txn.Success = append(txn.Success, &pb.RequestOp{
  455. Request: &pb.RequestOp_RequestPut{
  456. RequestPut: preq}})
  457. rreq := &pb.RangeRequest{Key: []byte("foo"), Revision: 100}
  458. txn.Success = append(txn.Success, &pb.RequestOp{
  459. Request: &pb.RequestOp_RequestRange{
  460. RequestRange: rreq}})
  461. if _, err := kvc.Txn(context.TODO(), txn); !eqErrGRPC(err, rpctypes.ErrGRPCFutureRev) {
  462. t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCFutureRev)
  463. }
  464. // compacted rev
  465. tv, _ := txn.Success[1].Request.(*pb.RequestOp_RequestRange)
  466. tv.RequestRange.Revision = 1
  467. if _, err := kvc.Txn(context.TODO(), txn); !eqErrGRPC(err, rpctypes.ErrGRPCCompacted) {
  468. t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCCompacted)
  469. }
  470. }
  471. func TestV3TooLargeRequest(t *testing.T) {
  472. defer testutil.AfterTest(t)
  473. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  474. defer clus.Terminate(t)
  475. kvc := toGRPC(clus.RandClient()).KV
  476. // 2MB request value
  477. largeV := make([]byte, 2*1024*1024)
  478. preq := &pb.PutRequest{Key: []byte("foo"), Value: largeV}
  479. _, err := kvc.Put(context.Background(), preq)
  480. if !eqErrGRPC(err, rpctypes.ErrGRPCRequestTooLarge) {
  481. t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCRequestTooLarge)
  482. }
  483. }
  484. // TestV3Hash tests hash.
  485. func TestV3Hash(t *testing.T) {
  486. defer testutil.AfterTest(t)
  487. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  488. defer clus.Terminate(t)
  489. cli := clus.RandClient()
  490. kvc := toGRPC(cli).KV
  491. m := toGRPC(cli).Maintenance
  492. preq := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  493. for i := 0; i < 3; i++ {
  494. _, err := kvc.Put(context.Background(), preq)
  495. if err != nil {
  496. t.Fatalf("couldn't put key (%v)", err)
  497. }
  498. }
  499. resp, err := m.Hash(context.Background(), &pb.HashRequest{})
  500. if err != nil || resp.Hash == 0 {
  501. t.Fatalf("couldn't hash (%v, hash %d)", err, resp.Hash)
  502. }
  503. }
  504. // TestV3StorageQuotaAPI tests the V3 server respects quotas at the API layer
  505. func TestV3StorageQuotaAPI(t *testing.T) {
  506. defer testutil.AfterTest(t)
  507. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  508. clus.Members[0].QuotaBackendBytes = 64 * 1024
  509. clus.Members[0].Stop(t)
  510. clus.Members[0].Restart(t)
  511. defer clus.Terminate(t)
  512. kvc := toGRPC(clus.Client(0)).KV
  513. key := []byte("abc")
  514. // test small put that fits in quota
  515. smallbuf := make([]byte, 512)
  516. if _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}, grpc.FailFast(false)); err != nil {
  517. t.Fatal(err)
  518. }
  519. // test big put
  520. bigbuf := make([]byte, 64*1024)
  521. _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: bigbuf})
  522. if !eqErrGRPC(err, rpctypes.ErrGRPCNoSpace) {
  523. t.Fatalf("big put got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
  524. }
  525. // test big txn
  526. puttxn := &pb.RequestOp{
  527. Request: &pb.RequestOp_RequestPut{
  528. RequestPut: &pb.PutRequest{
  529. Key: key,
  530. Value: bigbuf,
  531. },
  532. },
  533. }
  534. txnreq := &pb.TxnRequest{}
  535. txnreq.Success = append(txnreq.Success, puttxn)
  536. _, txnerr := kvc.Txn(context.TODO(), txnreq)
  537. if !eqErrGRPC(txnerr, rpctypes.ErrGRPCNoSpace) {
  538. t.Fatalf("big txn got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
  539. }
  540. }
  541. // TestV3StorageQuotaApply tests the V3 server respects quotas during apply
  542. func TestV3StorageQuotaApply(t *testing.T) {
  543. testutil.AfterTest(t)
  544. clus := NewClusterV3(t, &ClusterConfig{Size: 2})
  545. defer clus.Terminate(t)
  546. kvc0 := toGRPC(clus.Client(0)).KV
  547. kvc1 := toGRPC(clus.Client(1)).KV
  548. // force a node to have a different quota
  549. clus.Members[0].QuotaBackendBytes = 64 * 1024
  550. clus.Members[0].Stop(t)
  551. clus.Members[0].Restart(t)
  552. clus.waitLeader(t, clus.Members)
  553. key := []byte("abc")
  554. // test small put still works
  555. smallbuf := make([]byte, 1024)
  556. _, serr := kvc0.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}, grpc.FailFast(false))
  557. if serr != nil {
  558. t.Fatal(serr)
  559. }
  560. // test big put
  561. bigbuf := make([]byte, 64*1024)
  562. _, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: bigbuf})
  563. if err != nil {
  564. t.Fatal(err)
  565. }
  566. // quorum get should work regardless of whether alarm is raised
  567. _, err = kvc0.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  568. if err != nil {
  569. t.Fatal(err)
  570. }
  571. // wait until alarm is raised for sure-- poll the alarms
  572. stopc := time.After(5 * time.Second)
  573. for {
  574. req := &pb.AlarmRequest{Action: pb.AlarmRequest_GET}
  575. resp, aerr := clus.Members[0].s.Alarm(context.TODO(), req)
  576. if aerr != nil {
  577. t.Fatal(aerr)
  578. }
  579. if len(resp.Alarms) != 0 {
  580. break
  581. }
  582. select {
  583. case <-stopc:
  584. t.Fatalf("timed out waiting for alarm")
  585. case <-time.After(10 * time.Millisecond):
  586. }
  587. }
  588. // small quota machine should reject put
  589. if _, err := kvc0.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
  590. t.Fatalf("past-quota instance should reject put")
  591. }
  592. // large quota machine should reject put
  593. if _, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
  594. t.Fatalf("past-quota instance should reject put")
  595. }
  596. // reset large quota node to ensure alarm persisted
  597. clus.Members[1].Stop(t)
  598. clus.Members[1].Restart(t)
  599. clus.waitLeader(t, clus.Members)
  600. if _, err := kvc1.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err == nil {
  601. t.Fatalf("alarmed instance should reject put after reset")
  602. }
  603. }
  604. // TestV3AlarmDeactivate ensures that space alarms can be deactivated so puts go through.
  605. func TestV3AlarmDeactivate(t *testing.T) {
  606. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  607. defer clus.Terminate(t)
  608. kvc := toGRPC(clus.RandClient()).KV
  609. mt := toGRPC(clus.RandClient()).Maintenance
  610. alarmReq := &pb.AlarmRequest{
  611. MemberID: 123,
  612. Action: pb.AlarmRequest_ACTIVATE,
  613. Alarm: pb.AlarmType_NOSPACE,
  614. }
  615. if _, err := mt.Alarm(context.TODO(), alarmReq); err != nil {
  616. t.Fatal(err)
  617. }
  618. key := []byte("abc")
  619. smallbuf := make([]byte, 512)
  620. _, err := kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf})
  621. if err == nil && !eqErrGRPC(err, rpctypes.ErrGRPCNoSpace) {
  622. t.Fatalf("put got %v, expected %v", err, rpctypes.ErrGRPCNoSpace)
  623. }
  624. alarmReq.Action = pb.AlarmRequest_DEACTIVATE
  625. if _, err = mt.Alarm(context.TODO(), alarmReq); err != nil {
  626. t.Fatal(err)
  627. }
  628. if _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: key, Value: smallbuf}); err != nil {
  629. t.Fatal(err)
  630. }
  631. }
  632. func TestV3RangeRequest(t *testing.T) {
  633. defer testutil.AfterTest(t)
  634. tests := []struct {
  635. putKeys []string
  636. reqs []pb.RangeRequest
  637. wresps [][]string
  638. wmores []bool
  639. }{
  640. // single key
  641. {
  642. []string{"foo", "bar"},
  643. []pb.RangeRequest{
  644. // exists
  645. {Key: []byte("foo")},
  646. // doesn't exist
  647. {Key: []byte("baz")},
  648. },
  649. [][]string{
  650. {"foo"},
  651. {},
  652. },
  653. []bool{false, false},
  654. },
  655. // multi-key
  656. {
  657. []string{"a", "b", "c", "d", "e"},
  658. []pb.RangeRequest{
  659. // all in range
  660. {Key: []byte("a"), RangeEnd: []byte("z")},
  661. // [b, d)
  662. {Key: []byte("b"), RangeEnd: []byte("d")},
  663. // out of range
  664. {Key: []byte("f"), RangeEnd: []byte("z")},
  665. // [c,c) = empty
  666. {Key: []byte("c"), RangeEnd: []byte("c")},
  667. // [d, b) = empty
  668. {Key: []byte("d"), RangeEnd: []byte("b")},
  669. // ["\0", "\0") => all in range
  670. {Key: []byte{0}, RangeEnd: []byte{0}},
  671. },
  672. [][]string{
  673. {"a", "b", "c", "d", "e"},
  674. {"b", "c"},
  675. {},
  676. {},
  677. {},
  678. {"a", "b", "c", "d", "e"},
  679. },
  680. []bool{false, false, false, false, false, false},
  681. },
  682. // revision
  683. {
  684. []string{"a", "b", "c", "d", "e"},
  685. []pb.RangeRequest{
  686. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 0},
  687. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 1},
  688. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 2},
  689. {Key: []byte("a"), RangeEnd: []byte("z"), Revision: 3},
  690. },
  691. [][]string{
  692. {"a", "b", "c", "d", "e"},
  693. {},
  694. {"a"},
  695. {"a", "b"},
  696. },
  697. []bool{false, false, false, false},
  698. },
  699. // limit
  700. {
  701. []string{"foo", "bar"},
  702. []pb.RangeRequest{
  703. // more
  704. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 1},
  705. // no more
  706. {Key: []byte("a"), RangeEnd: []byte("z"), Limit: 2},
  707. },
  708. [][]string{
  709. {"bar"},
  710. {"bar", "foo"},
  711. },
  712. []bool{true, false},
  713. },
  714. // sort
  715. {
  716. []string{"b", "a", "c", "d", "c"},
  717. []pb.RangeRequest{
  718. {
  719. Key: []byte("a"), RangeEnd: []byte("z"),
  720. Limit: 1,
  721. SortOrder: pb.RangeRequest_ASCEND,
  722. SortTarget: pb.RangeRequest_KEY,
  723. },
  724. {
  725. Key: []byte("a"), RangeEnd: []byte("z"),
  726. Limit: 1,
  727. SortOrder: pb.RangeRequest_DESCEND,
  728. SortTarget: pb.RangeRequest_KEY,
  729. },
  730. {
  731. Key: []byte("a"), RangeEnd: []byte("z"),
  732. Limit: 1,
  733. SortOrder: pb.RangeRequest_ASCEND,
  734. SortTarget: pb.RangeRequest_CREATE,
  735. },
  736. {
  737. Key: []byte("a"), RangeEnd: []byte("z"),
  738. Limit: 1,
  739. SortOrder: pb.RangeRequest_DESCEND,
  740. SortTarget: pb.RangeRequest_MOD,
  741. },
  742. {
  743. Key: []byte("z"), RangeEnd: []byte("z"),
  744. Limit: 1,
  745. SortOrder: pb.RangeRequest_DESCEND,
  746. SortTarget: pb.RangeRequest_CREATE,
  747. },
  748. },
  749. [][]string{
  750. {"a"},
  751. {"d"},
  752. {"b"},
  753. {"c"},
  754. {},
  755. },
  756. []bool{true, true, true, true, false},
  757. },
  758. }
  759. for i, tt := range tests {
  760. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  761. for _, k := range tt.putKeys {
  762. kvc := toGRPC(clus.RandClient()).KV
  763. req := &pb.PutRequest{Key: []byte(k), Value: []byte("bar")}
  764. if _, err := kvc.Put(context.TODO(), req); err != nil {
  765. t.Fatalf("#%d: couldn't put key (%v)", i, err)
  766. }
  767. }
  768. for j, req := range tt.reqs {
  769. kvc := toGRPC(clus.RandClient()).KV
  770. resp, err := kvc.Range(context.TODO(), &req)
  771. if err != nil {
  772. t.Errorf("#%d.%d: Range error: %v", i, j, err)
  773. continue
  774. }
  775. if len(resp.Kvs) != len(tt.wresps[j]) {
  776. t.Errorf("#%d.%d: bad len(resp.Kvs). got = %d, want = %d, ", i, j, len(resp.Kvs), len(tt.wresps[j]))
  777. continue
  778. }
  779. for k, wKey := range tt.wresps[j] {
  780. respKey := string(resp.Kvs[k].Key)
  781. if respKey != wKey {
  782. t.Errorf("#%d.%d: key[%d]. got = %v, want = %v, ", i, j, k, respKey, wKey)
  783. }
  784. }
  785. if resp.More != tt.wmores[j] {
  786. t.Errorf("#%d.%d: bad more. got = %v, want = %v, ", i, j, resp.More, tt.wmores[j])
  787. }
  788. wrev := int64(len(tt.putKeys) + 1)
  789. if resp.Header.Revision != wrev {
  790. t.Errorf("#%d.%d: bad header revision. got = %d. want = %d", i, j, resp.Header.Revision, wrev)
  791. }
  792. }
  793. clus.Terminate(t)
  794. }
  795. }
  796. func newClusterV3NoClients(t *testing.T, cfg *ClusterConfig) *ClusterV3 {
  797. cfg.UseGRPC = true
  798. clus := &ClusterV3{cluster: NewClusterByConfig(t, cfg)}
  799. clus.Launch(t)
  800. return clus
  801. }
  802. // TestTLSGRPCRejectInsecureClient checks that connection is rejected if server is TLS but not client.
  803. func TestTLSGRPCRejectInsecureClient(t *testing.T) {
  804. defer testutil.AfterTest(t)
  805. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  806. clus := newClusterV3NoClients(t, &cfg)
  807. defer clus.Terminate(t)
  808. // nil out TLS field so client will use an insecure connection
  809. clus.Members[0].ClientTLSInfo = nil
  810. client, err := NewClientV3(clus.Members[0])
  811. if err != nil && err != grpc.ErrClientConnTimeout {
  812. t.Fatalf("unexpected error (%v)", err)
  813. } else if client == nil {
  814. // Ideally, no client would be returned. However, grpc will
  815. // return a connection without trying to handshake first so
  816. // the connection appears OK.
  817. return
  818. }
  819. defer client.Close()
  820. donec := make(chan error, 1)
  821. go func() {
  822. ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)
  823. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  824. _, perr := toGRPC(client).KV.Put(ctx, reqput)
  825. cancel()
  826. donec <- perr
  827. }()
  828. if perr := <-donec; perr == nil {
  829. t.Fatalf("expected client error on put")
  830. }
  831. }
  832. // TestTLSGRPCRejectSecureClient checks that connection is rejected if client is TLS but not server.
  833. func TestTLSGRPCRejectSecureClient(t *testing.T) {
  834. defer testutil.AfterTest(t)
  835. cfg := ClusterConfig{Size: 3}
  836. clus := newClusterV3NoClients(t, &cfg)
  837. defer clus.Terminate(t)
  838. clus.Members[0].ClientTLSInfo = &testTLSInfo
  839. client, err := NewClientV3(clus.Members[0])
  840. if client != nil || err == nil {
  841. t.Fatalf("expected no client")
  842. } else if err != grpc.ErrClientConnTimeout {
  843. t.Fatalf("unexpected error (%v)", err)
  844. }
  845. }
  846. // TestTLSGRPCAcceptSecureAll checks that connection is accepted if both client and server are TLS
  847. func TestTLSGRPCAcceptSecureAll(t *testing.T) {
  848. defer testutil.AfterTest(t)
  849. cfg := ClusterConfig{Size: 3, ClientTLS: &testTLSInfo}
  850. clus := newClusterV3NoClients(t, &cfg)
  851. defer clus.Terminate(t)
  852. client, err := NewClientV3(clus.Members[0])
  853. if err != nil {
  854. t.Fatalf("expected tls client (%v)", err)
  855. }
  856. defer client.Close()
  857. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  858. if _, err := toGRPC(client).KV.Put(context.TODO(), reqput); err != nil {
  859. t.Fatalf("unexpected error on put over tls (%v)", err)
  860. }
  861. }
  862. func TestGRPCRequireLeader(t *testing.T) {
  863. defer testutil.AfterTest(t)
  864. cfg := ClusterConfig{Size: 3}
  865. clus := newClusterV3NoClients(t, &cfg)
  866. defer clus.Terminate(t)
  867. clus.Members[1].Stop(t)
  868. clus.Members[2].Stop(t)
  869. client, err := NewClientV3(clus.Members[0])
  870. if err != nil {
  871. t.Fatalf("cannot create client: %v", err)
  872. }
  873. defer client.Close()
  874. // wait for election timeout, then member[0] will not have a leader.
  875. time.Sleep(time.Duration(3*electionTicks) * tickDuration)
  876. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  877. ctx := metadata.NewContext(context.Background(), md)
  878. reqput := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")}
  879. if _, err := toGRPC(client).KV.Put(ctx, reqput); grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
  880. t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
  881. }
  882. }
  883. func TestGRPCStreamRequireLeader(t *testing.T) {
  884. defer testutil.AfterTest(t)
  885. cfg := ClusterConfig{Size: 3}
  886. clus := newClusterV3NoClients(t, &cfg)
  887. defer clus.Terminate(t)
  888. client, err := NewClientV3(clus.Members[0])
  889. if err != nil {
  890. t.Fatalf("failed to create client (%v)", err)
  891. }
  892. defer client.Close()
  893. wAPI := toGRPC(client).Watch
  894. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  895. ctx := metadata.NewContext(context.Background(), md)
  896. wStream, err := wAPI.Watch(ctx)
  897. if err != nil {
  898. t.Fatalf("wAPI.Watch error: %v", err)
  899. }
  900. clus.Members[1].Stop(t)
  901. clus.Members[2].Stop(t)
  902. // existing stream should be rejected
  903. _, err = wStream.Recv()
  904. if grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
  905. t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
  906. }
  907. // new stream should also be rejected
  908. wStream, err = wAPI.Watch(ctx)
  909. if err != nil {
  910. t.Fatalf("wAPI.Watch error: %v", err)
  911. }
  912. _, err = wStream.Recv()
  913. if grpc.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
  914. t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
  915. }
  916. clus.Members[1].Restart(t)
  917. clus.Members[2].Restart(t)
  918. clus.waitLeader(t, clus.Members)
  919. time.Sleep(time.Duration(2*electionTicks) * tickDuration)
  920. // new stream should also be OK now after we restarted the other members
  921. wStream, err = wAPI.Watch(ctx)
  922. if err != nil {
  923. t.Fatalf("wAPI.Watch error: %v", err)
  924. }
  925. wreq := &pb.WatchRequest{
  926. RequestUnion: &pb.WatchRequest_CreateRequest{
  927. CreateRequest: &pb.WatchCreateRequest{Key: []byte("foo")},
  928. },
  929. }
  930. err = wStream.Send(wreq)
  931. if err != nil {
  932. t.Errorf("err = %v, want nil", err)
  933. }
  934. }
  935. func eqErrGRPC(err1 error, err2 error) bool {
  936. return !(err1 == nil && err2 != nil) || err1.Error() == err2.Error()
  937. }