-
Notifications
You must be signed in to change notification settings - Fork 0
/
raft_util.go
96 lines (80 loc) · 1.62 KB
/
raft_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
91
92
93
94
95
96
package raft
import (
"fmt"
"log"
"math/rand"
"time"
)
func sleepMs(n int) {
time.Sleep(time.Duration(n) * time.Millisecond)
}
func min(a, b int32) int32 {
if a < b {
return a
}
return b
}
func (r *raft) debugLog(format string, args ...interface{}) {
if !r.showLog {
return
}
format = fmt.Sprintf("[%s] ", r.currentAddress) + format
log.Printf(format, args...)
}
func (r *raft) electionTimeout() time.Duration {
return time.Duration(r.electionTimeoutMinMs+rand.Intn(r.electionTimeoutMaxMs-r.electionTimeoutMinMs)) * time.Millisecond
}
func (r *raft) term() int32 {
r.mu.RLock()
defer r.mu.RUnlock()
return r.currentTerm
}
func (r *raft) state() FSM {
r.mu.RLock()
defer r.mu.RUnlock()
return r.currentState
}
func (r *raft) voteFor() string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.votedFor
}
func (r *raft) address() string {
r.mu.RLock()
defer r.mu.RUnlock()
return r.currentAddress
}
func (r *raft) electionTimer() time.Time {
r.mu.RLock()
defer r.mu.RUnlock()
return r.currentElectionTimer
}
func (r *raft) nodes() map[string]*struct{} {
m := make(map[string]*struct{})
r.mu.RLock()
defer r.mu.RUnlock()
for k, v := range r.nodeIDs {
m[k] = v
}
return m
}
func (r *raft) lastLogIndexAndTerm() (int32, int32) {
r.mu.RLock()
defer r.mu.RUnlock()
if len(r.log) > 0 {
lastIndex := len(r.log) - 1
return int32(lastIndex), r.log[lastIndex].Term
} else {
return -1, -1
}
}
func (r *raft) addNode(address string) {
r.mu.Lock()
defer r.mu.Unlock()
if _, ok := r.nodeIDs[address]; !ok {
if _, e := r.server.connect(address); e == nil {
r.nodeIDs[address] = &struct{}{}
}
}
return
}