lessor.go 12 KB

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