lessor.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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. "container/heap"
  17. "context"
  18. "encoding/binary"
  19. "errors"
  20. "math"
  21. "sort"
  22. "sync"
  23. "time"
  24. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  25. "go.etcd.io/etcd/lease/leasepb"
  26. "go.etcd.io/etcd/mvcc/backend"
  27. "go.uber.org/zap"
  28. )
  29. // NoLease is a special LeaseID representing the absence of a lease.
  30. const NoLease = LeaseID(0)
  31. // MaxLeaseTTL is the maximum lease TTL value
  32. const MaxLeaseTTL = 9000000000
  33. var (
  34. forever = time.Time{}
  35. leaseBucketName = []byte("lease")
  36. // maximum number of leases to revoke per second; configurable for tests
  37. leaseRevokeRate = 1000
  38. // maximum number of lease checkpoints recorded to the consensus log per second; configurable for tests
  39. leaseCheckpointRate = 1000
  40. // the default interval of lease checkpoint
  41. defaultLeaseCheckpointInterval = 5 * time.Minute
  42. // maximum number of lease checkpoints to batch into a single consensus log entry
  43. maxLeaseCheckpointBatchSize = 1000
  44. // the default interval to check if the expired lease is revoked
  45. defaultExpiredleaseRetryInterval = 3 * time.Second
  46. ErrNotPrimary = errors.New("not a primary lessor")
  47. ErrLeaseNotFound = errors.New("lease not found")
  48. ErrLeaseExists = errors.New("lease already exists")
  49. ErrLeaseTTLTooLarge = errors.New("too large lease TTL")
  50. )
  51. // TxnDelete is a TxnWrite that only permits deletes. Defined here
  52. // to avoid circular dependency with mvcc.
  53. type TxnDelete interface {
  54. DeleteRange(key, end []byte) (n, rev int64)
  55. End()
  56. }
  57. // RangeDeleter is a TxnDelete constructor.
  58. type RangeDeleter func() TxnDelete
  59. // Checkpointer permits checkpointing of lease remaining TTLs to the consensus log. Defined here to
  60. // avoid circular dependency with mvcc.
  61. type Checkpointer func(ctx context.Context, lc *pb.LeaseCheckpointRequest)
  62. type LeaseID int64
  63. // Lessor owns leases. It can grant, revoke, renew and modify leases for lessee.
  64. type Lessor interface {
  65. // SetRangeDeleter lets the lessor create TxnDeletes to the store.
  66. // Lessor deletes the items in the revoked or expired lease by creating
  67. // new TxnDeletes.
  68. SetRangeDeleter(rd RangeDeleter)
  69. SetCheckpointer(cp Checkpointer)
  70. // Grant grants a lease that expires at least after TTL seconds.
  71. Grant(id LeaseID, ttl int64) (*Lease, error)
  72. // Revoke revokes a lease with given ID. The item attached to the
  73. // given lease will be removed. If the ID does not exist, an error
  74. // will be returned.
  75. Revoke(id LeaseID) error
  76. // Checkpoint applies the remainingTTL of a lease. The remainingTTL is used in Promote to set
  77. // the expiry of leases to less than the full TTL when possible.
  78. Checkpoint(id LeaseID, remainingTTL int64) error
  79. // Attach attaches given leaseItem to the lease with given LeaseID.
  80. // If the lease does not exist, an error will be returned.
  81. Attach(id LeaseID, items []LeaseItem) error
  82. // GetLease returns LeaseID for given item.
  83. // If no lease found, NoLease value will be returned.
  84. GetLease(item LeaseItem) LeaseID
  85. // Detach detaches given leaseItem from the lease with given LeaseID.
  86. // If the lease does not exist, an error will be returned.
  87. Detach(id LeaseID, items []LeaseItem) error
  88. // Promote promotes the lessor to be the primary lessor. Primary lessor manages
  89. // the expiration and renew of leases.
  90. // Newly promoted lessor renew the TTL of all lease to extend + previous TTL.
  91. Promote(extend time.Duration)
  92. // Demote demotes the lessor from being the primary lessor.
  93. Demote()
  94. // Renew renews a lease with given ID. It returns the renewed TTL. If the ID does not exist,
  95. // an error will be returned.
  96. Renew(id LeaseID) (int64, error)
  97. // Lookup gives the lease at a given lease id, if any
  98. Lookup(id LeaseID) *Lease
  99. // Leases lists all leases.
  100. Leases() []*Lease
  101. // ExpiredLeasesC returns a chan that is used to receive expired leases.
  102. ExpiredLeasesC() <-chan []*Lease
  103. // Recover recovers the lessor state from the given backend and RangeDeleter.
  104. Recover(b backend.Backend, rd RangeDeleter)
  105. // Stop stops the lessor for managing leases. The behavior of calling Stop multiple
  106. // times is undefined.
  107. Stop()
  108. }
  109. // lessor implements Lessor interface.
  110. // TODO: use clockwork for testability.
  111. type lessor struct {
  112. mu sync.RWMutex
  113. // demotec is set when the lessor is the primary.
  114. // demotec will be closed if the lessor is demoted.
  115. demotec chan struct{}
  116. leaseMap map[LeaseID]*Lease
  117. leaseExpiredNotifier *LeaseExpiredNotifier
  118. leaseCheckpointHeap LeaseQueue
  119. itemMap map[LeaseItem]LeaseID
  120. // When a lease expires, the lessor will delete the
  121. // leased range (or key) by the RangeDeleter.
  122. rd RangeDeleter
  123. // When a lease's deadline should be persisted to preserve the remaining TTL across leader
  124. // elections and restarts, the lessor will checkpoint the lease by the Checkpointer.
  125. cp Checkpointer
  126. // backend to persist leases. We only persist lease ID and expiry for now.
  127. // The leased items can be recovered by iterating all the keys in kv.
  128. b backend.Backend
  129. // minLeaseTTL is the minimum lease TTL that can be granted for a lease. Any
  130. // requests for shorter TTLs are extended to the minimum TTL.
  131. minLeaseTTL int64
  132. expiredC chan []*Lease
  133. // stopC is a channel whose closure indicates that the lessor should be stopped.
  134. stopC chan struct{}
  135. // doneC is a channel whose closure indicates that the lessor is stopped.
  136. doneC chan struct{}
  137. lg *zap.Logger
  138. // Wait duration between lease checkpoints.
  139. checkpointInterval time.Duration
  140. // the interval to check if the expired lease is revoked
  141. expiredLeaseRetryInterval time.Duration
  142. }
  143. type LessorConfig struct {
  144. MinLeaseTTL int64
  145. CheckpointInterval time.Duration
  146. ExpiredLeasesRetryInterval time.Duration
  147. }
  148. func NewLessor(lg *zap.Logger, b backend.Backend, cfg LessorConfig) Lessor {
  149. return newLessor(lg, b, cfg)
  150. }
  151. func newLessor(lg *zap.Logger, b backend.Backend, cfg LessorConfig) *lessor {
  152. checkpointInterval := cfg.CheckpointInterval
  153. expiredLeaseRetryInterval := cfg.ExpiredLeasesRetryInterval
  154. if checkpointInterval == 0 {
  155. checkpointInterval = defaultLeaseCheckpointInterval
  156. }
  157. if expiredLeaseRetryInterval == 0 {
  158. expiredLeaseRetryInterval = defaultExpiredleaseRetryInterval
  159. }
  160. l := &lessor{
  161. leaseMap: make(map[LeaseID]*Lease),
  162. itemMap: make(map[LeaseItem]LeaseID),
  163. leaseExpiredNotifier: newLeaseExpiredNotifier(),
  164. leaseCheckpointHeap: make(LeaseQueue, 0),
  165. b: b,
  166. minLeaseTTL: cfg.MinLeaseTTL,
  167. checkpointInterval: checkpointInterval,
  168. expiredLeaseRetryInterval: expiredLeaseRetryInterval,
  169. // expiredC is a small buffered chan to avoid unnecessary blocking.
  170. expiredC: make(chan []*Lease, 16),
  171. stopC: make(chan struct{}),
  172. doneC: make(chan struct{}),
  173. lg: lg,
  174. }
  175. l.initAndRecover()
  176. go l.runLoop()
  177. return l
  178. }
  179. // isPrimary indicates if this lessor is the primary lessor. The primary
  180. // lessor manages lease expiration and renew.
  181. //
  182. // in etcd, raft leader is the primary. Thus there might be two primary
  183. // leaders at the same time (raft allows concurrent leader but with different term)
  184. // for at most a leader election timeout.
  185. // The old primary leader cannot affect the correctness since its proposal has a
  186. // smaller term and will not be committed.
  187. //
  188. // TODO: raft follower do not forward lease management proposals. There might be a
  189. // very small window (within second normally which depends on go scheduling) that
  190. // a raft follow is the primary between the raft leader demotion and lessor demotion.
  191. // Usually this should not be a problem. Lease should not be that sensitive to timing.
  192. func (le *lessor) isPrimary() bool {
  193. return le.demotec != nil
  194. }
  195. func (le *lessor) SetRangeDeleter(rd RangeDeleter) {
  196. le.mu.Lock()
  197. defer le.mu.Unlock()
  198. le.rd = rd
  199. }
  200. func (le *lessor) SetCheckpointer(cp Checkpointer) {
  201. le.mu.Lock()
  202. defer le.mu.Unlock()
  203. le.cp = cp
  204. }
  205. func (le *lessor) Grant(id LeaseID, ttl int64) (*Lease, error) {
  206. if id == NoLease {
  207. return nil, ErrLeaseNotFound
  208. }
  209. if ttl > MaxLeaseTTL {
  210. return nil, ErrLeaseTTLTooLarge
  211. }
  212. // TODO: when lessor is under high load, it should give out lease
  213. // with longer TTL to reduce renew load.
  214. l := &Lease{
  215. ID: id,
  216. ttl: ttl,
  217. itemSet: make(map[LeaseItem]struct{}),
  218. revokec: make(chan struct{}),
  219. }
  220. le.mu.Lock()
  221. defer le.mu.Unlock()
  222. if _, ok := le.leaseMap[id]; ok {
  223. return nil, ErrLeaseExists
  224. }
  225. if l.ttl < le.minLeaseTTL {
  226. l.ttl = le.minLeaseTTL
  227. }
  228. if le.isPrimary() {
  229. l.refresh(0)
  230. } else {
  231. l.forever()
  232. }
  233. le.leaseMap[id] = l
  234. item := &LeaseWithTime{id: l.ID, time: l.expiry.UnixNano()}
  235. le.leaseExpiredNotifier.RegisterOrUpdate(item)
  236. l.persistTo(le.b)
  237. leaseTotalTTLs.Observe(float64(l.ttl))
  238. leaseGranted.Inc()
  239. if le.isPrimary() {
  240. le.scheduleCheckpointIfNeeded(l)
  241. }
  242. return l, nil
  243. }
  244. func (le *lessor) Revoke(id LeaseID) error {
  245. le.mu.Lock()
  246. l := le.leaseMap[id]
  247. if l == nil {
  248. le.mu.Unlock()
  249. return ErrLeaseNotFound
  250. }
  251. defer close(l.revokec)
  252. // unlock before doing external work
  253. le.mu.Unlock()
  254. if le.rd == nil {
  255. return nil
  256. }
  257. txn := le.rd()
  258. // sort keys so deletes are in same order among all members,
  259. // otherwise the backend hashes will be different
  260. keys := l.Keys()
  261. sort.StringSlice(keys).Sort()
  262. for _, key := range keys {
  263. txn.DeleteRange([]byte(key), nil)
  264. }
  265. le.mu.Lock()
  266. defer le.mu.Unlock()
  267. delete(le.leaseMap, l.ID)
  268. // lease deletion needs to be in the same backend transaction with the
  269. // kv deletion. Or we might end up with not executing the revoke or not
  270. // deleting the keys if etcdserver fails in between.
  271. le.b.BatchTx().UnsafeDelete(leaseBucketName, int64ToBytes(int64(l.ID)))
  272. txn.End()
  273. leaseRevoked.Inc()
  274. return nil
  275. }
  276. func (le *lessor) Checkpoint(id LeaseID, remainingTTL int64) error {
  277. le.mu.Lock()
  278. defer le.mu.Unlock()
  279. if l, ok := le.leaseMap[id]; ok {
  280. // when checkpointing, we only update the remainingTTL, Promote is responsible for applying this to lease expiry
  281. l.remainingTTL = remainingTTL
  282. if le.isPrimary() {
  283. // schedule the next checkpoint as needed
  284. le.scheduleCheckpointIfNeeded(l)
  285. }
  286. }
  287. return nil
  288. }
  289. // Renew renews an existing lease. If the given lease does not exist or
  290. // has expired, an error will be returned.
  291. func (le *lessor) Renew(id LeaseID) (int64, error) {
  292. le.mu.RLock()
  293. if !le.isPrimary() {
  294. // forward renew request to primary instead of returning error.
  295. le.mu.RUnlock()
  296. return -1, ErrNotPrimary
  297. }
  298. demotec := le.demotec
  299. l := le.leaseMap[id]
  300. if l == nil {
  301. le.mu.RUnlock()
  302. return -1, ErrLeaseNotFound
  303. }
  304. // Clear remaining TTL when we renew if it is set
  305. clearRemainingTTL := le.cp != nil && l.remainingTTL > 0
  306. le.mu.RUnlock()
  307. if l.expired() {
  308. select {
  309. // A expired lease might be pending for revoking or going through
  310. // quorum to be revoked. To be accurate, renew request must wait for the
  311. // deletion to complete.
  312. case <-l.revokec:
  313. return -1, ErrLeaseNotFound
  314. // The expired lease might fail to be revoked if the primary changes.
  315. // The caller will retry on ErrNotPrimary.
  316. case <-demotec:
  317. return -1, ErrNotPrimary
  318. case <-le.stopC:
  319. return -1, ErrNotPrimary
  320. }
  321. }
  322. // Clear remaining TTL when we renew if it is set
  323. // By applying a RAFT entry only when the remainingTTL is already set, we limit the number
  324. // of RAFT entries written per lease to a max of 2 per checkpoint interval.
  325. if clearRemainingTTL {
  326. le.cp(context.Background(), &pb.LeaseCheckpointRequest{Checkpoints: []*pb.LeaseCheckpoint{{ID: int64(l.ID), Remaining_TTL: 0}}})
  327. }
  328. le.mu.Lock()
  329. l.refresh(0)
  330. item := &LeaseWithTime{id: l.ID, time: l.expiry.UnixNano()}
  331. le.leaseExpiredNotifier.RegisterOrUpdate(item)
  332. le.mu.Unlock()
  333. leaseRenewed.Inc()
  334. return l.ttl, nil
  335. }
  336. func (le *lessor) Lookup(id LeaseID) *Lease {
  337. le.mu.RLock()
  338. defer le.mu.RUnlock()
  339. return le.leaseMap[id]
  340. }
  341. func (le *lessor) unsafeLeases() []*Lease {
  342. leases := make([]*Lease, 0, len(le.leaseMap))
  343. for _, l := range le.leaseMap {
  344. leases = append(leases, l)
  345. }
  346. return leases
  347. }
  348. func (le *lessor) Leases() []*Lease {
  349. le.mu.RLock()
  350. ls := le.unsafeLeases()
  351. le.mu.RUnlock()
  352. sort.Sort(leasesByExpiry(ls))
  353. return ls
  354. }
  355. func (le *lessor) Promote(extend time.Duration) {
  356. le.mu.Lock()
  357. defer le.mu.Unlock()
  358. le.demotec = make(chan struct{})
  359. // refresh the expiries of all leases.
  360. for _, l := range le.leaseMap {
  361. l.refresh(extend)
  362. item := &LeaseWithTime{id: l.ID, time: l.expiry.UnixNano()}
  363. le.leaseExpiredNotifier.RegisterOrUpdate(item)
  364. }
  365. if len(le.leaseMap) < leaseRevokeRate {
  366. // no possibility of lease pile-up
  367. return
  368. }
  369. // adjust expiries in case of overlap
  370. leases := le.unsafeLeases()
  371. sort.Sort(leasesByExpiry(leases))
  372. baseWindow := leases[0].Remaining()
  373. nextWindow := baseWindow + time.Second
  374. expires := 0
  375. // have fewer expires than the total revoke rate so piled up leases
  376. // don't consume the entire revoke limit
  377. targetExpiresPerSecond := (3 * leaseRevokeRate) / 4
  378. for _, l := range leases {
  379. remaining := l.Remaining()
  380. if remaining > nextWindow {
  381. baseWindow = remaining
  382. nextWindow = baseWindow + time.Second
  383. expires = 1
  384. continue
  385. }
  386. expires++
  387. if expires <= targetExpiresPerSecond {
  388. continue
  389. }
  390. rateDelay := float64(time.Second) * (float64(expires) / float64(targetExpiresPerSecond))
  391. // If leases are extended by n seconds, leases n seconds ahead of the
  392. // base window should be extended by only one second.
  393. rateDelay -= float64(remaining - baseWindow)
  394. delay := time.Duration(rateDelay)
  395. nextWindow = baseWindow + delay
  396. l.refresh(delay + extend)
  397. item := &LeaseWithTime{id: l.ID, time: l.expiry.UnixNano()}
  398. le.leaseExpiredNotifier.RegisterOrUpdate(item)
  399. le.scheduleCheckpointIfNeeded(l)
  400. }
  401. }
  402. type leasesByExpiry []*Lease
  403. func (le leasesByExpiry) Len() int { return len(le) }
  404. func (le leasesByExpiry) Less(i, j int) bool { return le[i].Remaining() < le[j].Remaining() }
  405. func (le leasesByExpiry) Swap(i, j int) { le[i], le[j] = le[j], le[i] }
  406. func (le *lessor) Demote() {
  407. le.mu.Lock()
  408. defer le.mu.Unlock()
  409. // set the expiries of all leases to forever
  410. for _, l := range le.leaseMap {
  411. l.forever()
  412. }
  413. le.clearScheduledLeasesCheckpoints()
  414. if le.demotec != nil {
  415. close(le.demotec)
  416. le.demotec = nil
  417. }
  418. }
  419. // Attach attaches items to the lease with given ID. When the lease
  420. // expires, the attached items will be automatically removed.
  421. // If the given lease does not exist, an error will be returned.
  422. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  423. le.mu.Lock()
  424. defer le.mu.Unlock()
  425. l := le.leaseMap[id]
  426. if l == nil {
  427. return ErrLeaseNotFound
  428. }
  429. l.mu.Lock()
  430. for _, it := range items {
  431. l.itemSet[it] = struct{}{}
  432. le.itemMap[it] = id
  433. }
  434. l.mu.Unlock()
  435. return nil
  436. }
  437. func (le *lessor) GetLease(item LeaseItem) LeaseID {
  438. le.mu.RLock()
  439. id := le.itemMap[item]
  440. le.mu.RUnlock()
  441. return id
  442. }
  443. // Detach detaches items from the lease with given ID.
  444. // If the given lease does not exist, an error will be returned.
  445. func (le *lessor) Detach(id LeaseID, items []LeaseItem) error {
  446. le.mu.Lock()
  447. defer le.mu.Unlock()
  448. l := le.leaseMap[id]
  449. if l == nil {
  450. return ErrLeaseNotFound
  451. }
  452. l.mu.Lock()
  453. for _, it := range items {
  454. delete(l.itemSet, it)
  455. delete(le.itemMap, it)
  456. }
  457. l.mu.Unlock()
  458. return nil
  459. }
  460. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  461. le.mu.Lock()
  462. defer le.mu.Unlock()
  463. le.b = b
  464. le.rd = rd
  465. le.leaseMap = make(map[LeaseID]*Lease)
  466. le.itemMap = make(map[LeaseItem]LeaseID)
  467. le.initAndRecover()
  468. }
  469. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  470. return le.expiredC
  471. }
  472. func (le *lessor) Stop() {
  473. close(le.stopC)
  474. <-le.doneC
  475. }
  476. func (le *lessor) runLoop() {
  477. defer close(le.doneC)
  478. for {
  479. le.revokeExpiredLeases()
  480. le.checkpointScheduledLeases()
  481. select {
  482. case <-time.After(500 * time.Millisecond):
  483. case <-le.stopC:
  484. return
  485. }
  486. }
  487. }
  488. // revokeExpiredLeases finds all leases past their expiry and sends them to expired channel for
  489. // to be revoked.
  490. func (le *lessor) revokeExpiredLeases() {
  491. var ls []*Lease
  492. // rate limit
  493. revokeLimit := leaseRevokeRate / 2
  494. le.mu.RLock()
  495. if le.isPrimary() {
  496. ls = le.findExpiredLeases(revokeLimit)
  497. }
  498. le.mu.RUnlock()
  499. if len(ls) != 0 {
  500. select {
  501. case <-le.stopC:
  502. return
  503. case le.expiredC <- ls:
  504. default:
  505. // the receiver of expiredC is probably busy handling
  506. // other stuff
  507. // let's try this next time after 500ms
  508. }
  509. }
  510. }
  511. // checkpointScheduledLeases finds all scheduled lease checkpoints that are due and
  512. // submits them to the checkpointer to persist them to the consensus log.
  513. func (le *lessor) checkpointScheduledLeases() {
  514. var cps []*pb.LeaseCheckpoint
  515. // rate limit
  516. for i := 0; i < leaseCheckpointRate/2; i++ {
  517. le.mu.Lock()
  518. if le.isPrimary() {
  519. cps = le.findDueScheduledCheckpoints(maxLeaseCheckpointBatchSize)
  520. }
  521. le.mu.Unlock()
  522. if len(cps) != 0 {
  523. le.cp(context.Background(), &pb.LeaseCheckpointRequest{Checkpoints: cps})
  524. }
  525. if len(cps) < maxLeaseCheckpointBatchSize {
  526. return
  527. }
  528. }
  529. }
  530. func (le *lessor) clearScheduledLeasesCheckpoints() {
  531. le.leaseCheckpointHeap = make(LeaseQueue, 0)
  532. }
  533. // expireExists returns true if expiry items exist.
  534. // It pops only when expiry item exists.
  535. // "next" is true, to indicate that it may exist in next attempt.
  536. func (le *lessor) expireExists() (l *Lease, ok bool, next bool) {
  537. if le.leaseExpiredNotifier.Len() == 0 {
  538. return nil, false, false
  539. }
  540. item := le.leaseExpiredNotifier.Poll()
  541. l = le.leaseMap[item.id]
  542. if l == nil {
  543. // lease has expired or been revoked
  544. // no need to revoke (nothing is expiry)
  545. le.leaseExpiredNotifier.Unregister() // O(log N)
  546. return nil, false, true
  547. }
  548. now := time.Now()
  549. if now.UnixNano() < item.time /* expiration time */ {
  550. // Candidate expirations are caught up, reinsert this item
  551. // and no need to revoke (nothing is expiry)
  552. return l, false, false
  553. }
  554. // recheck if revoke is complete after retry interval
  555. item.time = now.Add(le.expiredLeaseRetryInterval).UnixNano()
  556. le.leaseExpiredNotifier.RegisterOrUpdate(item)
  557. return l, true, false
  558. }
  559. // findExpiredLeases loops leases in the leaseMap until reaching expired limit
  560. // and returns the expired leases that needed to be revoked.
  561. func (le *lessor) findExpiredLeases(limit int) []*Lease {
  562. leases := make([]*Lease, 0, 16)
  563. for {
  564. l, ok, next := le.expireExists()
  565. if !ok && !next {
  566. break
  567. }
  568. if !ok {
  569. continue
  570. }
  571. if next {
  572. continue
  573. }
  574. if l.expired() {
  575. leases = append(leases, l)
  576. // reach expired limit
  577. if len(leases) == limit {
  578. break
  579. }
  580. }
  581. }
  582. return leases
  583. }
  584. func (le *lessor) scheduleCheckpointIfNeeded(lease *Lease) {
  585. if le.cp == nil {
  586. return
  587. }
  588. if lease.RemainingTTL() > int64(le.checkpointInterval.Seconds()) {
  589. if le.lg != nil {
  590. le.lg.Debug("Scheduling lease checkpoint",
  591. zap.Int64("leaseID", int64(lease.ID)),
  592. zap.Duration("intervalSeconds", le.checkpointInterval),
  593. )
  594. }
  595. heap.Push(&le.leaseCheckpointHeap, &LeaseWithTime{
  596. id: lease.ID,
  597. time: time.Now().Add(le.checkpointInterval).UnixNano(),
  598. })
  599. }
  600. }
  601. func (le *lessor) findDueScheduledCheckpoints(checkpointLimit int) []*pb.LeaseCheckpoint {
  602. if le.cp == nil {
  603. return nil
  604. }
  605. now := time.Now()
  606. cps := []*pb.LeaseCheckpoint{}
  607. for le.leaseCheckpointHeap.Len() > 0 && len(cps) < checkpointLimit {
  608. lt := le.leaseCheckpointHeap[0]
  609. if lt.time /* next checkpoint time */ > now.UnixNano() {
  610. return cps
  611. }
  612. heap.Pop(&le.leaseCheckpointHeap)
  613. var l *Lease
  614. var ok bool
  615. if l, ok = le.leaseMap[lt.id]; !ok {
  616. continue
  617. }
  618. if !now.Before(l.expiry) {
  619. continue
  620. }
  621. remainingTTL := int64(math.Ceil(l.expiry.Sub(now).Seconds()))
  622. if remainingTTL >= l.ttl {
  623. continue
  624. }
  625. if le.lg != nil {
  626. le.lg.Debug("Checkpointing lease",
  627. zap.Int64("leaseID", int64(lt.id)),
  628. zap.Int64("remainingTTL", remainingTTL),
  629. )
  630. }
  631. cps = append(cps, &pb.LeaseCheckpoint{ID: int64(lt.id), Remaining_TTL: remainingTTL})
  632. }
  633. return cps
  634. }
  635. func (le *lessor) initAndRecover() {
  636. tx := le.b.BatchTx()
  637. tx.Lock()
  638. tx.UnsafeCreateBucket(leaseBucketName)
  639. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  640. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  641. for i := range vs {
  642. var lpb leasepb.Lease
  643. err := lpb.Unmarshal(vs[i])
  644. if err != nil {
  645. tx.Unlock()
  646. panic("failed to unmarshal lease proto item")
  647. }
  648. ID := LeaseID(lpb.ID)
  649. if lpb.TTL < le.minLeaseTTL {
  650. lpb.TTL = le.minLeaseTTL
  651. }
  652. le.leaseMap[ID] = &Lease{
  653. ID: ID,
  654. ttl: lpb.TTL,
  655. // itemSet will be filled in when recover key-value pairs
  656. // set expiry to forever, refresh when promoted
  657. itemSet: make(map[LeaseItem]struct{}),
  658. expiry: forever,
  659. revokec: make(chan struct{}),
  660. }
  661. }
  662. le.leaseExpiredNotifier.Init()
  663. heap.Init(&le.leaseCheckpointHeap)
  664. tx.Unlock()
  665. le.b.ForceCommit()
  666. }
  667. type Lease struct {
  668. ID LeaseID
  669. ttl int64 // time to live of the lease in seconds
  670. remainingTTL int64 // remaining time to live in seconds, if zero valued it is considered unset and the full ttl should be used
  671. // expiryMu protects concurrent accesses to expiry
  672. expiryMu sync.RWMutex
  673. // expiry is time when lease should expire. no expiration when expiry.IsZero() is true
  674. expiry time.Time
  675. // mu protects concurrent accesses to itemSet
  676. mu sync.RWMutex
  677. itemSet map[LeaseItem]struct{}
  678. revokec chan struct{}
  679. }
  680. func (l *Lease) expired() bool {
  681. return l.Remaining() <= 0
  682. }
  683. func (l *Lease) persistTo(b backend.Backend) {
  684. key := int64ToBytes(int64(l.ID))
  685. lpb := leasepb.Lease{ID: int64(l.ID), TTL: l.ttl, RemainingTTL: l.remainingTTL}
  686. val, err := lpb.Marshal()
  687. if err != nil {
  688. panic("failed to marshal lease proto item")
  689. }
  690. b.BatchTx().Lock()
  691. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  692. b.BatchTx().Unlock()
  693. }
  694. // TTL returns the TTL of the Lease.
  695. func (l *Lease) TTL() int64 {
  696. return l.ttl
  697. }
  698. // RemainingTTL returns the last checkpointed remaining TTL of the lease.
  699. // TODO(jpbetz): do not expose this utility method
  700. func (l *Lease) RemainingTTL() int64 {
  701. if l.remainingTTL > 0 {
  702. return l.remainingTTL
  703. }
  704. return l.ttl
  705. }
  706. // refresh refreshes the expiry of the lease.
  707. func (l *Lease) refresh(extend time.Duration) {
  708. newExpiry := time.Now().Add(extend + time.Duration(l.RemainingTTL())*time.Second)
  709. l.expiryMu.Lock()
  710. defer l.expiryMu.Unlock()
  711. l.expiry = newExpiry
  712. }
  713. // forever sets the expiry of lease to be forever.
  714. func (l *Lease) forever() {
  715. l.expiryMu.Lock()
  716. defer l.expiryMu.Unlock()
  717. l.expiry = forever
  718. }
  719. // Keys returns all the keys attached to the lease.
  720. func (l *Lease) Keys() []string {
  721. l.mu.RLock()
  722. keys := make([]string, 0, len(l.itemSet))
  723. for k := range l.itemSet {
  724. keys = append(keys, k.Key)
  725. }
  726. l.mu.RUnlock()
  727. return keys
  728. }
  729. // Remaining returns the remaining time of the lease.
  730. func (l *Lease) Remaining() time.Duration {
  731. l.expiryMu.RLock()
  732. defer l.expiryMu.RUnlock()
  733. if l.expiry.IsZero() {
  734. return time.Duration(math.MaxInt64)
  735. }
  736. return time.Until(l.expiry)
  737. }
  738. type LeaseItem struct {
  739. Key string
  740. }
  741. func int64ToBytes(n int64) []byte {
  742. bytes := make([]byte, 8)
  743. binary.BigEndian.PutUint64(bytes, uint64(n))
  744. return bytes
  745. }
  746. // FakeLessor is a fake implementation of Lessor interface.
  747. // Used for testing only.
  748. type FakeLessor struct{}
  749. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  750. func (fl *FakeLessor) SetCheckpointer(cp Checkpointer) {}
  751. func (fl *FakeLessor) Grant(id LeaseID, ttl int64) (*Lease, error) { return nil, nil }
  752. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  753. func (fl *FakeLessor) Checkpoint(id LeaseID, remainingTTL int64) error { return nil }
  754. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  755. func (fl *FakeLessor) GetLease(item LeaseItem) LeaseID { return 0 }
  756. func (fl *FakeLessor) Detach(id LeaseID, items []LeaseItem) error { return nil }
  757. func (fl *FakeLessor) Promote(extend time.Duration) {}
  758. func (fl *FakeLessor) Demote() {}
  759. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  760. func (fl *FakeLessor) Lookup(id LeaseID) *Lease { return nil }
  761. func (fl *FakeLessor) Leases() []*Lease { return nil }
  762. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  763. func (fl *FakeLessor) Recover(b backend.Backend, rd RangeDeleter) {}
  764. func (fl *FakeLessor) Stop() {}
  765. type FakeTxnDelete struct {
  766. backend.BatchTx
  767. }
  768. func (ftd *FakeTxnDelete) DeleteRange(key, end []byte) (n, rev int64) { return 0, 0 }
  769. func (ftd *FakeTxnDelete) End() { ftd.Unlock() }