lessor.go 13 KB

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