-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfsm.go
More file actions
330 lines (300 loc) · 7.84 KB
/
fsm.go
File metadata and controls
330 lines (300 loc) · 7.84 KB
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
// Copyright 2019 Santhosh Kumar Tekuri
//
// 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 raft
import (
"bufio"
"bytes"
"io"
"github.com/santhosh-tekuri/raft/log"
)
// FSM provides an interface that can be implemented by
// clients replicate state across raft cluster.
//
// The methods in FSM are not called concurrently.
type FSM interface {
// Update applies the given command to state machine.
// It is invoked once a log entry is committed.
// The value returned will be made available as result of
// UpdateFSM task.
Update(cmd []byte) interface{}
// Read executes the given command to state machine.
// The command should not modify the stateMachine.
// The value returned will be made available as result of
// ReadFSM task.
Read(cmd interface{}) interface{}
// Snapshot is used to support log compaction. This call should
// return an FSMState which can be used to save a point-in-time
// snapshot of the FSM.
Snapshot() (FSMState, error)
// Restore is used to restore an FSM from a snapshot. On success,
// FSM must discard all previous state. On failure, the FSM should be
// in the same state prior to this call.
Restore(io.Reader) error
}
// FSMState captures the current state of FSM.
// It is returned by an FSM in response to a Snapshot.
// It must be safe to invoke FSMState methods with concurrent
// calls to FSM methods.
type FSMState interface {
// Persist dumps all necessary state to given io.Writer.
Persist(w io.Writer) error
// Release is invoked when we are finished with the snapshot.
// FSM can release locks if any used during snapshot.
Release()
}
type stateMachine struct {
FSM
id uint64
index uint64
term uint64
ch chan interface{}
snaps *snapshots
}
func (fsm *stateMachine) runLoop() {
// todo: panics are not handled by Raft
for t := range fsm.ch {
if trace {
println(fsm, t)
}
switch t := t.(type) {
case fsmApply:
fsm.onApply(t)
case fsmDirtyRead:
resp := fsm.Read(t.ne.cmd)
t.ne.reply(resp)
case fsmSnapReq:
fsm.onSnapReq(t)
case fsmRestoreReq:
err := fsm.onRestoreReq()
if trace {
if err != nil {
println(fsm, "fsmRestore failed", err)
} else {
println(fsm, "restored snapshot", fsm.index)
}
}
t.err <- err
case lastApplied:
t.reply(fsm.index)
}
}
}
func (fsm *stateMachine) onApply(t fsmApply) {
// process all entries before t.neHead from log
commitIndex := t.log.LastIndex()
front := commitIndex + 1
if t.neHead != nil {
front = t.neHead.index
}
for fsm.index+1 < front {
b, err := t.log.Get(fsm.index + 1)
if err != nil {
panic(opError(err, "Log.Get(%d)", fsm.index+1))
}
e := &entry{}
if err := e.decode(bytes.NewReader(b)); err != nil {
panic(opError(err, "Log.Get(%d).decode", fsm.index+1))
}
assert(e.index == fsm.index+1)
if trace {
println(fsm, "apply", e.typ, e.index)
}
if e.typ == entryUpdate {
fsm.Update(e.data)
}
fsm.index, fsm.term = e.index, e.term
}
// process all entries from t.neHead if any
for ne := t.neHead; ne != nil; ne = ne.next {
assert(ne.index == fsm.index+1)
if trace {
println(fsm, "apply", ne.typ, ne.index)
}
var resp interface{}
if ne.typ == entryRead || ne.typ == entryDirtyRead {
resp = fsm.Read(ne.cmd)
} else if ne.typ == entryUpdate {
resp = fsm.Update(ne.data)
}
if ne.isLogEntry() {
fsm.index, fsm.term = ne.index, ne.term
}
ne.reply(resp)
}
assert(fsm.index == commitIndex)
}
func (fsm *stateMachine) onSnapReq(t fsmSnapReq) {
if fsm.index == fsm.snaps.index {
t.reply(ErrNoUpdates)
return
}
if fsm.index < t.index {
t.reply(ErrSnapshotThreshold)
return
}
state, err := fsm.Snapshot()
if err != nil {
if trace {
println(fsm, "fsm.Snapshot failed", err)
}
t.reply(opError(err, "fsm.Snapshot"))
return
}
t.reply(fsmSnapResp{
index: fsm.index,
term: fsm.term,
state: state,
})
}
func (fsm *stateMachine) onRestoreReq() error {
snap, err := fsm.snaps.open()
if err != nil {
return opError(err, "snapshots.open")
}
defer snap.release()
if err = fsm.Restore(bufio.NewReader(snap.file)); err != nil {
return opError(err, "FSM.Restore")
}
fsm.index, fsm.term = snap.meta.index, snap.meta.term
return nil
}
type fsmApply struct {
neHead *newEntry
log *log.Log
}
type fsmDirtyRead struct {
ne *newEntry
}
type lastApplied struct {
*task
}
func (r *Raft) lastApplied() uint64 {
t := lastApplied{newTask()}
r.fsm.ch <- t
<-t.done
return t.result.(uint64)
}
// raft(onRestart/onInstallSnapReq) -> fsmLoop
type fsmRestoreReq struct {
err chan error
}
// takeSnapshot --------------------------------------------------------------------------
// todo: trace snapshot start and finish
func (r *Raft) onTakeSnapshot(t takeSnapshot) {
if r.snapTakenCh != nil {
t.reply(InProgressError("takeSnapshot"))
return
}
r.snapTakenCh = make(chan snapTaken, 1)
go func(index uint64, config Config) { // tracked by r.snapTakenCh
meta, err := doTakeSnapshot(r.fsm, index, config)
if trace {
println(r, "doTakeSnapshot err:", err)
}
r.snapTakenCh <- snapTaken{
req: t,
meta: meta,
err: err,
}
}(r.snaps.index+t.threshold, r.configs.Committed)
}
func doTakeSnapshot(fsm *stateMachine, index uint64, config Config) (snapshotMeta, error) {
// get fsm state
req := fsmSnapReq{task: newTask(), index: index}
fsm.ch <- req
<-req.Done()
if req.Err() != nil {
return snapshotMeta{}, req.Err()
}
resp := req.Result().(fsmSnapResp)
defer resp.state.Release()
// write snapshot to storage
sink, err := fsm.snaps.new(resp.index, resp.term, config)
if err != nil {
return snapshotMeta{}, opError(err, "snapshots.new")
}
bufw := bufio.NewWriter(sink.file)
err = resp.state.Persist(bufw)
if err == nil {
err = bufw.Flush()
}
meta, doneErr := sink.done(err)
if err != nil {
return meta, opError(err, "FSMState.Persist")
}
if doneErr != nil {
return meta, opError(err, "snapshotSink.done")
}
return meta, nil
}
func (r *Raft) onSnapshotTaken(t snapTaken) {
r.snapTakenCh = nil // clear in progress flag
if t.err != nil {
if err, ok := t.err.(OpError); ok {
r.logger.Warn(trimPrefix(err))
r.alerts.Error(err)
}
t.req.reply(t.err)
return
}
if r.storage.log.Contains(t.meta.index) {
// find compact index
// nowCompact: min of all matchIndex
// canCompact: min of online matchIndex
nowCompact, canCompact := t.meta.index, t.meta.index
if r.state == Leader {
for _, repl := range r.ldr.repls {
if repl.status.matchIndex < nowCompact {
nowCompact = repl.status.matchIndex
}
if repl.status.noContact.IsZero() && repl.status.matchIndex < canCompact {
canCompact = repl.status.matchIndex
}
}
}
if trace {
println(r, "nowCompact:", nowCompact, "canCompact:", canCompact)
}
nowCompact, canCompact = r.log.CanLTE(nowCompact), r.log.CanLTE(canCompact)
if trace {
println(r, "nowCompact:", nowCompact, "canCompact:", canCompact)
}
if nowCompact > r.log.PrevIndex() {
_ = r.compactLog(nowCompact)
}
if canCompact > nowCompact {
// notify repls with new logView
r.ldr.removeLTE = canCompact
r.ldr.notifyFlr(false)
}
}
t.req.reply(t.meta.index)
}
// takeSnapshot() -> fsmLoop
type fsmSnapReq struct {
*task
index uint64
}
// takeSnapshot() <- fsmLoop
type fsmSnapResp struct {
index uint64
term uint64
state FSMState
}
// snapLoop -> raft (after snapshot taken)
type snapTaken struct {
req takeSnapshot
meta snapshotMeta
err error
}