github.com/aergoio/aergo@v1.3.1/p2p/raftsupport/status.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package raftsupport
     7  
     8  import (
     9  	"github.com/aergoio/aergo-lib/log"
    10  	"github.com/aergoio/aergo/p2p/p2putil"
    11  	"github.com/aergoio/aergo/types"
    12  	rtypes "github.com/aergoio/etcd/pkg/types"
    13  	"sync"
    14  	"time"
    15  )
    16  
    17  
    18  type rPeerStatus struct {
    19  	logger *log.Logger
    20  	id     rtypes.ID
    21  	pid    types.PeerID
    22  	mu     sync.Mutex // protect variables below
    23  	active bool
    24  	since  time.Time
    25  }
    26  
    27  func newPeerStatus(id rtypes.ID, pid types.PeerID, logger *log.Logger) *rPeerStatus {
    28  	return &rPeerStatus{
    29  		id: id, pid: pid, logger:logger,
    30  	}
    31  }
    32  
    33  func (s *rPeerStatus) activate() {
    34  	s.mu.Lock()
    35  	defer s.mu.Unlock()
    36  	if !s.active {
    37  		s.logger.Info().Str(p2putil.LogPeerID, p2putil.ShortForm(s.pid)).Str("raftID", s.id.String()).Msgf("peer became active")
    38  		s.active = true
    39  		s.since = time.Now()
    40  	} else {
    41  		s.logger.Debug().Str(p2putil.LogPeerID, p2putil.ShortForm(s.pid)).Str("raftID", s.id.String()).Msgf("activate called to already active peer")
    42  	}
    43  }
    44  
    45  func (s *rPeerStatus) deactivate(cause string) {
    46  	s.mu.Lock()
    47  	defer s.mu.Unlock()
    48  
    49  	if s.active {
    50  		s.logger.Info().Str("cause",cause).Str(p2putil.LogPeerID, p2putil.ShortForm(s.pid)).Str("raftID", s.id.String()).Msgf("peer became inactive")
    51  
    52  		s.active = false
    53  		s.since = time.Time{}
    54  	} else {
    55  		s.logger.Debug().Str("cause",cause).Str(p2putil.LogPeerID, p2putil.ShortForm(s.pid)).Str("raftID", s.id.String()).Msgf("deactivate called to already inactive peer")
    56  	}
    57  }
    58  
    59  func (s *rPeerStatus) isActive() bool {
    60  	s.mu.Lock()
    61  	defer s.mu.Unlock()
    62  	return s.active
    63  }
    64  
    65  func (s *rPeerStatus) activeSince() time.Time {
    66  	s.mu.Lock()
    67  	defer s.mu.Unlock()
    68  	return s.since
    69  }
    70