lessor.go 17 KB

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