v3_lease_test.go 12 KB

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