void ProcessClientRequest() { this.LastClientRequest = this.ReceivedEvent as Client.Request; var log = new Log(this.CurrentTerm, this.LastClientRequest.Command); this.Logs.Add(log); this.BroadcastLastClientRequest(); }
void RespondAppendEntriesAsLeader() { var request = this.ReceivedEvent as AppendEntriesResponse; if (request.Term > this.CurrentTerm) { this.CurrentTerm = request.Term; this.VotedFor = null; this.RedirectLastClientRequestToClusterManager(); this.Raise(new BecomeFollower()); } else if (request.Term != this.CurrentTerm) { return; } if (request.Success) { this.NextIndex[request.Server] = this.Logs.Count + 1; this.MatchIndex[request.Server] = this.Logs.Count; this.VotesReceived++; if (request.ReceiverEndpoint != null && this.VotesReceived >= (this.Servers.Length / 2) + 1) { Console.WriteLine("\n [Leader] " + this.ServerId + " | term " + this.CurrentTerm + " | append votes " + this.VotesReceived + " | append success\n"); var commitIndex = this.MatchIndex[request.Server]; if (commitIndex > this.CommitIndex && this.Logs[commitIndex - 1].Term == this.CurrentTerm) { this.CommitIndex = commitIndex; Console.WriteLine("\n [Leader] " + this.ServerId + " | term " + this.CurrentTerm + " | log " + this.Logs.Count + " | command " + this.Logs[commitIndex - 1].Command + "\n"); } this.VotesReceived = 0; this.LastClientRequest = null; this.Send(request.ReceiverEndpoint, new Client.Response()); } } else { if (this.NextIndex[request.Server] > 1) { this.NextIndex[request.Server] = this.NextIndex[request.Server] - 1; } var logs = this.Logs.GetRange(this.NextIndex[request.Server] - 1, this.Logs.Count - (this.NextIndex[request.Server] - 1)); var prevLogIndex = this.NextIndex[request.Server] - 1; var prevLogTerm = this.GetLogTermForIndex(prevLogIndex); Console.WriteLine("\n [Leader] " + this.ServerId + " | term " + this.CurrentTerm + " | log " + this.Logs.Count + " | append votes " + this.VotesReceived + " | append fail (next idx = " + this.NextIndex[request.Server] + ")\n"); this.Send(request.Server, new AppendEntriesRequest(this.CurrentTerm, this.Id, prevLogIndex, prevLogTerm, logs, this.CommitIndex, request.ReceiverEndpoint)); } }