lessor.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. "time"
  22. "github.com/coreos/etcd/lease/leasepb"
  23. "github.com/coreos/etcd/mvcc/backend"
  24. )
  25. const (
  26. // NoLease is a special LeaseID representing the absence of a lease.
  27. NoLease = LeaseID(0)
  28. )
  29. var (
  30. leaseBucketName = []byte("lease")
  31. // do not use maxInt64 since it can overflow time which will add
  32. // the offset of unix time (1970yr to seconds).
  33. forever = time.Unix(math.MaxInt64>>1, 0)
  34. ErrNotPrimary = errors.New("not a primary lessor")
  35. ErrLeaseNotFound = errors.New("lease not found")
  36. ErrLeaseExists = errors.New("lease already exists")
  37. )
  38. type LeaseID int64
  39. // RangeDeleter defines an interface with Txn and DeleteRange method.
  40. // We define this interface only for lessor to limit the number
  41. // of methods of mvcc.KV to what lessor actually needs.
  42. //
  43. // Having a minimum interface makes testing easy.
  44. type RangeDeleter interface {
  45. // TxnBegin see comments on mvcc.KV
  46. TxnBegin() int64
  47. // TxnEnd see comments on mvcc.KV
  48. TxnEnd(txnID int64) error
  49. // TxnDeleteRange see comments on mvcc.KV
  50. TxnDeleteRange(txnID int64, key, end []byte) (n, rev int64, err error)
  51. }
  52. // Lessor owns leases. It can grant, revoke, renew and modify leases for lessee.
  53. type Lessor interface {
  54. // SetRangeDeleter sets the RangeDeleter to the Lessor.
  55. // Lessor deletes the items in the revoked or expired lease from the
  56. // the set RangeDeleter.
  57. SetRangeDeleter(dr RangeDeleter)
  58. // Grant grants a lease that expires at least after TTL seconds.
  59. Grant(id LeaseID, ttl int64) (*Lease, error)
  60. // Revoke revokes a lease with given ID. The item attached to the
  61. // given lease will be removed. If the ID does not exist, an error
  62. // will be returned.
  63. Revoke(id LeaseID) error
  64. // Attach attaches given leaseItem to the lease with given LeaseID.
  65. // If the lease does not exist, an error will be returned.
  66. Attach(id LeaseID, items []LeaseItem) error
  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. // When a lease expires, the lessor will delete the
  104. // leased range (or key) by the RangeDeleter.
  105. rd RangeDeleter
  106. // backend to persist leases. We only persist lease ID and expiry for now.
  107. // The leased items can be recovered by iterating all the keys in kv.
  108. b backend.Backend
  109. // minLeaseTTL is the minimum lease TTL that can be granted for a lease. Any
  110. // requests for shorter TTLs are extended to the minimum TTL.
  111. minLeaseTTL int64
  112. expiredC chan []*Lease
  113. // stopC is a channel whose closure indicates that the lessor should be stopped.
  114. stopC chan struct{}
  115. // doneC is a channel whose closure indicates that the lessor is stopped.
  116. doneC chan struct{}
  117. }
  118. func NewLessor(b backend.Backend, minLeaseTTL int64) Lessor {
  119. return newLessor(b, minLeaseTTL)
  120. }
  121. func newLessor(b backend.Backend, minLeaseTTL int64) *lessor {
  122. l := &lessor{
  123. leaseMap: make(map[LeaseID]*Lease),
  124. b: b,
  125. minLeaseTTL: minLeaseTTL,
  126. // expiredC is a small buffered chan to avoid unnecessary blocking.
  127. expiredC: make(chan []*Lease, 16),
  128. stopC: make(chan struct{}),
  129. doneC: make(chan struct{}),
  130. }
  131. l.initAndRecover()
  132. go l.runLoop()
  133. return l
  134. }
  135. // isPrimary indicates if this lessor is the primary lessor. The primary
  136. // lessor manages lease expiration and renew.
  137. //
  138. // in etcd, raft leader is the primary. Thus there might be two primary
  139. // leaders at the same time (raft allows concurrent leader but with different term)
  140. // for at most a leader election timeout.
  141. // The old primary leader cannot affect the correctness since its proposal has a
  142. // smaller term and will not be committed.
  143. //
  144. // TODO: raft follower do not forward lease management proposals. There might be a
  145. // very small window (within second normally which depends on go scheduling) that
  146. // a raft follow is the primary between the raft leader demotion and lessor demotion.
  147. // Usually this should not be a problem. Lease should not be that sensitive to timing.
  148. func (le *lessor) isPrimary() bool {
  149. return le.demotec != nil
  150. }
  151. func (le *lessor) SetRangeDeleter(rd RangeDeleter) {
  152. le.mu.Lock()
  153. defer le.mu.Unlock()
  154. le.rd = rd
  155. }
  156. func (le *lessor) Grant(id LeaseID, ttl int64) (*Lease, error) {
  157. if id == NoLease {
  158. return nil, ErrLeaseNotFound
  159. }
  160. // TODO: when lessor is under high load, it should give out lease
  161. // with longer TTL to reduce renew load.
  162. l := &Lease{
  163. ID: id,
  164. TTL: ttl,
  165. itemSet: make(map[LeaseItem]struct{}),
  166. revokec: make(chan struct{}),
  167. }
  168. le.mu.Lock()
  169. defer le.mu.Unlock()
  170. if _, ok := le.leaseMap[id]; ok {
  171. return nil, ErrLeaseExists
  172. }
  173. if l.TTL < le.minLeaseTTL {
  174. l.TTL = le.minLeaseTTL
  175. }
  176. if le.isPrimary() {
  177. l.refresh(0)
  178. } else {
  179. l.forever()
  180. }
  181. le.leaseMap[id] = l
  182. l.persistTo(le.b)
  183. return l, nil
  184. }
  185. func (le *lessor) Revoke(id LeaseID) error {
  186. le.mu.Lock()
  187. l := le.leaseMap[id]
  188. if l == nil {
  189. le.mu.Unlock()
  190. return ErrLeaseNotFound
  191. }
  192. defer close(l.revokec)
  193. // unlock before doing external work
  194. le.mu.Unlock()
  195. if le.rd == nil {
  196. return nil
  197. }
  198. tid := le.rd.TxnBegin()
  199. // sort keys so deletes are in same order among all members,
  200. // otherwise the backened hashes will be different
  201. keys := make([]string, 0, len(l.itemSet))
  202. for item := range l.itemSet {
  203. keys = append(keys, item.Key)
  204. }
  205. sort.StringSlice(keys).Sort()
  206. for _, key := range keys {
  207. _, _, err := le.rd.TxnDeleteRange(tid, []byte(key), nil)
  208. if err != nil {
  209. panic(err)
  210. }
  211. }
  212. le.mu.Lock()
  213. defer le.mu.Unlock()
  214. delete(le.leaseMap, l.ID)
  215. // lease deletion needs to be in the same backend transaction with the
  216. // kv deletion. Or we might end up with not executing the revoke or not
  217. // deleting the keys if etcdserver fails in between.
  218. le.b.BatchTx().UnsafeDelete(leaseBucketName, int64ToBytes(int64(l.ID)))
  219. err := le.rd.TxnEnd(tid)
  220. if err != nil {
  221. panic(err)
  222. }
  223. return nil
  224. }
  225. // Renew renews an existing lease. If the given lease does not exist or
  226. // has expired, an error will be returned.
  227. func (le *lessor) Renew(id LeaseID) (int64, error) {
  228. le.mu.Lock()
  229. unlock := func() { le.mu.Unlock() }
  230. defer func() { unlock() }()
  231. if !le.isPrimary() {
  232. // forward renew request to primary instead of returning error.
  233. return -1, ErrNotPrimary
  234. }
  235. demotec := le.demotec
  236. l := le.leaseMap[id]
  237. if l == nil {
  238. return -1, ErrLeaseNotFound
  239. }
  240. if l.expired() {
  241. le.mu.Unlock()
  242. unlock = func() {}
  243. select {
  244. // A expired lease might be pending for revoking or going through
  245. // quorum to be revoked. To be accurate, renew request must wait for the
  246. // deletion to complete.
  247. case <-l.revokec:
  248. return -1, ErrLeaseNotFound
  249. // The expired lease might fail to be revoked if the primary changes.
  250. // The caller will retry on ErrNotPrimary.
  251. case <-demotec:
  252. return -1, ErrNotPrimary
  253. case <-le.stopC:
  254. return -1, ErrNotPrimary
  255. }
  256. }
  257. l.refresh(0)
  258. return l.TTL, nil
  259. }
  260. func (le *lessor) Lookup(id LeaseID) *Lease {
  261. le.mu.Lock()
  262. defer le.mu.Unlock()
  263. return le.leaseMap[id]
  264. }
  265. func (le *lessor) Promote(extend time.Duration) {
  266. le.mu.Lock()
  267. defer le.mu.Unlock()
  268. le.demotec = make(chan struct{})
  269. // refresh the expiries of all leases.
  270. for _, l := range le.leaseMap {
  271. l.refresh(extend)
  272. }
  273. }
  274. func (le *lessor) Demote() {
  275. le.mu.Lock()
  276. defer le.mu.Unlock()
  277. // set the expiries of all leases to forever
  278. for _, l := range le.leaseMap {
  279. l.forever()
  280. }
  281. if le.demotec != nil {
  282. close(le.demotec)
  283. le.demotec = nil
  284. }
  285. }
  286. // Attach attaches items to the lease with given ID. When the lease
  287. // expires, the attached items will be automatically removed.
  288. // If the given lease does not exist, an error will be returned.
  289. func (le *lessor) Attach(id LeaseID, items []LeaseItem) error {
  290. le.mu.Lock()
  291. defer le.mu.Unlock()
  292. l := le.leaseMap[id]
  293. if l == nil {
  294. return ErrLeaseNotFound
  295. }
  296. for _, it := range items {
  297. l.itemSet[it] = struct{}{}
  298. }
  299. return nil
  300. }
  301. // Detach detaches items from the lease with given ID.
  302. // If the given lease does not exist, an error will be returned.
  303. func (le *lessor) Detach(id LeaseID, items []LeaseItem) error {
  304. le.mu.Lock()
  305. defer le.mu.Unlock()
  306. l := le.leaseMap[id]
  307. if l == nil {
  308. return ErrLeaseNotFound
  309. }
  310. for _, it := range items {
  311. delete(l.itemSet, it)
  312. }
  313. return nil
  314. }
  315. func (le *lessor) Recover(b backend.Backend, rd RangeDeleter) {
  316. le.mu.Lock()
  317. defer le.mu.Unlock()
  318. le.b = b
  319. le.rd = rd
  320. le.leaseMap = make(map[LeaseID]*Lease)
  321. le.initAndRecover()
  322. }
  323. func (le *lessor) ExpiredLeasesC() <-chan []*Lease {
  324. return le.expiredC
  325. }
  326. func (le *lessor) Stop() {
  327. close(le.stopC)
  328. <-le.doneC
  329. }
  330. func (le *lessor) runLoop() {
  331. defer close(le.doneC)
  332. for {
  333. var ls []*Lease
  334. le.mu.Lock()
  335. if le.isPrimary() {
  336. ls = le.findExpiredLeases()
  337. }
  338. le.mu.Unlock()
  339. if len(ls) != 0 {
  340. select {
  341. case <-le.stopC:
  342. return
  343. case le.expiredC <- ls:
  344. default:
  345. // the receiver of expiredC is probably busy handling
  346. // other stuff
  347. // let's try this next time after 500ms
  348. }
  349. }
  350. select {
  351. case <-time.After(500 * time.Millisecond):
  352. case <-le.stopC:
  353. return
  354. }
  355. }
  356. }
  357. // findExpiredLeases loops all the leases in the leaseMap and returns the expired
  358. // leases that needed to be revoked.
  359. func (le *lessor) findExpiredLeases() []*Lease {
  360. leases := make([]*Lease, 0, 16)
  361. for _, l := range le.leaseMap {
  362. // TODO: probably should change to <= 100-500 millisecond to
  363. // make up committing latency.
  364. if l.expired() {
  365. leases = append(leases, l)
  366. }
  367. }
  368. return leases
  369. }
  370. func (le *lessor) initAndRecover() {
  371. tx := le.b.BatchTx()
  372. tx.Lock()
  373. tx.UnsafeCreateBucket(leaseBucketName)
  374. _, vs := tx.UnsafeRange(leaseBucketName, int64ToBytes(0), int64ToBytes(math.MaxInt64), 0)
  375. // TODO: copy vs and do decoding outside tx lock if lock contention becomes an issue.
  376. for i := range vs {
  377. var lpb leasepb.Lease
  378. err := lpb.Unmarshal(vs[i])
  379. if err != nil {
  380. tx.Unlock()
  381. panic("failed to unmarshal lease proto item")
  382. }
  383. ID := LeaseID(lpb.ID)
  384. if lpb.TTL < le.minLeaseTTL {
  385. lpb.TTL = le.minLeaseTTL
  386. }
  387. le.leaseMap[ID] = &Lease{
  388. ID: ID,
  389. TTL: lpb.TTL,
  390. // itemSet will be filled in when recover key-value pairs
  391. // set expiry to forever, refresh when promoted
  392. itemSet: make(map[LeaseItem]struct{}),
  393. expiry: forever,
  394. revokec: make(chan struct{}),
  395. }
  396. }
  397. tx.Unlock()
  398. le.b.ForceCommit()
  399. }
  400. type Lease struct {
  401. ID LeaseID
  402. TTL int64 // time to live in seconds
  403. itemSet map[LeaseItem]struct{}
  404. // expiry time in unixnano
  405. expiry time.Time
  406. revokec chan struct{}
  407. }
  408. func (l Lease) expired() bool {
  409. return l.Remaining() <= 0
  410. }
  411. func (l Lease) persistTo(b backend.Backend) {
  412. key := int64ToBytes(int64(l.ID))
  413. lpb := leasepb.Lease{ID: int64(l.ID), TTL: int64(l.TTL)}
  414. val, err := lpb.Marshal()
  415. if err != nil {
  416. panic("failed to marshal lease proto item")
  417. }
  418. b.BatchTx().Lock()
  419. b.BatchTx().UnsafePut(leaseBucketName, key, val)
  420. b.BatchTx().Unlock()
  421. }
  422. // refresh refreshes the expiry of the lease.
  423. func (l *Lease) refresh(extend time.Duration) {
  424. l.expiry = time.Now().Add(extend + time.Second*time.Duration(l.TTL))
  425. }
  426. // forever sets the expiry of lease to be forever.
  427. func (l *Lease) forever() { l.expiry = forever }
  428. // Keys returns all the keys attached to the lease.
  429. func (l *Lease) Keys() []string {
  430. keys := make([]string, 0, len(l.itemSet))
  431. for k := range l.itemSet {
  432. keys = append(keys, k.Key)
  433. }
  434. return keys
  435. }
  436. // Remaining returns the remaining time of the lease.
  437. func (l *Lease) Remaining() time.Duration {
  438. return l.expiry.Sub(time.Now())
  439. }
  440. type LeaseItem struct {
  441. Key string
  442. }
  443. func int64ToBytes(n int64) []byte {
  444. bytes := make([]byte, 8)
  445. binary.BigEndian.PutUint64(bytes, uint64(n))
  446. return bytes
  447. }
  448. // FakeLessor is a fake implementation of Lessor interface.
  449. // Used for testing only.
  450. type FakeLessor struct{}
  451. func (fl *FakeLessor) SetRangeDeleter(dr RangeDeleter) {}
  452. func (fl *FakeLessor) Grant(id LeaseID, ttl int64) (*Lease, error) { return nil, nil }
  453. func (fl *FakeLessor) Revoke(id LeaseID) error { return nil }
  454. func (fl *FakeLessor) Attach(id LeaseID, items []LeaseItem) error { return nil }
  455. func (fl *FakeLessor) Detach(id LeaseID, items []LeaseItem) error { return nil }
  456. func (fl *FakeLessor) Promote(extend time.Duration) {}
  457. func (fl *FakeLessor) Demote() {}
  458. func (fl *FakeLessor) Renew(id LeaseID) (int64, error) { return 10, nil }
  459. func (le *FakeLessor) Lookup(id LeaseID) *Lease { return nil }
  460. func (fl *FakeLessor) ExpiredLeasesC() <-chan []*Lease { return nil }
  461. func (fl *FakeLessor) Recover(b backend.Backend, rd RangeDeleter) {}
  462. func (fl *FakeLessor) Stop() {}