v3_lease_test.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. // Copyright 2016 The etcd Authors
  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.
  14. package integration
  15. import (
  16. "context"
  17. "fmt"
  18. "testing"
  19. "time"
  20. "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes"
  21. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  22. "go.etcd.io/etcd/mvcc/mvccpb"
  23. "go.etcd.io/etcd/pkg/testutil"
  24. "google.golang.org/grpc/codes"
  25. "google.golang.org/grpc/metadata"
  26. "google.golang.org/grpc/status"
  27. )
  28. // TestV3LeasePrmote ensures the newly elected leader can promote itself
  29. // to the primary lessor, refresh the leases and start to manage leases.
  30. // TODO: use customized clock to make this test go faster?
  31. func TestV3LeasePrmote(t *testing.T) {
  32. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  33. defer clus.Terminate(t)
  34. // create lease
  35. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 3})
  36. ttl := time.Duration(lresp.TTL) * time.Second
  37. afterGrant := time.Now()
  38. if err != nil {
  39. t.Fatal(err)
  40. }
  41. if lresp.Error != "" {
  42. t.Fatal(lresp.Error)
  43. }
  44. // wait until the lease is going to expire.
  45. time.Sleep(time.Until(afterGrant.Add(ttl - time.Second)))
  46. // kill the current leader, all leases should be refreshed.
  47. toStop := clus.waitLeader(t, clus.Members)
  48. beforeStop := time.Now()
  49. clus.Members[toStop].Stop(t)
  50. var toWait []*member
  51. for i, m := range clus.Members {
  52. if i != toStop {
  53. toWait = append(toWait, m)
  54. }
  55. }
  56. clus.waitLeader(t, toWait)
  57. clus.Members[toStop].Restart(t)
  58. clus.waitLeader(t, clus.Members)
  59. afterReelect := time.Now()
  60. // ensure lease is refreshed by waiting for a "long" time.
  61. // it was going to expire anyway.
  62. time.Sleep(time.Until(beforeStop.Add(ttl - time.Second)))
  63. if !leaseExist(t, clus, lresp.ID) {
  64. t.Error("unexpected lease not exists")
  65. }
  66. // wait until the renewed lease is expected to expire.
  67. time.Sleep(time.Until(afterReelect.Add(ttl)))
  68. // wait for up to 10 seconds for lease to expire.
  69. expiredCondition := func() (bool, error) {
  70. return !leaseExist(t, clus, lresp.ID), nil
  71. }
  72. expired, err := testutil.Poll(100*time.Millisecond, 10*time.Second, expiredCondition)
  73. if err != nil {
  74. t.Error(err)
  75. }
  76. if !expired {
  77. t.Error("unexpected lease exists")
  78. }
  79. }
  80. // TestV3LeaseRevoke ensures a key is deleted once its lease is revoked.
  81. func TestV3LeaseRevoke(t *testing.T) {
  82. defer testutil.AfterTest(t)
  83. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  84. lc := toGRPC(clus.RandClient()).Lease
  85. _, err := lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseID})
  86. return err
  87. })
  88. }
  89. // TestV3LeaseGrantById ensures leases may be created by a given id.
  90. func TestV3LeaseGrantByID(t *testing.T) {
  91. defer testutil.AfterTest(t)
  92. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  93. defer clus.Terminate(t)
  94. // create fixed lease
  95. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  96. context.TODO(),
  97. &pb.LeaseGrantRequest{ID: 1, TTL: 1})
  98. if err != nil {
  99. t.Errorf("could not create lease 1 (%v)", err)
  100. }
  101. if lresp.ID != 1 {
  102. t.Errorf("got id %v, wanted id %v", lresp.ID, 1)
  103. }
  104. // create duplicate fixed lease
  105. _, err = toGRPC(clus.RandClient()).Lease.LeaseGrant(
  106. context.TODO(),
  107. &pb.LeaseGrantRequest{ID: 1, TTL: 1})
  108. if !eqErrGRPC(err, rpctypes.ErrGRPCLeaseExist) {
  109. t.Error(err)
  110. }
  111. // create fresh fixed lease
  112. lresp, err = toGRPC(clus.RandClient()).Lease.LeaseGrant(
  113. context.TODO(),
  114. &pb.LeaseGrantRequest{ID: 2, TTL: 1})
  115. if err != nil {
  116. t.Errorf("could not create lease 2 (%v)", err)
  117. }
  118. if lresp.ID != 2 {
  119. t.Errorf("got id %v, wanted id %v", lresp.ID, 2)
  120. }
  121. }
  122. // TestV3LeaseExpire ensures a key is deleted once a key expires.
  123. func TestV3LeaseExpire(t *testing.T) {
  124. defer testutil.AfterTest(t)
  125. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  126. // let lease lapse; wait for deleted key
  127. ctx, cancel := context.WithCancel(context.Background())
  128. defer cancel()
  129. wStream, err := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  130. if err != nil {
  131. return err
  132. }
  133. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  134. CreateRequest: &pb.WatchCreateRequest{
  135. Key: []byte("foo"), StartRevision: 1}}}
  136. if err := wStream.Send(wreq); err != nil {
  137. return err
  138. }
  139. if _, err := wStream.Recv(); err != nil {
  140. // the 'created' message
  141. return err
  142. }
  143. if _, err := wStream.Recv(); err != nil {
  144. // the 'put' message
  145. return err
  146. }
  147. errc := make(chan error, 1)
  148. go func() {
  149. resp, err := wStream.Recv()
  150. switch {
  151. case err != nil:
  152. errc <- err
  153. case len(resp.Events) != 1:
  154. fallthrough
  155. case resp.Events[0].Type != mvccpb.DELETE:
  156. errc <- fmt.Errorf("expected key delete, got %v", resp)
  157. default:
  158. errc <- nil
  159. }
  160. }()
  161. select {
  162. case <-time.After(15 * time.Second):
  163. return fmt.Errorf("lease expiration too slow")
  164. case err := <-errc:
  165. return err
  166. }
  167. })
  168. }
  169. // TestV3LeaseKeepAlive ensures keepalive keeps the lease alive.
  170. func TestV3LeaseKeepAlive(t *testing.T) {
  171. defer testutil.AfterTest(t)
  172. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  173. lc := toGRPC(clus.RandClient()).Lease
  174. lreq := &pb.LeaseKeepAliveRequest{ID: leaseID}
  175. ctx, cancel := context.WithCancel(context.Background())
  176. defer cancel()
  177. lac, err := lc.LeaseKeepAlive(ctx)
  178. if err != nil {
  179. return err
  180. }
  181. defer lac.CloseSend()
  182. // renew long enough so lease would've expired otherwise
  183. for i := 0; i < 3; i++ {
  184. if err = lac.Send(lreq); err != nil {
  185. return err
  186. }
  187. lresp, rxerr := lac.Recv()
  188. if rxerr != nil {
  189. return rxerr
  190. }
  191. if lresp.ID != leaseID {
  192. return fmt.Errorf("expected lease ID %v, got %v", leaseID, lresp.ID)
  193. }
  194. time.Sleep(time.Duration(lresp.TTL/2) * time.Second)
  195. }
  196. _, err = lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseID})
  197. return err
  198. })
  199. }
  200. // TestV3LeaseCheckpoint ensures a lease checkpoint results in a remaining TTL being persisted
  201. // across leader elections.
  202. func TestV3LeaseCheckpoint(t *testing.T) {
  203. var ttl int64 = 300
  204. leaseInterval := 2 * time.Second
  205. defer testutil.AfterTest(t)
  206. clus := NewClusterV3(t, &ClusterConfig{
  207. Size: 3,
  208. EnableLeaseCheckpoint: true,
  209. LeaseCheckpointInterval: leaseInterval,
  210. })
  211. defer clus.Terminate(t)
  212. // create lease
  213. ctx, cancel := context.WithCancel(context.Background())
  214. defer cancel()
  215. c := toGRPC(clus.RandClient())
  216. lresp, err := c.Lease.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: ttl})
  217. if err != nil {
  218. t.Fatal(err)
  219. }
  220. // wait for a checkpoint to occur
  221. time.Sleep(leaseInterval + 1*time.Second)
  222. // Force a leader election
  223. leaderId := clus.WaitLeader(t)
  224. leader := clus.Members[leaderId]
  225. leader.Stop(t)
  226. time.Sleep(time.Duration(3*electionTicks) * tickDuration)
  227. leader.Restart(t)
  228. newLeaderId := clus.WaitLeader(t)
  229. c2 := toGRPC(clus.Client(newLeaderId))
  230. time.Sleep(250 * time.Millisecond)
  231. // Check the TTL of the new leader
  232. var ttlresp *pb.LeaseTimeToLiveResponse
  233. for i := 0; i < 10; i++ {
  234. if ttlresp, err = c2.Lease.LeaseTimeToLive(ctx, &pb.LeaseTimeToLiveRequest{ID: lresp.ID}); err != nil {
  235. if status, ok := status.FromError(err); ok && status.Code() == codes.Unavailable {
  236. time.Sleep(time.Millisecond * 250)
  237. } else {
  238. t.Fatal(err)
  239. }
  240. }
  241. }
  242. expectedTTL := ttl - int64(leaseInterval.Seconds())
  243. if ttlresp.TTL < expectedTTL-1 || ttlresp.TTL > expectedTTL {
  244. t.Fatalf("expected lease to be checkpointed after restart such that %d < TTL <%d, but got TTL=%d", expectedTTL-1, expectedTTL, ttlresp.TTL)
  245. }
  246. }
  247. // TestV3LeaseExists creates a lease on a random client and confirms it exists in the cluster.
  248. func TestV3LeaseExists(t *testing.T) {
  249. defer testutil.AfterTest(t)
  250. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  251. defer clus.Terminate(t)
  252. // create lease
  253. ctx0, cancel0 := context.WithCancel(context.Background())
  254. defer cancel0()
  255. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  256. ctx0,
  257. &pb.LeaseGrantRequest{TTL: 30})
  258. if err != nil {
  259. t.Fatal(err)
  260. }
  261. if lresp.Error != "" {
  262. t.Fatal(lresp.Error)
  263. }
  264. if !leaseExist(t, clus, lresp.ID) {
  265. t.Error("unexpected lease not exists")
  266. }
  267. }
  268. // TestV3LeaseLeases creates leases and confirms list RPC fetches created ones.
  269. func TestV3LeaseLeases(t *testing.T) {
  270. defer testutil.AfterTest(t)
  271. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  272. defer clus.Terminate(t)
  273. ctx0, cancel0 := context.WithCancel(context.Background())
  274. defer cancel0()
  275. // create leases
  276. ids := []int64{}
  277. for i := 0; i < 5; i++ {
  278. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  279. ctx0,
  280. &pb.LeaseGrantRequest{TTL: 30})
  281. if err != nil {
  282. t.Fatal(err)
  283. }
  284. if lresp.Error != "" {
  285. t.Fatal(lresp.Error)
  286. }
  287. ids = append(ids, lresp.ID)
  288. }
  289. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseLeases(
  290. context.Background(),
  291. &pb.LeaseLeasesRequest{})
  292. if err != nil {
  293. t.Fatal(err)
  294. }
  295. for i := range lresp.Leases {
  296. if lresp.Leases[i].ID != ids[i] {
  297. t.Fatalf("#%d: lease ID expected %d, got %d", i, ids[i], lresp.Leases[i].ID)
  298. }
  299. }
  300. }
  301. // TestV3LeaseRenewStress keeps creating lease and renewing it immediately to ensure the renewal goes through.
  302. // it was oberserved that the immediate lease renewal after granting a lease from follower resulted lease not found.
  303. // related issue https://github.com/etcd-io/etcd/issues/6978
  304. func TestV3LeaseRenewStress(t *testing.T) {
  305. testLeaseStress(t, stressLeaseRenew)
  306. }
  307. // TestV3LeaseTimeToLiveStress keeps creating lease and retrieving it immediately to ensure the lease can be retrieved.
  308. // it was oberserved that the immediate lease retrieval after granting a lease from follower resulted lease not found.
  309. // related issue https://github.com/etcd-io/etcd/issues/6978
  310. func TestV3LeaseTimeToLiveStress(t *testing.T) {
  311. testLeaseStress(t, stressLeaseTimeToLive)
  312. }
  313. func testLeaseStress(t *testing.T, stresser func(context.Context, pb.LeaseClient) error) {
  314. defer testutil.AfterTest(t)
  315. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  316. defer clus.Terminate(t)
  317. ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
  318. defer cancel()
  319. errc := make(chan error)
  320. for i := 0; i < 30; i++ {
  321. for j := 0; j < 3; j++ {
  322. go func(i int) { errc <- stresser(ctx, toGRPC(clus.Client(i)).Lease) }(j)
  323. }
  324. }
  325. for i := 0; i < 90; i++ {
  326. if err := <-errc; err != nil {
  327. t.Fatal(err)
  328. }
  329. }
  330. }
  331. func stressLeaseRenew(tctx context.Context, lc pb.LeaseClient) (reterr error) {
  332. defer func() {
  333. if tctx.Err() != nil {
  334. reterr = nil
  335. }
  336. }()
  337. lac, err := lc.LeaseKeepAlive(tctx)
  338. if err != nil {
  339. return err
  340. }
  341. for tctx.Err() == nil {
  342. resp, gerr := lc.LeaseGrant(tctx, &pb.LeaseGrantRequest{TTL: 60})
  343. if gerr != nil {
  344. continue
  345. }
  346. err = lac.Send(&pb.LeaseKeepAliveRequest{ID: resp.ID})
  347. if err != nil {
  348. continue
  349. }
  350. rresp, rxerr := lac.Recv()
  351. if rxerr != nil {
  352. continue
  353. }
  354. if rresp.TTL == 0 {
  355. return fmt.Errorf("TTL shouldn't be 0 so soon")
  356. }
  357. }
  358. return nil
  359. }
  360. func stressLeaseTimeToLive(tctx context.Context, lc pb.LeaseClient) (reterr error) {
  361. defer func() {
  362. if tctx.Err() != nil {
  363. reterr = nil
  364. }
  365. }()
  366. for tctx.Err() == nil {
  367. resp, gerr := lc.LeaseGrant(tctx, &pb.LeaseGrantRequest{TTL: 60})
  368. if gerr != nil {
  369. continue
  370. }
  371. _, kerr := lc.LeaseTimeToLive(tctx, &pb.LeaseTimeToLiveRequest{ID: resp.ID})
  372. if rpctypes.Error(kerr) == rpctypes.ErrLeaseNotFound {
  373. return kerr
  374. }
  375. }
  376. return nil
  377. }
  378. func TestV3PutOnNonExistLease(t *testing.T) {
  379. defer testutil.AfterTest(t)
  380. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  381. defer clus.Terminate(t)
  382. ctx, cancel := context.WithCancel(context.Background())
  383. defer cancel()
  384. badLeaseID := int64(0x12345678)
  385. putr := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: badLeaseID}
  386. _, err := toGRPC(clus.RandClient()).KV.Put(ctx, putr)
  387. if !eqErrGRPC(err, rpctypes.ErrGRPCLeaseNotFound) {
  388. t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCLeaseNotFound)
  389. }
  390. }
  391. // TestV3GetNonExistLease ensures client retrieving nonexistent lease on a follower doesn't result node panic
  392. // related issue https://github.com/etcd-io/etcd/issues/6537
  393. func TestV3GetNonExistLease(t *testing.T) {
  394. defer testutil.AfterTest(t)
  395. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  396. defer clus.Terminate(t)
  397. ctx, cancel := context.WithCancel(context.Background())
  398. defer cancel()
  399. lc := toGRPC(clus.RandClient()).Lease
  400. lresp, err := lc.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: 10})
  401. if err != nil {
  402. t.Errorf("failed to create lease %v", err)
  403. }
  404. _, err = lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. leaseTTLr := &pb.LeaseTimeToLiveRequest{
  409. ID: lresp.ID,
  410. Keys: true,
  411. }
  412. for _, client := range clus.clients {
  413. // quorum-read to ensure revoke completes before TimeToLive
  414. if _, err := toGRPC(client).KV.Range(ctx, &pb.RangeRequest{Key: []byte("_")}); err != nil {
  415. t.Fatal(err)
  416. }
  417. resp, err := toGRPC(client).Lease.LeaseTimeToLive(ctx, leaseTTLr)
  418. if err != nil {
  419. t.Fatalf("expected non nil error, but go %v", err)
  420. }
  421. if resp.TTL != -1 {
  422. t.Fatalf("expected TTL to be -1, but got %v", resp.TTL)
  423. }
  424. }
  425. }
  426. // TestV3LeaseSwitch tests a key can be switched from one lease to another.
  427. func TestV3LeaseSwitch(t *testing.T) {
  428. defer testutil.AfterTest(t)
  429. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  430. defer clus.Terminate(t)
  431. key := "foo"
  432. // create lease
  433. ctx, cancel := context.WithCancel(context.Background())
  434. defer cancel()
  435. lresp1, err1 := toGRPC(clus.RandClient()).Lease.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: 30})
  436. if err1 != nil {
  437. t.Fatal(err1)
  438. }
  439. lresp2, err2 := toGRPC(clus.RandClient()).Lease.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: 30})
  440. if err2 != nil {
  441. t.Fatal(err2)
  442. }
  443. // attach key on lease1 then switch it to lease2
  444. put1 := &pb.PutRequest{Key: []byte(key), Lease: lresp1.ID}
  445. _, err := toGRPC(clus.RandClient()).KV.Put(ctx, put1)
  446. if err != nil {
  447. t.Fatal(err)
  448. }
  449. put2 := &pb.PutRequest{Key: []byte(key), Lease: lresp2.ID}
  450. _, err = toGRPC(clus.RandClient()).KV.Put(ctx, put2)
  451. if err != nil {
  452. t.Fatal(err)
  453. }
  454. // revoke lease1 should not remove key
  455. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp1.ID})
  456. if err != nil {
  457. t.Fatal(err)
  458. }
  459. rreq := &pb.RangeRequest{Key: []byte("foo")}
  460. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  461. if err != nil {
  462. t.Fatal(err)
  463. }
  464. if len(rresp.Kvs) != 1 {
  465. t.Fatalf("unexpect removal of key")
  466. }
  467. // revoke lease2 should remove key
  468. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp2.ID})
  469. if err != nil {
  470. t.Fatal(err)
  471. }
  472. rresp, err = toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  473. if err != nil {
  474. t.Fatal(err)
  475. }
  476. if len(rresp.Kvs) != 0 {
  477. t.Fatalf("lease removed but key remains")
  478. }
  479. }
  480. // TestV3LeaseFailover ensures the old leader drops lease keepalive requests within
  481. // election timeout after it loses its quorum. And the new leader extends the TTL of
  482. // the lease to at least TTL + election timeout.
  483. func TestV3LeaseFailover(t *testing.T) {
  484. defer testutil.AfterTest(t)
  485. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  486. defer clus.Terminate(t)
  487. toIsolate := clus.waitLeader(t, clus.Members)
  488. lc := toGRPC(clus.Client(toIsolate)).Lease
  489. // create lease
  490. lresp, err := lc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 5})
  491. if err != nil {
  492. t.Fatal(err)
  493. }
  494. if lresp.Error != "" {
  495. t.Fatal(lresp.Error)
  496. }
  497. // isolate the current leader with its followers.
  498. clus.Members[toIsolate].Pause()
  499. lreq := &pb.LeaseKeepAliveRequest{ID: lresp.ID}
  500. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  501. mctx := metadata.NewOutgoingContext(context.Background(), md)
  502. ctx, cancel := context.WithCancel(mctx)
  503. defer cancel()
  504. lac, err := lc.LeaseKeepAlive(ctx)
  505. if err != nil {
  506. t.Fatal(err)
  507. }
  508. // send keep alive to old leader until the old leader starts
  509. // to drop lease request.
  510. var expectedExp time.Time
  511. for {
  512. if err = lac.Send(lreq); err != nil {
  513. break
  514. }
  515. lkresp, rxerr := lac.Recv()
  516. if rxerr != nil {
  517. break
  518. }
  519. expectedExp = time.Now().Add(time.Duration(lkresp.TTL) * time.Second)
  520. time.Sleep(time.Duration(lkresp.TTL/2) * time.Second)
  521. }
  522. clus.Members[toIsolate].Resume()
  523. clus.waitLeader(t, clus.Members)
  524. // lease should not expire at the last received expire deadline.
  525. time.Sleep(time.Until(expectedExp) - 500*time.Millisecond)
  526. if !leaseExist(t, clus, lresp.ID) {
  527. t.Error("unexpected lease not exists")
  528. }
  529. }
  530. // TestV3LeaseRequireLeader ensures that a Recv will get a leader
  531. // loss error if there is no leader.
  532. func TestV3LeaseRequireLeader(t *testing.T) {
  533. defer testutil.AfterTest(t)
  534. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  535. defer clus.Terminate(t)
  536. lc := toGRPC(clus.Client(0)).Lease
  537. clus.Members[1].Stop(t)
  538. clus.Members[2].Stop(t)
  539. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  540. mctx := metadata.NewOutgoingContext(context.Background(), md)
  541. ctx, cancel := context.WithCancel(mctx)
  542. defer cancel()
  543. lac, err := lc.LeaseKeepAlive(ctx)
  544. if err != nil {
  545. t.Fatal(err)
  546. }
  547. donec := make(chan struct{})
  548. go func() {
  549. defer close(donec)
  550. resp, err := lac.Recv()
  551. if err == nil {
  552. t.Errorf("got response %+v, expected error", resp)
  553. }
  554. if rpctypes.ErrorDesc(err) != rpctypes.ErrNoLeader.Error() {
  555. t.Errorf("err = %v, want %v", err, rpctypes.ErrNoLeader)
  556. }
  557. }()
  558. select {
  559. case <-time.After(5 * time.Second):
  560. t.Fatal("did not receive leader loss error (in 5-sec)")
  561. case <-donec:
  562. }
  563. }
  564. const fiveMinTTL int64 = 300
  565. // TestV3LeaseRecoverAndRevoke ensures that revoking a lease after restart deletes the attached key.
  566. func TestV3LeaseRecoverAndRevoke(t *testing.T) {
  567. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  568. defer clus.Terminate(t)
  569. kvc := toGRPC(clus.Client(0)).KV
  570. lsc := toGRPC(clus.Client(0)).Lease
  571. lresp, err := lsc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: fiveMinTTL})
  572. if err != nil {
  573. t.Fatal(err)
  574. }
  575. if lresp.Error != "" {
  576. t.Fatal(lresp.Error)
  577. }
  578. _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: lresp.ID})
  579. if err != nil {
  580. t.Fatal(err)
  581. }
  582. // restart server and ensure lease still exists
  583. clus.Members[0].Stop(t)
  584. clus.Members[0].Restart(t)
  585. clus.waitLeader(t, clus.Members)
  586. // overwrite old client with newly dialed connection
  587. // otherwise, error with "grpc: RPC failed fast due to transport failure"
  588. nc, err := NewClientV3(clus.Members[0])
  589. if err != nil {
  590. t.Fatal(err)
  591. }
  592. kvc = toGRPC(nc).KV
  593. lsc = toGRPC(nc).Lease
  594. defer nc.Close()
  595. // revoke should delete the key
  596. _, err = lsc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
  597. if err != nil {
  598. t.Fatal(err)
  599. }
  600. rresp, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  601. if err != nil {
  602. t.Fatal(err)
  603. }
  604. if len(rresp.Kvs) != 0 {
  605. t.Fatalf("lease removed but key remains")
  606. }
  607. }
  608. // TestV3LeaseRevokeAndRecover ensures that revoked key stays deleted after restart.
  609. func TestV3LeaseRevokeAndRecover(t *testing.T) {
  610. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  611. defer clus.Terminate(t)
  612. kvc := toGRPC(clus.Client(0)).KV
  613. lsc := toGRPC(clus.Client(0)).Lease
  614. lresp, err := lsc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: fiveMinTTL})
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. if lresp.Error != "" {
  619. t.Fatal(lresp.Error)
  620. }
  621. _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: lresp.ID})
  622. if err != nil {
  623. t.Fatal(err)
  624. }
  625. // revoke should delete the key
  626. _, err = lsc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
  627. if err != nil {
  628. t.Fatal(err)
  629. }
  630. // restart server and ensure revoked key doesn't exist
  631. clus.Members[0].Stop(t)
  632. clus.Members[0].Restart(t)
  633. clus.waitLeader(t, clus.Members)
  634. // overwrite old client with newly dialed connection
  635. // otherwise, error with "grpc: RPC failed fast due to transport failure"
  636. nc, err := NewClientV3(clus.Members[0])
  637. if err != nil {
  638. t.Fatal(err)
  639. }
  640. kvc = toGRPC(nc).KV
  641. defer nc.Close()
  642. rresp, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  643. if err != nil {
  644. t.Fatal(err)
  645. }
  646. if len(rresp.Kvs) != 0 {
  647. t.Fatalf("lease removed but key remains")
  648. }
  649. }
  650. // TestV3LeaseRecoverKeyWithDetachedLease ensures that revoking a detached lease after restart
  651. // does not delete the key.
  652. func TestV3LeaseRecoverKeyWithDetachedLease(t *testing.T) {
  653. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  654. defer clus.Terminate(t)
  655. kvc := toGRPC(clus.Client(0)).KV
  656. lsc := toGRPC(clus.Client(0)).Lease
  657. lresp, err := lsc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: fiveMinTTL})
  658. if err != nil {
  659. t.Fatal(err)
  660. }
  661. if lresp.Error != "" {
  662. t.Fatal(lresp.Error)
  663. }
  664. _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: lresp.ID})
  665. if err != nil {
  666. t.Fatal(err)
  667. }
  668. // overwrite lease with none
  669. _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar")})
  670. if err != nil {
  671. t.Fatal(err)
  672. }
  673. // restart server and ensure lease still exists
  674. clus.Members[0].Stop(t)
  675. clus.Members[0].Restart(t)
  676. clus.waitLeader(t, clus.Members)
  677. // overwrite old client with newly dialed connection
  678. // otherwise, error with "grpc: RPC failed fast due to transport failure"
  679. nc, err := NewClientV3(clus.Members[0])
  680. if err != nil {
  681. t.Fatal(err)
  682. }
  683. kvc = toGRPC(nc).KV
  684. lsc = toGRPC(nc).Lease
  685. defer nc.Close()
  686. // revoke the detached lease
  687. _, err = lsc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: lresp.ID})
  688. if err != nil {
  689. t.Fatal(err)
  690. }
  691. rresp, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  692. if err != nil {
  693. t.Fatal(err)
  694. }
  695. if len(rresp.Kvs) != 1 {
  696. t.Fatalf("only detached lease removed, key should remain")
  697. }
  698. }
  699. func TestV3LeaseRecoverKeyWithMutipleLease(t *testing.T) {
  700. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  701. defer clus.Terminate(t)
  702. kvc := toGRPC(clus.Client(0)).KV
  703. lsc := toGRPC(clus.Client(0)).Lease
  704. var leaseIDs []int64
  705. for i := 0; i < 2; i++ {
  706. lresp, err := lsc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: fiveMinTTL})
  707. if err != nil {
  708. t.Fatal(err)
  709. }
  710. if lresp.Error != "" {
  711. t.Fatal(lresp.Error)
  712. }
  713. leaseIDs = append(leaseIDs, lresp.ID)
  714. _, err = kvc.Put(context.TODO(), &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: lresp.ID})
  715. if err != nil {
  716. t.Fatal(err)
  717. }
  718. }
  719. // restart server and ensure lease still exists
  720. clus.Members[0].Stop(t)
  721. clus.Members[0].Restart(t)
  722. clus.waitLeader(t, clus.Members)
  723. for i, leaseID := range leaseIDs {
  724. if !leaseExist(t, clus, leaseID) {
  725. t.Errorf("#%d: unexpected lease not exists", i)
  726. }
  727. }
  728. // overwrite old client with newly dialed connection
  729. // otherwise, error with "grpc: RPC failed fast due to transport failure"
  730. nc, err := NewClientV3(clus.Members[0])
  731. if err != nil {
  732. t.Fatal(err)
  733. }
  734. kvc = toGRPC(nc).KV
  735. lsc = toGRPC(nc).Lease
  736. defer nc.Close()
  737. // revoke the old lease
  738. _, err = lsc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseIDs[0]})
  739. if err != nil {
  740. t.Fatal(err)
  741. }
  742. // key should still exist
  743. rresp, err := kvc.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  744. if err != nil {
  745. t.Fatal(err)
  746. }
  747. if len(rresp.Kvs) != 1 {
  748. t.Fatalf("only detached lease removed, key should remain")
  749. }
  750. // revoke the latest lease
  751. _, err = lsc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseIDs[1]})
  752. if err != nil {
  753. t.Fatal(err)
  754. }
  755. rresp, err = kvc.Range(context.TODO(), &pb.RangeRequest{Key: []byte("foo")})
  756. if err != nil {
  757. t.Fatal(err)
  758. }
  759. if len(rresp.Kvs) != 0 {
  760. t.Fatalf("lease removed but key remains")
  761. }
  762. }
  763. // acquireLeaseAndKey creates a new lease and creates an attached key.
  764. func acquireLeaseAndKey(clus *ClusterV3, key string) (int64, error) {
  765. // create lease
  766. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  767. context.TODO(),
  768. &pb.LeaseGrantRequest{TTL: 1})
  769. if err != nil {
  770. return 0, err
  771. }
  772. if lresp.Error != "" {
  773. return 0, fmt.Errorf(lresp.Error)
  774. }
  775. // attach to key
  776. put := &pb.PutRequest{Key: []byte(key), Lease: lresp.ID}
  777. if _, err := toGRPC(clus.RandClient()).KV.Put(context.TODO(), put); err != nil {
  778. return 0, err
  779. }
  780. return lresp.ID, nil
  781. }
  782. // testLeaseRemoveLeasedKey performs some action while holding a lease with an
  783. // attached key "foo", then confirms the key is gone.
  784. func testLeaseRemoveLeasedKey(t *testing.T, act func(*ClusterV3, int64) error) {
  785. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  786. defer clus.Terminate(t)
  787. leaseID, err := acquireLeaseAndKey(clus, "foo")
  788. if err != nil {
  789. t.Fatal(err)
  790. }
  791. if err = act(clus, leaseID); err != nil {
  792. t.Fatal(err)
  793. }
  794. // confirm no key
  795. rreq := &pb.RangeRequest{Key: []byte("foo")}
  796. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  797. if err != nil {
  798. t.Fatal(err)
  799. }
  800. if len(rresp.Kvs) != 0 {
  801. t.Fatalf("lease removed but key remains")
  802. }
  803. }
  804. func leaseExist(t *testing.T, clus *ClusterV3, leaseID int64) bool {
  805. l := toGRPC(clus.RandClient()).Lease
  806. _, err := l.LeaseGrant(context.Background(), &pb.LeaseGrantRequest{ID: leaseID, TTL: 5})
  807. if err == nil {
  808. _, err = l.LeaseRevoke(context.Background(), &pb.LeaseRevokeRequest{ID: leaseID})
  809. if err != nil {
  810. t.Fatalf("failed to check lease %v", err)
  811. }
  812. return false
  813. }
  814. if eqErrGRPC(err, rpctypes.ErrGRPCLeaseExist) {
  815. return true
  816. }
  817. t.Fatalf("unexpecter error %v", err)
  818. return true
  819. }