lessor_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. // Copyright 2015 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 lease
  15. import (
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. "reflect"
  21. "sort"
  22. "sync"
  23. "testing"
  24. "time"
  25. "github.com/coreos/etcd/mvcc/backend"
  26. )
  27. const (
  28. minLeaseTTL = int64(5)
  29. minLeaseTTLDuration = time.Duration(minLeaseTTL) * time.Second
  30. )
  31. // TestLessorGrant ensures Lessor can grant wanted lease.
  32. // The granted lease should have a unique ID with a term
  33. // that is greater than minLeaseTTL.
  34. func TestLessorGrant(t *testing.T) {
  35. dir, be := NewTestBackend(t)
  36. defer os.RemoveAll(dir)
  37. defer be.Close()
  38. le := newLessor(be, minLeaseTTL)
  39. defer le.Stop()
  40. le.Promote(0)
  41. l, err := le.Grant(1, 1)
  42. if err != nil {
  43. t.Fatalf("could not grant lease 1 (%v)", err)
  44. }
  45. gl := le.Lookup(l.ID)
  46. if !reflect.DeepEqual(gl, l) {
  47. t.Errorf("lease = %v, want %v", gl, l)
  48. }
  49. if l.Remaining() < minLeaseTTLDuration-time.Second {
  50. t.Errorf("term = %v, want at least %v", l.Remaining(), minLeaseTTLDuration-time.Second)
  51. }
  52. _, err = le.Grant(1, 1)
  53. if err == nil {
  54. t.Errorf("allocated the same lease")
  55. }
  56. var nl *Lease
  57. nl, err = le.Grant(2, 1)
  58. if err != nil {
  59. t.Errorf("could not grant lease 2 (%v)", err)
  60. }
  61. if nl.ID == l.ID {
  62. t.Errorf("new lease.id = %x, want != %x", nl.ID, l.ID)
  63. }
  64. be.BatchTx().Lock()
  65. _, vs := be.BatchTx().UnsafeRange(leaseBucketName, int64ToBytes(int64(l.ID)), nil, 0)
  66. if len(vs) != 1 {
  67. t.Errorf("len(vs) = %d, want 1", len(vs))
  68. }
  69. be.BatchTx().Unlock()
  70. }
  71. // TestLeaseConcurrentKeys ensures Lease.Keys method calls are guarded
  72. // from concurrent map writes on 'itemSet'.
  73. func TestLeaseConcurrentKeys(t *testing.T) {
  74. dir, be := NewTestBackend(t)
  75. defer os.RemoveAll(dir)
  76. defer be.Close()
  77. le := newLessor(be, minLeaseTTL)
  78. defer le.Stop()
  79. le.SetRangeDeleter(func() TxnDelete { return newFakeDeleter(be) })
  80. // grant a lease with long term (100 seconds) to
  81. // avoid early termination during the test.
  82. l, err := le.Grant(1, 100)
  83. if err != nil {
  84. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  85. }
  86. itemn := 10
  87. items := make([]LeaseItem, itemn)
  88. for i := 0; i < itemn; i++ {
  89. items[i] = LeaseItem{Key: fmt.Sprintf("foo%d", i)}
  90. }
  91. if err = le.Attach(l.ID, items); err != nil {
  92. t.Fatalf("failed to attach items to the lease: %v", err)
  93. }
  94. donec := make(chan struct{})
  95. go func() {
  96. le.Detach(l.ID, items)
  97. close(donec)
  98. }()
  99. var wg sync.WaitGroup
  100. wg.Add(itemn)
  101. for i := 0; i < itemn; i++ {
  102. go func() {
  103. defer wg.Done()
  104. l.Keys()
  105. }()
  106. }
  107. <-donec
  108. wg.Wait()
  109. }
  110. // TestLessorRevoke ensures Lessor can revoke a lease.
  111. // The items in the revoked lease should be removed from
  112. // the backend.
  113. // The revoked lease cannot be got from Lessor again.
  114. func TestLessorRevoke(t *testing.T) {
  115. dir, be := NewTestBackend(t)
  116. defer os.RemoveAll(dir)
  117. defer be.Close()
  118. le := newLessor(be, minLeaseTTL)
  119. defer le.Stop()
  120. var fd *fakeDeleter
  121. le.SetRangeDeleter(func() TxnDelete {
  122. fd = newFakeDeleter(be)
  123. return fd
  124. })
  125. // grant a lease with long term (100 seconds) to
  126. // avoid early termination during the test.
  127. l, err := le.Grant(1, 100)
  128. if err != nil {
  129. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  130. }
  131. items := []LeaseItem{
  132. {"foo"},
  133. {"bar"},
  134. }
  135. if err = le.Attach(l.ID, items); err != nil {
  136. t.Fatalf("failed to attach items to the lease: %v", err)
  137. }
  138. if err = le.Revoke(l.ID); err != nil {
  139. t.Fatal("failed to revoke lease:", err)
  140. }
  141. if le.Lookup(l.ID) != nil {
  142. t.Errorf("got revoked lease %x", l.ID)
  143. }
  144. wdeleted := []string{"bar_", "foo_"}
  145. sort.Sort(sort.StringSlice(fd.deleted))
  146. if !reflect.DeepEqual(fd.deleted, wdeleted) {
  147. t.Errorf("deleted= %v, want %v", fd.deleted, wdeleted)
  148. }
  149. be.BatchTx().Lock()
  150. _, vs := be.BatchTx().UnsafeRange(leaseBucketName, int64ToBytes(int64(l.ID)), nil, 0)
  151. if len(vs) != 0 {
  152. t.Errorf("len(vs) = %d, want 0", len(vs))
  153. }
  154. be.BatchTx().Unlock()
  155. }
  156. // TestLessorRenew ensures Lessor can renew an existing lease.
  157. func TestLessorRenew(t *testing.T) {
  158. dir, be := NewTestBackend(t)
  159. defer be.Close()
  160. defer os.RemoveAll(dir)
  161. le := newLessor(be, minLeaseTTL)
  162. defer le.Stop()
  163. le.Promote(0)
  164. l, err := le.Grant(1, minLeaseTTL)
  165. if err != nil {
  166. t.Fatalf("failed to grant lease (%v)", err)
  167. }
  168. // manually change the ttl field
  169. le.mu.Lock()
  170. l.ttl = 10
  171. le.mu.Unlock()
  172. ttl, err := le.Renew(l.ID)
  173. if err != nil {
  174. t.Fatalf("failed to renew lease (%v)", err)
  175. }
  176. if ttl != l.ttl {
  177. t.Errorf("ttl = %d, want %d", ttl, l.ttl)
  178. }
  179. l = le.Lookup(l.ID)
  180. if l.Remaining() < 9*time.Second {
  181. t.Errorf("failed to renew the lease")
  182. }
  183. }
  184. // TestLessorRenewExtendPileup ensures Lessor extends leases on promotion if too many
  185. // expire at the same time.
  186. func TestLessorRenewExtendPileup(t *testing.T) {
  187. oldRevokeRate := leaseRevokeRate
  188. defer func() { leaseRevokeRate = oldRevokeRate }()
  189. leaseRevokeRate = 10
  190. dir, be := NewTestBackend(t)
  191. defer os.RemoveAll(dir)
  192. le := newLessor(be, minLeaseTTL)
  193. ttl := int64(10)
  194. for i := 1; i <= leaseRevokeRate*10; i++ {
  195. if _, err := le.Grant(LeaseID(2*i), ttl); err != nil {
  196. t.Fatal(err)
  197. }
  198. // ttls that overlap spillover for ttl=10
  199. if _, err := le.Grant(LeaseID(2*i+1), ttl+1); err != nil {
  200. t.Fatal(err)
  201. }
  202. }
  203. // simulate stop and recovery
  204. le.Stop()
  205. be.Close()
  206. bcfg := backend.DefaultBackendConfig()
  207. bcfg.Path = filepath.Join(dir, "be")
  208. be = backend.New(bcfg)
  209. defer be.Close()
  210. le = newLessor(be, minLeaseTTL)
  211. defer le.Stop()
  212. // extend after recovery should extend expiration on lease pile-up
  213. le.Promote(0)
  214. windowCounts := make(map[int64]int)
  215. for _, l := range le.leaseMap {
  216. // round up slightly for baseline ttl
  217. s := int64(l.Remaining().Seconds() + 0.1)
  218. windowCounts[s]++
  219. }
  220. for i := ttl; i < ttl+20; i++ {
  221. c := windowCounts[i]
  222. if c > leaseRevokeRate {
  223. t.Errorf("expected at most %d expiring at %ds, got %d", leaseRevokeRate, i, c)
  224. }
  225. if c < leaseRevokeRate/2 {
  226. t.Errorf("expected at least %d expiring at %ds, got %d", leaseRevokeRate/2, i, c)
  227. }
  228. }
  229. }
  230. func TestLessorDetach(t *testing.T) {
  231. dir, be := NewTestBackend(t)
  232. defer os.RemoveAll(dir)
  233. defer be.Close()
  234. le := newLessor(be, minLeaseTTL)
  235. defer le.Stop()
  236. le.SetRangeDeleter(func() TxnDelete { return newFakeDeleter(be) })
  237. // grant a lease with long term (100 seconds) to
  238. // avoid early termination during the test.
  239. l, err := le.Grant(1, 100)
  240. if err != nil {
  241. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  242. }
  243. items := []LeaseItem{
  244. {"foo"},
  245. {"bar"},
  246. }
  247. if err := le.Attach(l.ID, items); err != nil {
  248. t.Fatalf("failed to attach items to the lease: %v", err)
  249. }
  250. if err := le.Detach(l.ID, items[0:1]); err != nil {
  251. t.Fatalf("failed to de-attach items to the lease: %v", err)
  252. }
  253. l = le.Lookup(l.ID)
  254. if len(l.itemSet) != 1 {
  255. t.Fatalf("len(l.itemSet) = %d, failed to de-attach items", len(l.itemSet))
  256. }
  257. if _, ok := l.itemSet[LeaseItem{"bar"}]; !ok {
  258. t.Fatalf("de-attached wrong item, want %q exists", "bar")
  259. }
  260. }
  261. // TestLessorRecover ensures Lessor recovers leases from
  262. // persist backend.
  263. func TestLessorRecover(t *testing.T) {
  264. dir, be := NewTestBackend(t)
  265. defer os.RemoveAll(dir)
  266. defer be.Close()
  267. le := newLessor(be, minLeaseTTL)
  268. defer le.Stop()
  269. l1, err1 := le.Grant(1, 10)
  270. l2, err2 := le.Grant(2, 20)
  271. if err1 != nil || err2 != nil {
  272. t.Fatalf("could not grant initial leases (%v, %v)", err1, err2)
  273. }
  274. // Create a new lessor with the same backend
  275. nle := newLessor(be, minLeaseTTL)
  276. defer nle.Stop()
  277. nl1 := nle.Lookup(l1.ID)
  278. if nl1 == nil || nl1.ttl != l1.ttl {
  279. t.Errorf("nl1 = %v, want nl1.ttl= %d", nl1.ttl, l1.ttl)
  280. }
  281. nl2 := nle.Lookup(l2.ID)
  282. if nl2 == nil || nl2.ttl != l2.ttl {
  283. t.Errorf("nl2 = %v, want nl2.ttl= %d", nl2.ttl, l2.ttl)
  284. }
  285. }
  286. func TestLessorExpire(t *testing.T) {
  287. dir, be := NewTestBackend(t)
  288. defer os.RemoveAll(dir)
  289. defer be.Close()
  290. testMinTTL := int64(1)
  291. le := newLessor(be, testMinTTL)
  292. defer le.Stop()
  293. le.Promote(1 * time.Second)
  294. l, err := le.Grant(1, testMinTTL)
  295. if err != nil {
  296. t.Fatalf("failed to create lease: %v", err)
  297. }
  298. select {
  299. case el := <-le.ExpiredLeasesC():
  300. if el[0].ID != l.ID {
  301. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  302. }
  303. case <-time.After(10 * time.Second):
  304. t.Fatalf("failed to receive expired lease")
  305. }
  306. donec := make(chan struct{})
  307. go func() {
  308. // expired lease cannot be renewed
  309. if _, err := le.Renew(l.ID); err != ErrLeaseNotFound {
  310. t.Fatalf("unexpected renew")
  311. }
  312. donec <- struct{}{}
  313. }()
  314. select {
  315. case <-donec:
  316. t.Fatalf("renew finished before lease revocation")
  317. case <-time.After(50 * time.Millisecond):
  318. }
  319. // expired lease can be revoked
  320. if err := le.Revoke(l.ID); err != nil {
  321. t.Fatalf("failed to revoke expired lease: %v", err)
  322. }
  323. select {
  324. case <-donec:
  325. case <-time.After(10 * time.Second):
  326. t.Fatalf("renew has not returned after lease revocation")
  327. }
  328. }
  329. func TestLessorExpireAndDemote(t *testing.T) {
  330. dir, be := NewTestBackend(t)
  331. defer os.RemoveAll(dir)
  332. defer be.Close()
  333. testMinTTL := int64(1)
  334. le := newLessor(be, testMinTTL)
  335. defer le.Stop()
  336. le.Promote(1 * time.Second)
  337. l, err := le.Grant(1, testMinTTL)
  338. if err != nil {
  339. t.Fatalf("failed to create lease: %v", err)
  340. }
  341. select {
  342. case el := <-le.ExpiredLeasesC():
  343. if el[0].ID != l.ID {
  344. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  345. }
  346. case <-time.After(10 * time.Second):
  347. t.Fatalf("failed to receive expired lease")
  348. }
  349. donec := make(chan struct{})
  350. go func() {
  351. // expired lease cannot be renewed
  352. if _, err := le.Renew(l.ID); err != ErrNotPrimary {
  353. t.Fatalf("unexpected renew: %v", err)
  354. }
  355. donec <- struct{}{}
  356. }()
  357. select {
  358. case <-donec:
  359. t.Fatalf("renew finished before demotion")
  360. case <-time.After(50 * time.Millisecond):
  361. }
  362. // demote will cause the renew request to fail with ErrNotPrimary
  363. le.Demote()
  364. select {
  365. case <-donec:
  366. case <-time.After(10 * time.Second):
  367. t.Fatalf("renew has not returned after lessor demotion")
  368. }
  369. }
  370. func TestLessorMaxTTL(t *testing.T) {
  371. dir, be := NewTestBackend(t)
  372. defer os.RemoveAll(dir)
  373. defer be.Close()
  374. le := newLessor(be, minLeaseTTL)
  375. defer le.Stop()
  376. _, err := le.Grant(1, MaxLeaseTTL+1)
  377. if err != ErrLeaseTTLTooLarge {
  378. t.Fatalf("grant unexpectedly succeeded")
  379. }
  380. }
  381. type fakeDeleter struct {
  382. deleted []string
  383. tx backend.BatchTx
  384. }
  385. func newFakeDeleter(be backend.Backend) *fakeDeleter {
  386. fd := &fakeDeleter{nil, be.BatchTx()}
  387. fd.tx.Lock()
  388. return fd
  389. }
  390. func (fd *fakeDeleter) End() { fd.tx.Unlock() }
  391. func (fd *fakeDeleter) DeleteRange(key, end []byte) (int64, int64) {
  392. fd.deleted = append(fd.deleted, string(key)+"_"+string(end))
  393. return 0, 0
  394. }
  395. func NewTestBackend(t *testing.T) (string, backend.Backend) {
  396. tmpPath, err := ioutil.TempDir("", "lease")
  397. if err != nil {
  398. t.Fatalf("failed to create tmpdir (%v)", err)
  399. }
  400. bcfg := backend.DefaultBackendConfig()
  401. bcfg.Path = filepath.Join(tmpPath, "be")
  402. return tmpPath, backend.New(bcfg)
  403. }