v3_grpc_test.go 35 KB

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