github.com/aergoio/aergo@v1.3.1/p2p/subproto/raftwrap.go (about)

     1  /*
     2   * @file
     3   * @copyright defined in aergo/LICENSE.txt
     4   */
     5  
     6  package subproto
     7  
     8  import (
     9  	"context"
    10  	"github.com/aergoio/aergo-lib/log"
    11  	"github.com/aergoio/aergo/consensus"
    12  	"github.com/aergoio/aergo/p2p/p2pcommon"
    13  	"github.com/aergoio/aergo/p2p/p2putil"
    14  	"github.com/aergoio/aergo/p2p/raftsupport"
    15  	"github.com/aergoio/etcd/raft/raftpb"
    16  )
    17  
    18  // receive message, decode payload to raftpb.Message and toss it to raft
    19  type raftWrapperHandler struct {
    20  	BaseMsgHandler
    21  
    22  	consAcc consensus.ConsensusAccessor
    23  }
    24  
    25  var _ p2pcommon.MessageHandler = (*raftWrapperHandler)(nil)
    26  
    27  // NewGetClusterReqHandler creates handler for PingRequest
    28  func NewRaftWrapperHandler(pm p2pcommon.PeerManager, peer p2pcommon.RemotePeer, logger *log.Logger, actor p2pcommon.ActorService, consAcc consensus.ConsensusAccessor) *raftWrapperHandler {
    29  	ph := &raftWrapperHandler{
    30  		BaseMsgHandler: BaseMsgHandler{protocol: p2pcommon.RaftWrapperMessage, pm: pm, peer: peer, actor: actor, logger: logger},
    31  		consAcc:        consAcc,
    32  	}
    33  	return ph
    34  }
    35  
    36  func (ph *raftWrapperHandler) ParsePayload(rawbytes []byte) (p2pcommon.MessageBody, error) {
    37  	return p2putil.UnmarshalAndReturn(rawbytes, &raftpb.Message{})
    38  }
    39  
    40  func (ph *raftWrapperHandler) Handle(msg p2pcommon.Message, msgBody p2pcommon.MessageBody) {
    41  	remotePeer := ph.peer
    42  	data := msgBody.(*raftpb.Message)
    43  	if ph.logger.IsDebugEnabled() &&
    44  		(data.Type != raftpb.MsgHeartbeatResp && data.Type != raftpb.MsgHeartbeat) {
    45  		DebugLogRaftWrapMsg(ph.logger, remotePeer, msg.ID(), data)
    46  	}
    47  
    48  	// toss data to raft module
    49  	if err := ph.consAcc.RaftAccessor().Process(context.TODO(), remotePeer.ID(), *data); err != nil {
    50  		ph.logger.Debug().Str(p2putil.LogPeerName, remotePeer.Name()).Err(err).Msg("error while processing raft message ")
    51  	}
    52  }
    53  
    54  func (ph *raftWrapperHandler) PostHandle(msg p2pcommon.Message, msgBody p2pcommon.MessageBody) {
    55  	data, ok := msgBody.(*raftpb.Message)
    56  	if ok && (data.Type != raftpb.MsgHeartbeatResp && data.Type != raftpb.MsgHeartbeat) {
    57  		// TODO change to show more meaningful information of raft message
    58  		ph.BaseMsgHandler.PostHandle(msg, msgBody)
    59  	}
    60  }
    61  
    62  
    63  
    64  func DebugLogRaftWrapMsg(logger *log.Logger, peer p2pcommon.RemotePeer, msgID p2pcommon.MsgID, body *raftpb.Message) {
    65  	logger.Debug().Str(p2putil.LogMsgID, msgID.String()).Str("from_peer", peer.Name()).Object("raftMsg", raftsupport.RaftMsgMarshaller{body}).Msg("Received raft message")
    66  }
    67  
    68