Example #1
0
 public VoteBackStruct voteForMe(int term, int CandidateId, int lastLogIdx, int lastLogTerm)
 {
     lock (this)
     {
         VoteBackStruct ret = new VoteBackStruct();
         ret.Term        = term_;
         ret.VoteGranted = false;
         if (term > term_) // recv higher term request
         {
             Console.WriteLine(String.Format("{0} [{1}] voted in term {2}, recv_term {3} from {4}, isVoteInThisTerm_ {5}!", id, role, term, term, CandidateId, isVoteInThisTerm_));
             role_             = NodeRole.Follower;
             state_            = ServerState.HigherTerm;
             term_             = term;
             isVoteInThisTerm_ = false;
             if (lastLogTerm < getLastLogTerm()) //log最后的term比我小
             {
                 return(ret);
             }
             if (lastLogTerm == getLastLogTerm() && lastLogIdx < log_.Count) //log最后的term和我一样,但是log没有我多
             {
                 return(ret);
             }
             //if(timeout_timer_ != null)
             //    timeout_timer_.Change(curRandTime_, curRandTime_);
             ret.VoteGranted = isVoteInThisTerm_ = true;
             return(ret);
         }
         else
         {
             ret.VoteGranted = false;
             return(ret);
         }
     }
 }
Example #2
0
        public ElectionState candidate_vote_sender()
        {
            LOG(String.Format("term {0} calling for votes", term));

            int            alive_num = 1;
            int            votes     = 1;
            VoteBackStruct ret       = new VoteBackStruct();

            foreach (ClusterNodeSocket node in ExClusterNodeList_)
            {
                try
                {
                    if (node.transport.IsOpen)
                    {
                        ++alive_num;
                        ret = node.client.voteForMe(term, id, log_.Count, getLastLogTerm());
                        if (ret.VoteGranted)
                        {
                            ++votes;
                        }
                        if (ret.Term > term)
                        {
                            return(ElectionState.HigherTerm);
                        }
                        //Console.WriteLine(String.Format("{0} [{1}] term {2} calling for votes", ID, curRole_, curTerm_));
                    }
                }
                catch (Exception ex)
                {
                    LOG(String.Format("get votes error! {0} {1}", leader_should_stop_, ex.Message));
                    if (leader_should_stop_)
                    {
                        return(ElectionState.Stop);
                    }
                }
            }
            LOG(String.Format("get votes {0}", votes));
            if (votes > alive_num / 2)
            {
                return(ElectionState.ElectionSuccess);
            }
            else
            {
                return(ElectionState.ElectionFailed);
            }
        }