-
Notifications
You must be signed in to change notification settings - Fork 0
/
election_timer.go
89 lines (72 loc) · 1.97 KB
/
election_timer.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
package graft
import (
"math/rand"
"sync"
"time"
)
type (
electionTimer struct {
sync.Mutex
electionTimeoutBound time.Duration
currentElectionTimeout time.Duration
isActive bool
timer *time.Timer
// runElection should return a boolean indicating if the current machine
// won the election
runElection func()
}
)
func newElectionTimer(config graftConfig, electionRunner func()) *electionTimer {
return &electionTimer{
electionTimeoutBound: config.electionTimeoutDuration,
runElection: electionRunner,
}
}
// start actually starts the election timer and puts it in a state to begin triggering elections
func (timer *electionTimer) start() {
timer.Lock()
defer timer.Unlock()
if timer.isActive {
return
}
timer.currentElectionTimeout = getRandomDuration(timer.electionTimeoutBound)
timer.timer = time.NewTimer(timer.currentElectionTimeout)
timer.isActive = true
go func() {
// wait for the timer to end and rerun an election cycle afterwards
for range timer.timer.C {
timer.runElection()
timer.Lock()
timerIsActive := timer.isActive
timer.Unlock()
if timerIsActive {
timer.Lock()
timer.currentElectionTimeout = getRandomDuration(timer.electionTimeoutBound)
timer.timer.Reset(timer.currentElectionTimeout)
timer.Unlock()
} else {
// terminate this goroutine since this timer is done anyways
// (basically to prevent goroutine leaks)
return
}
}
}()
}
// stops the timer countdown from occurring again
func (timer *electionTimer) stop() {
timer.Lock()
defer timer.Unlock()
timer.isActive = false
timer.timer.Stop()
}
// resets the timer countdown
func (timer *electionTimer) reset() {
timer.Lock()
defer timer.Unlock()
timer.timer.Reset(timer.currentElectionTimeout)
}
func getRandomDuration(durationBound time.Duration) time.Duration {
rand.Seed(time.Now().Unix())
newTimeout := rand.Int63n(durationBound.Nanoseconds()) + durationBound.Nanoseconds()
return time.Duration(newTimeout)
}