-
Notifications
You must be signed in to change notification settings - Fork 542
/
peer.go
374 lines (343 loc) · 10.2 KB
/
peer.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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2017-2019 Lei Ni (nilei81@gmail.com)
//
// 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.
//
//
// Copyright 2015 The etcd Authors
//
// 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.
//
//
// Peer.go is the interface used by the upper layer to access functionalities
// provided by the raft protocol. It translates all incoming requests to raftpb
// messages and pass them to the raft protocol implementation to be handled.
// Such a state machine style design together with the iterative style interface
// here is derived from etcd.
// Compared to etcd raft, we strictly model all inputs to the raft protocol as
// messages including those used to advance the raft state.
//
package raft
import (
"sort"
"sync/atomic"
"github.com/lni/dragonboat/config"
pb "github.com/lni/dragonboat/raftpb"
)
// PeerAddress is the basic info for a peer in the Raft cluster.
type PeerAddress struct {
NodeID uint64
Address string
}
// Peer is the interface struct for interacting with the underlying Raft
// protocol implementation.
type Peer struct {
leaderID uint64
raft *raft
prevState pb.State
}
// LaunchPeer starts or restarts a Raft node.
func LaunchPeer(config *config.Config, logdb ILogDB,
addresses []PeerAddress, initial bool, newNode bool) (*Peer, error) {
checkLaunchRequest(config, addresses, initial, newNode)
r := newRaft(config, logdb)
rc := &Peer{raft: r}
rc.raft.recordLeader = rc.recordLeader
_, lastIndex := logdb.GetRange()
if newNode && !config.IsObserver {
r.becomeFollower(1, NoLeader)
}
plog.Infof("LaunchPeer %s, lastIndex %d, initial %t, newNode %t",
r.describe(), lastIndex, initial, newNode)
if initial && newNode {
bootstrap(r, addresses)
}
if lastIndex == 0 {
rc.prevState = emptyState
} else {
rc.prevState = r.raftState()
}
return rc, nil
}
// Tick moves the logical clock forward by one tick.
func (rc *Peer) Tick() {
rc.raft.Handle(pb.Message{
Type: pb.LocalTick,
Reject: false,
})
}
// QuiescedTick moves the logical clock forward by one tick in quiesced mode.
func (rc *Peer) QuiescedTick() {
rc.raft.Handle(pb.Message{
Type: pb.LocalTick,
Reject: true,
})
}
// RequestLeaderTransfer makes a request to transfer the leadership to the
// specified target node.
func (rc *Peer) RequestLeaderTransfer(target uint64) {
plog.Infof("RequestLeaderTransfer called, target %d", target)
rc.raft.Handle(pb.Message{
Type: pb.LeaderTransfer,
To: rc.raft.nodeID,
From: target,
Hint: target,
})
}
// ProposeEntries proposes specified entries in a batched mode using a single
// MTPropose message.
func (rc *Peer) ProposeEntries(ents []pb.Entry) {
rc.raft.Handle(pb.Message{
Type: pb.Propose,
From: rc.raft.nodeID,
Entries: ents,
})
}
// ProposeConfigChange proposes a raft membership change.
func (rc *Peer) ProposeConfigChange(configChange pb.ConfigChange, key uint64) {
data, err := configChange.Marshal()
if err != nil {
panic(err)
}
rc.raft.Handle(pb.Message{
Type: pb.Propose,
Entries: []pb.Entry{{Type: pb.ConfigChangeEntry, Cmd: data, Key: key}},
})
}
// ApplyConfigChange applies a raft membership change to the local raft node.
func (rc *Peer) ApplyConfigChange(cc pb.ConfigChange) {
if cc.NodeID == NoLeader {
rc.raft.clearPendingConfigChange()
return
}
rc.raft.Handle(pb.Message{
Type: pb.ConfigChangeEvent,
Reject: false,
Hint: cc.NodeID,
HintHigh: uint64(cc.Type),
})
}
// RejectConfigChange rejects the currently pending raft membership change.
func (rc *Peer) RejectConfigChange() {
rc.raft.Handle(pb.Message{
Type: pb.ConfigChangeEvent,
Reject: true,
})
}
// RestoreRemotes applies the remotes info obtained from the specified snapshot.
func (rc *Peer) RestoreRemotes(ss pb.Snapshot) {
rc.raft.Handle(pb.Message{
Type: pb.SnapshotReceived,
Snapshot: ss,
})
}
// ReportUnreachableNode marks the specified node as not reachable.
func (rc *Peer) ReportUnreachableNode(nodeID uint64) {
rc.raft.Handle(pb.Message{
Type: pb.Unreachable,
From: nodeID,
})
}
// ReportSnapshotStatus reports the status of the snapshot to the local raft
// node.
func (rc *Peer) ReportSnapshotStatus(nodeID uint64, reject bool) {
rc.raft.Handle(pb.Message{
Type: pb.SnapshotStatus,
From: nodeID,
Reject: reject,
})
}
// Handle processes the given message.
func (rc *Peer) Handle(m pb.Message) {
if IsLocalMessageType(m.Type) {
panic("local message sent to Step")
}
_, rok := rc.raft.remotes[m.From]
_, ook := rc.raft.observers[m.From]
if rok || ook || !isResponseMessageType(m.Type) {
rc.raft.Handle(m)
}
}
// GetUpdate returns the current state of the Peer.
func (rc *Peer) GetUpdate(moreEntriesToApply bool) pb.Update {
return getUpdate(rc.raft, rc.prevState, moreEntriesToApply)
}
// HasUpdate returns a boolean value indicating whether there is any Update
// ready to be processed.
func (rc *Peer) HasUpdate(moreEntriesToApply bool) bool {
r := rc.raft
if pst := r.raftState(); !pb.IsEmptyState(pst) &&
!pb.IsStateEqual(pst, rc.prevState) {
return true
}
if r.log.inmem.snapshot != nil &&
!pb.IsEmptySnapshot(*r.log.inmem.snapshot) {
return true
}
if len(r.msgs) > 0 {
return true
}
if len(r.log.entriesToSave()) > 0 {
return true
}
if moreEntriesToApply && r.log.hasEntriesToApply() {
return true
}
if len(r.readyToRead) != 0 {
return true
}
return false
}
// Commit commits the Update state to mark it as processed.
func (rc *Peer) Commit(ud pb.Update) {
rc.raft.msgs = nil
if !pb.IsEmptyState(ud.State) {
rc.prevState = ud.State
}
if ud.UpdateCommit.ReadyToRead > 0 {
rc.raft.clearReadyToRead()
}
rc.entryLog().commitUpdate(ud.UpdateCommit)
}
// LocalStatus returns the current local status of the raft node.
func (rc *Peer) LocalStatus() Status {
return getLocalStatus(rc.raft)
}
// ReadIndex starts a ReadIndex operation. The ReadIndex protocol is defined in
// the section 6.4 of the Raft thesis.
func (rc *Peer) ReadIndex(ctx pb.SystemCtx) {
rc.raft.Handle(pb.Message{
Type: pb.ReadIndex,
Hint: ctx.Low,
HintHigh: ctx.High,
})
}
// DumpRaftInfoToLog prints the raft state to log for debugging purposes.
func (rc *Peer) DumpRaftInfoToLog(addrMap map[uint64]string) {
rc.raft.dumpRaftInfoToLog(addrMap)
}
// GetLeaderID returns the leader id.
func (rc *Peer) GetLeaderID() uint64 {
return atomic.LoadUint64(&rc.leaderID)
}
// NotifyRaftLastApplied passes on the lastApplied index confirmed by the RSM to
// the raft state machine.
func (rc *Peer) NotifyRaftLastApplied(lastApplied uint64) {
rc.raft.setApplied(lastApplied)
}
func (rc *Peer) recordLeader(leaderID uint64) {
atomic.StoreUint64(&rc.leaderID, leaderID)
}
func (rc *Peer) entryLog() *entryLog {
return rc.raft.log
}
func checkLaunchRequest(config *config.Config,
addresses []PeerAddress, initial bool, newNode bool) {
if config.NodeID == 0 {
panic("config.NodeID must not be zero")
}
plog.Infof("initial node: %t, new node %t", initial, newNode)
if initial && newNode && len(addresses) == 0 {
panic("addresses must be specified")
}
uniqueAddressList := make(map[string]struct{})
for _, addr := range addresses {
uniqueAddressList[string(addr.Address)] = struct{}{}
}
if len(uniqueAddressList) != len(addresses) {
plog.Panicf("duplicated address found %v", addresses)
}
}
func bootstrap(r *raft, addresses []PeerAddress) {
sort.Slice(addresses, func(i, j int) bool {
return addresses[i].NodeID < addresses[j].NodeID
})
ents := make([]pb.Entry, len(addresses))
for i, peer := range addresses {
plog.Infof("%s inserting a bootstrap ConfigChangeAddNode, %d, %s",
r.describe(), peer.NodeID, string(peer.Address))
cc := pb.ConfigChange{
Type: pb.AddNode,
NodeID: peer.NodeID,
Initialize: true,
Address: peer.Address,
}
data, err := cc.Marshal()
if err != nil {
panic("unexpected marshal error")
}
ents[i] = pb.Entry{
Type: pb.ConfigChangeEntry,
Term: 1,
Index: uint64(i + 1),
Cmd: data,
}
}
r.log.append(ents)
r.log.committed = uint64(len(ents))
for _, peer := range addresses {
r.addNode(peer.NodeID)
}
}
func getUpdateCommit(ud pb.Update) pb.UpdateCommit {
var uc pb.UpdateCommit
uc.ReadyToRead = uint64(len(ud.ReadyToReads))
if len(ud.CommittedEntries) > 0 {
uc.AppliedTo = ud.CommittedEntries[len(ud.CommittedEntries)-1].Index
}
if len(ud.EntriesToSave) > 0 {
lastEntry := ud.EntriesToSave[len(ud.EntriesToSave)-1]
uc.StableLogTo, uc.StableLogTerm = lastEntry.Index, lastEntry.Term
}
if !pb.IsEmptySnapshot(ud.Snapshot) {
uc.StableSnapshotTo = ud.Snapshot.Index
uc.AppliedTo = max(uc.AppliedTo, uc.StableSnapshotTo)
}
return uc
}
func getUpdate(r *raft,
ppst pb.State, moreEntriesToApply bool) pb.Update {
ud := pb.Update{
ClusterID: r.clusterID,
NodeID: r.nodeID,
EntriesToSave: r.log.entriesToSave(),
Messages: r.msgs,
}
if moreEntriesToApply {
ud.CommittedEntries = r.log.entriesToApply()
}
if len(ud.CommittedEntries) > 0 {
lastIndex := ud.CommittedEntries[len(ud.CommittedEntries)-1].Index
ud.MoreCommittedEntries = r.log.hasMoreEntriesToApply(lastIndex)
}
if pst := r.raftState(); !pb.IsStateEqual(pst, ppst) {
ud.State = pst
}
if r.log.inmem.snapshot != nil {
ud.Snapshot = *r.log.inmem.snapshot
}
if len(r.readyToRead) > 0 {
ud.ReadyToReads = r.readyToRead
}
ud.UpdateCommit = getUpdateCommit(ud)
return ud
}