BUGFIX: Use atomic reads/writes for heartbeats.

This commit is contained in:
Tyler Smith 2020-05-07 13:27:18 -07:00
parent 14daa76e92
commit 99aa6d3724
No known key found for this signature in database
GPG Key ID: CA38F1A9BE0EC890
2 changed files with 8 additions and 7 deletions

View File

@ -53,7 +53,7 @@ func (c gosundheitCheck) Execute() (interface{}, error) { return c.checkFn() }
// heartbeater provides a getter to the most recently observed heartbeat
type heartbeater interface {
GetHeartbeat() time.Time
GetHeartbeat() int64
}
// HeartbeatCheckFn returns a CheckFn that checks the given heartbeater has
@ -62,11 +62,11 @@ func HeartbeatCheckFn(hb heartbeater, max time.Duration) CheckFn {
return func() (data interface{}, err error) {
// Get the heartbeat and create a data set to return to the caller
hb := hb.GetHeartbeat()
data = map[string]int64{"heartbeat": hb.UTC().Unix()}
data = map[string]int64{"heartbeat": hb}
// If the current time is after the last known heartbeat + the limit then
// mark our check as failed
if hb.Add(max).Before(time.Now()) {
if time.Unix(hb, 0).Add(max).Before(time.Now()) {
err = ErrHeartbeatNotDetected
}
return data, err

View File

@ -22,6 +22,7 @@ import (
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unsafe"
@ -148,7 +149,7 @@ type Handshake struct {
awaitingLock sync.Mutex
awaiting []*networking.AwaitingConnections
lastHeartbeat time.Time
lastHeartbeat int64
}
// Initialize to the c networking library. This should only be done once during
@ -599,12 +600,12 @@ func (nm *Handshake) checkCompatibility(peerVersion string) bool {
// heartbeat registers a new heartbeat to signal liveness
func (nm *Handshake) heartbeat() {
nm.lastHeartbeat = nm.clock.Time()
atomic.StoreInt64(&nm.lastHeartbeat, nm.clock.Time().Unix())
}
// GetHeartbeat returns the most recent heartbeat time
func (nm *Handshake) GetHeartbeat() time.Time {
return nm.lastHeartbeat
func (nm *Handshake) GetHeartbeat() int64 {
return atomic.LoadInt64(&nm.lastHeartbeat)
}
// peerHandler notifies a change to the set of connected peers