lessor_test.go 11 KB

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