v3_grpc_test.go 38 KB

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