-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.go
77 lines (62 loc) · 1.57 KB
/
rpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package raft
type RequestVoteReq struct {
CandidateTerm int
CandidateId string
LastLogIdx int
LastLogTerm int
}
type RequestVoteRes struct {
Term int
VoteGranted bool
}
type AppendEntriesReq struct {
// Leader's term
Term int `json:"term,omitempty"`
LeaderID string `json:"leaderID,omitempty"`
PrevLogIdx int `json:"prevLogIdx,omitempty"`
PrevLogTerm int `json:"prevLogTerm,omitempty"`
Entries []logEntry `json:"entries,omitempty"`
// leader's commitIndex
LeaderCommit int `json:"leaderCommit,omitempty"`
}
type AppendEntriesRes struct {
// CurrentTerm, for leader to update itself
Term int
Success bool
}
const (
requestvoteRpcMethodname = "Node.RequestVote"
appendEntriesRpcMethodname = "Node.AppendEntries"
)
func (n *Node) RequestVote(req *RequestVoteReq, reply *RequestVoteRes) error {
currentTerm, voteGranted := n.handleRequestVote(req.CandidateId, req.CandidateTerm, req.LastLogIdx, req.LastLogTerm)
reply.Term = currentTerm
reply.VoteGranted = voteGranted
return nil
}
func (n *Node) AppendEntries(req *AppendEntriesReq, reply *AppendEntriesRes) error {
if reply == nil {
reply = new(AppendEntriesRes)
}
reply.Term, reply.Success = n.handleAppendEntriesRequest(req)
return nil
}
type CmdReq struct {
Add bool
Cmd string
Count int
}
type CmdRes struct {
Res bool
}
func (n *Node) Add(req *CmdReq, reply *CmdRes) error {
if req.Add {
n.log = append(n.log, logEntry{Term: n.currentTerm, Command: req.Cmd})
} else {
if req.Count == 0 {
req.Count = 1
}
}
reply.Res = true
return nil
}