lessor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  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. "math/rand"
  20. "sort"
  21. "sync"
  22. "sync/atomic"
  23. "time"
  24. "github.com/coreos/etcd/lease/leasepb"
  25. "github.com/coreos/etcd/mvcc/backend"
  26. "github.com/coreos/etcd/pkg/monotime"
  27. )
  28. const (
  29. // NoLease is a special LeaseID representing the absence of a lease.
  30. NoLease = LeaseID(0)
  31. // maximum number of leases to revoke per iteration
  32. // TODO: make this configurable?
  33. leaseRevokeRate = 1000
  34. )
  35. var (
  36. leaseBucketName = []byte("lease")
  37. forever = monotime.Time(math.MaxInt64)
  38. ErrNotPrimary = errors.New("not a primary lessor")
  39. ErrLeaseNotFound = errors.New("lease not found")
  40. ErrLeaseExists = errors.New("lease already exists")
  41. )
  42. // TxnDelete is a TxnWrite that only permits deletes. Defined here
  43. // to avoid circular dependency with mvcc.
  44. type TxnDelete interface {
  45. DeleteRange(key, end []byte) (n, rev int64)
  46. End()
  47. }
  48. // RangeDeleter is a TxnDelete constructor.
  49. type RangeDeleter func() TxnDelete
  50. type LeaseID int64
  51. // Lessor owns leases. It can grant, revoke, renew and modify leases for lessee.
  52. type Lessor interface {
  53. // SetRangeDeleter lets the lessor create TxnDeletes to the store.
  54. // Lessor deletes the items in the revoked or expired lease by creating
  55. // new TxnDeletes.
  56. SetRangeDeleter(rd RangeDeleter)
  57. // Grant grants a lease that expires at least after TTL seconds.
  58. Grant(id LeaseID, ttl int64) (*Lease, error)
  59. // Revoke revokes a lease with given ID. The item attached to the
  60. // given lease will be removed. If the ID does not exist, an error
  61. // will be returned.
  62. Revoke(id LeaseID) error
  63. // Attach attaches given leaseItem to the lease with given LeaseID.
  64. // If the lease does not exist, an error will be returned.
  65. Attach(id LeaseID, items []LeaseItem) error
  66. // GetLease returns LeaseID for given item.
  67. // If no lease found, NoLease value will be returned.
  68. GetLease(item LeaseItem) LeaseID
  69. // Detach detaches given leaseItem from the lease with given LeaseID.
  70. // If the lease does not exist, an error will be returned.
  71. Detach(id LeaseID, items []LeaseItem) error
  72. // Promote promotes the lessor to be the primary lessor. Primary lessor manages
  73. // the expiration and renew of leases.
  74. // Newly promoted lessor renew the TTL of all lease to extend + previous TTL.
  75. Promote(extend time.Duration)
  76. // Demote demotes the lessor from being the primary lessor.
  77. Demote()
  78. // Renew renews a lease with given ID. It returns the renewed TTL. If the ID does not exist,
  79. // an error will be returned.
  80. Renew(id LeaseID) (int64, error)
  81. // Lookup gives the lease at a given lease id, if any
  82. Lookup(id LeaseID) *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) Promote(extend time.Duration) {
  261. le.mu.Lock()
  262. defer le.mu.Unlock()
  263. le.demotec = make(chan struct{})
  264. // refresh the expiries of all leases.
  265. for _, l := range le.leaseMap {
  266. // randomize expiry with 士10%, otherwise leases of same TTL
  267. // will expire all at the same time,
  268. l.refresh(extend + computeRandomDelta(l.ttl))
  269. }
  270. }
  271. func computeRandomDelta(seconds int64) time.Duration {
  272. var delta int64
  273. if seconds > 10 {
  274. delta = int64(float64(seconds) * 0.1 * rand.Float64())
  275. } else {
  276. delta = rand.Int63n(10)
  277. }
  278. return time.Duration(delta) * time.Second
  279. }
  280. func (le *lessor) Demote() {
  281. le.mu.Lock()
  282. defer le.mu.Unlock()
  283. // set the expiries of all leases to forever
  284. for _, l := range le.leaseMap {
  285. l.forever()
  286. }
  287. if le.demotec != nil {
  288. close(le.demotec)
  289. le.demotec = nil
  290. }
  291. }
  292. // Attach attaches items to the lease with given ID. When the lease
  293. // expires, the attached items will be automatically removed.
  294. // If the given lease does not exist, an error will be returned.
  295. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  296. le.mu.Lock()
  297. defer le.mu.Unlock()
  298. l := le.leaseMap[id]
  299. if l == nil {
  300. return ErrLeaseNotFound
  301. }
  302. l.mu.Lock()
  303. for _, it := range items {
  304. l.itemSet[it] = struct{}{}
  305. le.itemMap[it] = id
  306. }
  307. l.mu.Unlock()
  308. return nil
  309. }
  310. func (le *lessor) GetLease(item LeaseItem) LeaseID {
  311. le.mu.Lock()
  312. id := le.itemMap[item]
  313. le.mu.Unlock()
  314. return id
  315. }
  316. // Detach detaches items from the lease with given ID.
  317. // If the given lease does not exist, an error will be returned.
  318. func (le *lessor) Detach(id LeaseID, items []LeaseItem) error {
  319. le.mu.Lock()
  320. defer le.mu.Unlock()
  321. l := le.leaseMap[id]
  322. if l == nil {
  323. return ErrLeaseNotFound
  324. }
  325. l.mu.Lock()
  326. for _, it := range items {
  327. delete(l.itemSet, it)
  328. delete(le.itemMap, it)
  329. }
  330. l.mu.Unlock()
  331. return nil
  332. }
  333. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  334. le.mu.Lock()
  335. defer le.mu.Unlock()
  336. le.b = b
  337. le.rd = rd
  338. le.leaseMap = make(map[LeaseID]*Lease)
  339. le.itemMap = make(map[LeaseItem]LeaseID)
  340. le.initAndRecover()
  341. }
  342. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  343. return le.expiredC
  344. }
  345. func (le *lessor) Stop() {
  346. close(le.stopC)
  347. <-le.doneC
  348. }
  349. func (le *lessor) runLoop() {
  350. defer close(le.doneC)
  351. for {
  352. var ls []*Lease
  353. le.mu.Lock()
  354. if le.isPrimary() {
  355. ls = le.findExpiredLeases()
  356. }
  357. le.mu.Unlock()
  358. if len(ls) != 0 {
  359. // rate limit
  360. if len(ls) > leaseRevokeRate/2 {
  361. ls = ls[:leaseRevokeRate/2]
  362. }
  363. select {
  364. case <-le.stopC:
  365. return
  366. case le.expiredC <- ls:
  367. default:
  368. // the receiver of expiredC is probably busy handling
  369. // other stuff
  370. // let's try this next time after 500ms
  371. }
  372. }
  373. select {
  374. case <-time.After(500 * time.Millisecond):
  375. case <-le.stopC:
  376. return
  377. }
  378. }
  379. }
  380. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  381. // leases that needed to be revoked.
  382. func (le *lessor) findExpiredLeases() []*Lease {
  383. leases := make([]*Lease, 0, 16)
  384. for _, l := range le.leaseMap {
  385. // TODO: probably should change to <= 100-500 millisecond to
  386. // make up committing latency.
  387. if l.expired() {
  388. leases = append(leases, l)
  389. }
  390. }
  391. return leases
  392. }
  393. func (le *lessor) initAndRecover() {
  394. tx := le.b.BatchTx()
  395. tx.Lock()
  396. tx.UnsafeCreateBucket(leaseBucketName)
  397. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  398. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  399. for i := range vs {
  400. var lpb leasepb.Lease
  401. err := lpb.Unmarshal(vs[i])
  402. if err != nil {
  403. tx.Unlock()
  404. panic("failed to unmarshal lease proto item")
  405. }
  406. ID := LeaseID(lpb.ID)
  407. if lpb.TTL < le.minLeaseTTL {
  408. lpb.TTL = le.minLeaseTTL
  409. }
  410. le.leaseMap[ID] = &Lease{
  411. ID: ID,
  412. ttl: lpb.TTL,
  413. // itemSet will be filled in when recover key-value pairs
  414. // set expiry to forever, refresh when promoted
  415. itemSet: make(map[LeaseItem]struct{}),
  416. expiry: forever,
  417. revokec: make(chan struct{}),
  418. }
  419. }
  420. tx.Unlock()
  421. le.b.ForceCommit()
  422. }
  423. type Lease struct {
  424. ID LeaseID
  425. ttl int64 // time to live in seconds
  426. // expiry is time when lease should expire; must be 64-bit aligned.
  427. expiry monotime.Time
  428. // mu protects concurrent accesses to itemSet
  429. mu sync.RWMutex
  430. itemSet map[LeaseItem]struct{}
  431. revokec chan struct{}
  432. }
  433. func (l *Lease) expired() bool {
  434. return l.Remaining() <= 0
  435. }
  436. func (l *Lease) persistTo(b backend.Backend) {
  437. key := int64ToBytes(int64(l.ID))
  438. lpb := leasepb.Lease{ID: int64(l.ID), TTL: int64(l.ttl)}
  439. val, err := lpb.Marshal()
  440. if err != nil {
  441. panic("failed to marshal lease proto item")
  442. }
  443. b.BatchTx().Lock()
  444. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  445. b.BatchTx().Unlock()
  446. }
  447. // TTL returns the TTL of the Lease.
  448. func (l *Lease) TTL() int64 {
  449. return l.ttl
  450. }
  451. // refresh refreshes the expiry of the lease.
  452. func (l *Lease) refresh(extend time.Duration) {
  453. t := monotime.Now().Add(extend + time.Duration(l.ttl)*time.Second)
  454. atomic.StoreUint64((*uint64)(&l.expiry), uint64(t))
  455. }
  456. // forever sets the expiry of lease to be forever.
  457. func (l *Lease) forever() { atomic.StoreUint64((*uint64)(&l.expiry), uint64(forever)) }
  458. // Keys returns all the keys attached to the lease.
  459. func (l *Lease) Keys() []string {
  460. l.mu.RLock()
  461. keys := make([]string, 0, len(l.itemSet))
  462. for k := range l.itemSet {
  463. keys = append(keys, k.Key)
  464. }
  465. l.mu.RUnlock()
  466. return keys
  467. }
  468. // Remaining returns the remaining time of the lease.
  469. func (l *Lease) Remaining() time.Duration {
  470. t := monotime.Time(atomic.LoadUint64((*uint64)(&l.expiry)))
  471. return time.Duration(t - monotime.Now())
  472. }
  473. type LeaseItem struct {
  474. Key string
  475. }
  476. func int64ToBytes(n int64) []byte {
  477. bytes := make([]byte, 8)
  478. binary.BigEndian.PutUint64(bytes, uint64(n))
  479. return bytes
  480. }
  481. // FakeLessor is a fake implementation of Lessor interface.
  482. // Used for testing only.
  483. type FakeLessor struct{}
  484. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  485. func (fl *FakeLessor) Grant(id LeaseID, ttl int64) (*Lease, error) { return nil, nil }
  486. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  487. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  488. func (fl *FakeLessor) GetLease(item LeaseItem) LeaseID { return 0 }
  489. func (fl *FakeLessor) Detach(id LeaseID, items []LeaseItem) error { return nil }
  490. func (fl *FakeLessor) Promote(extend time.Duration) {}
  491. func (fl *FakeLessor) Demote() {}
  492. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  493. func (le *FakeLessor) Lookup(id LeaseID) *Lease { return nil }
  494. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  495. func (fl *FakeLessor) Recover(b backend.Backend, rd RangeDeleter) {}
  496. func (fl *FakeLessor) Stop() {}