-
Notifications
You must be signed in to change notification settings - Fork 178
/
wal.go
354 lines (295 loc) · 8.85 KB
/
wal.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
package wal
import (
"fmt"
"sort"
"time"
prometheusWAL "github.com/m4ksio/wal/wal"
"github.com/prometheus/client_golang/prometheus"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/ledger"
"github.com/onflow/flow-go/ledger/complete/mtrie"
"github.com/onflow/flow-go/ledger/complete/mtrie/trie"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/utils/io"
)
const SegmentSize = 32 * 1024 * 1024
type DiskWAL struct {
wal *prometheusWAL.WAL
paused bool
forestCapacity int
pathByteSize int
log zerolog.Logger
// disk size reading can be time consuming, so limit how often its read
diskUpdateLimiter *time.Ticker
metrics module.WALMetrics
dir string
}
// TODO use real logger and metrics, but that would require passing them to Trie storage
func NewDiskWAL(logger zerolog.Logger, reg prometheus.Registerer, metrics module.WALMetrics, dir string, forestCapacity int, pathByteSize int, segmentSize int) (*DiskWAL, error) {
w, err := prometheusWAL.NewSize(logger, reg, dir, segmentSize, false)
if err != nil {
return nil, err
}
return &DiskWAL{
wal: w,
paused: false,
forestCapacity: forestCapacity,
pathByteSize: pathByteSize,
log: logger,
diskUpdateLimiter: time.NewTicker(5 * time.Second),
metrics: metrics,
dir: dir,
}, nil
}
func (w *DiskWAL) PauseRecord() {
w.paused = true
}
func (w *DiskWAL) UnpauseRecord() {
w.paused = false
}
func (w *DiskWAL) RecordUpdate(update *ledger.TrieUpdate) error {
if w.paused {
return nil
}
bytes := EncodeUpdate(update)
_, err := w.wal.Log(bytes)
if err != nil {
return fmt.Errorf("error while recording update in LedgerWAL: %w", err)
}
select {
case <-w.diskUpdateLimiter.C:
diskSize, err := w.DiskSize()
if err != nil {
w.log.Warn().Err(err).Msg("error while checking forest disk size")
} else {
w.metrics.DiskSize(diskSize)
}
default: //don't block
}
return nil
}
// DiskSize returns the amount of disk space used by the storage (in bytes)
func (w *DiskWAL) DiskSize() (uint64, error) {
return io.DirSize(w.dir)
}
func (w *DiskWAL) RecordDelete(rootHash ledger.RootHash) error {
if w.paused {
return nil
}
bytes := EncodeDelete(rootHash)
_, err := w.wal.Log(bytes)
if err != nil {
return fmt.Errorf("error while recording delete in LedgerWAL: %w", err)
}
return nil
}
func (w *DiskWAL) ReplayOnForest(forest *mtrie.Forest) error {
return w.Replay(
func(tries []*trie.MTrie) error {
err := forest.AddTries(tries)
if err != nil {
return fmt.Errorf("adding rebuilt tries to forest failed: %w", err)
}
return nil
},
func(update *ledger.TrieUpdate) error {
_, err := forest.Update(update)
return err
},
func(rootHash ledger.RootHash) error {
forest.RemoveTrie(rootHash)
return nil
},
)
}
func (w *DiskWAL) Segments() (first, last int, err error) {
return prometheusWAL.Segments(w.wal.Dir())
}
func (w *DiskWAL) Replay(
checkpointFn func(tries []*trie.MTrie) error,
updateFn func(update *ledger.TrieUpdate) error,
deleteFn func(ledger.RootHash) error,
) error {
from, to, err := w.Segments()
if err != nil {
return err
}
return w.replay(from, to, checkpointFn, updateFn, deleteFn, true)
}
func (w *DiskWAL) ReplayLogsOnly(
checkpointFn func(tries []*trie.MTrie) error,
updateFn func(update *ledger.TrieUpdate) error,
deleteFn func(rootHash ledger.RootHash) error,
) error {
from, to, err := w.Segments()
if err != nil {
return err
}
return w.replay(from, to, checkpointFn, updateFn, deleteFn, false)
}
func (w *DiskWAL) replay(
from, to int,
checkpointFn func(tries []*trie.MTrie) error,
updateFn func(update *ledger.TrieUpdate) error,
deleteFn func(rootHash ledger.RootHash) error,
useCheckpoints bool,
) error {
w.log.Debug().Msgf("replaying WAL from %d to %d", from, to)
if to < from {
return fmt.Errorf("end of range cannot be smaller than beginning")
}
loadedCheckpoint := -1
startSegment := from
checkpointer, err := w.NewCheckpointer()
if err != nil {
return fmt.Errorf("cannot create checkpointer: %w", err)
}
if useCheckpoints {
allCheckpoints, err := checkpointer.Checkpoints()
if err != nil {
return fmt.Errorf("cannot get list of checkpoints: %w", err)
}
var availableCheckpoints []int
// if there are no checkpoints already, don't bother
if len(allCheckpoints) > 0 {
// from-1 to account for checkpoints connected to segments, ie. checkpoint 8 if replaying segments 9-12
availableCheckpoints = getPossibleCheckpoints(allCheckpoints, from-1, to)
}
for len(availableCheckpoints) > 0 {
// as long as there are checkpoints to try, we always try with the last checkpoint file, since
// it allows us to load less segments.
latestCheckpoint := availableCheckpoints[len(availableCheckpoints)-1]
w.log.Info().Int("checkpoint", latestCheckpoint).Msg("loading checkpoint")
forestSequencing, err := checkpointer.LoadCheckpoint(latestCheckpoint)
if err != nil {
w.log.Warn().Int("checkpoint", latestCheckpoint).Err(err).
Msg("checkpoint loading failed")
availableCheckpoints = availableCheckpoints[:len(availableCheckpoints)-1]
continue
}
w.log.Info().Int("checkpoint", latestCheckpoint).Msg("checkpoint loaded")
err = checkpointFn(forestSequencing)
if err != nil {
return fmt.Errorf("error while handling checkpoint: %w", err)
}
loadedCheckpoint = latestCheckpoint
break
}
if loadedCheckpoint != -1 && loadedCheckpoint == to {
return nil
}
if loadedCheckpoint >= 0 {
startSegment = loadedCheckpoint + 1
}
}
if loadedCheckpoint == -1 && startSegment == 0 {
hasRootCheckpoint, err := checkpointer.HasRootCheckpoint()
if err != nil {
return fmt.Errorf("cannot check root checkpoint existence: %w", err)
}
if hasRootCheckpoint {
flattenedForest, err := checkpointer.LoadRootCheckpoint()
if err != nil {
return fmt.Errorf("cannot load root checkpoint: %w", err)
}
err = checkpointFn(flattenedForest)
if err != nil {
return fmt.Errorf("error while handling root checkpoint: %w", err)
}
}
}
w.log.Info().Msgf("replaying segments from %d to %d", startSegment, to)
sr, err := prometheusWAL.NewSegmentsRangeReader(prometheusWAL.SegmentRange{
Dir: w.wal.Dir(),
First: startSegment,
Last: to,
})
if err != nil {
return fmt.Errorf("cannot create segment reader: %w", err)
}
reader := prometheusWAL.NewReader(sr)
defer sr.Close()
for reader.Next() {
record := reader.Record()
operation, rootHash, update, err := Decode(record)
if err != nil {
return fmt.Errorf("cannot decode LedgerWAL record: %w", err)
}
switch operation {
case WALUpdate:
err = updateFn(update)
if err != nil {
return fmt.Errorf("error while processing LedgerWAL update: %w", err)
}
case WALDelete:
err = deleteFn(rootHash)
if err != nil {
return fmt.Errorf("error while processing LedgerWAL deletion: %w", err)
}
}
err = reader.Err()
if err != nil {
return fmt.Errorf("cannot read LedgerWAL: %w", err)
}
}
w.log.Info().Msgf("finished replaying WAL from %d to %d", from, to)
return nil
}
func getPossibleCheckpoints(allCheckpoints []int, from, to int) []int {
// list of checkpoints is sorted
indexFrom := sort.SearchInts(allCheckpoints, from)
indexTo := sort.SearchInts(allCheckpoints, to)
// all checkpoints are earlier, return last one
if indexTo == len(allCheckpoints) {
return allCheckpoints[indexFrom:indexTo]
}
// exact match
if allCheckpoints[indexTo] == to {
return allCheckpoints[indexFrom : indexTo+1]
}
// earliest checkpoint from list doesn't match, index 0 means no match at all
if indexTo == 0 {
return nil
}
return allCheckpoints[indexFrom:indexTo]
}
// NewCheckpointer returns a Checkpointer for this WAL
func (w *DiskWAL) NewCheckpointer() (*Checkpointer, error) {
return NewCheckpointer(w, w.pathByteSize, w.forestCapacity), nil
}
func (w *DiskWAL) Ready() <-chan struct{} {
ready := make(chan struct{})
close(ready)
return ready
}
// Done implements interface module.ReadyDoneAware
// it closes all the open write-ahead log files.
func (w *DiskWAL) Done() <-chan struct{} {
err := w.wal.Close()
if err != nil {
w.log.Err(err).Msg("error while closing WAL")
}
done := make(chan struct{})
close(done)
return done
}
type LedgerWAL interface {
module.ReadyDoneAware
NewCheckpointer() (*Checkpointer, error)
PauseRecord()
UnpauseRecord()
RecordUpdate(update *ledger.TrieUpdate) error
RecordDelete(rootHash ledger.RootHash) error
ReplayOnForest(forest *mtrie.Forest) error
Segments() (first, last int, err error)
Replay(
checkpointFn func(tries []*trie.MTrie) error,
updateFn func(update *ledger.TrieUpdate) error,
deleteFn func(ledger.RootHash) error,
) error
ReplayLogsOnly(
checkpointFn func(tries []*trie.MTrie) error,
updateFn func(update *ledger.TrieUpdate) error,
deleteFn func(rootHash ledger.RootHash) error,
) error
}