v3_lease_test.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. "fmt"
  17. "testing"
  18. "time"
  19. "github.com/coreos/etcd/Godeps/_workspace/src/golang.org/x/net/context"
  20. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  21. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  22. "github.com/coreos/etcd/pkg/testutil"
  23. "github.com/coreos/etcd/storage/storagepb"
  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.LeaseCreate(context.TODO(), &pb.LeaseCreateRequest{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. // TestV3LeaseCreateById ensures leases may be created by a given id.
  76. func TestV3LeaseCreateByID(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.LeaseCreate(
  82. context.TODO(),
  83. &pb.LeaseCreateRequest{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.LeaseCreate(
  92. context.TODO(),
  93. &pb.LeaseCreateRequest{ID: 1, TTL: 1})
  94. if err != v3rpc.ErrLeaseExist {
  95. t.Error(err)
  96. }
  97. // create fresh fixed lease
  98. lresp, err = toGRPC(clus.RandClient()).Lease.LeaseCreate(
  99. context.TODO(),
  100. &pb.LeaseCreateRequest{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.LeaseCreate(
  195. ctx0,
  196. &pb.LeaseCreateRequest{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. // TestV3LeaseSwitch tests a key can be switched from one lease to another.
  208. func TestV3LeaseSwitch(t *testing.T) {
  209. defer testutil.AfterTest(t)
  210. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  211. defer clus.Terminate(t)
  212. key := "foo"
  213. // create lease
  214. ctx, cancel := context.WithCancel(context.Background())
  215. defer cancel()
  216. lresp1, err1 := toGRPC(clus.RandClient()).Lease.LeaseCreate(ctx, &pb.LeaseCreateRequest{TTL: 30})
  217. if err1 != nil {
  218. t.Fatal(err1)
  219. }
  220. lresp2, err2 := toGRPC(clus.RandClient()).Lease.LeaseCreate(ctx, &pb.LeaseCreateRequest{TTL: 30})
  221. if err2 != nil {
  222. t.Fatal(err2)
  223. }
  224. // attach key on lease1 then switch it to lease2
  225. put1 := &pb.PutRequest{Key: []byte(key), Lease: lresp1.ID}
  226. _, err := toGRPC(clus.RandClient()).KV.Put(ctx, put1)
  227. if err != nil {
  228. t.Fatal(err)
  229. }
  230. put2 := &pb.PutRequest{Key: []byte(key), Lease: lresp2.ID}
  231. _, err = toGRPC(clus.RandClient()).KV.Put(ctx, put2)
  232. if err != nil {
  233. t.Fatal(err)
  234. }
  235. // revoke lease1 should not remove key
  236. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp1.ID})
  237. if err != nil {
  238. t.Fatal(err)
  239. }
  240. rreq := &pb.RangeRequest{Key: []byte("foo")}
  241. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  242. if err != nil {
  243. t.Fatal(err)
  244. }
  245. if len(rresp.Kvs) != 1 {
  246. t.Fatalf("unexpect removal of key")
  247. }
  248. // revoke lease2 should remove key
  249. _, err = toGRPC(clus.RandClient()).Lease.LeaseRevoke(ctx, &pb.LeaseRevokeRequest{ID: lresp2.ID})
  250. if err != nil {
  251. t.Fatal(err)
  252. }
  253. rresp, err = toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  254. if err != nil {
  255. t.Fatal(err)
  256. }
  257. if len(rresp.Kvs) != 0 {
  258. t.Fatalf("lease removed but key remains")
  259. }
  260. }
  261. // acquireLeaseAndKey creates a new lease and creates an attached key.
  262. func acquireLeaseAndKey(clus *ClusterV3, key string) (int64, error) {
  263. // create lease
  264. lresp, err := toGRPC(clus.RandClient()).Lease.LeaseCreate(
  265. context.TODO(),
  266. &pb.LeaseCreateRequest{TTL: 1})
  267. if err != nil {
  268. return 0, err
  269. }
  270. if lresp.Error != "" {
  271. return 0, fmt.Errorf(lresp.Error)
  272. }
  273. // attach to key
  274. put := &pb.PutRequest{Key: []byte(key), Lease: lresp.ID}
  275. if _, err := toGRPC(clus.RandClient()).KV.Put(context.TODO(), put); err != nil {
  276. return 0, err
  277. }
  278. return lresp.ID, nil
  279. }
  280. // testLeaseRemoveLeasedKey performs some action while holding a lease with an
  281. // attached key "foo", then confirms the key is gone.
  282. func testLeaseRemoveLeasedKey(t *testing.T, act func(*ClusterV3, int64) error) {
  283. clus := NewClusterV3(t, &ClusterConfig{Size: 3})
  284. defer clus.Terminate(t)
  285. leaseID, err := acquireLeaseAndKey(clus, "foo")
  286. if err != nil {
  287. t.Fatal(err)
  288. }
  289. if err = act(clus, leaseID); err != nil {
  290. t.Fatal(err)
  291. }
  292. // confirm no key
  293. rreq := &pb.RangeRequest{Key: []byte("foo")}
  294. rresp, err := toGRPC(clus.RandClient()).KV.Range(context.TODO(), rreq)
  295. if err != nil {
  296. t.Fatal(err)
  297. }
  298. if len(rresp.Kvs) != 0 {
  299. t.Fatalf("lease removed but key remains")
  300. }
  301. }
  302. func leaseExist(t *testing.T, clus *ClusterV3, leaseID int64) bool {
  303. l := toGRPC(clus.RandClient()).Lease
  304. _, err := l.LeaseCreate(context.Background(), &pb.LeaseCreateRequest{ID: leaseID, TTL: 5})
  305. if err == nil {
  306. _, err = l.LeaseRevoke(context.Background(), &pb.LeaseRevokeRequest{ID: leaseID})
  307. if err != nil {
  308. t.Fatalf("failed to check lease %v", err)
  309. }
  310. return false
  311. }
  312. if err == v3rpc.ErrLeaseExist {
  313. return true
  314. }
  315. t.Fatalf("unexpecter error %v", err)
  316. return true
  317. }