v3_grpc_test.go 41 KB

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