lessor_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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. // TestLessorRenewExtendPileup ensures Lessor extends leases on promotion if too many
  205. // expire at the same time.
  206. func TestLessorRenewExtendPileup(t *testing.T) {
  207. oldRevokeRate := leaseRevokeRate
  208. defer func() { leaseRevokeRate = oldRevokeRate }()
  209. lg := zap.NewNop()
  210. leaseRevokeRate = 10
  211. dir, be := NewTestBackend(t)
  212. defer os.RemoveAll(dir)
  213. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  214. ttl := int64(10)
  215. for i := 1; i <= leaseRevokeRate*10; i++ {
  216. if _, err := le.Grant(LeaseID(2*i), ttl); err != nil {
  217. t.Fatal(err)
  218. }
  219. // ttls that overlap spillover for ttl=10
  220. if _, err := le.Grant(LeaseID(2*i+1), ttl+1); err != nil {
  221. t.Fatal(err)
  222. }
  223. }
  224. // simulate stop and recovery
  225. le.Stop()
  226. be.Close()
  227. bcfg := backend.DefaultBackendConfig()
  228. bcfg.Path = filepath.Join(dir, "be")
  229. be = backend.New(bcfg)
  230. defer be.Close()
  231. le = newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  232. defer le.Stop()
  233. // extend after recovery should extend expiration on lease pile-up
  234. le.Promote(0)
  235. windowCounts := make(map[int64]int)
  236. for _, l := range le.leaseMap {
  237. // round up slightly for baseline ttl
  238. s := int64(l.Remaining().Seconds() + 0.1)
  239. windowCounts[s]++
  240. }
  241. for i := ttl; i < ttl+20; i++ {
  242. c := windowCounts[i]
  243. if c > leaseRevokeRate {
  244. t.Errorf("expected at most %d expiring at %ds, got %d", leaseRevokeRate, i, c)
  245. }
  246. if c < leaseRevokeRate/2 {
  247. t.Errorf("expected at least %d expiring at %ds, got %d", leaseRevokeRate/2, i, c)
  248. }
  249. }
  250. }
  251. func TestLessorDetach(t *testing.T) {
  252. lg := zap.NewNop()
  253. dir, be := NewTestBackend(t)
  254. defer os.RemoveAll(dir)
  255. defer be.Close()
  256. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  257. defer le.Stop()
  258. le.SetRangeDeleter(func() TxnDelete { return newFakeDeleter(be) })
  259. // grant a lease with long term (100 seconds) to
  260. // avoid early termination during the test.
  261. l, err := le.Grant(1, 100)
  262. if err != nil {
  263. t.Fatalf("could not grant lease for 100s ttl (%v)", err)
  264. }
  265. items := []LeaseItem{
  266. {"foo"},
  267. {"bar"},
  268. }
  269. if err := le.Attach(l.ID, items); err != nil {
  270. t.Fatalf("failed to attach items to the lease: %v", err)
  271. }
  272. if err := le.Detach(l.ID, items[0:1]); err != nil {
  273. t.Fatalf("failed to de-attach items to the lease: %v", err)
  274. }
  275. l = le.Lookup(l.ID)
  276. if len(l.itemSet) != 1 {
  277. t.Fatalf("len(l.itemSet) = %d, failed to de-attach items", len(l.itemSet))
  278. }
  279. if _, ok := l.itemSet[LeaseItem{"bar"}]; !ok {
  280. t.Fatalf("de-attached wrong item, want %q exists", "bar")
  281. }
  282. }
  283. // TestLessorRecover ensures Lessor recovers leases from
  284. // persist backend.
  285. func TestLessorRecover(t *testing.T) {
  286. lg := zap.NewNop()
  287. dir, be := NewTestBackend(t)
  288. defer os.RemoveAll(dir)
  289. defer be.Close()
  290. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  291. defer le.Stop()
  292. l1, err1 := le.Grant(1, 10)
  293. l2, err2 := le.Grant(2, 20)
  294. if err1 != nil || err2 != nil {
  295. t.Fatalf("could not grant initial leases (%v, %v)", err1, err2)
  296. }
  297. // Create a new lessor with the same backend
  298. nle := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  299. defer nle.Stop()
  300. nl1 := nle.Lookup(l1.ID)
  301. if nl1 == nil || nl1.ttl != l1.ttl {
  302. t.Errorf("nl1 = %v, want nl1.ttl= %d", nl1.ttl, l1.ttl)
  303. }
  304. nl2 := nle.Lookup(l2.ID)
  305. if nl2 == nil || nl2.ttl != l2.ttl {
  306. t.Errorf("nl2 = %v, want nl2.ttl= %d", nl2.ttl, l2.ttl)
  307. }
  308. }
  309. func TestLessorExpire(t *testing.T) {
  310. lg := zap.NewNop()
  311. dir, be := NewTestBackend(t)
  312. defer os.RemoveAll(dir)
  313. defer be.Close()
  314. testMinTTL := int64(1)
  315. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: testMinTTL})
  316. defer le.Stop()
  317. le.Promote(1 * time.Second)
  318. l, err := le.Grant(1, testMinTTL)
  319. if err != nil {
  320. t.Fatalf("failed to create lease: %v", err)
  321. }
  322. select {
  323. case el := <-le.ExpiredLeasesC():
  324. if el[0].ID != l.ID {
  325. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  326. }
  327. case <-time.After(10 * time.Second):
  328. t.Fatalf("failed to receive expired lease")
  329. }
  330. donec := make(chan struct{})
  331. go func() {
  332. // expired lease cannot be renewed
  333. if _, err := le.Renew(l.ID); err != ErrLeaseNotFound {
  334. t.Fatalf("unexpected renew")
  335. }
  336. donec <- struct{}{}
  337. }()
  338. select {
  339. case <-donec:
  340. t.Fatalf("renew finished before lease revocation")
  341. case <-time.After(50 * time.Millisecond):
  342. }
  343. // expired lease can be revoked
  344. if err := le.Revoke(l.ID); err != nil {
  345. t.Fatalf("failed to revoke expired lease: %v", err)
  346. }
  347. select {
  348. case <-donec:
  349. case <-time.After(10 * time.Second):
  350. t.Fatalf("renew has not returned after lease revocation")
  351. }
  352. }
  353. func TestLessorExpireAndDemote(t *testing.T) {
  354. lg := zap.NewNop()
  355. dir, be := NewTestBackend(t)
  356. defer os.RemoveAll(dir)
  357. defer be.Close()
  358. testMinTTL := int64(1)
  359. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: testMinTTL})
  360. defer le.Stop()
  361. le.Promote(1 * time.Second)
  362. l, err := le.Grant(1, testMinTTL)
  363. if err != nil {
  364. t.Fatalf("failed to create lease: %v", err)
  365. }
  366. select {
  367. case el := <-le.ExpiredLeasesC():
  368. if el[0].ID != l.ID {
  369. t.Fatalf("expired id = %x, want %x", el[0].ID, l.ID)
  370. }
  371. case <-time.After(10 * time.Second):
  372. t.Fatalf("failed to receive expired lease")
  373. }
  374. donec := make(chan struct{})
  375. go func() {
  376. // expired lease cannot be renewed
  377. if _, err := le.Renew(l.ID); err != ErrNotPrimary {
  378. t.Fatalf("unexpected renew: %v", err)
  379. }
  380. donec <- struct{}{}
  381. }()
  382. select {
  383. case <-donec:
  384. t.Fatalf("renew finished before demotion")
  385. case <-time.After(50 * time.Millisecond):
  386. }
  387. // demote will cause the renew request to fail with ErrNotPrimary
  388. le.Demote()
  389. select {
  390. case <-donec:
  391. case <-time.After(10 * time.Second):
  392. t.Fatalf("renew has not returned after lessor demotion")
  393. }
  394. }
  395. func TestLessorMaxTTL(t *testing.T) {
  396. lg := zap.NewNop()
  397. dir, be := NewTestBackend(t)
  398. defer os.RemoveAll(dir)
  399. defer be.Close()
  400. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  401. defer le.Stop()
  402. _, err := le.Grant(1, MaxLeaseTTL+1)
  403. if err != ErrLeaseTTLTooLarge {
  404. t.Fatalf("grant unexpectedly succeeded")
  405. }
  406. }
  407. func TestLessorCheckpointScheduling(t *testing.T) {
  408. lg := zap.NewNop()
  409. dir, be := NewTestBackend(t)
  410. defer os.RemoveAll(dir)
  411. defer be.Close()
  412. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL, CheckpointInterval: 1 * time.Second})
  413. le.minLeaseTTL = 1
  414. checkpointedC := make(chan struct{})
  415. le.SetCheckpointer(func(ctx context.Context, lc *pb.LeaseCheckpointRequest) {
  416. close(checkpointedC)
  417. if len(lc.Checkpoints) != 1 {
  418. t.Errorf("expected 1 checkpoint but got %d", len(lc.Checkpoints))
  419. }
  420. c := lc.Checkpoints[0]
  421. if c.Remaining_TTL != 1 {
  422. t.Errorf("expected checkpoint to be called with Remaining_TTL=%d but got %d", 1, c.Remaining_TTL)
  423. }
  424. })
  425. defer le.Stop()
  426. le.Promote(0)
  427. _, err := le.Grant(1, 2)
  428. if err != nil {
  429. t.Fatal(err)
  430. }
  431. // TODO: Is there any way to avoid doing this wait? Lease TTL granularity is in seconds.
  432. select {
  433. case <-checkpointedC:
  434. case <-time.After(2 * time.Second):
  435. t.Fatal("expected checkpointer to be called, but it was not")
  436. }
  437. }
  438. func TestLessorCheckpointsRestoredOnPromote(t *testing.T) {
  439. lg := zap.NewNop()
  440. dir, be := NewTestBackend(t)
  441. defer os.RemoveAll(dir)
  442. defer be.Close()
  443. le := newLessor(lg, be, LessorConfig{MinLeaseTTL: minLeaseTTL})
  444. defer le.Stop()
  445. l, err := le.Grant(1, 10)
  446. if err != nil {
  447. t.Fatal(err)
  448. }
  449. le.Checkpoint(l.ID, 5)
  450. le.Promote(0)
  451. remaining := l.Remaining().Seconds()
  452. if !(remaining > 4 && remaining < 5) {
  453. t.Fatalf("expected expiry to be less than 1s in the future, but got %f seconds", remaining)
  454. }
  455. }
  456. type fakeDeleter struct {
  457. deleted []string
  458. tx backend.BatchTx
  459. }
  460. func newFakeDeleter(be backend.Backend) *fakeDeleter {
  461. fd := &fakeDeleter{nil, be.BatchTx()}
  462. fd.tx.Lock()
  463. return fd
  464. }
  465. func (fd *fakeDeleter) End() { fd.tx.Unlock() }
  466. func (fd *fakeDeleter) DeleteRange(key, end []byte) (int64, int64) {
  467. fd.deleted = append(fd.deleted, string(key)+"_"+string(end))
  468. return 0, 0
  469. }
  470. func NewTestBackend(t *testing.T) (string, backend.Backend) {
  471. tmpPath, err := ioutil.TempDir("", "lease")
  472. if err != nil {
  473. t.Fatalf("failed to create tmpdir (%v)", err)
  474. }
  475. bcfg := backend.DefaultBackendConfig()
  476. bcfg.Path = filepath.Join(tmpPath, "be")
  477. return tmpPath, backend.New(bcfg)
  478. }