void ReplicatorStateMachine::inLeaderStateHandler( ) { dprintf( D_ALWAYS, "ReplicatorStateMachine::inLeaderStateHandler started " "with state = %d\n", int( m_state ) ); // REPLICATION_ASSERT(m_state != BACKUP) if( m_state == VERSION_REQUESTING || m_state == VERSION_DOWNLOADING) { return ; } // receiving this notification message in BACKUP state means, that the // pool version downloading took more time than it took for the HAD to // become active, in this case we act as if we received AFTER_ELECTION // message if( m_state == BACKUP ) { becomeLeader( ); return ; } m_lastHadAliveTime = time( NULL ); dprintf( D_FULLDEBUG, "ReplicatorStateMachine::inLeaderStateHandler last HAD alive time " "is set to %s", ctime( &m_lastHadAliveTime ) ); //if( downloadTransferersNumber( ) == 0 && // replicaSelectionHandler( newVersion ) ) { // download( newVersion.getSinfulString( ).Value( ) ); //} }
void RaftConsensus::becomeCandidate() { std::cout << "RaftState: become candidate" << std::endl; state_ = StateCandidate; votes_ = 0; // 删除心跳定时器 removeHeartbeatTimer(); // 开启选举超时定时器 resetElectionTimer(); ++term_; // term + 1 ++votes_; // 给自己投票 if (votes_ >= majority_) becomeLeader(); VoteRequest req; req.set_term(term_); req.set_candidateid(id_); req.set_lastlogterm(0); //TODO: set logger req.set_lastlogindex(0); for (auto& kv: peers_) { auto stub = rpc_stubs_->getStub(kv.first); if (stub) { stub->RequesetVoteAsync( req, std::bind(&RaftConsensus::handleVoteResponse, this, term_, std::placeholders::_1, std::placeholders::_2), 1000 ); } } }
void ReplicatorStateMachine::afterElectionStateHandler() { dprintf( D_ALWAYS, "ReplicatorStateMachine::afterElectionStateHandler " "started\n" ); REPLICATION_ASSERT(m_state != REPLICATION_LEADER); // we stay in VERSION_REQUESTING or VERSION_DOWNLOADING state // of newly joining node, we will go to LEADER_STATE later // upon receiving of IN_LEADER message from HAD if( m_state == VERSION_REQUESTING || m_state == VERSION_DOWNLOADING ) { return ; } becomeLeader( ); }
// src_term: 本地发起投票请求时当时本地的term void RaftConsensus::handleVoteResponse(uint64_t src_term, const VoteResponse& resp, const grpc::Status& status) { if (!status.ok() && status.error_code() != grpc::StatusCode::CANCELLED) { std::cerr << "RequestVote RPC failed: " << status.error_message() << std::endl; return; } std::lock_guard<std::mutex> lock(mu_); if (src_term != term_) { std::cout << "Mismatched term in VoteResponse:" << src_term << ", cur:" << term_ << std::endl; return; } else if (StateCandidate == state_) { if (resp.votegranted()) { ++votes_; if (votes_ >= majority_) becomeLeader(); } } //TODO }