lessor.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. // Copyright 2015 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.
  14. package lease
  15. import (
  16. "fmt"
  17. "sync"
  18. "time"
  19. "github.com/coreos/etcd/pkg/idutil"
  20. )
  21. var (
  22. minLeaseTerm = 5 * time.Second
  23. )
  24. // a lessor is the owner of leases. It can grant, revoke,
  25. // renew and modify leases for lessee.
  26. // TODO: persist lease on to stable backend for failure recovery.
  27. // TODO: use clockwork for testability.
  28. type lessor struct {
  29. mu sync.Mutex
  30. // TODO: probably this should be a heap with a secondary
  31. // id index.
  32. // Now it is O(N) to loop over the leases to find expired ones.
  33. // We want to make Grant, Revoke, and FindExpired all O(logN) and
  34. // Renew O(1).
  35. // FindExpired and Renew should be the most frequent operations.
  36. leaseMap map[uint64]*lease
  37. idgen *idutil.Generator
  38. }
  39. func NewLessor(lessorID uint8) *lessor {
  40. return &lessor{
  41. leaseMap: make(map[uint64]*lease),
  42. idgen: idutil.NewGenerator(lessorID, time.Now()),
  43. }
  44. }
  45. // Grant grants a lease that expires at least at the given expiry
  46. // time.
  47. // TODO: when leassor is under highload, it should give out lease
  48. // with longer term to reduce renew load.
  49. func (le *lessor) Grant(expiry time.Time) *lease {
  50. expiry = minExpiry(time.Now(), expiry)
  51. id := le.idgen.Next()
  52. le.mu.Lock()
  53. defer le.mu.Unlock()
  54. l := &lease{id: id, expiry: expiry}
  55. if _, ok := le.leaseMap[id]; ok {
  56. panic("lease: unexpected duplicate ID!")
  57. }
  58. le.leaseMap[id] = l
  59. return l
  60. }
  61. // Revoke revokes a lease with given ID. The item attached to the
  62. // given lease will be removed. If the ID does not exist, an error
  63. // will be returned.
  64. func (le *lessor) Revoke(id uint64) error {
  65. le.mu.Lock()
  66. defer le.mu.Unlock()
  67. l := le.leaseMap[id]
  68. if l == nil {
  69. return fmt.Errorf("lease: cannot find lease %x", id)
  70. }
  71. delete(le.leaseMap, l.id)
  72. // TODO: remove attached items
  73. return nil
  74. }
  75. // Renew renews an existing lease with at least the given expiry.
  76. // If the given lease does not exist or has expired, an error will
  77. // be returned.
  78. func (le *lessor) Renew(id uint64, expiry time.Time) error {
  79. le.mu.Lock()
  80. defer le.mu.Unlock()
  81. l := le.leaseMap[id]
  82. if l == nil {
  83. return fmt.Errorf("lease: cannot find lease %x", id)
  84. }
  85. l.expiry = minExpiry(time.Now(), expiry)
  86. return nil
  87. }
  88. // Attach attaches items to the lease with given ID. When the lease
  89. // expires, the attached items will be automatically removed.
  90. // If the given lease does not exist, an error will be returned.
  91. func (le *lessor) Attach(id uint64, items []leaseItem) error {
  92. le.mu.Lock()
  93. defer le.mu.Unlock()
  94. l := le.leaseMap[id]
  95. if l == nil {
  96. return fmt.Errorf("lease: cannot find lease %x", id)
  97. }
  98. for _, it := range items {
  99. l.itemSet[it] = struct{}{}
  100. }
  101. return nil
  102. }
  103. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  104. // leases that needed to be revoked.
  105. func (le *lessor) findExpiredLeases() []*lease {
  106. le.mu.Lock()
  107. defer le.mu.Unlock()
  108. leases := make([]*lease, 0, 16)
  109. now := time.Now()
  110. for _, l := range le.leaseMap {
  111. if l.expiry.Sub(now) <= 0 {
  112. leases = append(leases, l)
  113. }
  114. }
  115. return leases
  116. }
  117. // get gets the lease with given id.
  118. // get is a helper fucntion for testing, at least for now.
  119. func (le *lessor) get(id uint64) *lease {
  120. le.mu.Lock()
  121. defer le.mu.Unlock()
  122. return le.leaseMap[id]
  123. }
  124. type lease struct {
  125. id uint64
  126. itemSet map[leaseItem]struct{}
  127. // expiry time in unixnano
  128. expiry time.Time
  129. }
  130. type leaseItem struct {
  131. key string
  132. endRange string
  133. }
  134. // minExpiry returns a minimal expiry. A minimal expiry is the larger on
  135. // between now + minLeaseTerm and the given expectedExpiry.
  136. func minExpiry(now time.Time, expectedExpiry time.Time) time.Time {
  137. minExpiry := time.Now().Add(minLeaseTerm)
  138. if expectedExpiry.Sub(minExpiry) < 0 {
  139. expectedExpiry = minExpiry
  140. }
  141. return expectedExpiry
  142. }