forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 8
/
sync.go
476 lines (419 loc) · 11.6 KB
/
sync.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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package stagedsync
import (
"context"
"fmt"
"time"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/dbg"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/log/v3"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
)
type Sync struct {
unwindPoint *uint64 // used to run stages
prevUnwindPoint *uint64 // used to get value from outside of staged sync after cycle (for example to notify RPCDaemon)
badBlock libcommon.Hash
stages []*Stage
unwindOrder []*Stage
pruningOrder []*Stage
currentStage uint
timings []Timing
logPrefixes []string
}
type Timing struct {
isUnwind bool
isPrune bool
stage stages.SyncStage
took time.Duration
}
func (s *Sync) Len() int { return len(s.stages) }
func (s *Sync) PrevUnwindPoint() *uint64 { return s.prevUnwindPoint }
func (s *Sync) NewUnwindState(id stages.SyncStage, unwindPoint, currentProgress uint64) *UnwindState {
return &UnwindState{id, unwindPoint, currentProgress, libcommon.Hash{}, s}
}
func (s *Sync) PruneStageState(id stages.SyncStage, forwardProgress uint64, tx kv.Tx, db kv.RwDB) (*PruneState, error) {
var pruneProgress uint64
var err error
useExternalTx := tx != nil
if useExternalTx {
pruneProgress, err = stages.GetStagePruneProgress(tx, id)
if err != nil {
return nil, err
}
} else {
if err = db.View(context.Background(), func(tx kv.Tx) error {
pruneProgress, err = stages.GetStagePruneProgress(tx, id)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
}
return &PruneState{id, forwardProgress, pruneProgress, s}, nil
}
func (s *Sync) NextStage() {
if s == nil {
return
}
s.currentStage++
}
// IsBefore returns true if stage1 goes before stage2 in staged sync
func (s *Sync) IsBefore(stage1, stage2 stages.SyncStage) bool {
idx1 := -1
idx2 := -1
for i, stage := range s.stages {
if stage.ID == stage1 {
idx1 = i
}
if stage.ID == stage2 {
idx2 = i
}
}
return idx1 < idx2
}
// IsAfter returns true if stage1 goes after stage2 in staged sync
func (s *Sync) IsAfter(stage1, stage2 stages.SyncStage) bool {
idx1 := -1
idx2 := -1
for i, stage := range s.stages {
if stage.ID == stage1 {
idx1 = i
}
if stage.ID == stage2 {
idx2 = i
}
}
return idx1 > idx2
}
func (s *Sync) UnwindTo(unwindPoint uint64, badBlock libcommon.Hash) {
log.Info("UnwindTo", "block", unwindPoint, "bad_block_hash", badBlock.String())
s.unwindPoint = &unwindPoint
s.badBlock = badBlock
}
func (s *Sync) IsDone() bool {
return s.currentStage >= uint(len(s.stages)) && s.unwindPoint == nil
}
func (s *Sync) LogPrefix() string {
if s == nil {
return ""
}
return s.logPrefixes[s.currentStage]
}
func (s *Sync) SetCurrentStage(id stages.SyncStage) error {
for i, stage := range s.stages {
if stage.ID == id {
s.currentStage = uint(i)
return nil
}
}
return fmt.Errorf("stage not found with id: %v", id)
}
func New(stagesList []*Stage, unwindOrder UnwindOrder, pruneOrder PruneOrder) *Sync {
unwindStages := make([]*Stage, len(stagesList))
for i, stageIndex := range unwindOrder {
for _, s := range stagesList {
if s.ID == stageIndex {
unwindStages[i] = s
break
}
}
}
pruneStages := make([]*Stage, len(stagesList))
for i, stageIndex := range pruneOrder {
for _, s := range stagesList {
if s.ID == stageIndex {
pruneStages[i] = s
break
}
}
}
logPrefixes := make([]string, len(stagesList))
for i := range stagesList {
logPrefixes[i] = fmt.Sprintf("%d/%d %s", i+1, len(stagesList), stagesList[i].ID)
}
return &Sync{
stages: stagesList,
currentStage: 0,
unwindOrder: unwindStages,
pruningOrder: pruneStages,
logPrefixes: logPrefixes,
}
}
func (s *Sync) StageState(stage stages.SyncStage, tx kv.Tx, db kv.RoDB) (*StageState, error) {
var blockNum uint64
var err error
useExternalTx := tx != nil
if useExternalTx {
blockNum, err = stages.GetStageProgress(tx, stage)
if err != nil {
return nil, err
}
} else {
if err = db.View(context.Background(), func(tx kv.Tx) error {
blockNum, err = stages.GetStageProgress(tx, stage)
if err != nil {
return err
}
return nil
}); err != nil {
return nil, err
}
}
return &StageState{s, stage, blockNum}, nil
}
func (s *Sync) RunUnwind(db kv.RwDB, tx kv.RwTx) error {
if s.unwindPoint == nil {
return nil
}
for j := 0; j < len(s.unwindOrder); j++ {
if s.unwindOrder[j] == nil || s.unwindOrder[j].Disabled || s.unwindOrder[j].Unwind == nil {
continue
}
if err := s.unwindStage(false, s.unwindOrder[j], db, tx); err != nil {
return err
}
}
s.prevUnwindPoint = s.unwindPoint
s.unwindPoint = nil
s.badBlock = libcommon.Hash{}
if err := s.SetCurrentStage(s.stages[0].ID); err != nil {
return err
}
return nil
}
func (s *Sync) Run(db kv.RwDB, tx kv.RwTx, firstCycle bool, quiet bool) error {
s.prevUnwindPoint = nil
s.timings = s.timings[:0]
for !s.IsDone() {
var badBlockUnwind bool
if s.unwindPoint != nil {
for j := 0; j < len(s.unwindOrder); j++ {
if s.unwindOrder[j] == nil || s.unwindOrder[j].Disabled || s.unwindOrder[j].Unwind == nil {
continue
}
if err := s.unwindStage(firstCycle, s.unwindOrder[j], db, tx); err != nil {
return err
}
}
s.prevUnwindPoint = s.unwindPoint
s.unwindPoint = nil
if s.badBlock != (libcommon.Hash{}) {
badBlockUnwind = true
}
s.badBlock = libcommon.Hash{}
if err := s.SetCurrentStage(s.stages[0].ID); err != nil {
return err
}
// If there were unwinds at the start, a heavier but invalid chain may be present, so
// we relax the rules for Stage1
firstCycle = false
}
stage := s.stages[s.currentStage]
if string(stage.ID) == dbg.StopBeforeStage() { // stop process for debugging reasons
log.Warn("STOP_BEFORE_STAGE env flag forced to stop app")
return libcommon.ErrStopped
}
if stage.Disabled || stage.Forward == nil {
log.Trace(fmt.Sprintf("%s disabled. %s", stage.ID, stage.DisabledDescription))
s.NextStage()
continue
}
if err := s.runStage(stage, db, tx, firstCycle, badBlockUnwind, quiet); err != nil {
return err
}
if string(stage.ID) == dbg.StopAfterStage() { // stop process for debugging reasons
log.Warn("STOP_AFTER_STAGE env flag forced to stop app")
return libcommon.ErrStopped
}
s.NextStage()
}
if err := s.SetCurrentStage(s.stages[0].ID); err != nil {
return err
}
s.currentStage = 0
return nil
}
func (s *Sync) RunPrune(db kv.RwDB, tx kv.RwTx, firstCycle bool) error {
s.timings = s.timings[:0]
for i := 0; i < len(s.pruningOrder); i++ {
if s.pruningOrder[i] == nil || s.pruningOrder[i].Disabled || s.pruningOrder[i].Prune == nil {
continue
}
if err := s.pruneStage(firstCycle, s.pruningOrder[i], db, tx); err != nil {
return err
}
}
if err := s.SetCurrentStage(s.stages[0].ID); err != nil {
return err
}
s.currentStage = 0
return nil
}
func (s *Sync) PrintTimings() []interface{} {
var logCtx []interface{}
count := 0
for i := range s.timings {
if s.timings[i].took < 50*time.Millisecond {
continue
}
count++
if count == 50 {
break
}
if s.timings[i].isUnwind {
logCtx = append(logCtx, "Unwind "+string(s.timings[i].stage), s.timings[i].took.Truncate(time.Millisecond).String())
} else if s.timings[i].isPrune {
logCtx = append(logCtx, "Prune "+string(s.timings[i].stage), s.timings[i].took.Truncate(time.Millisecond).String())
} else {
logCtx = append(logCtx, string(s.timings[i].stage), s.timings[i].took.Truncate(time.Millisecond).String())
}
}
return logCtx
}
func PrintTables(db kv.RoDB, tx kv.RwTx) []interface{} {
if tx == nil {
return nil
}
buckets := []string{
kv.PlainState,
kv.AccountChangeSet,
kv.StorageChangeSet,
kv.EthTx,
kv.Log,
}
bucketSizes := make([]interface{}, 0, 2*(len(buckets)+2))
for _, bucket := range buckets {
sz, err1 := tx.BucketSize(bucket)
if err1 != nil {
return bucketSizes
}
bucketSizes = append(bucketSizes, bucket, libcommon.ByteCount(sz))
}
sz, err1 := tx.BucketSize("freelist")
if err1 != nil {
return bucketSizes
}
bucketSizes = append(bucketSizes, "FreeList", libcommon.ByteCount(sz))
amountOfFreePagesInDb := sz / 4 // page_id encoded as bigEndian_u32
if db != nil {
bucketSizes = append(bucketSizes, "ReclaimableSpace", libcommon.ByteCount(amountOfFreePagesInDb*db.PageSize()))
}
tx.CollectMetrics()
return bucketSizes
}
func (s *Sync) runStage(stage *Stage, db kv.RwDB, tx kv.RwTx, firstCycle bool, badBlockUnwind bool, quiet bool) (err error) {
start := time.Now()
stageState, err := s.StageState(stage.ID, tx, db)
if err != nil {
return err
}
if err = stage.Forward(firstCycle, badBlockUnwind, stageState, s, tx, quiet); err != nil {
wrappedError := fmt.Errorf("[%s] %w", s.LogPrefix(), err)
log.Debug("Error while executing stage", "err", wrappedError)
return wrappedError
}
took := time.Since(start)
logPrefix := s.LogPrefix()
if took > 60*time.Second {
log.Info(fmt.Sprintf("[%s] DONE", logPrefix), "in", took)
} else {
log.Debug(fmt.Sprintf("[%s] DONE", logPrefix), "in", took)
}
s.timings = append(s.timings, Timing{stage: stage.ID, took: took})
return nil
}
func (s *Sync) unwindStage(firstCycle bool, stage *Stage, db kv.RwDB, tx kv.RwTx) error {
start := time.Now()
log.Trace("Unwind...", "stage", stage.ID)
stageState, err := s.StageState(stage.ID, tx, db)
if err != nil {
return err
}
unwind := s.NewUnwindState(stage.ID, *s.unwindPoint, stageState.BlockNumber)
unwind.BadBlock = s.badBlock
if stageState.BlockNumber <= unwind.UnwindPoint {
return nil
}
if err = s.SetCurrentStage(stage.ID); err != nil {
return err
}
err = stage.Unwind(firstCycle, unwind, stageState, tx)
if err != nil {
return fmt.Errorf("[%s] %w", s.LogPrefix(), err)
}
took := time.Since(start)
if took > 60*time.Second {
logPrefix := s.LogPrefix()
log.Info(fmt.Sprintf("[%s] Unwind done", logPrefix), "in", took)
}
s.timings = append(s.timings, Timing{isUnwind: true, stage: stage.ID, took: took})
return nil
}
func (s *Sync) pruneStage(firstCycle bool, stage *Stage, db kv.RwDB, tx kv.RwTx) error {
start := time.Now()
log.Trace("Prune...", "stage", stage.ID)
stageState, err := s.StageState(stage.ID, tx, db)
if err != nil {
return err
}
prune, err := s.PruneStageState(stage.ID, stageState.BlockNumber, tx, db)
if err != nil {
return err
}
if err = s.SetCurrentStage(stage.ID); err != nil {
return err
}
err = stage.Prune(firstCycle, prune, tx)
if err != nil {
return fmt.Errorf("[%s] %w", s.LogPrefix(), err)
}
took := time.Since(start)
if took > 60*time.Second {
logPrefix := s.LogPrefix()
log.Info(fmt.Sprintf("[%s] Prune done", logPrefix), "in", took)
}
s.timings = append(s.timings, Timing{isPrune: true, stage: stage.ID, took: took})
return nil
}
// DisableAllStages - including their unwinds
func (s *Sync) DisableAllStages() []stages.SyncStage {
var backupEnabledIds []stages.SyncStage
for i := range s.stages {
if !s.stages[i].Disabled {
backupEnabledIds = append(backupEnabledIds, s.stages[i].ID)
}
}
for i := range s.stages {
s.stages[i].Disabled = true
}
return backupEnabledIds
}
func (s *Sync) DisableStages(ids ...stages.SyncStage) {
for i := range s.stages {
for _, id := range ids {
if s.stages[i].ID != id {
continue
}
s.stages[i].Disabled = true
}
}
}
func (s *Sync) EnableStages(ids ...stages.SyncStage) {
for i := range s.stages {
for _, id := range ids {
if s.stages[i].ID != id {
continue
}
s.stages[i].Disabled = false
}
}
}
func (s *Sync) MockExecFunc(id stages.SyncStage, f ExecFunc) {
for i := range s.stages {
if s.stages[i].ID == id {
s.stages[i].Forward = f
}
}
}