v3_grpc_test.go 39 KB

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