-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpcproxy.go
76 lines (67 loc) · 1.97 KB
/
rpcproxy.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
package raft
import (
"fmt"
"math/rand"
"time"
)
type RPCProxy struct {
cm *ConsensusModule
}
type RequestVoteArgs struct {
Term int
CandidateId int
LastLogIndex int
LastLogTerm int
}
type RequestVoteReply struct {
Term int
VoteGranted bool
}
func (p *RPCProxy) RequestVote(args RequestVoteArgs, reply *RequestVoteReply) error {
f := rand.Float32()
// 模拟 rpc 请求失败
if f < MockUnreliableRpcFailureRate {
p.cm.debug("drop RequestVote")
time.Sleep(time.Duration(MockUnreliableRpcFailureDuration) * TimeoutUnit)
return fmt.Errorf("RPC failed")
}
// 模拟网络延迟
if f < MockUnreliableRpcDelayRate {
p.cm.debug("delay RequestVote")
time.Sleep(time.Duration(MockUnreliableRpcDelayMin+rand.Intn(MockUnreliableRpcDelayMax-MockUnreliableRpcDelayMin)) * TimeoutUnit)
} else {
time.Sleep(time.Duration(MockUnreliableRpcLatencyMin+rand.Intn(MockUnreliableRpcLatencyMax-MockUnreliableRpcLatencyMin)) * TimeoutUnit)
}
return p.cm.RequestVote(args, reply)
}
type AppendEntriesArgs struct {
Term int
LeaderId int
PrevLogIndex int
PrevLogTerm int
Entries []LogEntry
LeaderCommit int
}
type AppendEntriesReply struct {
Term int
Success bool
ConflictIndex int
ConflictTerm int
}
func (p *RPCProxy) AppendEntries(args AppendEntriesArgs, reply *AppendEntriesReply) error {
f := rand.Float32()
// 模拟 rpc 请求失败
if f < MockUnreliableRpcFailureRate {
p.cm.debug("drop RequestVote")
time.Sleep(time.Duration(MockUnreliableRpcFailureDuration) * TimeoutUnit)
return fmt.Errorf("RPC failed")
}
// 模拟网络延迟
if f < MockUnreliableRpcDelayRate {
p.cm.debug("delay RequestVote")
time.Sleep(time.Duration(MockUnreliableRpcDelayMin+rand.Intn(MockUnreliableRpcDelayMax-MockUnreliableRpcDelayMin)) * TimeoutUnit)
} else {
time.Sleep(time.Duration(MockUnreliableRpcLatencyMin+rand.Intn(MockUnreliableRpcLatencyMax-MockUnreliableRpcLatencyMin)) * TimeoutUnit)
}
return p.cm.AppendEntries(args, reply)
}