lessor.go 16 KB

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