forked from goraft/raft
/
log.go
360 lines (295 loc) · 9.06 KB
/
log.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
package raft
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"sync"
)
//------------------------------------------------------------------------------
//
// Typedefs
//
//------------------------------------------------------------------------------
// A log is a collection of log entries that are persisted to durable storage.
type Log struct {
ApplyFunc func(Command) error
file *os.File
entries []*LogEntry
commitIndex uint64
mutex sync.Mutex
}
//------------------------------------------------------------------------------
//
// Constructor
//
//------------------------------------------------------------------------------
// Creates a new log.
func NewLog() *Log {
return &Log{}
}
//------------------------------------------------------------------------------
//
// Accessors
//
//------------------------------------------------------------------------------
//--------------------------------------
// Log Indices
//--------------------------------------
// The current index in the log.
func (l *Log) CurrentIndex() uint64 {
l.mutex.Lock()
defer l.mutex.Unlock()
if len(l.entries) == 0 {
return 0
}
return l.entries[len(l.entries)-1].Index
}
// The next index in the log.
func (l *Log) NextIndex() uint64 {
return l.CurrentIndex() + 1
}
// The last committed index in the log.
func (l *Log) CommitIndex() uint64 {
return l.commitIndex
}
// Determines if the log contains zero entries.
func (l *Log) IsEmpty() bool {
l.mutex.Lock()
defer l.mutex.Unlock()
return (len(l.entries) == 0)
}
//--------------------------------------
// Log Terms
//--------------------------------------
// The current term in the log.
func (l *Log) CurrentTerm() uint64 {
l.mutex.Lock()
defer l.mutex.Unlock()
if len(l.entries) == 0 {
return 0
}
return l.entries[len(l.entries)-1].Term
}
//------------------------------------------------------------------------------
//
// Methods
//
//------------------------------------------------------------------------------
//--------------------------------------
// State
//--------------------------------------
// Opens the log file and reads existing entries. The log can remain open and
// continue to append entries to the end of the log.
func (l *Log) Open(path string) error {
l.mutex.Lock()
defer l.mutex.Unlock()
// Read all the entries from the log if one exists.
var lastIndex int = 0
if _, err := os.Stat(path); !os.IsNotExist(err) {
// Open the log file.
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
reader := bufio.NewReader(file)
// Read the file and decode entries.
for {
if _, err := reader.Peek(1); err == io.EOF {
break
}
// Instantiate log entry and decode into it.
entry := NewLogEntry(l, 0, 0, nil)
n, err := entry.Decode(reader)
if err != nil {
file.Close()
if err = os.Truncate(path, int64(lastIndex)); err != nil {
return fmt.Errorf("raft.Log: Unable to recover: %v", err)
}
break
}
// Apply the command.
if err = l.ApplyFunc(entry.Command); err != nil {
file.Close()
return err
}
// Append entry.
l.entries = append(l.entries, entry)
l.commitIndex = entry.Index
lastIndex += n
}
file.Close()
}
// Open the file for appending.
var err error
l.file, err = os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
return err
}
return nil
}
// Closes the log file.
func (l *Log) Close() {
l.mutex.Lock()
defer l.mutex.Unlock()
if l.file != nil {
l.file.Close()
l.file = nil
}
l.entries = make([]*LogEntry, 0)
}
//--------------------------------------
// Entries
//--------------------------------------
// Creates a log entry associated with this log.
func (l *Log) CreateEntry(term uint64, command Command) *LogEntry {
return NewLogEntry(l, l.NextIndex(), term, command)
}
// Checks if the log contains a given index/term combination.
func (l *Log) ContainsEntry(index uint64, term uint64) bool {
l.mutex.Lock()
defer l.mutex.Unlock()
if index == 0 || index > uint64(len(l.entries)) {
return false
}
return (l.entries[index-1].Term == term)
}
// Retrieves a list of entries after a given index. This function also returns
// the term of the index provided.
func (l *Log) GetEntriesAfter(index uint64) ([]*LogEntry, uint64) {
l.mutex.Lock()
defer l.mutex.Unlock()
// Return an error if the index doesn't exist.
if index > uint64(len(l.entries)) {
panic(fmt.Sprintf("raft.Log: Index is beyond end of log: %v", index))
}
// If we're going from the beginning of the log then return the whole log.
if index == 0 {
return l.entries, 0
}
// Determine the term at the given entry and return a subslice.
term := l.entries[index-1].Term
return l.entries[index:], term
}
//--------------------------------------
// Commit
//--------------------------------------
// Retrieves the last index and term that has been committed to the log.
func (l *Log) CommitInfo() (index uint64, term uint64) {
l.mutex.Lock()
defer l.mutex.Unlock()
// If we don't have any entries then just return zeros.
if l.commitIndex == 0 {
return 0, 0
}
// Return the last index & term from the last committed entry.
lastCommitEntry := l.entries[l.commitIndex-1]
return lastCommitEntry.Index, lastCommitEntry.Term
}
// Updates the commit index and writes entries after that index to the stable storage.
func (l *Log) SetCommitIndex(index uint64) error {
l.mutex.Lock()
defer l.mutex.Unlock()
// Panic if we don't have any way to apply commands.
if l.ApplyFunc == nil {
panic("raft.Log: Apply function not set")
}
// Do not allow previous indices to be committed again.
if index < l.commitIndex {
return fmt.Errorf("raft.Log: Commit index (%d) ahead of requested commit index (%d)", l.commitIndex, index)
}
if index > uint64(len(l.entries)) {
return fmt.Errorf("raft.Log: Commit index (%d) out of range (%d)", index, len(l.entries))
}
// Find all entries whose index is between the previous index and the current index.
for i := l.commitIndex + 1; i <= index; i++ {
entry := l.entries[i-1]
// Apply the changes to the state machine.
if err := l.ApplyFunc(entry.Command); err != nil {
return err
}
// Write to storage.
if err := entry.Encode(l.file); err != nil {
return err
}
// Update commit index.
l.commitIndex = entry.Index
}
return nil
}
//--------------------------------------
// Truncation
//--------------------------------------
// Truncates the log to the given index and term. This only works if the log
// at the index has not been committed.
func (l *Log) Truncate(index uint64, term uint64) error {
l.mutex.Lock()
defer l.mutex.Unlock()
// Do not allow committed entries to be truncated.
if index < l.CommitIndex() {
return fmt.Errorf("raft.Log: Index is already committed (%v): (IDX=%v, TERM=%v)", l.CommitIndex(), index, term)
}
// Do not truncate past end of entries.
if index > uint64(len(l.entries)) {
return fmt.Errorf("raft.Log: Entry index does not exist (MAX=%v): (IDX=%v, TERM=%v)", len(l.entries), index, term)
}
// If we're truncating everything then just clear the entries.
if index == 0 {
l.entries = []*LogEntry{}
} else {
// Do not truncate if the entry at index does not have the matching term.
entry := l.entries[index-1]
if len(l.entries) > 0 && entry.Term != term {
return fmt.Errorf("raft.Log: Entry at index does not have matching term (%v): (IDX=%v, TERM=%v)", entry.Term, index, term)
}
// Otherwise truncate up to the desired entry.
if index < uint64(len(l.entries)) {
l.entries = l.entries[0:index]
}
}
return nil
}
//--------------------------------------
// Append
//--------------------------------------
// Appends a series of entries to the log. These entries are not written to
// disk until SetCommitIndex() is called.
func (l *Log) AppendEntries(entries []*LogEntry) error {
l.mutex.Lock()
defer l.mutex.Unlock()
// Append each entry but exit if we hit an error.
for _, entry := range entries {
if err := l.appendEntry(entry); err != nil {
return err
}
}
return nil
}
// Appends a single entry to the log.
func (l *Log) AppendEntry(entry *LogEntry) error {
l.mutex.Lock()
defer l.mutex.Unlock()
return l.appendEntry(entry)
}
// Writes a single log entry to the end of the log. This function does not
// obtain a lock and should only be used internally. Use AppendEntries() and
// AppendEntry() to use it externally.
func (l *Log) appendEntry(entry *LogEntry) error {
if l.file == nil {
return errors.New("raft.Log: Log is not open")
}
// Make sure the term and index are greater than the previous.
if len(l.entries) > 0 {
lastEntry := l.entries[len(l.entries)-1]
if entry.Term < lastEntry.Term {
return fmt.Errorf("raft.Log: Cannot append entry with earlier term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
} else if entry.Term == lastEntry.Term && entry.Index <= lastEntry.Index {
return fmt.Errorf("raft.Log: Cannot append entry with earlier index in the same term (%x:%x <= %x:%x)", entry.Term, entry.Index, lastEntry.Term, lastEntry.Index)
}
}
// Append to entries list if stored on disk.
l.entries = append(l.entries, entry)
return nil
}