lessor.go 11 KB

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