v3_grpc_test.go 35 KB

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