lessor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. "errors"
  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. const (
  26. // NoLease is a special LeaseID representing the absence of a lease.
  27. NoLease = LeaseID(0)
  28. )
  29. var (
  30. minLeaseTTL = int64(5)
  31. leaseBucketName = []byte("lease")
  32. // do not use maxInt64 since it can overflow time which will add
  33. // the offset of unix time (1970yr to seconds).
  34. forever = time.Unix(math.MaxInt64>>1, 0)
  35. ErrNotPrimary = errors.New("not a primary lessor")
  36. ErrLeaseNotFound = errors.New("lease not found")
  37. )
  38. type LeaseID int64
  39. // RangeDeleter defines an interface with DeleteRange method.
  40. // We define this interface only for lessor to limit the number
  41. // of methods of storage.KV to what lessor actually needs.
  42. //
  43. // Having a minimum interface makes testing easy.
  44. type RangeDeleter interface {
  45. DeleteRange(key, end []byte) (int64, int64)
  46. }
  47. // A Lessor is the owner of leases. It can grant, revoke, renew and modify leases for lessee.
  48. type Lessor interface {
  49. // SetDeleteableRange sets the RangeDeleter to the Lessor.
  50. // Lessor deletes the items in the revoked or expired lease from the
  51. // the set RangeDeleter.
  52. SetRangeDeleter(dr RangeDeleter)
  53. // Grant grants a lease that expires at least after TTL seconds.
  54. Grant(ttl int64) *Lease
  55. // Revoke revokes a lease with given ID. The item attached to the
  56. // given lease will be removed. If the ID does not exist, an error
  57. // will be returned.
  58. Revoke(id LeaseID) error
  59. // Attach attaches given leaseItem to the lease with given LeaseID.
  60. // If the lease does not exist, an error will be returned.
  61. Attach(id LeaseID, items []LeaseItem) error
  62. // Promote promotes the lessor to be the primary lessor. Primary lessor manages
  63. // the expiration and renew of leases.
  64. Promote()
  65. // Demote demotes the lessor from being the primary lessor.
  66. Demote()
  67. // Renew renews a lease with given ID. It returns the renewed TTL. If the ID does not exist,
  68. // an error will be returned.
  69. Renew(id LeaseID) (int64, error)
  70. // ExpiredLeasesC returns a chan that is used to receive expired leases.
  71. ExpiredLeasesC() <-chan []*Lease
  72. // Stop stops the lessor for managing leases. The behavior of calling Stop multiple
  73. // times is undefined.
  74. Stop()
  75. }
  76. // lessor implements Lessor interface.
  77. // TODO: use clockwork for testability.
  78. type lessor struct {
  79. mu sync.Mutex
  80. // primary indicates if this lessor is the primary lessor. The primary
  81. // lessor manages lease expiration and renew.
  82. //
  83. // in etcd, raft leader is the primary. Thus there might be two primary
  84. // leaders at the same time (raft allows concurrent leader but with different term)
  85. // for at most a leader election timeout.
  86. // The old primary leader cannot affect the correctness since its proposal has a
  87. // smaller term and will not be committed.
  88. //
  89. // TODO: raft follower do not forward lease management proposals. There might be a
  90. // very small window (within second normally which depends on go scheduling) that
  91. // a raft follow is the primary between the raft leader demotion and lessor demotion.
  92. // Usually this should not be a problem. Lease should not be that sensitive to timing.
  93. primary bool
  94. // TODO: probably this should be a heap with a secondary
  95. // id index.
  96. // Now it is O(N) to loop over the leases to find expired ones.
  97. // We want to make Grant, Revoke, and FindExpired all O(logN) and
  98. // Renew O(1).
  99. // FindExpired and Renew should be the most frequent operations.
  100. leaseMap map[LeaseID]*Lease
  101. // When a lease expires, the lessor will delete the
  102. // leased range (or key) by the RangeDeleter.
  103. rd RangeDeleter
  104. // backend to persist leases. We only persist lease ID and expiry for now.
  105. // The leased items can be recovered by iterating all the keys in kv.
  106. b backend.Backend
  107. expiredC chan []*Lease
  108. // stopC is a channel whose closure indicates that the lessor should be stopped.
  109. stopC chan struct{}
  110. // doneC is a channel whose closure indicates that the lessor is stopped.
  111. doneC chan struct{}
  112. idgen *idutil.Generator
  113. }
  114. func NewLessor(lessorID uint8, b backend.Backend) Lessor {
  115. return newLessor(lessorID, b)
  116. }
  117. func newLessor(lessorID uint8, b backend.Backend) *lessor {
  118. // ensure the most significant bit of lessorID is 0.
  119. // so all the IDs generated by id generator will be greater than 0.
  120. if int8(lessorID) < 0 {
  121. lessorID = uint8(-int8(lessorID))
  122. }
  123. l := &lessor{
  124. leaseMap: make(map[LeaseID]*Lease),
  125. b: b,
  126. // expiredC is a small buffered chan to avoid unnecessary blocking.
  127. expiredC: make(chan []*Lease, 16),
  128. stopC: make(chan struct{}),
  129. doneC: make(chan struct{}),
  130. idgen: idutil.NewGenerator(lessorID, time.Now()),
  131. }
  132. l.initAndRecover()
  133. go l.runLoop()
  134. return l
  135. }
  136. func (le *lessor) SetRangeDeleter(rd RangeDeleter) {
  137. le.mu.Lock()
  138. defer le.mu.Unlock()
  139. le.rd = rd
  140. }
  141. // TODO: when lessor is under high load, it should give out lease
  142. // with longer TTL to reduce renew load.
  143. func (le *lessor) Grant(ttl int64) *Lease {
  144. id := LeaseID(le.idgen.Next())
  145. le.mu.Lock()
  146. defer le.mu.Unlock()
  147. l := &Lease{ID: id, TTL: ttl, itemSet: make(map[LeaseItem]struct{})}
  148. if le.primary {
  149. l.refresh()
  150. } else {
  151. l.forever()
  152. }
  153. if _, ok := le.leaseMap[id]; ok {
  154. panic("lease: unexpected duplicate ID!")
  155. }
  156. le.leaseMap[id] = l
  157. l.persistTo(le.b)
  158. return l
  159. }
  160. func (le *lessor) Revoke(id LeaseID) error {
  161. le.mu.Lock()
  162. defer le.mu.Unlock()
  163. l := le.leaseMap[id]
  164. if l == nil {
  165. return ErrLeaseNotFound
  166. }
  167. if le.rd != nil {
  168. for item := range l.itemSet {
  169. le.rd.DeleteRange([]byte(item.Key), nil)
  170. }
  171. }
  172. delete(le.leaseMap, l.ID)
  173. l.removeFrom(le.b)
  174. return nil
  175. }
  176. // Renew renews an existing lease. If the given lease does not exist or
  177. // has expired, an error will be returned.
  178. func (le *lessor) Renew(id LeaseID) (int64, error) {
  179. le.mu.Lock()
  180. defer le.mu.Unlock()
  181. if !le.primary {
  182. // forward renew request to primary instead of returning error.
  183. return -1, ErrNotPrimary
  184. }
  185. l := le.leaseMap[id]
  186. if l == nil {
  187. return -1, ErrLeaseNotFound
  188. }
  189. l.refresh()
  190. return l.TTL, nil
  191. }
  192. func (le *lessor) Promote() {
  193. le.mu.Lock()
  194. defer le.mu.Unlock()
  195. le.primary = true
  196. // refresh the expiries of all leases.
  197. for _, l := range le.leaseMap {
  198. l.refresh()
  199. }
  200. }
  201. func (le *lessor) Demote() {
  202. le.mu.Lock()
  203. defer le.mu.Unlock()
  204. // set the expiries of all leases to forever
  205. for _, l := range le.leaseMap {
  206. l.forever()
  207. }
  208. le.primary = false
  209. }
  210. // Attach attaches items to the lease with given ID. When the lease
  211. // expires, the attached items will be automatically removed.
  212. // If the given lease does not exist, an error will be returned.
  213. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  214. le.mu.Lock()
  215. defer le.mu.Unlock()
  216. l := le.leaseMap[id]
  217. if l == nil {
  218. return ErrLeaseNotFound
  219. }
  220. for _, it := range items {
  221. l.itemSet[it] = struct{}{}
  222. }
  223. return nil
  224. }
  225. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  226. le.mu.Lock()
  227. defer le.mu.Unlock()
  228. le.b = b
  229. le.rd = rd
  230. le.leaseMap = make(map[LeaseID]*Lease)
  231. le.initAndRecover()
  232. }
  233. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  234. return le.expiredC
  235. }
  236. func (le *lessor) Stop() {
  237. close(le.stopC)
  238. <-le.doneC
  239. }
  240. func (le *lessor) runLoop() {
  241. defer close(le.doneC)
  242. for {
  243. var ls []*Lease
  244. le.mu.Lock()
  245. if le.primary {
  246. ls = le.findExpiredLeases()
  247. }
  248. le.mu.Unlock()
  249. if len(ls) != 0 {
  250. select {
  251. case <-le.stopC:
  252. return
  253. case le.expiredC <- ls:
  254. default:
  255. // the receiver of expiredC is probably busy handling
  256. // other stuff
  257. // let's try this next time after 500ms
  258. }
  259. }
  260. select {
  261. case <-time.After(500 * time.Millisecond):
  262. case <-le.stopC:
  263. return
  264. }
  265. }
  266. }
  267. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  268. // leases that needed to be revoked.
  269. func (le *lessor) findExpiredLeases() []*Lease {
  270. leases := make([]*Lease, 0, 16)
  271. now := time.Now()
  272. for _, l := range le.leaseMap {
  273. // TODO: probably should change to <= 100-500 millisecond to
  274. // make up committing latency.
  275. if l.expiry.Sub(now) <= 0 {
  276. leases = append(leases, l)
  277. }
  278. }
  279. return leases
  280. }
  281. // get gets the lease with given id.
  282. // get is a helper fucntion for testing, at least for now.
  283. func (le *lessor) get(id LeaseID) *Lease {
  284. le.mu.Lock()
  285. defer le.mu.Unlock()
  286. return le.leaseMap[id]
  287. }
  288. func (le *lessor) initAndRecover() {
  289. tx := le.b.BatchTx()
  290. tx.Lock()
  291. tx.UnsafeCreateBucket(leaseBucketName)
  292. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  293. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  294. for i := range vs {
  295. var lpb leasepb.Lease
  296. err := lpb.Unmarshal(vs[i])
  297. if err != nil {
  298. tx.Unlock()
  299. panic("failed to unmarshal lease proto item")
  300. }
  301. ID := LeaseID(lpb.ID)
  302. le.leaseMap[ID] = &Lease{
  303. ID: ID,
  304. TTL: lpb.TTL,
  305. // itemSet will be filled in when recover key-value pairs
  306. // set expiry to forever, refresh when promoted
  307. expiry: forever,
  308. }
  309. }
  310. tx.Unlock()
  311. le.b.ForceCommit()
  312. }
  313. type Lease struct {
  314. ID LeaseID
  315. TTL int64 // time to live in seconds
  316. itemSet map[LeaseItem]struct{}
  317. // expiry time in unixnano
  318. expiry time.Time
  319. }
  320. func (l Lease) persistTo(b backend.Backend) {
  321. key := int64ToBytes(int64(l.ID))
  322. lpb := leasepb.Lease{ID: int64(l.ID), TTL: int64(l.TTL)}
  323. val, err := lpb.Marshal()
  324. if err != nil {
  325. panic("failed to marshal lease proto item")
  326. }
  327. b.BatchTx().Lock()
  328. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  329. b.BatchTx().Unlock()
  330. }
  331. func (l Lease) removeFrom(b backend.Backend) {
  332. key := int64ToBytes(int64(l.ID))
  333. b.BatchTx().Lock()
  334. b.BatchTx().UnsafeDelete(leaseBucketName, key)
  335. b.BatchTx().Unlock()
  336. }
  337. // refresh refreshes the expiry of the lease. It extends the expiry at least
  338. // minLeaseTTL second.
  339. func (l *Lease) refresh() {
  340. ttl := l.TTL
  341. if l.TTL < minLeaseTTL {
  342. ttl = minLeaseTTL
  343. }
  344. l.expiry = time.Now().Add(time.Second * time.Duration(ttl))
  345. }
  346. // forever sets the expiry of lease to be forever.
  347. func (l *Lease) forever() {
  348. l.expiry = forever
  349. }
  350. type LeaseItem struct {
  351. Key string
  352. }
  353. func int64ToBytes(n int64) []byte {
  354. bytes := make([]byte, 8)
  355. binary.BigEndian.PutUint64(bytes, uint64(n))
  356. return bytes
  357. }
  358. // FakeLessor is a fake implementation of Lessor interface.
  359. // Used for testing only.
  360. type FakeLessor struct {
  361. }
  362. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  363. func (fl *FakeLessor) Grant(ttl int64) *Lease { return nil }
  364. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  365. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  366. func (fl *FakeLessor) Promote() {}
  367. func (fl *FakeLessor) Demote() {}
  368. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  369. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  370. func (fl *FakeLessor) Stop() {}