lessor.go 13 KB

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