-
Notifications
You must be signed in to change notification settings - Fork 0
/
election.go
61 lines (52 loc) · 1.37 KB
/
election.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
// Copyright (c) 2019 Meng Huang ([email protected])
// This package is licensed under a MIT license that can be found in the LICENSE file.
package raft
import (
"math/rand"
"sync"
"time"
)
type election struct {
node *node
once sync.Once
onceDisabled bool
random bool
startTime time.Time
defaultElectionTimeout time.Duration
electionTimeout time.Duration
}
func newElection(n *node, electionTimeout time.Duration) *election {
e := &election{
node: n,
defaultElectionTimeout: electionTimeout,
random: true,
}
return e
}
func (e *election) Reset() {
e.startTime = time.Now()
if e.onceDisabled {
if e.random {
e.electionTimeout = e.defaultElectionTimeout + randomDurationTime(e.defaultElectionTimeout)
} else {
e.electionTimeout = e.defaultElectionTimeout
}
}
e.once.Do(func() {
e.electionTimeout = defaultStartWait
})
}
func (e *election) Random(random bool) {
e.random = random
}
func (e *election) Timeout() bool {
if e.startTime.Add(e.electionTimeout).Before(time.Now()) {
e.onceDisabled = true
return true
}
return false
}
var random = rand.New(rand.NewSource(time.Now().UnixNano()))
func randomDurationTime(maxRange time.Duration) time.Duration {
return maxRange * time.Duration((random.Intn(900) + 100)) / time.Duration(1000)
}