Пример #1
0
        private void RequestVote()
        {
            _stateController.UpdateTerm(_stateController.PersistentState.CurrentTerm + 1);
            DebugConsole.WriteLine($"Starting election ... term :{_stateController.PersistentState.CurrentTerm}" + Environment.NewLine);
            //Vote for current object
            int  votes            = 1;
            bool transferedLeader = false;

            List <Task> taskList      = new List <Task>();
            int         majorityCount = _node.Peers.Count;

            foreach (Peer peer in _node.Peers)
            {
                Task task = Task.Run(() =>
                {
                    try
                    {
                        VoteResponse response = RequestVoteCore(peer.RemoteClient);
                        if (_node.EnsureExistGreaterTermAndChangeRole(response.Term))
                        {
                            return;
                        }

                        if (response.VoteGranted)
                        {
                            lock (_transferedLeaderLockObj)
                            {
                                votes += 1;
                                if (!transferedLeader && votes > majorityCount / 2 + 1)
                                {
                                    transferedLeader = true;
                                    _node.ChangeRole(RoleType.Leader);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugConsole.WriteLine($"{ex.Message}");
                    }
                });
                taskList.Add(task);
            }
            Task.WaitAll(taskList.ToArray());
        }
Пример #2
0
        public VoteResponse GetVote(VoteReqeust request)
        {
            VoteResponse    response = new VoteResponse();
            PersistentState state    = _stateController.PersistentState;

            if (request.Term < state.CurrentTerm)
            {
                response.VoteGranted = false;
            }
            else if ((string.IsNullOrEmpty(state.VotedFor) || state.VotedFor == request.CandidateId) && request.LastLogTerm >= state.LastLogTerm && request.LastLogIndex >= state.LastLogIndex)
            {
                _stateController.UpdateVoteFor(request.CandidateId);
                response.VoteGranted = true;
                DebugConsole.WriteLine($"Voting for candidate {request.CandidateId} for term {request.Term}...");
            }
            response.Term = state.CurrentTerm;
            return(response);
        }