lessor.go 17 KB

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