lessor.go 12 KB

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