etcd/lease/lessor.go

247 lines
6.1 KiB
Go
Raw Normal View History

2015-11-08 22:15:39 +03:00
// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package lease
import (
"encoding/binary"
2015-11-08 22:15:39 +03:00
"fmt"
"sync"
"time"
"github.com/coreos/etcd/lease/leasepb"
2015-11-08 22:15:39 +03:00
"github.com/coreos/etcd/pkg/idutil"
"github.com/coreos/etcd/storage/backend"
2015-11-08 22:15:39 +03:00
)
var (
minLeaseTerm = 5 * time.Second
leaseBucketName = []byte("lease")
2015-11-08 22:15:39 +03:00
)
2016-01-05 21:16:50 +03:00
type LeaseID int64
// DeleteableRange defines an interface with DeleteRange method.
// We define this interface only for lessor to limit the number
// of methods of storage.KV to what lessor actually needs.
//
// Having a minimum interface makes testing easy.
type DeleteableRange interface {
DeleteRange(key, end []byte) (int64, int64)
}
2015-11-08 22:15:39 +03:00
// a lessor is the owner of leases. It can grant, revoke,
// renew and modify leases for lessee.
// TODO: use clockwork for testability.
type lessor struct {
mu sync.Mutex
// TODO: probably this should be a heap with a secondary
// id index.
// Now it is O(N) to loop over the leases to find expired ones.
// We want to make Grant, Revoke, and FindExpired all O(logN) and
// Renew O(1).
// FindExpired and Renew should be the most frequent operations.
2016-01-05 21:16:50 +03:00
leaseMap map[LeaseID]*lease
2015-11-08 22:15:39 +03:00
// A DeleteableRange the lessor operates on.
// When a lease expires, the lessor will delete the
// leased range (or key) from the DeleteableRange.
dr DeleteableRange
// backend to persist leases. We only persist lease ID and expiry for now.
// The leased items can be recovered by iterating all the keys in kv.
b backend.Backend
2015-11-08 22:15:39 +03:00
idgen *idutil.Generator
}
func NewLessor(lessorID uint8, b backend.Backend, dr DeleteableRange) *lessor {
l := &lessor{
2016-01-05 21:16:50 +03:00
leaseMap: make(map[LeaseID]*lease),
b: b,
dr: dr,
2015-11-08 22:15:39 +03:00
idgen: idutil.NewGenerator(lessorID, time.Now()),
}
tx := l.b.BatchTx()
tx.Lock()
tx.UnsafeCreateBucket(leaseBucketName)
tx.Unlock()
l.b.ForceCommit()
// TODO: recover from previous state in backend.
return l
2015-11-08 22:15:39 +03:00
}
// Grant grants a lease that expires at least after TTL seconds.
// TODO: when lessor is under high load, it should give out lease
// with longer TTL to reduce renew load.
func (le *lessor) Grant(ttl int64) *lease {
// TODO: define max TTL
expiry := time.Now().Add(time.Duration(ttl) * time.Second)
2015-11-08 22:15:39 +03:00
expiry = minExpiry(time.Now(), expiry)
2016-01-05 21:16:50 +03:00
id := LeaseID(le.idgen.Next())
2015-11-08 22:15:39 +03:00
le.mu.Lock()
defer le.mu.Unlock()
l := &lease{id: id, ttl: ttl, expiry: expiry, itemSet: make(map[leaseItem]struct{})}
2015-11-08 22:15:39 +03:00
if _, ok := le.leaseMap[id]; ok {
panic("lease: unexpected duplicate ID!")
}
le.leaseMap[id] = l
l.persistTo(le.b)
2015-11-08 22:15:39 +03:00
return l
}
// Revoke revokes a lease with given ID. The item attached to the
// given lease will be removed. If the ID does not exist, an error
// will be returned.
2016-01-05 21:16:50 +03:00
func (le *lessor) Revoke(id LeaseID) error {
2015-11-08 22:15:39 +03:00
le.mu.Lock()
defer le.mu.Unlock()
l := le.leaseMap[id]
if l == nil {
return fmt.Errorf("lease: cannot find lease %x", id)
}
for item := range l.itemSet {
le.dr.DeleteRange([]byte(item.key), nil)
}
delete(le.leaseMap, l.id)
l.removeFrom(le.b)
2015-11-08 22:15:39 +03:00
return nil
}
// Renew renews an existing lease. If the given lease does not exist or
// has expired, an error will be returned.
// TODO: return new TTL?
2016-01-05 21:16:50 +03:00
func (le *lessor) Renew(id LeaseID) error {
2015-11-08 22:15:39 +03:00
le.mu.Lock()
defer le.mu.Unlock()
l := le.leaseMap[id]
if l == nil {
return fmt.Errorf("lease: cannot find lease %x", id)
}
expiry := time.Now().Add(time.Duration(l.ttl) * time.Second)
2015-11-08 22:15:39 +03:00
l.expiry = minExpiry(time.Now(), expiry)
return nil
}
// Attach attaches items to the lease with given ID. When the lease
// expires, the attached items will be automatically removed.
// If the given lease does not exist, an error will be returned.
2016-01-05 21:16:50 +03:00
func (le *lessor) Attach(id LeaseID, items []leaseItem) error {
2015-11-08 22:15:39 +03:00
le.mu.Lock()
defer le.mu.Unlock()
l := le.leaseMap[id]
if l == nil {
return fmt.Errorf("lease: cannot find lease %x", id)
}
for _, it := range items {
l.itemSet[it] = struct{}{}
}
return nil
}
// findExpiredLeases loops all the leases in the leaseMap and returns the expired
// leases that needed to be revoked.
func (le *lessor) findExpiredLeases() []*lease {
le.mu.Lock()
defer le.mu.Unlock()
leases := make([]*lease, 0, 16)
now := time.Now()
for _, l := range le.leaseMap {
if l.expiry.Sub(now) <= 0 {
leases = append(leases, l)
}
}
return leases
}
// get gets the lease with given id.
// get is a helper fucntion for testing, at least for now.
2016-01-05 21:16:50 +03:00
func (le *lessor) get(id LeaseID) *lease {
2015-11-08 22:15:39 +03:00
le.mu.Lock()
defer le.mu.Unlock()
return le.leaseMap[id]
}
type lease struct {
2016-01-05 21:16:50 +03:00
id LeaseID
ttl int64 // time to live in seconds
2015-11-08 22:15:39 +03:00
itemSet map[leaseItem]struct{}
// expiry time in unixnano
expiry time.Time
}
func (l lease) persistTo(b backend.Backend) {
2016-01-05 21:16:50 +03:00
key := int64ToBytes(int64(l.id))
2016-01-05 21:16:50 +03:00
lpb := leasepb.Lease{ID: int64(l.id), TTL: int64(l.ttl)}
val, err := lpb.Marshal()
if err != nil {
panic("failed to marshal lease proto item")
}
b.BatchTx().Lock()
b.BatchTx().UnsafePut(leaseBucketName, key, val)
b.BatchTx().Unlock()
}
func (l lease) removeFrom(b backend.Backend) {
2016-01-05 21:16:50 +03:00
key := int64ToBytes(int64(l.id))
b.BatchTx().Lock()
b.BatchTx().UnsafeDelete(leaseBucketName, key)
b.BatchTx().Unlock()
}
2015-11-08 22:15:39 +03:00
type leaseItem struct {
key string
2015-11-08 22:15:39 +03:00
}
// minExpiry returns a minimal expiry. A minimal expiry is the larger on
// between now + minLeaseTerm and the given expectedExpiry.
func minExpiry(now time.Time, expectedExpiry time.Time) time.Time {
minExpiry := time.Now().Add(minLeaseTerm)
if expectedExpiry.Sub(minExpiry) < 0 {
expectedExpiry = minExpiry
}
return expectedExpiry
}
func int64ToBytes(n int64) []byte {
bytes := make([]byte, 8)
binary.BigEndian.PutUint64(bytes, uint64(n))
return bytes
}