v3_grpc_test.go 39 KB

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