lessor_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. "context"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path/filepath"
  21. "reflect"
  22. "sort"
  23. "sync"
  24. "testing"
  25. "time"
  26. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  27. "go.etcd.io/etcd/mvcc/backend"
  28. "go.uber.org/zap"
  29. )
  30. const (
  31. minLeaseTTL = int64(5)
  32. minLeaseTTLDuration = time.Duration(minLeaseTTL) * time.Second
  33. )
  34. // TestLessorGrant ensures Lessor can grant wanted lease.
  35. // The granted lease should have a unique ID with a term
  36. // that is greater than minLeaseTTL.
  37. func TestLessorGrant(t *testing.T) {
  38. lg := zap.NewNop()
  39. dir, be := NewTestBackend(t)
  40. defer os.RemoveAll(dir)
  41. defer be.Close()
  42. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  43. defer le.Stop()
  44. le.Promote(0)
  45. l, err := le.Grant(1, 1)
  46. if err != nil {
  47. t.Fatalf("could not grant lease 1 (%v)", err)
  48. }
  49. if l.ttl != minLeaseTTL {
  50. t.Fatalf("ttl = %v, expect minLeaseTTL %v", l.ttl, minLeaseTTL)
  51. }
  52. gl := le.Lookup(l.ID)
  53. if !reflect.DeepEqual(gl, l) {
  54. t.Errorf("lease = %v, want %v", gl, l)
  55. }
  56. if l.Remaining() < minLeaseTTLDuration-time.Second {
  57. t.Errorf("term = %v, want at least %v", l.Remaining(), minLeaseTTLDuration-time.Second)
  58. }
  59. _, err = le.Grant(1, 1)
  60. if err == nil {
  61. t.Errorf("allocated the same lease")
  62. }
  63. var nl *Lease
  64. nl, err = le.Grant(2, 1)
  65. if err != nil {
  66. t.Errorf("could not grant lease 2 (%v)", err)
  67. }
  68. if nl.ID == l.ID {
  69. t.Errorf("new lease.id = %x, want != %x", nl.ID, l.ID)
  70. }
  71. lss := []*Lease{gl, nl}
  72. leases := le.Leases()
  73. for i := range lss {
  74. if lss[i].ID != leases[i].ID {
  75. t.Fatalf("lease ID expected %d, got %d", lss[i].ID, leases[i].ID)
  76. }
  77. if lss[i].ttl != leases[i].ttl {
  78. t.Fatalf("ttl expected %d, got %d", lss[i].ttl, leases[i].ttl)
  79. }
  80. }
  81. be.BatchTx().Lock()
  82. _, vs := be.BatchTx().UnsafeRange(leaseBucketName, int64ToBytes(int64(l.ID)), nil, 0)
  83. if len(vs) != 1 {
  84. t.Errorf("len(vs) = %d, want 1", len(vs))
  85. }
  86. be.BatchTx().Unlock()
  87. }
  88. // TestLeaseConcurrentKeys ensures Lease.Keys method calls are guarded
  89. // from concurrent map writes on 'itemSet'.
  90. func TestLeaseConcurrentKeys(t *testing.T) {
  91. lg := zap.NewNop()
  92. dir, be := NewTestBackend(t)
  93. defer os.RemoveAll(dir)
  94. defer be.Close()
  95. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  96. defer le.Stop()
  97. le.SetRangeDeleter(func() TxnDelete { return newFakeDeleter(be) })
  98. // grant a lease with long term (100 seconds) to
  99. // avoid early termination during the test.
  100. l, err := le.Grant(1, 100)
  101. if err != nil {
  102. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  103. }
  104. itemn := 10
  105. items := make([]LeaseItem, itemn)
  106. for i := 0; i < itemn; i++ {
  107. items[i] = LeaseItem{Key: fmt.Sprintf("foo%d", i)}
  108. }
  109. if err = le.Attach(l.ID, items); err != nil {
  110. t.Fatalf("failed to attach items to the lease: %v", err)
  111. }
  112. donec := make(chan struct{})
  113. go func() {
  114. le.Detach(l.ID, items)
  115. close(donec)
  116. }()
  117. var wg sync.WaitGroup
  118. wg.Add(itemn)
  119. for i := 0; i < itemn; i++ {
  120. go func() {
  121. defer wg.Done()
  122. l.Keys()
  123. }()
  124. }
  125. <-donec
  126. wg.Wait()
  127. }
  128. // TestLessorRevoke ensures Lessor can revoke a lease.
  129. // The items in the revoked lease should be removed from
  130. // the backend.
  131. // The revoked lease cannot be got from Lessor again.
  132. func TestLessorRevoke(t *testing.T) {
  133. lg := zap.NewNop()
  134. dir, be := NewTestBackend(t)
  135. defer os.RemoveAll(dir)
  136. defer be.Close()
  137. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  138. defer le.Stop()
  139. var fd *fakeDeleter
  140. le.SetRangeDeleter(func() TxnDelete {
  141. fd = newFakeDeleter(be)
  142. return fd
  143. })
  144. // grant a lease with long term (100 seconds) to
  145. // avoid early termination during the test.
  146. l, err := le.Grant(1, 100)
  147. if err != nil {
  148. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  149. }
  150. items := []LeaseItem{
  151. {"foo"},
  152. {"bar"},
  153. }
  154. if err = le.Attach(l.ID, items); err != nil {
  155. t.Fatalf("failed to attach items to the lease: %v", err)
  156. }
  157. if err = le.Revoke(l.ID); err != nil {
  158. t.Fatal("failed to revoke lease:", err)
  159. }
  160. if le.Lookup(l.ID) != nil {
  161. t.Errorf("got revoked lease %x", l.ID)
  162. }
  163. wdeleted := []string{"bar_", "foo_"}
  164. sort.Strings(fd.deleted)
  165. if !reflect.DeepEqual(fd.deleted, wdeleted) {
  166. t.Errorf("deleted= %v, want %v", fd.deleted, wdeleted)
  167. }
  168. be.BatchTx().Lock()
  169. _, vs := be.BatchTx().UnsafeRange(leaseBucketName, int64ToBytes(int64(l.ID)), nil, 0)
  170. if len(vs) != 0 {
  171. t.Errorf("len(vs) = %d, want 0", len(vs))
  172. }
  173. be.BatchTx().Unlock()
  174. }
  175. // TestLessorRenew ensures Lessor can renew an existing lease.
  176. func TestLessorRenew(t *testing.T) {
  177. lg := zap.NewNop()
  178. dir, be := NewTestBackend(t)
  179. defer be.Close()
  180. defer os.RemoveAll(dir)
  181. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  182. defer le.Stop()
  183. le.Promote(0)
  184. l, err := le.Grant(1, minLeaseTTL)
  185. if err != nil {
  186. t.Fatalf("failed to grant lease (%v)", err)
  187. }
  188. // manually change the ttl field
  189. le.mu.Lock()
  190. l.ttl = 10
  191. le.mu.Unlock()
  192. ttl, err := le.Renew(l.ID)
  193. if err != nil {
  194. t.Fatalf("failed to renew lease (%v)", err)
  195. }
  196. if ttl != l.ttl {
  197. t.Errorf("ttl = %d, want %d", ttl, l.ttl)
  198. }
  199. l = le.Lookup(l.ID)
  200. if l.Remaining() < 9*time.Second {
  201. t.Errorf("failed to renew the lease")
  202. }
  203. }
  204. func TestLessorRenewWithCheckpointer(t *testing.T) {
  205. lg := zap.NewNop()
  206. dir, be := NewTestBackend(t)
  207. defer be.Close()
  208. defer os.RemoveAll(dir)
  209. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  210. fakerCheckerpointer := func(ctx context.Context, cp *pb.LeaseCheckpointRequest) {
  211. for _, cp := range cp.GetCheckpoints() {
  212. le.Checkpoint(LeaseID(cp.GetID()), cp.GetRemaining_TTL())
  213. }
  214. }
  215. defer le.Stop()
  216. // Set checkpointer
  217. le.SetCheckpointer(fakerCheckerpointer)
  218. le.Promote(0)
  219. l, err := le.Grant(1, minLeaseTTL)
  220. if err != nil {
  221. t.Fatalf("failed to grant lease (%v)", err)
  222. }
  223. // manually change the ttl field
  224. le.mu.Lock()
  225. l.ttl = 10
  226. l.remainingTTL = 10
  227. le.mu.Unlock()
  228. ttl, err := le.Renew(l.ID)
  229. if err != nil {
  230. t.Fatalf("failed to renew lease (%v)", err)
  231. }
  232. if ttl != l.ttl {
  233. t.Errorf("ttl = %d, want %d", ttl, l.ttl)
  234. }
  235. if l.remainingTTL != 0 {
  236. t.Fatalf("remianingTTL = %d, want %d", l.remainingTTL, 0)
  237. }
  238. l = le.Lookup(l.ID)
  239. if l.Remaining() < 9*time.Second {
  240. t.Errorf("failed to renew the lease")
  241. }
  242. }
  243. // TestLessorRenewExtendPileup ensures Lessor extends leases on promotion if too many
  244. // expire at the same time.
  245. func TestLessorRenewExtendPileup(t *testing.T) {
  246. oldRevokeRate := leaseRevokeRate
  247. defer func() { leaseRevokeRate = oldRevokeRate }()
  248. lg := zap.NewNop()
  249. leaseRevokeRate = 10
  250. dir, be := NewTestBackend(t)
  251. defer os.RemoveAll(dir)
  252. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  253. ttl := int64(10)
  254. for i := 1; i <= leaseRevokeRate*10; i++ {
  255. if _, err := le.Grant(LeaseID(2*i), ttl); err != nil {
  256. t.Fatal(err)
  257. }
  258. // ttls that overlap spillover for ttl=10
  259. if _, err := le.Grant(LeaseID(2*i+1), ttl+1); err != nil {
  260. t.Fatal(err)
  261. }
  262. }
  263. // simulate stop and recovery
  264. le.Stop()
  265. be.Close()
  266. bcfg := backend.DefaultBackendConfig()
  267. bcfg.Path = filepath.Join(dir, "be")
  268. be = backend.New(bcfg)
  269. defer be.Close()
  270. le = newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  271. defer le.Stop()
  272. // extend after recovery should extend expiration on lease pile-up
  273. le.Promote(0)
  274. windowCounts := make(map[int64]int)
  275. for _, l := range le.leaseMap {
  276. // round up slightly for baseline ttl
  277. s := int64(l.Remaining().Seconds() + 0.1)
  278. windowCounts[s]++
  279. }
  280. for i := ttl; i < ttl+20; i++ {
  281. c := windowCounts[i]
  282. if c > leaseRevokeRate {
  283. t.Errorf("expected at most %d expiring at %ds, got %d", leaseRevokeRate, i, c)
  284. }
  285. if c < leaseRevokeRate/2 {
  286. t.Errorf("expected at least %d expiring at %ds, got %d", leaseRevokeRate/2, i, c)
  287. }
  288. }
  289. }
  290. func TestLessorDetach(t *testing.T) {
  291. lg := zap.NewNop()
  292. dir, be := NewTestBackend(t)
  293. defer os.RemoveAll(dir)
  294. defer be.Close()
  295. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  296. defer le.Stop()
  297. le.SetRangeDeleter(func() TxnDelete { return newFakeDeleter(be) })
  298. // grant a lease with long term (100 seconds) to
  299. // avoid early termination during the test.
  300. l, err := le.Grant(1, 100)
  301. if err != nil {
  302. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  303. }
  304. items := []LeaseItem{
  305. {"foo"},
  306. {"bar"},
  307. }
  308. if err := le.Attach(l.ID, items); err != nil {
  309. t.Fatalf("failed to attach items to the lease: %v", err)
  310. }
  311. if err := le.Detach(l.ID, items[0:1]); err != nil {
  312. t.Fatalf("failed to de-attach items to the lease: %v", err)
  313. }
  314. l = le.Lookup(l.ID)
  315. if len(l.itemSet) != 1 {
  316. t.Fatalf("len(l.itemSet) = %d, failed to de-attach items", len(l.itemSet))
  317. }
  318. if _, ok := l.itemSet[LeaseItem{"bar"}]; !ok {
  319. t.Fatalf("de-attached wrong item, want %q exists", "bar")
  320. }
  321. }
  322. // TestLessorRecover ensures Lessor recovers leases from
  323. // persist backend.
  324. func TestLessorRecover(t *testing.T) {
  325. lg := zap.NewNop()
  326. dir, be := NewTestBackend(t)
  327. defer os.RemoveAll(dir)
  328. defer be.Close()
  329. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  330. defer le.Stop()
  331. l1, err1 := le.Grant(1, 10)
  332. l2, err2 := le.Grant(2, 20)
  333. if err1 != nil || err2 != nil {
  334. t.Fatalf("could not grant initial leases (%v, %v)", err1, err2)
  335. }
  336. // Create a new lessor with the same backend
  337. nle := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  338. defer nle.Stop()
  339. nl1 := nle.Lookup(l1.ID)
  340. if nl1 == nil || nl1.ttl != l1.ttl {
  341. t.Errorf("nl1 = %v, want nl1.ttl= %d", nl1.ttl, l1.ttl)
  342. }
  343. nl2 := nle.Lookup(l2.ID)
  344. if nl2 == nil || nl2.ttl != l2.ttl {
  345. t.Errorf("nl2 = %v, want nl2.ttl= %d", nl2.ttl, l2.ttl)
  346. }
  347. }
  348. func TestLessorExpire(t *testing.T) {
  349. lg := zap.NewNop()
  350. dir, be := NewTestBackend(t)
  351. defer os.RemoveAll(dir)
  352. defer be.Close()
  353. testMinTTL := int64(1)
  354. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: testMinTTL})
  355. defer le.Stop()
  356. le.Promote(1 * time.Second)
  357. l, err := le.Grant(1, testMinTTL)
  358. if err != nil {
  359. t.Fatalf("failed to create lease: %v", err)
  360. }
  361. select {
  362. case el := <-le.ExpiredLeasesC():
  363. if el[0].ID != l.ID {
  364. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  365. }
  366. case <-time.After(10 * time.Second):
  367. t.Fatalf("failed to receive expired lease")
  368. }
  369. donec := make(chan struct{})
  370. go func() {
  371. // expired lease cannot be renewed
  372. if _, err := le.Renew(l.ID); err != ErrLeaseNotFound {
  373. t.Errorf("unexpected renew")
  374. }
  375. donec <- struct{}{}
  376. }()
  377. select {
  378. case <-donec:
  379. t.Fatalf("renew finished before lease revocation")
  380. case <-time.After(50 * time.Millisecond):
  381. }
  382. // expired lease can be revoked
  383. if err := le.Revoke(l.ID); err != nil {
  384. t.Fatalf("failed to revoke expired lease: %v", err)
  385. }
  386. select {
  387. case <-donec:
  388. case <-time.After(10 * time.Second):
  389. t.Fatalf("renew has not returned after lease revocation")
  390. }
  391. }
  392. func TestLessorExpireAndDemote(t *testing.T) {
  393. lg := zap.NewNop()
  394. dir, be := NewTestBackend(t)
  395. defer os.RemoveAll(dir)
  396. defer be.Close()
  397. testMinTTL := int64(1)
  398. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: testMinTTL})
  399. defer le.Stop()
  400. le.Promote(1 * time.Second)
  401. l, err := le.Grant(1, testMinTTL)
  402. if err != nil {
  403. t.Fatalf("failed to create lease: %v", err)
  404. }
  405. select {
  406. case el := <-le.ExpiredLeasesC():
  407. if el[0].ID != l.ID {
  408. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  409. }
  410. case <-time.After(10 * time.Second):
  411. t.Fatalf("failed to receive expired lease")
  412. }
  413. donec := make(chan struct{})
  414. go func() {
  415. // expired lease cannot be renewed
  416. if _, err := le.Renew(l.ID); err != ErrNotPrimary {
  417. t.Errorf("unexpected renew: %v", err)
  418. }
  419. donec <- struct{}{}
  420. }()
  421. select {
  422. case <-donec:
  423. t.Fatalf("renew finished before demotion")
  424. case <-time.After(50 * time.Millisecond):
  425. }
  426. // demote will cause the renew request to fail with ErrNotPrimary
  427. le.Demote()
  428. select {
  429. case <-donec:
  430. case <-time.After(10 * time.Second):
  431. t.Fatalf("renew has not returned after lessor demotion")
  432. }
  433. }
  434. func TestLessorMaxTTL(t *testing.T) {
  435. lg := zap.NewNop()
  436. dir, be := NewTestBackend(t)
  437. defer os.RemoveAll(dir)
  438. defer be.Close()
  439. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  440. defer le.Stop()
  441. _, err := le.Grant(1, MaxLeaseTTL+1)
  442. if err != ErrLeaseTTLTooLarge {
  443. t.Fatalf("grant unexpectedly succeeded")
  444. }
  445. }
  446. func TestLessorCheckpointScheduling(t *testing.T) {
  447. lg := zap.NewNop()
  448. dir, be := NewTestBackend(t)
  449. defer os.RemoveAll(dir)
  450. defer be.Close()
  451. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL, CheckpointInterval: 1 * time.Second})
  452. le.minLeaseTTL = 1
  453. checkpointedC := make(chan struct{})
  454. le.SetCheckpointer(func(ctx context.Context, lc *pb.LeaseCheckpointRequest) {
  455. close(checkpointedC)
  456. if len(lc.Checkpoints) != 1 {
  457. t.Errorf("expected 1 checkpoint but got %d", len(lc.Checkpoints))
  458. }
  459. c := lc.Checkpoints[0]
  460. if c.Remaining_TTL != 1 {
  461. t.Errorf("expected checkpoint to be called with Remaining_TTL=%d but got %d", 1, c.Remaining_TTL)
  462. }
  463. })
  464. defer le.Stop()
  465. le.Promote(0)
  466. _, err := le.Grant(1, 2)
  467. if err != nil {
  468. t.Fatal(err)
  469. }
  470. // TODO: Is there any way to avoid doing this wait? Lease TTL granularity is in seconds.
  471. select {
  472. case <-checkpointedC:
  473. case <-time.After(2 * time.Second):
  474. t.Fatal("expected checkpointer to be called, but it was not")
  475. }
  476. }
  477. func TestLessorCheckpointsRestoredOnPromote(t *testing.T) {
  478. lg := zap.NewNop()
  479. dir, be := NewTestBackend(t)
  480. defer os.RemoveAll(dir)
  481. defer be.Close()
  482. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  483. defer le.Stop()
  484. l, err := le.Grant(1, 10)
  485. if err != nil {
  486. t.Fatal(err)
  487. }
  488. le.Checkpoint(l.ID, 5)
  489. le.Promote(0)
  490. remaining := l.Remaining().Seconds()
  491. if !(remaining > 4 && remaining < 5) {
  492. t.Fatalf("expected expiry to be less than 1s in the future, but got %f seconds", remaining)
  493. }
  494. }
  495. type fakeDeleter struct {
  496. deleted []string
  497. tx backend.BatchTx
  498. }
  499. func newFakeDeleter(be backend.Backend) *fakeDeleter {
  500. fd := &fakeDeleter{nil, be.BatchTx()}
  501. fd.tx.Lock()
  502. return fd
  503. }
  504. func (fd *fakeDeleter) End() { fd.tx.Unlock() }
  505. func (fd *fakeDeleter) DeleteRange(key, end []byte) (int64, int64) {
  506. fd.deleted = append(fd.deleted, string(key)+"_"+string(end))
  507. return 0, 0
  508. }
  509. func NewTestBackend(t *testing.T) (string, backend.Backend) {
  510. tmpPath, err := ioutil.TempDir("", "lease")
  511. if err != nil {
  512. t.Fatalf("failed to create tmpdir (%v)", err)
  513. }
  514. bcfg := backend.DefaultBackendConfig()
  515. bcfg.Path = filepath.Join(tmpPath, "be")
  516. return tmpPath, backend.New(bcfg)
  517. }