-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.go
90 lines (74 loc) · 1.58 KB
/
util.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
78
79
80
81
82
83
84
85
86
87
88
89
90
package raft
import (
"log"
"math/rand"
"time"
)
// Debugging
var debug bool = false
// Color for better debug
const colorReset string = "\033[0m"
var color = []string{
"\033[31m",
"\033[32m",
"\033[33m",
"\033[34m",
"\033[35m",
"\033[36m",
"\033[37m",
"\033[38m",
"\033[39m",
"\033[40m",
"\033[41m",
"\033[42m",
}
func init() {
log.SetFlags(log.Ltime)
}
func DPrintf(format string, a ...interface{}) (n int, err error) {
if debug {
log.Printf(format, a...)
}
return
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// get a random election timeout
func randomElectionTime() time.Duration {
return time.Duration((150 + (rand.Int63() % 150))) * (time.Millisecond)
}
func (rf *Raft) getLastLog() LogEntry {
return rf.log[len(rf.log)-1]
}
func (rf *Raft) getLastLogIndex() int {
return rf.logSize() - 1
}
func (rf *Raft) getLastLogTerm() int {
return rf.getLastLog().Term
}
func (rf *Raft) becomeFollower(term int) {
rf.state = Follower
rf.currentTerm = term
rf.votedFor = -1
}
// check if candidate's log is at least as new as the voter.
func (rf *Raft) isUpToDate(candidateTerm int, candidateIndex int) bool {
index, term := rf.getLastLogIndex(), rf.getLastLogTerm()
return candidateTerm > term || (candidateTerm == term && candidateIndex >= index)
}
// replace for len(rf.log)
func (rf *Raft) logSize() int {
return rf.logBase + len(rf.log)
}
// replace for rf.log[i]
func (rf *Raft) logAt(index int) LogEntry {
return rf.log[index-rf.logBase]
}
// replace for rf.log[i] = e
func (rf *Raft) logSetAt(index int, e LogEntry) {
rf.log[index-rf.logBase] = e
}