Пример #1
0
        public AppendEntriesResponse AppendEntry(AppendEntriesRequest requestVote)
        {
            var electTime = ElectionTimeout;

            Election.Change(electTime, Timeout.Infinite);
            lock (_lockObject)
            {
                Peer.MyState.ThisServerInfo.PersistedState.SavePeerState(Peer.MyState);
                foreach (var peer in Peer.MyState.PeerlList)
                {
                    peer.Value.Persist(Peer.MyState.ThisServerInfo);
                }

                var differentStateOrLeader = Peer.MyState.CurrentState != CurrentServerState.Follower ||
                                             Peer.MyState.Leader != null && Peer.MyState.Leader.Id != requestVote.Leader.Id;
                if (requestVote.Term > Peer.MyState.CurrentTerm || Peer.MyState.CurrentTerm <= requestVote.Term && differentStateOrLeader)
                {
                    WriteLine($"Server {Peer.MyState.Id} is reverting to follower from {Peer.MyState.CurrentState}");
                    Peer.MyState.CurrentTerm  = requestVote.Term;
                    Peer.MyState.CurrentState = CurrentServerState.Follower;
                    Peer.MyState.Leader       = requestVote.Leader;
                }
                var success = GrantSuccess(requestVote);

                return(new AppendEntriesResponse(Peer.MyState.CurrentTerm, success, Peer.MyState.ThisServerInfo.Id));
            }
        }
Пример #2
0
 public ResponseVote GetVote(RequestVote requestVote)
 {
     lock (_lockObject)
     {
         Peer.MyState.ThisServerInfo.PersistedState.SavePeerState(Peer.MyState);
         if (requestVote.Term > Peer.MyState.CurrentTerm || (Peer.MyState.CurrentState == CurrentServerState.Candidate &&
                                                             Peer.MyState.CurrentTerm <= requestVote.Term))
         {
             WriteLine($"Server {Peer.MyState.Id} is reverting to follower from {Peer.MyState.CurrentState}");
             Peer.MyState.CurrentTerm  = requestVote.Term;
             Peer.MyState.CurrentState = CurrentServerState.Follower;
         }
         var voteGranted = GrantVote(requestVote);
         if (!voteGranted)
         {
             return(new ResponseVote(Peer.MyState.CurrentTerm, false));
         }
         Peer.MyState.VotedForId = requestVote.CandidateId;
         var electTime = ElectionTimeout;
         Election.Change(electTime, Timeout.Infinite);
     }
     return(new ResponseVote(Peer.MyState.CurrentTerm, true));
 }