forked from erigontech/erigon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstage_snapshots.go
414 lines (372 loc) · 13 KB
/
stage_snapshots.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
package stagedsync
import (
"context"
"encoding/binary"
"fmt"
"math/big"
"runtime"
"time"
"github.com/holiman/uint256"
libcommon "github.com/ledgerwatch/erigon-lib/common"
"github.com/ledgerwatch/erigon-lib/common/cmp"
"github.com/ledgerwatch/erigon-lib/etl"
proto_downloader "github.com/ledgerwatch/erigon-lib/gointerfaces/downloader"
"github.com/ledgerwatch/erigon-lib/kv"
"github.com/ledgerwatch/erigon/common/dbutils"
"github.com/ledgerwatch/erigon/core/rawdb"
"github.com/ledgerwatch/erigon/core/types"
"github.com/ledgerwatch/erigon/eth/stagedsync/stages"
"github.com/ledgerwatch/erigon/params"
"github.com/ledgerwatch/erigon/turbo/services"
"github.com/ledgerwatch/erigon/turbo/snapshotsync"
"github.com/ledgerwatch/erigon/turbo/snapshotsync/snapcfg"
"github.com/ledgerwatch/erigon/turbo/stages/headerdownload"
"github.com/ledgerwatch/log/v3"
)
type SnapshotsCfg struct {
db kv.RwDB
hd *headerdownload.HeaderDownload
chainConfig params.ChainConfig
tmpdir string
snapshots *snapshotsync.RoSnapshots
blockRetire *snapshotsync.BlockRetire
snapshotDownloader proto_downloader.DownloaderClient
blockReader services.FullBlockReader
dbEventNotifier snapshotsync.DBEventNotifier
}
func StageSnapshotsCfg(
db kv.RwDB,
hd *headerdownload.HeaderDownload,
chainConfig params.ChainConfig,
tmpdir string,
snapshots *snapshotsync.RoSnapshots,
blockRetire *snapshotsync.BlockRetire,
snapshotDownloader proto_downloader.DownloaderClient,
blockReader services.FullBlockReader,
dbEventNotifier snapshotsync.DBEventNotifier,
) SnapshotsCfg {
return SnapshotsCfg{
db: db,
hd: hd,
chainConfig: chainConfig,
tmpdir: tmpdir,
snapshots: snapshots,
blockRetire: blockRetire,
snapshotDownloader: snapshotDownloader,
blockReader: blockReader,
dbEventNotifier: dbEventNotifier,
}
}
func SpawnStageSnapshots(
s *StageState,
ctx context.Context,
tx kv.RwTx,
cfg SnapshotsCfg,
initialCycle bool,
) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
if err := DownloadAndIndexSnapshotsIfNeed(s, ctx, tx, cfg, initialCycle); err != nil {
return err
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
func DownloadAndIndexSnapshotsIfNeed(s *StageState, ctx context.Context, tx kv.RwTx, cfg SnapshotsCfg, initialCycle bool) error {
if !initialCycle || cfg.snapshots == nil || !cfg.snapshots.Cfg().Enabled {
return nil
}
if err := WaitForDownloader(s, ctx, cfg, tx); err != nil {
return err
}
cfg.snapshots.LogStat()
// Create .idx files
if cfg.snapshots.IndicesMax() < cfg.snapshots.SegmentsMax() {
if !cfg.snapshots.Cfg().Produce && cfg.snapshots.IndicesMax() == 0 {
return fmt.Errorf("please remove --snap.stop, erigon can't work without creating basic indices")
}
if cfg.snapshots.Cfg().Produce {
if !cfg.snapshots.SegmentsReady() {
return fmt.Errorf("not all snapshot segments are available")
}
// wait for Downloader service to download all expected snapshots
if cfg.snapshots.IndicesMax() < cfg.snapshots.SegmentsMax() {
chainID, _ := uint256.FromBig(cfg.chainConfig.ChainID)
workers := cmp.InRange(1, 2, runtime.GOMAXPROCS(-1)-1)
if err := snapshotsync.BuildMissedIndices(s.LogPrefix(), ctx, cfg.snapshots.Dir(), *chainID, cfg.tmpdir, workers, log.LvlInfo); err != nil {
return fmt.Errorf("BuildMissedIndices: %w", err)
}
}
if err := cfg.snapshots.ReopenFolder(); err != nil {
return err
}
if cfg.dbEventNotifier != nil {
cfg.dbEventNotifier.OnNewSnapshot()
}
}
}
if s.BlockNumber < cfg.snapshots.BlocksAvailable() { // allow genesis
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
h2n := etl.NewCollector("Snapshots", cfg.tmpdir, etl.NewSortableBuffer(etl.BufferOptimalSize))
defer h2n.Close()
h2n.LogLvl(log.LvlDebug)
// fill some small tables from snapshots, in future we may store this data in snapshots also, but
// for now easier just store them in db
td := big.NewInt(0)
if err := snapshotsync.ForEachHeader(ctx, cfg.snapshots, func(header *types.Header) error {
blockNum, blockHash := header.Number.Uint64(), header.Hash()
td.Add(td, header.Difficulty)
if err := rawdb.WriteTd(tx, blockHash, blockNum, td); err != nil {
return err
}
if err := rawdb.WriteCanonicalHash(tx, blockHash, blockNum); err != nil {
return err
}
if err := h2n.Collect(blockHash[:], dbutils.EncodeBlockNumber(blockNum)); err != nil {
return err
}
select {
case <-ctx.Done():
return ctx.Err()
case <-logEvery.C:
log.Info(fmt.Sprintf("[%s] Writing total difficulty index for snapshots", s.LogPrefix()), "block_num", header.Number.Uint64())
default:
}
return nil
}); err != nil {
return err
}
if err := h2n.Load(tx, kv.HeaderNumber, etl.IdentityLoadFunc, etl.TransformArgs{}); err != nil {
return err
}
// ResetSequence - allow set arbitrary value to sequence (for example to decrement it to exact value)
ok, err := cfg.snapshots.ViewTxs(cfg.snapshots.BlocksAvailable(), func(sn *snapshotsync.TxnSegment) error {
lastTxnID := sn.IdxTxnHash.BaseDataID() + uint64(sn.Seg.Count())
if err := rawdb.ResetSequence(tx, kv.EthTx, lastTxnID+1); err != nil {
return err
}
return nil
})
if err != nil {
return err
}
if !ok {
return fmt.Errorf("snapshot not found for block: %d", cfg.snapshots.BlocksAvailable())
}
canonicalHash, err := cfg.blockReader.CanonicalHash(ctx, tx, cfg.snapshots.BlocksAvailable())
if err != nil {
return err
}
if err = rawdb.WriteHeadHeaderHash(tx, canonicalHash); err != nil {
return err
}
if err := s.Update(tx, cfg.snapshots.BlocksAvailable()); err != nil {
return err
}
// saving the stage progress of other stages that are contained inside of snapshots
_ = stages.SaveStageProgress(tx, stages.Headers, cfg.snapshots.BlocksAvailable())
_ = stages.SaveStageProgress(tx, stages.Bodies, cfg.snapshots.BlocksAvailable())
_ = stages.SaveStageProgress(tx, stages.BlockHashes, cfg.snapshots.BlocksAvailable())
_ = stages.SaveStageProgress(tx, stages.Senders, cfg.snapshots.BlocksAvailable())
s.BlockNumber = cfg.snapshots.BlocksAvailable()
}
if err := cfg.hd.AddHeadersFromSnapshot(tx, cfg.snapshots.BlocksAvailable(), cfg.blockReader); err != nil {
return err
}
return nil
}
// WaitForDownloader - wait for Downloader service to download all expected snapshots
// for MVP we sync with Downloader only once, in future will send new snapshots also
func WaitForDownloader(s *StageState, ctx context.Context, cfg SnapshotsCfg, tx kv.RwTx) error {
if cfg.snapshots.Cfg().NoDownloader {
if err := cfg.snapshots.ReopenFolder(); err != nil {
return err
}
if cfg.dbEventNotifier != nil { // can notify right here, even that write txn is not commit
cfg.dbEventNotifier.OnNewSnapshot()
}
return nil
}
snInDB, err := rawdb.ReadSnapshots(tx)
if err != nil {
return err
}
dbEmpty := len(snInDB) == 0
var missingSnapshots []snapshotsync.Range
if !dbEmpty {
_, missingSnapshots, err = snapshotsync.Segments(cfg.snapshots.Dir())
if err != nil {
return err
}
}
if len(missingSnapshots) > 0 {
log.Warn(fmt.Sprintf("[%s] downloading missing snapshots", s.LogPrefix()))
}
// send all hashes to the Downloader service
preverified := snapcfg.KnownCfg(cfg.chainConfig.ChainName, snInDB).Preverified
downloadRequest := make([]snapshotsync.DownloadRequest, 0, len(preverified)+len(missingSnapshots))
// build all download requests
// builds preverified snapshots request
for _, p := range preverified {
downloadRequest = append(downloadRequest, snapshotsync.NewDownloadRequest(nil, p.Name, p.Hash))
}
// builds missing snapshots request
for i := range missingSnapshots {
downloadRequest = append(downloadRequest, snapshotsync.NewDownloadRequest(&missingSnapshots[i], "", ""))
}
log.Info(fmt.Sprintf("[%s] Fetching torrent files metadata", s.LogPrefix()))
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
}
if err := snapshotsync.RequestSnapshotsDownload(ctx, downloadRequest, cfg.snapshotDownloader); err != nil {
log.Error(fmt.Sprintf("[%s] call downloader", s.LogPrefix()), "err", err)
time.Sleep(10 * time.Second)
continue
}
break
}
downloadStartTime := time.Now()
logEvery := time.NewTicker(logInterval)
defer logEvery.Stop()
var m runtime.MemStats
// Check once without delay, for faster erigon re-start
stats, err := cfg.snapshotDownloader.Stats(ctx, &proto_downloader.StatsRequest{})
if err == nil && stats.Completed {
goto Finish
}
// Print download progress until all segments are available
Loop:
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-logEvery.C:
if stats, err := cfg.snapshotDownloader.Stats(ctx, &proto_downloader.StatsRequest{}); err != nil {
log.Warn("Error while waiting for snapshots progress", "err", err)
} else if stats.Completed {
if !cfg.snapshots.Cfg().Verify { // will verify after loop
if _, err := cfg.snapshotDownloader.Verify(ctx, &proto_downloader.VerifyRequest{}); err != nil {
return err
}
}
log.Info(fmt.Sprintf("[%s] download finished", s.LogPrefix()), "time", time.Since(downloadStartTime).String())
break Loop
} else {
if stats.MetadataReady < stats.FilesTotal {
log.Info(fmt.Sprintf("[%s] Waiting for torrents metadata: %d/%d", s.LogPrefix(), stats.MetadataReady, stats.FilesTotal))
continue
}
libcommon.ReadMemStats(&m)
downloadTimeLeft := calculateTime(stats.BytesTotal-stats.BytesCompleted, stats.DownloadRate)
log.Info(fmt.Sprintf("[%s] download", s.LogPrefix()),
"progress", fmt.Sprintf("%.2f%% %s/%s", stats.Progress, libcommon.ByteCount(stats.BytesCompleted), libcommon.ByteCount(stats.BytesTotal)),
"download-time-left", downloadTimeLeft,
"total-download-time", time.Since(downloadStartTime).Round(time.Second).String(),
"download", libcommon.ByteCount(stats.DownloadRate)+"/s",
"upload", libcommon.ByteCount(stats.UploadRate)+"/s",
)
log.Info(fmt.Sprintf("[%s] download", s.LogPrefix()),
"peers", stats.PeersUnique,
"connections", stats.ConnectionsTotal,
"files", stats.FilesTotal,
"alloc", libcommon.ByteCount(m.Alloc), "sys", libcommon.ByteCount(m.Sys),
)
}
}
}
Finish:
if cfg.snapshots.Cfg().Verify {
if _, err := cfg.snapshotDownloader.Verify(ctx, &proto_downloader.VerifyRequest{}); err != nil {
return err
}
}
if err := cfg.snapshots.ReopenFolder(); err != nil {
return err
}
if err := rawdb.WriteSnapshots(tx, cfg.snapshots.Files()); err != nil {
return err
}
if cfg.dbEventNotifier != nil { // can notify right here, even that write txn is not commit
cfg.dbEventNotifier.OnNewSnapshot()
}
firstNonGenesis, err := rawdb.SecondKey(tx, kv.Headers)
if err != nil {
return err
}
if firstNonGenesis != nil {
firstNonGenesisBlockNumber := binary.BigEndian.Uint64(firstNonGenesis)
if cfg.snapshots.SegmentsMax()+1 < firstNonGenesisBlockNumber {
log.Warn(fmt.Sprintf("[%s] Some blocks are not in snapshots and not in db", s.LogPrefix()), "max_in_snapshots", cfg.snapshots.SegmentsMax(), "min_in_db", firstNonGenesisBlockNumber)
}
}
return nil
}
func calculateTime(amountLeft, rate uint64) string {
if rate == 0 {
return "999hrs:99m:99s"
}
timeLeftInSeconds := amountLeft / rate
hours := timeLeftInSeconds / 3600
minutes := (timeLeftInSeconds / 60) % 60
seconds := timeLeftInSeconds % 60
return fmt.Sprintf("%dhrs:%dm:%ds", hours, minutes, seconds)
}
/* ====== PRUNING ====== */
// snapshots pruning sections works more as a retiring of blocks
// retiring blocks means moving block data from db into snapshots
func SnapshotsPrune(s *PruneState, cfg SnapshotsCfg, ctx context.Context, tx kv.RwTx) (err error) {
useExternalTx := tx != nil
if !useExternalTx {
tx, err = cfg.db.BeginRw(ctx)
if err != nil {
return err
}
defer tx.Rollback()
}
sn := cfg.blockRetire.Snapshots()
if sn != nil && sn.Cfg().Enabled && sn.Cfg().Produce {
if err := cfg.blockRetire.PruneAncientBlocks(tx); err != nil {
return err
}
if err := retireBlocksInSingleBackgroundThread(s, cfg.blockRetire, ctx, tx); err != nil {
return fmt.Errorf("retireBlocksInSingleBackgroundThread: %w", err)
}
}
if !useExternalTx {
if err := tx.Commit(); err != nil {
return err
}
}
return nil
}
// retiring blocks in a single thread in the brackground
func retireBlocksInSingleBackgroundThread(s *PruneState, blockRetire *snapshotsync.BlockRetire, ctx context.Context, tx kv.RwTx) (err error) {
// if something already happens in background - noop
if blockRetire.Working() {
return nil
}
if res := blockRetire.Result(); res != nil {
if res.Err != nil {
return fmt.Errorf("[%s] retire blocks last error: %w, fromBlock=%d, toBlock=%d", s.LogPrefix(), res.Err, res.BlockFrom, res.BlockTo)
}
if err := rawdb.WriteSnapshots(tx, blockRetire.Snapshots().Files()); err != nil {
return err
}
}
blockRetire.RetireBlocksInBackground(ctx, s.ForwardProgress, log.LvlInfo)
return nil
}