forked from lni/dragonboat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
election.go
279 lines (258 loc) · 6.33 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// Copyright 2017-2019 Lei Ni ([email protected])
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package drummer
import (
"context"
"errors"
"sync"
"time"
pb "github.com/lni/dragonboat/drummer/drummerpb"
"github.com/lni/dragonboat/internal/utils/lang"
"github.com/lni/dragonboat/internal/utils/random"
"github.com/lni/dragonboat/internal/utils/syncutil"
)
const (
deadLeaderMinRound = 3
leadershipRenewalSecond = 10
)
type nodeState uint64
const (
stateFollower nodeState = iota
stateLeader
)
type leaderInfo struct {
instanceID uint64
tick uint64
staticRound uint64
}
type electionManager struct {
mu sync.Mutex
instanceID uint64
currentLeader *leaderInfo
state nodeState
drummerServer *server
randSrc random.Source
stopper *syncutil.Stopper
cancel context.CancelFunc
*sessionUser
}
func newElectionManager(stopper *syncutil.Stopper,
drummerServer *server, randSrc random.Source) *electionManager {
e := &electionManager{
state: stateFollower,
drummerServer: drummerServer,
randSrc: randSrc,
stopper: stopper,
}
e.instanceID = e.randSrc.Uint64()
e.sessionUser = &sessionUser{
nh: drummerServer.nh,
}
ctx, cancel := context.WithCancel(context.Background())
e.cancel = cancel
stopper.RunWorker(func() {
e.workerMain(ctx)
})
return e
}
func (d *electionManager) stop() {
d.cancel()
}
func (d *electionManager) isLeader() bool {
d.mu.Lock()
defer d.mu.Unlock()
return d.state == stateLeader
}
func (d *electionManager) setLeaderInfo(l *leaderInfo) {
if d.currentLeader == nil {
d.currentLeader = l
d.currentLeader.staticRound = 0
return
}
if d.currentLeader.instanceID == l.instanceID &&
d.currentLeader.tick < l.tick {
d.currentLeader.tick = l.tick
d.currentLeader.staticRound = 0
} else if d.currentLeader.instanceID == l.instanceID &&
d.currentLeader.tick == l.tick {
d.currentLeader.staticRound++
} else if d.currentLeader.instanceID != l.instanceID {
d.currentLeader = l
d.currentLeader.staticRound = 0
} else {
panic("unknown state")
}
}
func (d *electionManager) leaderDead() bool {
if d.currentLeader == nil {
return false
}
return d.currentLeader.staticRound > deadLeaderMinRound
}
func (d *electionManager) becomeFollower(l *leaderInfo) {
d.mu.Lock()
defer d.mu.Unlock()
d.currentLeader = l
if l != nil {
d.currentLeader.staticRound = 0
}
d.state = stateFollower
}
func (d *electionManager) resetFollower() {
d.mu.Lock()
defer d.mu.Unlock()
if d.currentLeader != nil {
d.currentLeader.staticRound = 0
}
d.state = stateFollower
}
func (d *electionManager) becomeLeader() {
d.mu.Lock()
defer d.mu.Unlock()
d.currentLeader = nil
d.state = stateLeader
}
func (d *electionManager) workerMain(ctx context.Context) {
tick := uint64(0)
td := time.Duration(leadershipRenewalSecond) * time.Second
tf := func() bool {
tick++
if d.isLeader() {
d.leaderMain(ctx, tick)
} else {
d.followerMain(ctx, tick)
}
return false
}
lang.RunTicker(td, tf, ctx.Done(), d.stopper.ShouldStop())
}
func (d *electionManager) leaderMain(ctx context.Context, tick uint64) {
// check who is the leader
kv, err := d.drummerServer.getElectionInfo(ctx)
if err != nil {
d.becomeFollower(nil)
return
}
// someone else became the leader
if kv.InstanceId != d.instanceID {
l := &leaderInfo{
instanceID: kv.InstanceId,
tick: kv.Tick,
}
d.becomeFollower(l)
return
}
if err := d.renewLeadership(ctx, tick); err != nil {
plog.Errorf(err.Error())
}
}
func (d *electionManager) renewLeadership(ctx context.Context,
tick uint64) error {
// leader is still the leader, renew tick on drummerdb so followers can
// observe that the leader is still around.
renewalKV := pb.KV{
Key: electionKey,
Value: electionKey,
InstanceId: d.instanceID,
Tick: tick,
Finalized: false,
}
session := d.getSession(ctx)
if session != nil {
code, err := d.drummerServer.makeDrummerVote(ctx, session, renewalKV)
if err != nil {
d.resetSession(ctx)
d.becomeFollower(nil)
return err
}
d.clientProposalCompleted()
if code != DBKVUpdated {
d.becomeFollower(nil)
}
return nil
}
return errors.New("failed to get session")
}
func (d *electionManager) followerMain(ctx context.Context, tick uint64) {
// who is the leader?
kv, err := d.drummerServer.getElectionInfo(ctx)
if err != nil {
plog.Warningf("failed to get election info")
d.resetFollower()
return
}
// no leader at all
if kv.InstanceId == 0 {
plog.Infof("no leader, start to campaign")
d.campaign(ctx, tick)
return
} else if kv.InstanceId == d.instanceID {
err = d.renewLeadership(ctx, tick)
if err != nil {
plog.Warningf("leadership renewal failed")
d.resetFollower()
return
}
plog.Infof("node %d become leader", kv.InstanceId)
d.becomeLeader()
return
}
l := &leaderInfo{
instanceID: kv.InstanceId,
tick: kv.Tick,
}
d.setLeaderInfo(l)
if d.leaderDead() {
plog.Infof("leader is dead, start to campaign")
d.campaign(ctx, tick)
return
}
}
func (d *electionManager) campaign(ctx context.Context, tick uint64) {
if d.state != stateFollower {
panic("campaign requested by leader")
}
oldInstanceID := uint64(0)
if d.currentLeader != nil {
oldInstanceID = d.currentLeader.instanceID
}
renewalKV := pb.KV{
Key: electionKey,
Value: electionKey,
InstanceId: d.instanceID,
OldInstanceId: oldInstanceID,
Tick: tick,
Finalized: false,
}
session := d.getSession(ctx)
if session == nil {
return
}
code, err := d.drummerServer.makeDrummerVote(ctx, session, renewalKV)
if err != nil || code != DBKVUpdated {
d.resetSession(ctx)
d.resetFollower()
return
}
d.clientProposalCompleted()
kv, err := d.drummerServer.getElectionInfo(ctx)
if err != nil {
d.resetFollower()
return
}
if kv.InstanceId == d.instanceID {
d.becomeLeader()
return
}
}