lessor.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  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. "encoding/binary"
  17. "errors"
  18. "math"
  19. "sort"
  20. "sync"
  21. "time"
  22. "github.com/coreos/etcd/lease/leasepb"
  23. "github.com/coreos/etcd/mvcc/backend"
  24. )
  25. // NoLease is a special LeaseID representing the absence of a lease.
  26. const NoLease = LeaseID(0)
  27. // MaxLeaseTTL is the maximum lease TTL value
  28. const MaxLeaseTTL = 9000000000
  29. var (
  30. forever = time.Time{}
  31. leaseBucketName = []byte("lease")
  32. // maximum number of leases to revoke per second; configurable for tests
  33. leaseRevokeRate = 1000
  34. ErrNotPrimary = errors.New("not a primary lessor")
  35. ErrLeaseNotFound = errors.New("lease not found")
  36. ErrLeaseExists = errors.New("lease already exists")
  37. ErrLeaseTTLTooLarge = errors.New("too large lease TTL")
  38. )
  39. // TxnDelete is a TxnWrite that only permits deletes. Defined here
  40. // to avoid circular dependency with mvcc.
  41. type TxnDelete interface {
  42. DeleteRange(key, end []byte) (n, rev int64)
  43. End()
  44. }
  45. // RangeDeleter is a TxnDelete constructor.
  46. type RangeDeleter func() TxnDelete
  47. type LeaseID int64
  48. // Lessor owns leases. It can grant, revoke, renew and modify leases for lessee.
  49. type Lessor interface {
  50. // SetRangeDeleter lets the lessor create TxnDeletes to the store.
  51. // Lessor deletes the items in the revoked or expired lease by creating
  52. // new TxnDeletes.
  53. SetRangeDeleter(rd RangeDeleter)
  54. // Grant grants a lease that expires at least after TTL seconds.
  55. Grant(id LeaseID, ttl int64) (*Lease, error)
  56. // Revoke revokes a lease with given ID. The item attached to the
  57. // given lease will be removed. If the ID does not exist, an error
  58. // will be returned.
  59. Revoke(id LeaseID) error
  60. // Attach attaches given leaseItem to the lease with given LeaseID.
  61. // If the lease does not exist, an error will be returned.
  62. Attach(id LeaseID, items []LeaseItem) error
  63. // GetLease returns LeaseID for given item.
  64. // If no lease found, NoLease value will be returned.
  65. GetLease(item LeaseItem) LeaseID
  66. // Detach detaches given leaseItem from the lease with given LeaseID.
  67. // If the lease does not exist, an error will be returned.
  68. Detach(id LeaseID, items []LeaseItem) error
  69. // Promote promotes the lessor to be the primary lessor. Primary lessor manages
  70. // the expiration and renew of leases.
  71. // Newly promoted lessor renew the TTL of all lease to extend + previous TTL.
  72. Promote(extend time.Duration)
  73. // Demote demotes the lessor from being the primary lessor.
  74. Demote()
  75. // Renew renews a lease with given ID. It returns the renewed TTL. If the ID does not exist,
  76. // an error will be returned.
  77. Renew(id LeaseID) (int64, error)
  78. // Lookup gives the lease at a given lease id, if any
  79. Lookup(id LeaseID) *Lease
  80. // Leases lists all leases.
  81. Leases() []*Lease
  82. // ExpiredLeasesC returns a chan that is used to receive expired leases.
  83. ExpiredLeasesC() <-chan []*Lease
  84. // Recover recovers the lessor state from the given backend and RangeDeleter.
  85. Recover(b backend.Backend, rd RangeDeleter)
  86. // Stop stops the lessor for managing leases. The behavior of calling Stop multiple
  87. // times is undefined.
  88. Stop()
  89. }
  90. // lessor implements Lessor interface.
  91. // TODO: use clockwork for testability.
  92. type lessor struct {
  93. mu sync.Mutex
  94. // demotec is set when the lessor is the primary.
  95. // demotec will be closed if the lessor is demoted.
  96. demotec chan struct{}
  97. // TODO: probably this should be a heap with a secondary
  98. // id index.
  99. // Now it is O(N) to loop over the leases to find expired ones.
  100. // We want to make Grant, Revoke, and findExpiredLeases all O(logN) and
  101. // Renew O(1).
  102. // findExpiredLeases and Renew should be the most frequent operations.
  103. leaseMap map[LeaseID]*Lease
  104. itemMap map[LeaseItem]LeaseID
  105. // When a lease expires, the lessor will delete the
  106. // leased range (or key) by the RangeDeleter.
  107. rd RangeDeleter
  108. // backend to persist leases. We only persist lease ID and expiry for now.
  109. // The leased items can be recovered by iterating all the keys in kv.
  110. b backend.Backend
  111. // minLeaseTTL is the minimum lease TTL that can be granted for a lease. Any
  112. // requests for shorter TTLs are extended to the minimum TTL.
  113. minLeaseTTL int64
  114. expiredC chan []*Lease
  115. // stopC is a channel whose closure indicates that the lessor should be stopped.
  116. stopC chan struct{}
  117. // doneC is a channel whose closure indicates that the lessor is stopped.
  118. doneC chan struct{}
  119. }
  120. func NewLessor(b backend.Backend, minLeaseTTL int64) Lessor {
  121. return newLessor(b, minLeaseTTL)
  122. }
  123. func newLessor(b backend.Backend, minLeaseTTL int64) *lessor {
  124. l := &lessor{
  125. leaseMap: make(map[LeaseID]*Lease),
  126. itemMap: make(map[LeaseItem]LeaseID),
  127. b: b,
  128. minLeaseTTL: minLeaseTTL,
  129. // expiredC is a small buffered chan to avoid unnecessary blocking.
  130. expiredC: make(chan []*Lease, 16),
  131. stopC: make(chan struct{}),
  132. doneC: make(chan struct{}),
  133. }
  134. l.initAndRecover()
  135. go l.runLoop()
  136. return l
  137. }
  138. // isPrimary indicates if this lessor is the primary lessor. The primary
  139. // lessor manages lease expiration and renew.
  140. //
  141. // in etcd, raft leader is the primary. Thus there might be two primary
  142. // leaders at the same time (raft allows concurrent leader but with different term)
  143. // for at most a leader election timeout.
  144. // The old primary leader cannot affect the correctness since its proposal has a
  145. // smaller term and will not be committed.
  146. //
  147. // TODO: raft follower do not forward lease management proposals. There might be a
  148. // very small window (within second normally which depends on go scheduling) that
  149. // a raft follow is the primary between the raft leader demotion and lessor demotion.
  150. // Usually this should not be a problem. Lease should not be that sensitive to timing.
  151. func (le *lessor) isPrimary() bool {
  152. return le.demotec != nil
  153. }
  154. func (le *lessor) SetRangeDeleter(rd RangeDeleter) {
  155. le.mu.Lock()
  156. defer le.mu.Unlock()
  157. le.rd = rd
  158. }
  159. func (le *lessor) Grant(id LeaseID, ttl int64) (*Lease, error) {
  160. if id == NoLease {
  161. return nil, ErrLeaseNotFound
  162. }
  163. if ttl > MaxLeaseTTL {
  164. return nil, ErrLeaseTTLTooLarge
  165. }
  166. // TODO: when lessor is under high load, it should give out lease
  167. // with longer TTL to reduce renew load.
  168. l := &Lease{
  169. ID: id,
  170. ttl: ttl,
  171. itemSet: make(map[LeaseItem]struct{}),
  172. revokec: make(chan struct{}),
  173. }
  174. le.mu.Lock()
  175. defer le.mu.Unlock()
  176. if _, ok := le.leaseMap[id]; ok {
  177. return nil, ErrLeaseExists
  178. }
  179. if l.ttl < le.minLeaseTTL {
  180. l.ttl = le.minLeaseTTL
  181. }
  182. if le.isPrimary() {
  183. l.refresh(0)
  184. } else {
  185. l.forever()
  186. }
  187. le.leaseMap[id] = l
  188. l.persistTo(le.b)
  189. return l, nil
  190. }
  191. func (le *lessor) Revoke(id LeaseID) error {
  192. le.mu.Lock()
  193. l := le.leaseMap[id]
  194. if l == nil {
  195. le.mu.Unlock()
  196. return ErrLeaseNotFound
  197. }
  198. defer close(l.revokec)
  199. // unlock before doing external work
  200. le.mu.Unlock()
  201. if le.rd == nil {
  202. return nil
  203. }
  204. txn := le.rd()
  205. // sort keys so deletes are in same order among all members,
  206. // otherwise the backened hashes will be different
  207. keys := l.Keys()
  208. sort.StringSlice(keys).Sort()
  209. for _, key := range keys {
  210. txn.DeleteRange([]byte(key), nil)
  211. }
  212. le.mu.Lock()
  213. defer le.mu.Unlock()
  214. delete(le.leaseMap, l.ID)
  215. // lease deletion needs to be in the same backend transaction with the
  216. // kv deletion. Or we might end up with not executing the revoke or not
  217. // deleting the keys if etcdserver fails in between.
  218. le.b.BatchTx().UnsafeDelete(leaseBucketName, int64ToBytes(int64(l.ID)))
  219. txn.End()
  220. return nil
  221. }
  222. // Renew renews an existing lease. If the given lease does not exist or
  223. // has expired, an error will be returned.
  224. func (le *lessor) Renew(id LeaseID) (int64, error) {
  225. le.mu.Lock()
  226. unlock := func() { le.mu.Unlock() }
  227. defer func() { unlock() }()
  228. if !le.isPrimary() {
  229. // forward renew request to primary instead of returning error.
  230. return -1, ErrNotPrimary
  231. }
  232. demotec := le.demotec
  233. l := le.leaseMap[id]
  234. if l == nil {
  235. return -1, ErrLeaseNotFound
  236. }
  237. if l.expired() {
  238. le.mu.Unlock()
  239. unlock = func() {}
  240. select {
  241. // A expired lease might be pending for revoking or going through
  242. // quorum to be revoked. To be accurate, renew request must wait for the
  243. // deletion to complete.
  244. case <-l.revokec:
  245. return -1, ErrLeaseNotFound
  246. // The expired lease might fail to be revoked if the primary changes.
  247. // The caller will retry on ErrNotPrimary.
  248. case <-demotec:
  249. return -1, ErrNotPrimary
  250. case <-le.stopC:
  251. return -1, ErrNotPrimary
  252. }
  253. }
  254. l.refresh(0)
  255. return l.ttl, nil
  256. }
  257. func (le *lessor) Lookup(id LeaseID) *Lease {
  258. le.mu.Lock()
  259. defer le.mu.Unlock()
  260. return le.leaseMap[id]
  261. }
  262. func (le *lessor) unsafeLeases() []*Lease {
  263. leases := make([]*Lease, 0, len(le.leaseMap))
  264. for _, l := range le.leaseMap {
  265. leases = append(leases, l)
  266. }
  267. sort.Sort(leasesByExpiry(leases))
  268. return leases
  269. }
  270. func (le *lessor) Leases() []*Lease {
  271. le.mu.Lock()
  272. ls := le.unsafeLeases()
  273. le.mu.Unlock()
  274. return ls
  275. }
  276. func (le *lessor) Promote(extend time.Duration) {
  277. le.mu.Lock()
  278. defer le.mu.Unlock()
  279. le.demotec = make(chan struct{})
  280. // refresh the expiries of all leases.
  281. for _, l := range le.leaseMap {
  282. l.refresh(extend)
  283. }
  284. if len(le.leaseMap) < leaseRevokeRate {
  285. // no possibility of lease pile-up
  286. return
  287. }
  288. // adjust expiries in case of overlap
  289. leases := le.unsafeLeases()
  290. baseWindow := leases[0].Remaining()
  291. nextWindow := baseWindow + time.Second
  292. expires := 0
  293. // have fewer expires than the total revoke rate so piled up leases
  294. // don't consume the entire revoke limit
  295. targetExpiresPerSecond := (3 * leaseRevokeRate) / 4
  296. for _, l := range leases {
  297. remaining := l.Remaining()
  298. if remaining > nextWindow {
  299. baseWindow = remaining
  300. nextWindow = baseWindow + time.Second
  301. expires = 1
  302. continue
  303. }
  304. expires++
  305. if expires <= targetExpiresPerSecond {
  306. continue
  307. }
  308. rateDelay := float64(time.Second) * (float64(expires) / float64(targetExpiresPerSecond))
  309. // If leases are extended by n seconds, leases n seconds ahead of the
  310. // base window should be extended by only one second.
  311. rateDelay -= float64(remaining - baseWindow)
  312. delay := time.Duration(rateDelay)
  313. nextWindow = baseWindow + delay
  314. l.refresh(delay + extend)
  315. }
  316. }
  317. type leasesByExpiry []*Lease
  318. func (le leasesByExpiry) Len() int { return len(le) }
  319. func (le leasesByExpiry) Less(i, j int) bool { return le[i].Remaining() < le[j].Remaining() }
  320. func (le leasesByExpiry) Swap(i, j int) { le[i], le[j] = le[j], le[i] }
  321. func (le *lessor) Demote() {
  322. le.mu.Lock()
  323. defer le.mu.Unlock()
  324. // set the expiries of all leases to forever
  325. for _, l := range le.leaseMap {
  326. l.forever()
  327. }
  328. if le.demotec != nil {
  329. close(le.demotec)
  330. le.demotec = nil
  331. }
  332. }
  333. // Attach attaches items to the lease with given ID. When the lease
  334. // expires, the attached items will be automatically removed.
  335. // If the given lease does not exist, an error will be returned.
  336. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  337. le.mu.Lock()
  338. defer le.mu.Unlock()
  339. l := le.leaseMap[id]
  340. if l == nil {
  341. return ErrLeaseNotFound
  342. }
  343. l.mu.Lock()
  344. for _, it := range items {
  345. l.itemSet[it] = struct{}{}
  346. le.itemMap[it] = id
  347. }
  348. l.mu.Unlock()
  349. return nil
  350. }
  351. func (le *lessor) GetLease(item LeaseItem) LeaseID {
  352. le.mu.Lock()
  353. id := le.itemMap[item]
  354. le.mu.Unlock()
  355. return id
  356. }
  357. // Detach detaches items from the lease with given ID.
  358. // If the given lease does not exist, an error will be returned.
  359. func (le *lessor) Detach(id LeaseID, items []LeaseItem) error {
  360. le.mu.Lock()
  361. defer le.mu.Unlock()
  362. l := le.leaseMap[id]
  363. if l == nil {
  364. return ErrLeaseNotFound
  365. }
  366. l.mu.Lock()
  367. for _, it := range items {
  368. delete(l.itemSet, it)
  369. delete(le.itemMap, it)
  370. }
  371. l.mu.Unlock()
  372. return nil
  373. }
  374. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  375. le.mu.Lock()
  376. defer le.mu.Unlock()
  377. le.b = b
  378. le.rd = rd
  379. le.leaseMap = make(map[LeaseID]*Lease)
  380. le.itemMap = make(map[LeaseItem]LeaseID)
  381. le.initAndRecover()
  382. }
  383. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  384. return le.expiredC
  385. }
  386. func (le *lessor) Stop() {
  387. close(le.stopC)
  388. <-le.doneC
  389. }
  390. func (le *lessor) runLoop() {
  391. defer close(le.doneC)
  392. for {
  393. var ls []*Lease
  394. // rate limit
  395. revokeLimit := leaseRevokeRate / 2
  396. le.mu.Lock()
  397. if le.isPrimary() {
  398. ls = le.findExpiredLeases(revokeLimit)
  399. }
  400. le.mu.Unlock()
  401. if len(ls) != 0 {
  402. select {
  403. case <-le.stopC:
  404. return
  405. case le.expiredC <- ls:
  406. default:
  407. // the receiver of expiredC is probably busy handling
  408. // other stuff
  409. // let's try this next time after 500ms
  410. }
  411. }
  412. select {
  413. case <-time.After(500 * time.Millisecond):
  414. case <-le.stopC:
  415. return
  416. }
  417. }
  418. }
  419. // findExpiredLeases loops leases in the leaseMap until reaching expired limit
  420. // and returns the expired leases that needed to be revoked.
  421. func (le *lessor) findExpiredLeases(limit int) []*Lease {
  422. leases := make([]*Lease, 0, 16)
  423. for _, l := range le.leaseMap {
  424. // TODO: probably should change to <= 100-500 millisecond to
  425. // make up committing latency.
  426. if l.expired() {
  427. leases = append(leases, l)
  428. // reach expired limit
  429. if len(leases) == limit {
  430. break
  431. }
  432. }
  433. }
  434. return leases
  435. }
  436. func (le *lessor) initAndRecover() {
  437. tx := le.b.BatchTx()
  438. tx.Lock()
  439. tx.UnsafeCreateBucket(leaseBucketName)
  440. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  441. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  442. for i := range vs {
  443. var lpb leasepb.Lease
  444. err := lpb.Unmarshal(vs[i])
  445. if err != nil {
  446. tx.Unlock()
  447. panic("failed to unmarshal lease proto item")
  448. }
  449. ID := LeaseID(lpb.ID)
  450. if lpb.TTL < le.minLeaseTTL {
  451. lpb.TTL = le.minLeaseTTL
  452. }
  453. le.leaseMap[ID] = &Lease{
  454. ID: ID,
  455. ttl: lpb.TTL,
  456. // itemSet will be filled in when recover key-value pairs
  457. // set expiry to forever, refresh when promoted
  458. itemSet: make(map[LeaseItem]struct{}),
  459. expiry: forever,
  460. revokec: make(chan struct{}),
  461. }
  462. }
  463. tx.Unlock()
  464. le.b.ForceCommit()
  465. }
  466. type Lease struct {
  467. ID LeaseID
  468. ttl int64 // time to live in seconds
  469. // expiryMu protects concurrent accesses to expiry
  470. expiryMu sync.RWMutex
  471. // expiry is time when lease should expire. no expiration when expiry.IsZero() is true
  472. expiry time.Time
  473. // mu protects concurrent accesses to itemSet
  474. mu sync.RWMutex
  475. itemSet map[LeaseItem]struct{}
  476. revokec chan struct{}
  477. }
  478. func (l *Lease) expired() bool {
  479. return l.Remaining() <= 0
  480. }
  481. func (l *Lease) persistTo(b backend.Backend) {
  482. key := int64ToBytes(int64(l.ID))
  483. lpb := leasepb.Lease{ID: int64(l.ID), TTL: int64(l.ttl)}
  484. val, err := lpb.Marshal()
  485. if err != nil {
  486. panic("failed to marshal lease proto item")
  487. }
  488. b.BatchTx().Lock()
  489. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  490. b.BatchTx().Unlock()
  491. }
  492. // TTL returns the TTL of the Lease.
  493. func (l *Lease) TTL() int64 {
  494. return l.ttl
  495. }
  496. // refresh refreshes the expiry of the lease.
  497. func (l *Lease) refresh(extend time.Duration) {
  498. newExpiry := time.Now().Add(extend + time.Duration(l.ttl)*time.Second)
  499. l.expiryMu.Lock()
  500. defer l.expiryMu.Unlock()
  501. l.expiry = newExpiry
  502. }
  503. // forever sets the expiry of lease to be forever.
  504. func (l *Lease) forever() {
  505. l.expiryMu.Lock()
  506. defer l.expiryMu.Unlock()
  507. l.expiry = forever
  508. }
  509. // Keys returns all the keys attached to the lease.
  510. func (l *Lease) Keys() []string {
  511. l.mu.RLock()
  512. keys := make([]string, 0, len(l.itemSet))
  513. for k := range l.itemSet {
  514. keys = append(keys, k.Key)
  515. }
  516. l.mu.RUnlock()
  517. return keys
  518. }
  519. // Remaining returns the remaining time of the lease.
  520. func (l *Lease) Remaining() time.Duration {
  521. l.expiryMu.RLock()
  522. defer l.expiryMu.RUnlock()
  523. if l.expiry.IsZero() {
  524. return time.Duration(math.MaxInt64)
  525. }
  526. return time.Until(l.expiry)
  527. }
  528. type LeaseItem struct {
  529. Key string
  530. }
  531. func int64ToBytes(n int64) []byte {
  532. bytes := make([]byte, 8)
  533. binary.BigEndian.PutUint64(bytes, uint64(n))
  534. return bytes
  535. }
  536. // FakeLessor is a fake implementation of Lessor interface.
  537. // Used for testing only.
  538. type FakeLessor struct{}
  539. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  540. func (fl *FakeLessor) Grant(id LeaseID, ttl int64) (*Lease, error) { return nil, nil }
  541. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  542. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  543. func (fl *FakeLessor) GetLease(item LeaseItem) LeaseID { return 0 }
  544. func (fl *FakeLessor) Detach(id LeaseID, items []LeaseItem) error { return nil }
  545. func (fl *FakeLessor) Promote(extend time.Duration) {}
  546. func (fl *FakeLessor) Demote() {}
  547. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  548. func (fl *FakeLessor) Lookup(id LeaseID) *Lease { return nil }
  549. func (fl *FakeLessor) Leases() []*Lease { return nil }
  550. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  551. func (fl *FakeLessor) Recover(b backend.Backend, rd RangeDeleter) {}
  552. func (fl *FakeLessor) Stop() {}