lessor.go 13 KB

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