lessor.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. "encoding/binary"
  17. "fmt"
  18. "math"
  19. "sync"
  20. "time"
  21. "github.com/coreos/etcd/lease/leasepb"
  22. "github.com/coreos/etcd/pkg/idutil"
  23. "github.com/coreos/etcd/storage/backend"
  24. )
  25. var (
  26. minLeaseTerm = 5 * time.Second
  27. leaseBucketName = []byte("lease")
  28. )
  29. type LeaseID int64
  30. // DeleteableRange defines an interface with DeleteRange method.
  31. // We define this interface only for lessor to limit the number
  32. // of methods of storage.KV to what lessor actually needs.
  33. //
  34. // Having a minimum interface makes testing easy.
  35. type DeleteableRange interface {
  36. DeleteRange(key, end []byte) (int64, int64)
  37. }
  38. // a lessor is the owner of leases. It can grant, revoke,
  39. // renew and modify leases for lessee.
  40. // TODO: use clockwork for testability.
  41. type lessor struct {
  42. mu sync.Mutex
  43. // TODO: probably this should be a heap with a secondary
  44. // id index.
  45. // Now it is O(N) to loop over the leases to find expired ones.
  46. // We want to make Grant, Revoke, and FindExpired all O(logN) and
  47. // Renew O(1).
  48. // FindExpired and Renew should be the most frequent operations.
  49. leaseMap map[LeaseID]*lease
  50. // A DeleteableRange the lessor operates on.
  51. // When a lease expires, the lessor will delete the
  52. // leased range (or key) from the DeleteableRange.
  53. dr DeleteableRange
  54. // backend to persist leases. We only persist lease ID and expiry for now.
  55. // The leased items can be recovered by iterating all the keys in kv.
  56. b backend.Backend
  57. idgen *idutil.Generator
  58. }
  59. func NewLessor(lessorID uint8, b backend.Backend, dr DeleteableRange) *lessor {
  60. l := &lessor{
  61. leaseMap: make(map[LeaseID]*lease),
  62. b: b,
  63. dr: dr,
  64. idgen: idutil.NewGenerator(lessorID, time.Now()),
  65. }
  66. l.initAndRecover()
  67. return l
  68. }
  69. // Grant grants a lease that expires at least after TTL seconds.
  70. // TODO: when lessor is under high load, it should give out lease
  71. // with longer TTL to reduce renew load.
  72. func (le *lessor) Grant(ttl int64) *lease {
  73. // TODO: define max TTL
  74. expiry := time.Now().Add(time.Duration(ttl) * time.Second)
  75. expiry = minExpiry(time.Now(), expiry)
  76. id := LeaseID(le.idgen.Next())
  77. le.mu.Lock()
  78. defer le.mu.Unlock()
  79. l := &lease{id: id, ttl: ttl, expiry: expiry, itemSet: make(map[leaseItem]struct{})}
  80. if _, ok := le.leaseMap[id]; ok {
  81. panic("lease: unexpected duplicate ID!")
  82. }
  83. le.leaseMap[id] = l
  84. l.persistTo(le.b)
  85. return l
  86. }
  87. // Revoke revokes a lease with given ID. The item attached to the
  88. // given lease will be removed. If the ID does not exist, an error
  89. // will be returned.
  90. func (le *lessor) Revoke(id LeaseID) error {
  91. le.mu.Lock()
  92. defer le.mu.Unlock()
  93. l := le.leaseMap[id]
  94. if l == nil {
  95. return fmt.Errorf("lease: cannot find lease %x", id)
  96. }
  97. for item := range l.itemSet {
  98. le.dr.DeleteRange([]byte(item.key), nil)
  99. }
  100. delete(le.leaseMap, l.id)
  101. l.removeFrom(le.b)
  102. return nil
  103. }
  104. // Renew renews an existing lease. If the given lease does not exist or
  105. // has expired, an error will be returned.
  106. // TODO: return new TTL?
  107. func (le *lessor) Renew(id LeaseID) error {
  108. le.mu.Lock()
  109. defer le.mu.Unlock()
  110. l := le.leaseMap[id]
  111. if l == nil {
  112. return fmt.Errorf("lease: cannot find lease %x", id)
  113. }
  114. expiry := time.Now().Add(time.Duration(l.ttl) * time.Second)
  115. l.expiry = minExpiry(time.Now(), expiry)
  116. return nil
  117. }
  118. // Attach attaches items to the lease with given ID. When the lease
  119. // expires, the attached items will be automatically removed.
  120. // If the given lease does not exist, an error will be returned.
  121. func (le *lessor) Attach(id LeaseID, items []leaseItem) error {
  122. le.mu.Lock()
  123. defer le.mu.Unlock()
  124. l := le.leaseMap[id]
  125. if l == nil {
  126. return fmt.Errorf("lease: cannot find lease %x", id)
  127. }
  128. for _, it := range items {
  129. l.itemSet[it] = struct{}{}
  130. }
  131. return nil
  132. }
  133. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  134. // leases that needed to be revoked.
  135. func (le *lessor) findExpiredLeases() []*lease {
  136. le.mu.Lock()
  137. defer le.mu.Unlock()
  138. leases := make([]*lease, 0, 16)
  139. now := time.Now()
  140. for _, l := range le.leaseMap {
  141. if l.expiry.Sub(now) <= 0 {
  142. leases = append(leases, l)
  143. }
  144. }
  145. return leases
  146. }
  147. // get gets the lease with given id.
  148. // get is a helper fucntion for testing, at least for now.
  149. func (le *lessor) get(id LeaseID) *lease {
  150. le.mu.Lock()
  151. defer le.mu.Unlock()
  152. return le.leaseMap[id]
  153. }
  154. func (le *lessor) initAndRecover() {
  155. tx := le.b.BatchTx()
  156. tx.Lock()
  157. defer tx.Unlock()
  158. tx.UnsafeCreateBucket(leaseBucketName)
  159. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  160. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  161. for i := range vs {
  162. var lpb leasepb.Lease
  163. err := lpb.Unmarshal(vs[i])
  164. if err != nil {
  165. panic("failed to unmarshal lease proto item")
  166. }
  167. id := LeaseID(lpb.ID)
  168. le.leaseMap[id] = &lease{
  169. id: id,
  170. ttl: lpb.TTL,
  171. // itemSet will be filled in when recover key-value pairs
  172. expiry: minExpiry(time.Now(), time.Now().Add(time.Second*time.Duration(lpb.TTL))),
  173. }
  174. }
  175. le.b.ForceCommit()
  176. }
  177. type lease struct {
  178. id LeaseID
  179. ttl int64 // time to live in seconds
  180. itemSet map[leaseItem]struct{}
  181. // expiry time in unixnano
  182. expiry time.Time
  183. }
  184. func (l lease) persistTo(b backend.Backend) {
  185. key := int64ToBytes(int64(l.id))
  186. lpb := leasepb.Lease{ID: int64(l.id), TTL: int64(l.ttl)}
  187. val, err := lpb.Marshal()
  188. if err != nil {
  189. panic("failed to marshal lease proto item")
  190. }
  191. b.BatchTx().Lock()
  192. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  193. b.BatchTx().Unlock()
  194. }
  195. func (l lease) removeFrom(b backend.Backend) {
  196. key := int64ToBytes(int64(l.id))
  197. b.BatchTx().Lock()
  198. b.BatchTx().UnsafeDelete(leaseBucketName, key)
  199. b.BatchTx().Unlock()
  200. }
  201. type leaseItem struct {
  202. key string
  203. }
  204. // minExpiry returns a minimal expiry. A minimal expiry is the larger on
  205. // between now + minLeaseTerm and the given expectedExpiry.
  206. func minExpiry(now time.Time, expectedExpiry time.Time) time.Time {
  207. minExpiry := time.Now().Add(minLeaseTerm)
  208. if expectedExpiry.Sub(minExpiry) < 0 {
  209. expectedExpiry = minExpiry
  210. }
  211. return expectedExpiry
  212. }
  213. func int64ToBytes(n int64) []byte {
  214. bytes := make([]byte, 8)
  215. binary.BigEndian.PutUint64(bytes, uint64(n))
  216. return bytes
  217. }