v3_lease_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. "fmt"
  17. "testing"
  18. "time"
  19. "golang.org/x/net/context"
  20. "google.golang.org/grpc/metadata"
  21. "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"
  22. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  23. "github.com/coreos/etcd/mvcc/mvccpb"
  24. "github.com/coreos/etcd/pkg/testutil"
  25. )
  26. // TestV3LeasePrmote ensures the newly elected leader can promote itself
  27. // to the primary lessor, refresh the leases and start to manage leases.
  28. // TODO: use customized clock to make this test go faster?
  29. func TestV3LeasePrmote(t *testing.T) {
  30. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  31. defer clus.Terminate(t)
  32. // create lease
  33. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 5})
  34. if err != nil {
  35. t.Fatal(err)
  36. }
  37. if lresp.Error != "" {
  38. t.Fatal(lresp.Error)
  39. }
  40. // wait until the lease is going to expire.
  41. time.Sleep(time.Duration(lresp.TTL-1) * time.Second)
  42. // kill the current leader, all leases should be refreshed.
  43. toStop := clus.waitLeader(t, clus.Members)
  44. clus.Members[toStop].Stop(t)
  45. var toWait []*member
  46. for i, m := range clus.Members {
  47. if i != toStop {
  48. toWait = append(toWait, m)
  49. }
  50. }
  51. clus.waitLeader(t, toWait)
  52. clus.Members[toStop].Restart(t)
  53. clus.waitLeader(t, clus.Members)
  54. // ensure lease is refreshed by waiting for a "long" time.
  55. // it was going to expire anyway.
  56. time.Sleep(3 * time.Second)
  57. if !leaseExist(t, clus, lresp.ID) {
  58. t.Error("unexpected lease not exists")
  59. }
  60. // let lease expires. total lease = 5 seconds and we already
  61. // waits for 3 seconds, so 3 seconds more is enough.
  62. time.Sleep(3 * time.Second)
  63. if leaseExist(t, clus, lresp.ID) {
  64. t.Error("unexpected lease exists")
  65. }
  66. }
  67. // TestV3LeaseRevoke ensures a key is deleted once its lease is revoked.
  68. func TestV3LeaseRevoke(t *testing.T) {
  69. defer testutil.AfterTest(t)
  70. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  71. lc := toGRPC(clus.RandClient()).Lease
  72. _, err := lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseID})
  73. return err
  74. })
  75. }
  76. // TestV3LeaseGrantById ensures leases may be created by a given id.
  77. func TestV3LeaseGrantByID(t *testing.T) {
  78. defer testutil.AfterTest(t)
  79. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  80. defer clus.Terminate(t)
  81. // create fixed lease
  82. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  83. context.TODO(),
  84. &pb.LeaseGrantRequest{ID: 1, TTL: 1})
  85. if err != nil {
  86. t.Errorf("could not create lease 1 (%v)", err)
  87. }
  88. if lresp.ID != 1 {
  89. t.Errorf("got id %v, wanted id %v", lresp.ID, 1)
  90. }
  91. // create duplicate fixed lease
  92. lresp, err = toGRPC(clus.RandClient()).Lease.LeaseGrant(
  93. context.TODO(),
  94. &pb.LeaseGrantRequest{ID: 1, TTL: 1})
  95. if !eqErrGRPC(err, rpctypes.ErrGRPCLeaseExist) {
  96. t.Error(err)
  97. }
  98. // create fresh fixed lease
  99. lresp, err = toGRPC(clus.RandClient()).Lease.LeaseGrant(
  100. context.TODO(),
  101. &pb.LeaseGrantRequest{ID: 2, TTL: 1})
  102. if err != nil {
  103. t.Errorf("could not create lease 2 (%v)", err)
  104. }
  105. if lresp.ID != 2 {
  106. t.Errorf("got id %v, wanted id %v", lresp.ID, 2)
  107. }
  108. }
  109. // TestV3LeaseExpire ensures a key is deleted once a key expires.
  110. func TestV3LeaseExpire(t *testing.T) {
  111. defer testutil.AfterTest(t)
  112. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  113. // let lease lapse; wait for deleted key
  114. ctx, cancel := context.WithCancel(context.Background())
  115. defer cancel()
  116. wStream, err := toGRPC(clus.RandClient()).Watch.Watch(ctx)
  117. if err != nil {
  118. return err
  119. }
  120. wreq := &pb.WatchRequest{RequestUnion: &pb.WatchRequest_CreateRequest{
  121. CreateRequest: &pb.WatchCreateRequest{
  122. Key: []byte("foo"), StartRevision: 1}}}
  123. if err := wStream.Send(wreq); err != nil {
  124. return err
  125. }
  126. if _, err := wStream.Recv(); err != nil {
  127. // the 'created' message
  128. return err
  129. }
  130. if _, err := wStream.Recv(); err != nil {
  131. // the 'put' message
  132. return err
  133. }
  134. errc := make(chan error, 1)
  135. go func() {
  136. resp, err := wStream.Recv()
  137. switch {
  138. case err != nil:
  139. errc <- err
  140. case len(resp.Events) != 1:
  141. fallthrough
  142. case resp.Events[0].Type != mvccpb.DELETE:
  143. errc <- fmt.Errorf("expected key delete, got %v", resp)
  144. default:
  145. errc <- nil
  146. }
  147. }()
  148. select {
  149. case <-time.After(15 * time.Second):
  150. return fmt.Errorf("lease expiration too slow")
  151. case err := <-errc:
  152. return err
  153. }
  154. })
  155. }
  156. // TestV3LeaseKeepAlive ensures keepalive keeps the lease alive.
  157. func TestV3LeaseKeepAlive(t *testing.T) {
  158. defer testutil.AfterTest(t)
  159. testLeaseRemoveLeasedKey(t, func(clus *ClusterV3, leaseID int64) error {
  160. lc := toGRPC(clus.RandClient()).Lease
  161. lreq := &pb.LeaseKeepAliveRequest{ID: leaseID}
  162. ctx, cancel := context.WithCancel(context.Background())
  163. defer cancel()
  164. lac, err := lc.LeaseKeepAlive(ctx)
  165. if err != nil {
  166. return err
  167. }
  168. defer lac.CloseSend()
  169. // renew long enough so lease would've expired otherwise
  170. for i := 0; i < 3; i++ {
  171. if err = lac.Send(lreq); err != nil {
  172. return err
  173. }
  174. lresp, rxerr := lac.Recv()
  175. if rxerr != nil {
  176. return rxerr
  177. }
  178. if lresp.ID != leaseID {
  179. return fmt.Errorf("expected lease ID %v, got %v", leaseID, lresp.ID)
  180. }
  181. time.Sleep(time.Duration(lresp.TTL/2) * time.Second)
  182. }
  183. _, err = lc.LeaseRevoke(context.TODO(), &pb.LeaseRevokeRequest{ID: leaseID})
  184. return err
  185. })
  186. }
  187. // TestV3LeaseExists creates a lease on a random client and confirms it exists in the cluster.
  188. func TestV3LeaseExists(t *testing.T) {
  189. defer testutil.AfterTest(t)
  190. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  191. defer clus.Terminate(t)
  192. // create lease
  193. ctx0, cancel0 := context.WithCancel(context.Background())
  194. defer cancel0()
  195. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  196. ctx0,
  197. &pb.LeaseGrantRequest{TTL: 30})
  198. if err != nil {
  199. t.Fatal(err)
  200. }
  201. if lresp.Error != "" {
  202. t.Fatal(lresp.Error)
  203. }
  204. if !leaseExist(t, clus, lresp.ID) {
  205. t.Error("unexpected lease not exists")
  206. }
  207. }
  208. func TestV3PutOnNonExistLease(t *testing.T) {
  209. defer testutil.AfterTest(t)
  210. clus := NewClusterV3(t, &ClusterConfig{Size: 1})
  211. defer clus.Terminate(t)
  212. ctx, cancel := context.WithCancel(context.Background())
  213. defer cancel()
  214. badLeaseID := int64(0x12345678)
  215. putr := &pb.PutRequest{Key: []byte("foo"), Value: []byte("bar"), Lease: badLeaseID}
  216. _, err := toGRPC(clus.RandClient()).KV.Put(ctx, putr)
  217. if !eqErrGRPC(err, rpctypes.ErrGRPCLeaseNotFound) {
  218. t.Errorf("err = %v, want %v", err, rpctypes.ErrGRPCCompacted)
  219. }
  220. }
  221. // TestV3LeaseSwitch tests a key can be switched from one lease to another.
  222. func TestV3LeaseSwitch(t *testing.T) {
  223. defer testutil.AfterTest(t)
  224. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  225. defer clus.Terminate(t)
  226. key := "foo"
  227. // create lease
  228. ctx, cancel := context.WithCancel(context.Background())
  229. defer cancel()
  230. lresp1, err1 := toGRPC(clus.RandClient()).Lease.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: 30})
  231. if err1 != nil {
  232. t.Fatal(err1)
  233. }
  234. lresp2, err2 := toGRPC(clus.RandClient()).Lease.LeaseGrant(ctx, &pb.LeaseGrantRequest{TTL: 30})
  235. if err2 != nil {
  236. t.Fatal(err2)
  237. }
  238. // attach key on lease1 then switch it to lease2
  239. put1 := &pb.PutRequest{Key: []byte(key), Lease: lresp1.ID}
  240. _, err := toGRPC(clus.RandClient()).KV.Put(ctx, put1)
  241. if err != nil {
  242. t.Fatal(err)
  243. }
  244. put2 := &pb.PutRequest{Key: []byte(key), Lease: lresp2.ID}
  245. _, err = toGRPC(clus.RandClient()).KV.Put(ctx, put2)
  246. if err != nil {
  247. t.Fatal(err)
  248. }
  249. // revoke lease1 should not remove key
  250. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp1.ID})
  251. if err != nil {
  252. t.Fatal(err)
  253. }
  254. rreq := &pb.RangeRequest{Key: []byte("foo")}
  255. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  256. if err != nil {
  257. t.Fatal(err)
  258. }
  259. if len(rresp.Kvs) != 1 {
  260. t.Fatalf("unexpect removal of key")
  261. }
  262. // revoke lease2 should remove key
  263. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp2.ID})
  264. if err != nil {
  265. t.Fatal(err)
  266. }
  267. rresp, err = toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  268. if err != nil {
  269. t.Fatal(err)
  270. }
  271. if len(rresp.Kvs) != 0 {
  272. t.Fatalf("lease removed but key remains")
  273. }
  274. }
  275. // TestV3LeaseFailover ensures the old leader drops lease keepalive requests within
  276. // election timeout after it loses its quorum. And the new leader extends the TTL of
  277. // the lease to at least TTL + election timeout.
  278. func TestV3LeaseFailover(t *testing.T) {
  279. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  280. defer clus.Terminate(t)
  281. toIsolate := clus.waitLeader(t, clus.Members)
  282. lc := toGRPC(clus.Client(toIsolate)).Lease
  283. // create lease
  284. lresp, err := lc.LeaseGrant(context.TODO(), &pb.LeaseGrantRequest{TTL: 5})
  285. if err != nil {
  286. t.Fatal(err)
  287. }
  288. if lresp.Error != "" {
  289. t.Fatal(lresp.Error)
  290. }
  291. // isolate the current leader with its followers.
  292. clus.Members[toIsolate].Pause()
  293. lreq := &pb.LeaseKeepAliveRequest{ID: lresp.ID}
  294. md := metadata.Pairs(rpctypes.MetadataRequireLeaderKey, rpctypes.MetadataHasLeader)
  295. mctx := metadata.NewContext(context.Background(), md)
  296. ctx, cancel := context.WithCancel(mctx)
  297. defer cancel()
  298. lac, err := lc.LeaseKeepAlive(ctx)
  299. if err != nil {
  300. t.Fatal(err)
  301. }
  302. defer lac.CloseSend()
  303. // send keep alive to old leader until the old leader starts
  304. // to drop lease request.
  305. var expectedExp time.Time
  306. for {
  307. if err = lac.Send(lreq); err != nil {
  308. break
  309. }
  310. lkresp, rxerr := lac.Recv()
  311. if rxerr != nil {
  312. break
  313. }
  314. expectedExp = time.Now().Add(time.Duration(lkresp.TTL) * time.Second)
  315. time.Sleep(time.Duration(lkresp.TTL/2) * time.Second)
  316. }
  317. clus.Members[toIsolate].Resume()
  318. clus.waitLeader(t, clus.Members)
  319. // lease should not expire at the last received expire deadline.
  320. time.Sleep(expectedExp.Sub(time.Now()) - 500*time.Millisecond)
  321. if !leaseExist(t, clus, lresp.ID) {
  322. t.Error("unexpected lease not exists")
  323. }
  324. }
  325. // acquireLeaseAndKey creates a new lease and creates an attached key.
  326. func acquireLeaseAndKey(clus *ClusterV3, key string) (int64, error) {
  327. // create lease
  328. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseGrant(
  329. context.TODO(),
  330. &pb.LeaseGrantRequest{TTL: 1})
  331. if err != nil {
  332. return 0, err
  333. }
  334. if lresp.Error != "" {
  335. return 0, fmt.Errorf(lresp.Error)
  336. }
  337. // attach to key
  338. put := &pb.PutRequest{Key: []byte(key), Lease: lresp.ID}
  339. if _, err := toGRPC(clus.RandClient()).KV.Put(context.TODO(), put); err != nil {
  340. return 0, err
  341. }
  342. return lresp.ID, nil
  343. }
  344. // testLeaseRemoveLeasedKey performs some action while holding a lease with an
  345. // attached key "foo", then confirms the key is gone.
  346. func testLeaseRemoveLeasedKey(t *testing.T, act func(*ClusterV3, int64) error) {
  347. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  348. defer clus.Terminate(t)
  349. leaseID, err := acquireLeaseAndKey(clus, "foo")
  350. if err != nil {
  351. t.Fatal(err)
  352. }
  353. if err = act(clus, leaseID); err != nil {
  354. t.Fatal(err)
  355. }
  356. // confirm no key
  357. rreq := &pb.RangeRequest{Key: []byte("foo")}
  358. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  359. if err != nil {
  360. t.Fatal(err)
  361. }
  362. if len(rresp.Kvs) != 0 {
  363. t.Fatalf("lease removed but key remains")
  364. }
  365. }
  366. func leaseExist(t *testing.T, clus *ClusterV3, leaseID int64) bool {
  367. l := toGRPC(clus.RandClient()).Lease
  368. _, err := l.LeaseGrant(context.Background(), &pb.LeaseGrantRequest{ID: leaseID, TTL: 5})
  369. if err == nil {
  370. _, err = l.LeaseRevoke(context.Background(), &pb.LeaseRevokeRequest{ID: leaseID})
  371. if err != nil {
  372. t.Fatalf("failed to check lease %v", err)
  373. }
  374. return false
  375. }
  376. if eqErrGRPC(err, rpctypes.ErrGRPCLeaseExist) {
  377. return true
  378. }
  379. t.Fatalf("unexpecter error %v", err)
  380. return true
  381. }