-
Notifications
You must be signed in to change notification settings - Fork 42
/
log_reader.go
374 lines (344 loc) · 10.4 KB
/
log_reader.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 2021 MatrixOrigin.
//
// 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,
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2017-2020 Lei Ni (nilei81@gmail.com) and other contributors.
//
// 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 Cockroach 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.
//
// 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.
package raftstore
import (
"fmt"
"sync"
"unsafe"
"go.etcd.io/etcd/raft/v3"
pb "go.etcd.io/etcd/raft/v3/raftpb"
"go.uber.org/zap"
"github.com/matrixorigin/matrixcube/components/log"
"github.com/matrixorigin/matrixcube/logdb"
)
const (
maxEntrySliceSize uint64 = 4 * 1024 * 1024
)
// LogReader code below is based on dragonboat's internal/logdb/logreader.go,
// which in turn made reference to CockraochDB's replicaRaftStorage and etcd
// raft's MemoryStorage.
// LogReader is the struct used to manage logs that have already been persisted
// into LogDB. LogReader implements the raft.Storage interface.
type LogReader struct {
sync.Mutex
logger *zap.Logger
snapshot pb.Snapshot
state pb.HardState
confState pb.ConfState
logdb logdb.LogDB
markerIndex uint64
markerTerm uint64
length uint64
shardID uint64
replicaID uint64
snapshotRequested bool
}
var _ raft.Storage = (*LogReader)(nil)
// NewLogReader creates and returns a new LogReader instance.
func NewLogReader(logger *zap.Logger, shardID uint64, replicaID uint64,
db logdb.LogDB) *LogReader {
return &LogReader{
logger: log.Adjust(logger),
logdb: db,
shardID: shardID,
replicaID: replicaID,
length: 1,
}
}
func (lr *LogReader) id() string {
return fmt.Sprintf("logreader %s index %d term %d length %d",
dn(lr.shardID, lr.replicaID), lr.markerIndex, lr.markerTerm, lr.length)
}
// InitialState returns the saved HardState and ConfState information.
func (lr *LogReader) InitialState() (pb.HardState, pb.ConfState, error) {
lr.Lock()
defer lr.Unlock()
return lr.state, lr.confState, nil
}
func (lr *LogReader) FirstIndex() (uint64, error) {
lr.Lock()
defer lr.Unlock()
return lr.firstIndex(), nil
}
func (lr *LogReader) LastIndex() (uint64, error) {
lr.Lock()
defer lr.Unlock()
return lr.lastIndex(), nil
}
func (lr *LogReader) firstIndex() uint64 {
return lr.markerIndex + 1
}
func (lr *LogReader) lastIndex() uint64 {
return lr.markerIndex + lr.length - 1
}
// Entries returns persisted entries between [low, high) with a total limit of
// up to maxSize bytes.
func (lr *LogReader) Entries(low uint64,
high uint64, maxSize uint64) ([]pb.Entry, error) {
ents, _, err := lr.entries(low, high, maxSize)
if err != nil {
return nil, err
}
return ents, nil
}
func (lr *LogReader) entries(low uint64,
high uint64, maxSize uint64) ([]pb.Entry, uint64, error) {
lr.Lock()
defer lr.Unlock()
return lr.entriesLocked(low, high, maxSize)
}
func (lr *LogReader) entriesLocked(low uint64,
high uint64, maxSize uint64) ([]pb.Entry, uint64, error) {
if low > high {
return nil, 0, fmt.Errorf("high (%d) < low (%d)", high, low)
}
if low <= lr.markerIndex {
return nil, 0, raft.ErrCompacted
}
if high > lr.lastIndex()+1 {
lr.logger.Error("log entry unavailable",
zap.String("id", lr.id()),
zap.Uint64("low", low),
zap.Uint64("high", high),
zap.Uint64("last-index", lr.lastIndex()))
return nil, 0, raft.ErrUnavailable
}
// limit the size the ents slice to handle the extreme situation in which
// high-low can be tens of millions, slice cap is > 50,000 when
// maxEntrySliceSize is 4MBytes
maxEntries := maxEntrySliceSize / uint64(unsafe.Sizeof(pb.Entry{}))
if high-low > maxEntries {
high = low + maxEntries
lr.logger.Warn("limited high in logReader.entriesLocked",
zap.String("id", lr.id()),
zap.Uint64("high", high))
}
ents := make([]pb.Entry, 0, high-low)
ents, size, err := lr.logdb.IterateEntries(ents, 0, lr.shardID, lr.replicaID, low, high, maxSize)
if err != nil {
return nil, 0, err
}
if uint64(len(ents)) == high-low || size >= maxSize {
return ents, size, nil
}
if len(ents) > 0 {
if ents[0].Index > low {
return nil, 0, raft.ErrCompacted
}
expected := ents[len(ents)-1].Index + 1
if lr.lastIndex() <= expected {
lr.logger.Error("log reader unavailable",
zap.String("id", lr.id()),
zap.Uint64("low", low),
zap.Uint64("high", high),
zap.Uint64("expected", expected),
zap.Uint64("last-index", lr.lastIndex()))
return nil, 0, raft.ErrUnavailable
}
return nil, 0, fmt.Errorf("gap found between [%d:%d) at %d",
low, high, expected)
}
lr.logger.Warn("failed to get anything from logreader",
zap.String("id", lr.id()))
return nil, 0, raft.ErrUnavailable
}
// Term returns the term of the entry specified by the entry index.
func (lr *LogReader) Term(index uint64) (uint64, error) {
lr.Lock()
defer lr.Unlock()
return lr.termLocked(index)
}
func (lr *LogReader) termLocked(index uint64) (uint64, error) {
if index == lr.markerIndex {
t := lr.markerTerm
return t, nil
}
ents, _, err := lr.entriesLocked(index, index+1, 0)
if err != nil {
return 0, err
}
if len(ents) == 0 {
return 0, nil
}
return ents[0].Term, nil
}
// Snapshot returns the metadata of the lastest snapshot.
func (lr *LogReader) Snapshot() (pb.Snapshot, error) {
lr.Lock()
defer lr.Unlock()
snapshot := lr.snapshot
if raft.IsEmptySnap(snapshot) {
lr.snapshotRequested = true
return pb.Snapshot{}, raft.ErrSnapshotTemporarilyUnavailable
}
lr.snapshot = pb.Snapshot{}
return snapshot, nil
}
// ApplySnapshot applies the specified snapshot.
func (lr *LogReader) ApplySnapshot(snapshot pb.Snapshot) error {
lr.Lock()
defer lr.Unlock()
lr.markerIndex = snapshot.Metadata.Index
lr.markerTerm = snapshot.Metadata.Term
lr.length = 1
return nil
}
// CreateSnapshot keeps the metadata of the specified snapshot.
func (lr *LogReader) CreateSnapshot(snapshot pb.Snapshot) error {
lr.Lock()
defer lr.Unlock()
return lr.setSnapshot(snapshot)
}
// GetSnapshotRequested returns a boolean value indicating whether creating a
// new snapshot has been requested.
func (lr *LogReader) GetSnapshotRequested() bool {
lr.Lock()
defer lr.Unlock()
v := lr.snapshotRequested
lr.snapshotRequested = false
return v
}
func (lr *LogReader) setSnapshot(snapshot pb.Snapshot) error {
if lr.snapshot.Metadata.Index > snapshot.Metadata.Index {
lr.logger.Debug("called setSnapshot",
zap.String("id", lr.id()),
zap.Uint64("existing", lr.snapshot.Metadata.Index),
zap.Uint64("new", snapshot.Metadata.Index))
return raft.ErrSnapOutOfDate
}
lr.logger.Debug("set snapshot",
zap.String("id", lr.id()),
zap.Uint64("new", snapshot.Metadata.Index))
lr.snapshot = snapshot
return nil
}
// Append marks the specified entries as persisted and make them available from
// logreader.
func (lr *LogReader) Append(entries []pb.Entry) error {
if len(entries) == 0 {
return nil
}
if len(entries) > 0 {
if entries[0].Index+uint64(len(entries))-1 != entries[len(entries)-1].Index {
panic("gap in entries")
}
}
lr.SetRange(entries[0].Index, uint64(len(entries)))
return nil
}
// SetRange updates the LogReader to reflect what is available in it.
func (lr *LogReader) SetRange(firstIndex uint64, length uint64) {
if length == 0 {
return
}
lr.Lock()
defer lr.Unlock()
inputFirstIndex, inputLength := firstIndex, length
first := lr.firstIndex()
last := firstIndex + length - 1
if last < first {
return
}
if first > firstIndex {
cut := first - firstIndex
firstIndex = first
length -= cut
}
offset := firstIndex - lr.markerIndex
switch {
case lr.length > offset:
lr.length = offset + length
case lr.length == offset:
lr.length += length
default:
lr.logger.Fatal("gap in log entries",
zap.String("id", lr.id()),
zap.Uint64("marker", lr.markerIndex),
zap.Uint64("lr.len", lr.length),
zap.Uint64("first", inputFirstIndex),
zap.Uint64("len", inputLength))
}
}
// SetState sets the persistent state.
func (lr *LogReader) SetState(s pb.HardState) {
lr.Lock()
defer lr.Unlock()
lr.state = s
}
func (lr *LogReader) SetConfState(cs pb.ConfState) {
lr.Lock()
defer lr.Unlock()
lr.confState = cs
}
// Compact compacts raft log entries up to index.
func (lr *LogReader) Compact(index uint64) error {
lr.Lock()
defer lr.Unlock()
if index < lr.markerIndex {
return raft.ErrCompacted
}
if index > lr.lastIndex() {
return raft.ErrUnavailable
}
term, err := lr.termLocked(index)
if err != nil {
return err
}
i := index - lr.markerIndex
lr.length -= i
lr.markerIndex = index
lr.markerTerm = term
return nil
}