v3_grpc_test.go 36 KB

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