Skip to content

Commit 745757a

Browse files
committed
core, eth: abort snapshot generation on snap sync and resume later
1 parent 871f50b commit 745757a

10 files changed

Lines changed: 115 additions & 31 deletions

File tree

‎core/blockchain.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,8 @@ func (bc *BlockChain) FastSyncCommitHead(hash common.Hash) error {
640640
headBlockGauge.Update(int64(block.NumberU64()))
641641
bc.chainmu.Unlock()
642642

643-
// Destroy any existing state snapshot and regenerate it in the background
643+
// Destroy any existing state snapshot and regenerate it in the background,
644+
// also resuming the normal maintenance of any previously paused snapshot.
644645
if bc.snaps != nil {
645646
bc.snaps.Rebuild(block.Root())
646647
}

‎core/rawdb/accessors_snapshot.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,26 @@ import (
2424
"github.com/ethereum/go-ethereum/log"
2525
)
2626

27+
// ReadSnapshotDisabled retrieves if the snapshot maintenance is disabled.
28+
func ReadSnapshotDisabled(db ethdb.KeyValueReader) bool {
29+
disabled, _ := db.Has(snapshotDisabledKey)
30+
return disabled
31+
}
32+
33+
// WriteSnapshotDisabled stores the snapshot pause flag.
34+
func WriteSnapshotDisabled(db ethdb.KeyValueWriter) {
35+
if err := db.Put(snapshotDisabledKey, []byte("42")); err != nil {
36+
log.Crit("Failed to store snapshot disabled flag", "err", err)
37+
}
38+
}
39+
40+
// DeleteSnapshotDisabled deletes the flag keeping the snapshot maintenance disabled.
41+
func DeleteSnapshotDisabled(db ethdb.KeyValueWriter) {
42+
if err := db.Delete(snapshotDisabledKey); err != nil {
43+
log.Crit("Failed to remove snapshot disabled flag", "err", err)
44+
}
45+
}
46+
2747
// ReadSnapshotRoot retrieves the root of the block whose state is contained in
2848
// the persisted snapshot.
2949
func ReadSnapshotRoot(db ethdb.KeyValueReader) common.Hash {

‎core/rawdb/database.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -371,9 +371,9 @@ func InspectDatabase(db ethdb.Database, keyPrefix, keyStart []byte) error {
371371
var accounted bool
372372
for _, meta := range [][]byte{
373373
databaseVersionKey, headHeaderKey, headBlockKey, headFastBlockKey, lastPivotKey,
374-
fastTrieProgressKey, snapshotRootKey, snapshotJournalKey, snapshotGeneratorKey,
375-
snapshotRecoveryKey, txIndexTailKey, fastTxLookupLimitKey, uncleanShutdownKey,
376-
badBlockKey,
374+
fastTrieProgressKey, snapshotDisabledKey, snapshotRootKey, snapshotJournalKey,
375+
snapshotGeneratorKey, snapshotRecoveryKey, txIndexTailKey, fastTxLookupLimitKey,
376+
uncleanShutdownKey, badBlockKey,
377377
} {
378378
if bytes.Equal(key, meta) {
379379
metadata.Add(size)

‎core/rawdb/schema.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,9 @@ var (
4545
// fastTrieProgressKey tracks the number of trie entries imported during fast sync.
4646
fastTrieProgressKey = []byte("TrieSync")
4747

48+
// snapshotDisabledKey flags that the snapshot should not be maintained due to initial sync.
49+
snapshotDisabledKey = []byte("SnapshotDisabled")
50+
4851
// snapshotRootKey tracks the hash of the last snapshot.
4952
snapshotRootKey = []byte("SnapshotRoot")
5053

‎core/state/snapshot/generate.go‎

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -141,16 +141,6 @@ func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) {
141141
log.Info(msg, ctx...)
142142
}
143143

144-
// ClearSnapshotMarker sets the snapshot marker to zero, meaning that snapshots
145-
// are not usable.
146-
func ClearSnapshotMarker(diskdb ethdb.KeyValueStore) {
147-
batch := diskdb.NewBatch()
148-
journalProgress(batch, []byte{}, nil)
149-
if err := batch.Write(); err != nil {
150-
log.Crit("Failed to write initialized state marker", "err", err)
151-
}
152-
}
153-
154144
// generateSnapshot regenerates a brand new snapshot based on an existing state
155145
// database and head block asynchronously. The snapshot is returned immediately
156146
// and generation is continued in the background until done.

‎core/state/snapshot/journal.go‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -126,12 +126,17 @@ func loadAndParseJournal(db ethdb.KeyValueStore, base *diskLayer) (snapshot, jou
126126
}
127127

128128
// loadSnapshot loads a pre-existing state snapshot backed by a key-value store.
129-
func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, recovery bool) (snapshot, error) {
129+
func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash, recovery bool) (snapshot, bool, error) {
130+
// If snapshotting is disabled (initial sync in progress), don't do anything,
131+
// wait for the chain to permit us to do something meaningful
132+
if rawdb.ReadSnapshotDisabled(diskdb) {
133+
return nil, true, nil
134+
}
130135
// Retrieve the block number and hash of the snapshot, failing if no snapshot
131136
// is present in the database (or crashed mid-update).
132137
baseRoot := rawdb.ReadSnapshotRoot(diskdb)
133138
if baseRoot == (common.Hash{}) {
134-
return nil, errors.New("missing or corrupted snapshot")
139+
return nil, false, errors.New("missing or corrupted snapshot")
135140
}
136141
base := &diskLayer{
137142
diskdb: diskdb,
@@ -142,7 +147,7 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int,
142147
snapshot, generator, err := loadAndParseJournal(diskdb, base)
143148
if err != nil {
144149
log.Warn("Failed to load new-format journal", "error", err)
145-
return nil, err
150+
return nil, false, err
146151
}
147152
// Entire snapshot journal loaded, sanity check the head. If the loaded
148153
// snapshot is not matched with current state root, print a warning log
@@ -157,7 +162,7 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int,
157162
// it's not in recovery mode, returns the error here for
158163
// rebuilding the entire snapshot forcibly.
159164
if !recovery {
160-
return nil, fmt.Errorf("head doesn't match snapshot: have %#x, want %#x", head, root)
165+
return nil, false, fmt.Errorf("head doesn't match snapshot: have %#x, want %#x", head, root)
161166
}
162167
// It's in snapshot recovery, the assumption is held that
163168
// the disk layer is always higher than chain head. It can
@@ -187,7 +192,7 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int,
187192
storage: common.StorageSize(generator.Storage),
188193
})
189194
}
190-
return snapshot, nil
195+
return snapshot, false, nil
191196
}
192197

193198
// loadDiffLayer reads the next sections of a snapshot journal, reconstructing a new

‎core/state/snapshot/snapshot.go‎

Lines changed: 61 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,11 @@ type snapshot interface {
148148
StorageIterator(account common.Hash, seek common.Hash) (StorageIterator, bool)
149149
}
150150

151-
// SnapshotTree is an Ethereum state snapshot tree. It consists of one persistent
152-
// base layer backed by a key-value store, on top of which arbitrarily many in-
153-
// memory diff layers are topped. The memory diffs can form a tree with branching,
154-
// but the disk layer is singleton and common to all. If a reorg goes deeper than
155-
// the disk layer, everything needs to be deleted.
151+
// Tree is an Ethereum state snapshot tree. It consists of one persistent base
152+
// layer backed by a key-value store, on top of which arbitrarily many in-memory
153+
// diff layers are topped. The memory diffs can form a tree with branching, but
154+
// the disk layer is singleton and common to all. If a reorg goes deeper than the
155+
// disk layer, everything needs to be deleted.
156156
//
157157
// The goal of a state snapshot is twofold: to allow direct access to account and
158158
// storage data to avoid expensive multi-level trie lookups; and to allow sorted,
@@ -186,7 +186,11 @@ func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root comm
186186
defer snap.waitBuild()
187187
}
188188
// Attempt to load a previously persisted snapshot and rebuild one if failed
189-
head, err := loadSnapshot(diskdb, triedb, cache, root, recovery)
189+
head, disabled, err := loadSnapshot(diskdb, triedb, cache, root, recovery)
190+
if disabled {
191+
log.Warn("Snapshot maintenance disabled (syncing)")
192+
return snap, nil
193+
}
190194
if err != nil {
191195
if rebuild {
192196
log.Warn("Failed to load snapshot, regenerating", "err", err)
@@ -224,6 +228,55 @@ func (t *Tree) waitBuild() {
224228
}
225229
}
226230

231+
// Disable interrupts any pending snapshot generator, deletes all the snapshot
232+
// layers in memory and marks snapshots disabled globally. In order to resume
233+
// the snapshot functionality, the caller must invoke Rebuild.
234+
func (t *Tree) Disable() {
235+
// Interrupt any live snapshot layers
236+
t.lock.Lock()
237+
defer t.lock.Unlock()
238+
239+
for _, layer := range t.layers {
240+
switch layer := layer.(type) {
241+
case *diskLayer:
242+
// If the base layer is generating, abort it
243+
if layer.genAbort != nil {
244+
abort := make(chan *generatorStats)
245+
layer.genAbort <- abort
246+
<-abort
247+
}
248+
// Layer should be inactive now, mark it as stale
249+
layer.lock.Lock()
250+
layer.stale = true
251+
layer.lock.Unlock()
252+
253+
case *diffLayer:
254+
// If the layer is a simple diff, simply mark as stale
255+
layer.lock.Lock()
256+
atomic.StoreUint32(&layer.stale, 1)
257+
layer.lock.Unlock()
258+
259+
default:
260+
panic(fmt.Sprintf("unknown layer type: %T", layer))
261+
}
262+
}
263+
t.layers = map[common.Hash]snapshot{}
264+
265+
// Delete all snapshot liveness information from the database
266+
batch := t.diskdb.NewBatch()
267+
268+
rawdb.WriteSnapshotDisabled(batch)
269+
rawdb.DeleteSnapshotRoot(batch)
270+
rawdb.DeleteSnapshotJournal(batch)
271+
rawdb.DeleteSnapshotGenerator(batch)
272+
rawdb.DeleteSnapshotRecoveryNumber(batch)
273+
// Note, we don't delete the sync progress
274+
275+
if err := batch.Write(); err != nil {
276+
log.Crit("Failed to disable snapshots", "err", err)
277+
}
278+
}
279+
227280
// Snapshot retrieves a snapshot belonging to the given block root, or nil if no
228281
// snapshot is maintained for that block.
229282
func (t *Tree) Snapshot(blockRoot common.Hash) Snapshot {
@@ -626,8 +679,9 @@ func (t *Tree) Rebuild(root common.Hash) {
626679
defer t.lock.Unlock()
627680

628681
// Firstly delete any recovery flag in the database. Because now we are
629-
// building a brand new snapshot.
682+
// building a brand new snapshot. Also reenable the snapshot feature.
630683
rawdb.DeleteSnapshotRecoveryNumber(t.diskdb)
684+
rawdb.DeleteSnapshotDisabled(t.diskdb)
631685

632686
// Iterate over and mark all layers stale
633687
for _, layer := range t.layers {

‎eth/downloader/downloader.go‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import (
2828
"github.com/ethereum/go-ethereum"
2929
"github.com/ethereum/go-ethereum/common"
3030
"github.com/ethereum/go-ethereum/core/rawdb"
31+
"github.com/ethereum/go-ethereum/core/state/snapshot"
3132
"github.com/ethereum/go-ethereum/core/types"
3233
"github.com/ethereum/go-ethereum/eth/protocols/eth"
3334
"github.com/ethereum/go-ethereum/eth/protocols/snap"
@@ -214,6 +215,9 @@ type BlockChain interface {
214215

215216
// InsertReceiptChain inserts a batch of receipts into the local chain.
216217
InsertReceiptChain(types.Blocks, []types.Receipts, uint64) (int, error)
218+
219+
// Snapshots returns the blockchain snapshot tree to paused it during sync.
220+
Snapshots() *snapshot.Tree
217221
}
218222

219223
// New creates a new downloader to fetch hashes and blocks from remote peers.
@@ -393,6 +397,12 @@ func (d *Downloader) synchronise(id string, hash common.Hash, td *big.Int, mode
393397
// but until snap becomes prevalent, we should support both. TODO(karalabe).
394398
if mode == SnapSync {
395399
if !d.snapSync {
400+
// Snap sync uses the snapshot namespace to store potentially flakey data until
401+
// sync completely heals and finishes. Pause snapshot maintenance in the mean
402+
// time to prevent access.
403+
if snapshots := d.blockchain.Snapshots(); snapshots != nil { // Only nil in tests
404+
snapshots.Disable()
405+
}
396406
log.Warn("Enabling snapshot sync prototype")
397407
d.snapSync = true
398408
}

‎eth/downloader/downloader_test.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import (
2929
"github.com/ethereum/go-ethereum"
3030
"github.com/ethereum/go-ethereum/common"
3131
"github.com/ethereum/go-ethereum/core/rawdb"
32+
"github.com/ethereum/go-ethereum/core/state/snapshot"
3233
"github.com/ethereum/go-ethereum/core/types"
3334
"github.com/ethereum/go-ethereum/eth/protocols/eth"
3435
"github.com/ethereum/go-ethereum/ethdb"
@@ -409,6 +410,11 @@ func (dl *downloadTester) dropPeer(id string) {
409410
dl.downloader.UnregisterPeer(id)
410411
}
411412

413+
// Snapshots implements the BlockChain interface for the downloader, but is a noop.
414+
func (dl *downloadTester) Snapshots() *snapshot.Tree {
415+
return nil
416+
}
417+
412418
type downloadTesterPeer struct {
413419
dl *downloadTester
414420
id string

‎eth/protocols/snap/sync.go‎

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -551,11 +551,6 @@ func (s *Syncer) Sync(root common.Hash, cancel chan struct{}) error {
551551
log.Debug("Snapshot sync already completed")
552552
return nil
553553
}
554-
// If sync is still not finished, we need to ensure that any marker is wiped.
555-
// Otherwise, it may happen that requests for e.g. genesis-data is delivered
556-
// from the snapshot data, instead of from the trie
557-
snapshot.ClearSnapshotMarker(s.db)
558-
559554
defer func() { // Persist any progress, independent of failure
560555
for _, task := range s.tasks {
561556
s.forwardAccountTask(task)

0 commit comments

Comments
 (0)