Skip to content

Commit

Permalink
lease: use monotime in time.Time for Go 1.9
Browse files Browse the repository at this point in the history
The golang/time package tracks monotonic time in each time.Time
returned by time.Now function for Go 1.9.

Use time.Time to measure whether a lease is expired, instead of previous
pkg/monotime.
  • Loading branch information
lorneli committed Sep 6, 2017
1 parent 589a7a1 commit 4907186
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions lease/lessor.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,24 @@ import (
"math"
"sort"
"sync"
"sync/atomic"
"time"

"github.com/coreos/etcd/lease/leasepb"
"github.com/coreos/etcd/mvcc/backend"
"github.com/coreos/etcd/pkg/monotime"
)

const (
// NoLease is a special LeaseID representing the absence of a lease.
NoLease = LeaseID(0)

forever = monotime.Time(math.MaxInt64)
// constants from golang/time
unixTimeSeconds = int64((1969*365 + 1969/4 - 1969/100 + 1969/400) * (24 * 60 * 60))
maxNanoseconds = 999999999
)

var (
forever = time.Unix(1<<63-1-unixTimeSeconds, maxNanoseconds)

leaseBucketName = []byte("lease")

// maximum number of leases to revoke per second; configurable for tests
Expand Down Expand Up @@ -560,8 +562,10 @@ func (le *lessor) initAndRecover() {
type Lease struct {
ID LeaseID
ttl int64 // time to live in seconds
// expiry is time when lease should expire; must be 64-bit aligned.
expiry monotime.Time
// expiryMu protects concurrent accesses to expiry
expiryMu sync.RWMutex
// expiry is time when lease should expire
expiry time.Time

// mu protects concurrent accesses to itemSet
mu sync.RWMutex
Expand Down Expand Up @@ -594,12 +598,18 @@ func (l *Lease) TTL() int64 {

// refresh refreshes the expiry of the lease.
func (l *Lease) refresh(extend time.Duration) {
t := monotime.Now().Add(extend + time.Duration(l.ttl)*time.Second)
atomic.StoreUint64((*uint64)(&l.expiry), uint64(t))
newExpiry := time.Now().Add(extend + time.Duration(l.ttl)*time.Second)
l.expiryMu.Lock()
defer l.expiryMu.Unlock()
l.expiry = newExpiry
}

// forever sets the expiry of lease to be forever.
func (l *Lease) forever() { atomic.StoreUint64((*uint64)(&l.expiry), uint64(forever)) }
func (l *Lease) forever() {
l.expiryMu.Lock()
defer l.expiryMu.Unlock()
l.expiry = forever
}

// Keys returns all the keys attached to the lease.
func (l *Lease) Keys() []string {
Expand All @@ -614,8 +624,9 @@ func (l *Lease) Keys() []string {

// Remaining returns the remaining time of the lease.
func (l *Lease) Remaining() time.Duration {
t := monotime.Time(atomic.LoadUint64((*uint64)(&l.expiry)))
return time.Duration(t - monotime.Now())
l.expiryMu.RLock()
defer l.expiryMu.RUnlock()
return l.expiry.Sub(time.Now())
}

type LeaseItem struct {
Expand Down

0 comments on commit 4907186

Please sign in to comment.