// 先定义 Leader 选举所需要的数据,Log 需要的数据在 2B 中实现。 type Raft struct { mu sync.Mutex // Lock to protect shared access to this peer's state peers []*labrpc.ClientEnd // RPC end points of all peers persister *Persister // Object to hold this peer's persisted state me int// this peer's index into peers[] dead int32// set by Kill()
// Persistent state on all servers. state string// what state of the server (Follower, Candidate, Leader) currentTerm int// latest term server has seen (initialized to 0) voteFor int// candidateId that received vote in current term (or -1 if none) logs []Entry // log entries, each entry contains command and term.
electionTimeout *time.Timer // time of election timeout, random value heartbeatsTimeout *time.Timer // time of heartbeat timeout, fixed value (120ms) }
// 下面两个是与 RequestVote RPC 相关的定义,也和图 2 给出的一致 type RequestVoteArgs struct { // Your data here (2A, 2B). Term int// candidate’s term CandidateId int// candidate requesting vote LastLogIndex int// index of candidate’s last log entry LastLogTerm int// term of candidate’s last log entry }
type RequestVoteReply struct { // Your data here (2A). Term int// current term of other servers, for candidate to update its term if necessary VoteGranted bool// true means that me agree candidateId to be leader }
/* 先定义好 AppendEntries RPC,因为需要 Leader 发送 heartbeat */ type AppendEntriesArgs struct { Term int// leader’s term LeadId int// follower can redirect clients }
type AppendEntriesReply struct { Term int// currentTerm, for leader to update itself Success bool// true if follower contained entry matching prevLogIndex and prevLogTerm }