lessor.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  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. // maximum number of leases to revoke per iteration
  31. // TODO: make this configurable?
  32. leaseRevokeRate = 1000
  33. )
  34. var (
  35. leaseBucketName = []byte("lease")
  36. forever = monotime.Time(math.MaxInt64)
  37. ErrNotPrimary = errors.New("not a primary lessor")
  38. ErrLeaseNotFound = errors.New("lease not found")
  39. ErrLeaseExists = errors.New("lease already exists")
  40. )
  41. // TxnDelete is a TxnWrite that only permits deletes. Defined here
  42. // to avoid circular dependency with mvcc.
  43. type TxnDelete interface {
  44. DeleteRange(key, end []byte) (n, rev int64)
  45. End()
  46. }
  47. // RangeDeleter is a TxnDelete constructor.
  48. type RangeDeleter func() TxnDelete
  49. type LeaseID int64
  50. // Lessor owns leases. It can grant, revoke, renew and modify leases for lessee.
  51. type Lessor interface {
  52. // SetRangeDeleter lets the lessor create TxnDeletes to the store.
  53. // Lessor deletes the items in the revoked or expired lease by creating
  54. // new TxnDeletes.
  55. SetRangeDeleter(rd RangeDeleter)
  56. // Grant grants a lease that expires at least after TTL seconds.
  57. Grant(id LeaseID, ttl int64) (*Lease, error)
  58. // Revoke revokes a lease with given ID. The item attached to the
  59. // given lease will be removed. If the ID does not exist, an error
  60. // will be returned.
  61. Revoke(id LeaseID) error
  62. // Attach attaches given leaseItem to the lease with given LeaseID.
  63. // If the lease does not exist, an error will be returned.
  64. Attach(id LeaseID, items []LeaseItem) error
  65. // GetLease returns LeaseID for given item.
  66. // If no lease found, NoLease value will be returned.
  67. GetLease(item LeaseItem) LeaseID
  68. // Detach detaches given leaseItem from the lease with given LeaseID.
  69. // If the lease does not exist, an error will be returned.
  70. Detach(id LeaseID, items []LeaseItem) error
  71. // Promote promotes the lessor to be the primary lessor. Primary lessor manages
  72. // the expiration and renew of leases.
  73. // Newly promoted lessor renew the TTL of all lease to extend + previous TTL.
  74. Promote(extend time.Duration)
  75. // Demote demotes the lessor from being the primary lessor.
  76. Demote()
  77. // Renew renews a lease with given ID. It returns the renewed TTL. If the ID does not exist,
  78. // an error will be returned.
  79. Renew(id LeaseID) (int64, error)
  80. // Lookup gives the lease at a given lease id, if any
  81. Lookup(id LeaseID) *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. // TODO: when lessor is under high load, it should give out lease
  164. // with longer TTL to reduce renew load.
  165. l := &Lease{
  166. ID: id,
  167. ttl: ttl,
  168. itemSet: make(map[LeaseItem]struct{}),
  169. revokec: make(chan struct{}),
  170. }
  171. le.mu.Lock()
  172. defer le.mu.Unlock()
  173. if _, ok := le.leaseMap[id]; ok {
  174. return nil, ErrLeaseExists
  175. }
  176. if l.ttl < le.minLeaseTTL {
  177. l.ttl = le.minLeaseTTL
  178. }
  179. if le.isPrimary() {
  180. l.refresh(0)
  181. } else {
  182. l.forever()
  183. }
  184. le.leaseMap[id] = l
  185. l.persistTo(le.b)
  186. return l, nil
  187. }
  188. func (le *lessor) Revoke(id LeaseID) error {
  189. le.mu.Lock()
  190. l := le.leaseMap[id]
  191. if l == nil {
  192. le.mu.Unlock()
  193. return ErrLeaseNotFound
  194. }
  195. defer close(l.revokec)
  196. // unlock before doing external work
  197. le.mu.Unlock()
  198. if le.rd == nil {
  199. return nil
  200. }
  201. txn := le.rd()
  202. // sort keys so deletes are in same order among all members,
  203. // otherwise the backened hashes will be different
  204. keys := l.Keys()
  205. sort.StringSlice(keys).Sort()
  206. for _, key := range keys {
  207. txn.DeleteRange([]byte(key), nil)
  208. }
  209. le.mu.Lock()
  210. defer le.mu.Unlock()
  211. delete(le.leaseMap, l.ID)
  212. // lease deletion needs to be in the same backend transaction with the
  213. // kv deletion. Or we might end up with not executing the revoke or not
  214. // deleting the keys if etcdserver fails in between.
  215. le.b.BatchTx().UnsafeDelete(leaseBucketName, int64ToBytes(int64(l.ID)))
  216. txn.End()
  217. return nil
  218. }
  219. // Renew renews an existing lease. If the given lease does not exist or
  220. // has expired, an error will be returned.
  221. func (le *lessor) Renew(id LeaseID) (int64, error) {
  222. le.mu.Lock()
  223. unlock := func() { le.mu.Unlock() }
  224. defer func() { unlock() }()
  225. if !le.isPrimary() {
  226. // forward renew request to primary instead of returning error.
  227. return -1, ErrNotPrimary
  228. }
  229. demotec := le.demotec
  230. l := le.leaseMap[id]
  231. if l == nil {
  232. return -1, ErrLeaseNotFound
  233. }
  234. if l.expired() {
  235. le.mu.Unlock()
  236. unlock = func() {}
  237. select {
  238. // A expired lease might be pending for revoking or going through
  239. // quorum to be revoked. To be accurate, renew request must wait for the
  240. // deletion to complete.
  241. case <-l.revokec:
  242. return -1, ErrLeaseNotFound
  243. // The expired lease might fail to be revoked if the primary changes.
  244. // The caller will retry on ErrNotPrimary.
  245. case <-demotec:
  246. return -1, ErrNotPrimary
  247. case <-le.stopC:
  248. return -1, ErrNotPrimary
  249. }
  250. }
  251. l.refresh(0)
  252. return l.ttl, nil
  253. }
  254. func (le *lessor) Lookup(id LeaseID) *Lease {
  255. le.mu.Lock()
  256. defer le.mu.Unlock()
  257. return le.leaseMap[id]
  258. }
  259. func (le *lessor) Promote(extend time.Duration) {
  260. le.mu.Lock()
  261. defer le.mu.Unlock()
  262. le.demotec = make(chan struct{})
  263. // refresh the expiries of all leases.
  264. for _, l := range le.leaseMap {
  265. l.refresh(extend)
  266. }
  267. }
  268. func (le *lessor) Demote() {
  269. le.mu.Lock()
  270. defer le.mu.Unlock()
  271. // set the expiries of all leases to forever
  272. for _, l := range le.leaseMap {
  273. l.forever()
  274. }
  275. if le.demotec != nil {
  276. close(le.demotec)
  277. le.demotec = nil
  278. }
  279. }
  280. // Attach attaches items to the lease with given ID. When the lease
  281. // expires, the attached items will be automatically removed.
  282. // If the given lease does not exist, an error will be returned.
  283. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  284. le.mu.Lock()
  285. defer le.mu.Unlock()
  286. l := le.leaseMap[id]
  287. if l == nil {
  288. return ErrLeaseNotFound
  289. }
  290. l.mu.Lock()
  291. for _, it := range items {
  292. l.itemSet[it] = struct{}{}
  293. le.itemMap[it] = id
  294. }
  295. l.mu.Unlock()
  296. return nil
  297. }
  298. func (le *lessor) GetLease(item LeaseItem) LeaseID {
  299. le.mu.Lock()
  300. id := le.itemMap[item]
  301. le.mu.Unlock()
  302. return id
  303. }
  304. // Detach detaches items from the lease with given ID.
  305. // If the given lease does not exist, an error will be returned.
  306. func (le *lessor) Detach(id LeaseID, items []LeaseItem) error {
  307. le.mu.Lock()
  308. defer le.mu.Unlock()
  309. l := le.leaseMap[id]
  310. if l == nil {
  311. return ErrLeaseNotFound
  312. }
  313. l.mu.Lock()
  314. for _, it := range items {
  315. delete(l.itemSet, it)
  316. delete(le.itemMap, it)
  317. }
  318. l.mu.Unlock()
  319. return nil
  320. }
  321. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  322. le.mu.Lock()
  323. defer le.mu.Unlock()
  324. le.b = b
  325. le.rd = rd
  326. le.leaseMap = make(map[LeaseID]*Lease)
  327. le.itemMap = make(map[LeaseItem]LeaseID)
  328. le.initAndRecover()
  329. }
  330. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  331. return le.expiredC
  332. }
  333. func (le *lessor) Stop() {
  334. close(le.stopC)
  335. <-le.doneC
  336. }
  337. func (le *lessor) runLoop() {
  338. defer close(le.doneC)
  339. for {
  340. var ls []*Lease
  341. le.mu.Lock()
  342. if le.isPrimary() {
  343. ls = le.findExpiredLeases()
  344. }
  345. le.mu.Unlock()
  346. if len(ls) != 0 {
  347. // rate limit
  348. if len(ls) > leaseRevokeRate/2 {
  349. ls = ls[:leaseRevokeRate/2]
  350. }
  351. select {
  352. case <-le.stopC:
  353. return
  354. case le.expiredC <- ls:
  355. default:
  356. // the receiver of expiredC is probably busy handling
  357. // other stuff
  358. // let's try this next time after 500ms
  359. }
  360. }
  361. select {
  362. case <-time.After(500 * time.Millisecond):
  363. case <-le.stopC:
  364. return
  365. }
  366. }
  367. }
  368. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  369. // leases that needed to be revoked.
  370. func (le *lessor) findExpiredLeases() []*Lease {
  371. leases := make([]*Lease, 0, 16)
  372. for _, l := range le.leaseMap {
  373. // TODO: probably should change to <= 100-500 millisecond to
  374. // make up committing latency.
  375. if l.expired() {
  376. leases = append(leases, l)
  377. }
  378. }
  379. return leases
  380. }
  381. func (le *lessor) initAndRecover() {
  382. tx := le.b.BatchTx()
  383. tx.Lock()
  384. tx.UnsafeCreateBucket(leaseBucketName)
  385. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  386. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  387. for i := range vs {
  388. var lpb leasepb.Lease
  389. err := lpb.Unmarshal(vs[i])
  390. if err != nil {
  391. tx.Unlock()
  392. panic("failed to unmarshal lease proto item")
  393. }
  394. ID := LeaseID(lpb.ID)
  395. if lpb.TTL < le.minLeaseTTL {
  396. lpb.TTL = le.minLeaseTTL
  397. }
  398. le.leaseMap[ID] = &Lease{
  399. ID: ID,
  400. ttl: lpb.TTL,
  401. // itemSet will be filled in when recover key-value pairs
  402. // set expiry to forever, refresh when promoted
  403. itemSet: make(map[LeaseItem]struct{}),
  404. expiry: forever,
  405. revokec: make(chan struct{}),
  406. }
  407. }
  408. tx.Unlock()
  409. le.b.ForceCommit()
  410. }
  411. type Lease struct {
  412. ID LeaseID
  413. ttl int64 // time to live in seconds
  414. // expiry is time when lease should expire; must be 64-bit aligned.
  415. expiry monotime.Time
  416. // mu protects concurrent accesses to itemSet
  417. mu sync.RWMutex
  418. itemSet map[LeaseItem]struct{}
  419. revokec chan struct{}
  420. }
  421. func (l *Lease) expired() bool {
  422. return l.Remaining() <= 0
  423. }
  424. func (l *Lease) persistTo(b backend.Backend) {
  425. key := int64ToBytes(int64(l.ID))
  426. lpb := leasepb.Lease{ID: int64(l.ID), TTL: int64(l.ttl)}
  427. val, err := lpb.Marshal()
  428. if err != nil {
  429. panic("failed to marshal lease proto item")
  430. }
  431. b.BatchTx().Lock()
  432. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  433. b.BatchTx().Unlock()
  434. }
  435. // TTL returns the TTL of the Lease.
  436. func (l *Lease) TTL() int64 {
  437. return l.ttl
  438. }
  439. // refresh refreshes the expiry of the lease.
  440. func (l *Lease) refresh(extend time.Duration) {
  441. t := monotime.Now().Add(extend + time.Duration(l.ttl)*time.Second)
  442. atomic.StoreUint64((*uint64)(&l.expiry), uint64(t))
  443. }
  444. // forever sets the expiry of lease to be forever.
  445. func (l *Lease) forever() { atomic.StoreUint64((*uint64)(&l.expiry), uint64(forever)) }
  446. // Keys returns all the keys attached to the lease.
  447. func (l *Lease) Keys() []string {
  448. l.mu.RLock()
  449. keys := make([]string, 0, len(l.itemSet))
  450. for k := range l.itemSet {
  451. keys = append(keys, k.Key)
  452. }
  453. l.mu.RUnlock()
  454. return keys
  455. }
  456. // Remaining returns the remaining time of the lease.
  457. func (l *Lease) Remaining() time.Duration {
  458. t := monotime.Time(atomic.LoadUint64((*uint64)(&l.expiry)))
  459. return time.Duration(t - monotime.Now())
  460. }
  461. type LeaseItem struct {
  462. Key string
  463. }
  464. func int64ToBytes(n int64) []byte {
  465. bytes := make([]byte, 8)
  466. binary.BigEndian.PutUint64(bytes, uint64(n))
  467. return bytes
  468. }
  469. // FakeLessor is a fake implementation of Lessor interface.
  470. // Used for testing only.
  471. type FakeLessor struct{}
  472. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  473. func (fl *FakeLessor) Grant(id LeaseID, ttl int64) (*Lease, error) { return nil, nil }
  474. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  475. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  476. func (fl *FakeLessor) GetLease(item LeaseItem) LeaseID { return 0 }
  477. func (fl *FakeLessor) Detach(id LeaseID, items []LeaseItem) error { return nil }
  478. func (fl *FakeLessor) Promote(extend time.Duration) {}
  479. func (fl *FakeLessor) Demote() {}
  480. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  481. func (le *FakeLessor) Lookup(id LeaseID) *Lease { return nil }
  482. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  483. func (fl *FakeLessor) Recover(b backend.Backend, rd RangeDeleter) {}
  484. func (fl *FakeLessor) Stop() {}