Skip to content

Commit fd39f72

Browse files
committed
core: journal the snapshot inside leveldb, not a flat file
1 parent d5d7c0c commit fd39f72

7 files changed

Lines changed: 72 additions & 61 deletions

File tree

‎core/blockchain.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ func NewBlockChain(db ethdb.Database, cacheConfig *CacheConfig, chainConfig *par
302302
}
303303
}
304304
// Load any existing snapshot, regenerating it if loading failed
305-
bc.snaps = snapshot.New(bc.db, bc.stateCache.TrieDB(), "snapshot.rlp", bc.cacheConfig.SnapshotLimit, bc.CurrentBlock().Root())
305+
bc.snaps = snapshot.New(bc.db, bc.stateCache.TrieDB(), bc.cacheConfig.SnapshotLimit, bc.CurrentBlock().Root())
306306

307307
// Take ownership of this particular state
308308
go bc.update()
@@ -854,7 +854,7 @@ func (bc *BlockChain) Stop() {
854854
bc.wg.Wait()
855855

856856
// Ensure that the entirety of the state snapshot is journalled to disk.
857-
snapBase, err := bc.snaps.Journal(bc.CurrentBlock().Root(), "snapshot.rlp")
857+
snapBase, err := bc.snaps.Journal(bc.CurrentBlock().Root())
858858
if err != nil {
859859
log.Error("Failed to journal state snapshot", "err", err)
860860
}

‎core/rawdb/accessors_snapshot.go‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,26 @@ func DeleteStorageSnapshot(db ethdb.KeyValueWriter, accountHash, storageHash com
9595
func IterateStorageSnapshots(db ethdb.Iteratee, accountHash common.Hash) ethdb.Iterator {
9696
return db.NewIteratorWithPrefix(storageSnapshotsKey(accountHash))
9797
}
98+
99+
// ReadSnapshotJournal retrieves the serialized in-memory diff layers saved at
100+
// the last shutdown. The blob is expected to be max a few 10s of megabytes.
101+
func ReadSnapshotJournal(db ethdb.KeyValueReader) []byte {
102+
data, _ := db.Get(snapshotJournalKey)
103+
return data
104+
}
105+
106+
// WriteSnapshotJournal stores the serialized in-memory diff layers to save at
107+
// shutdown. The blob is expected to be max a few 10s of megabytes.
108+
func WriteSnapshotJournal(db ethdb.KeyValueWriter, journal []byte) {
109+
if err := db.Put(snapshotJournalKey, journal); err != nil {
110+
log.Crit("Failed to store snapshot journal", "err", err)
111+
}
112+
}
113+
114+
// DeleteSnapshotJournal deletes the serialized in-memory diff layers saved at
115+
// the last shutdown
116+
func DeleteSnapshotJournal(db ethdb.KeyValueWriter) {
117+
if err := db.Delete(snapshotJournalKey); err != nil {
118+
log.Crit("Failed to remove snapshot journal", "err", err)
119+
}
120+
}

‎core/rawdb/schema.go‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,12 @@ var (
4141
// fastTrieProgressKey tracks the number of trie entries imported during fast sync.
4242
fastTrieProgressKey = []byte("TrieSync")
4343

44-
// snapshotRootKey tracks the number and hash of the last snapshot.
44+
// snapshotRootKey tracks the hash of the last snapshot.
4545
snapshotRootKey = []byte("SnapshotRoot")
4646

47+
// snapshotJournalKey tracks the in-memory diff layers across restarts.
48+
snapshotJournalKey = []byte("SnapshotJournal")
49+
4750
// Data item prefixes (use single byte to avoid mixing data types, avoid `i`, used for indexes).
4851
headerPrefix = []byte("h") // headerPrefix + num (uint64 big endian) + hash -> header
4952
headerTDSuffix = []byte("t") // headerPrefix + num (uint64 big endian) + hash + headerTDSuffix -> td

‎core/state/snapshot/difflayer_test.go‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ import (
2020
"bytes"
2121
"math/big"
2222
"math/rand"
23-
"os"
24-
"path"
2523
"testing"
2624

2725
"github.com/VictoriaMetrics/fastcache"
@@ -343,7 +341,6 @@ func BenchmarkJournal(b *testing.B) {
343341
b.ResetTimer()
344342

345343
for i := 0; i < b.N; i++ {
346-
f, _, _ := layer.Journal(path.Join(os.TempDir(), "difflayer_journal.tmp"))
347-
f.Close()
344+
layer.Journal(new(bytes.Buffer))
348345
}
349346
}

‎core/state/snapshot/journal.go‎

Lines changed: 27 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,11 @@
1717
package snapshot
1818

1919
import (
20-
"bufio"
20+
"bytes"
2121
"encoding/binary"
2222
"errors"
2323
"fmt"
2424
"io"
25-
"os"
2625
"time"
2726

2827
"github.com/VictoriaMetrics/fastcache"
@@ -58,7 +57,7 @@ type journalStorage struct {
5857
}
5958

6059
// loadSnapshot loads a pre-existing state snapshot backed by a key-value store.
61-
func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, journal string, cache int, root common.Hash) (snapshot, error) {
60+
func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash) (snapshot, error) {
6261
// Retrieve the block number and hash of the snapshot, failing if no snapshot
6362
// is present in the database (or crashed mid-update).
6463
baseRoot := rawdb.ReadSnapshotRoot(diskdb)
@@ -71,13 +70,13 @@ func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, journal str
7170
cache: fastcache.New(cache * 1024 * 1024),
7271
root: baseRoot,
7372
}
74-
// Open the journal, it must exist since even for 0 layer it stores whether
73+
// Retrieve the journal, it must exist since even for 0 layer it stores whether
7574
// we've already generated the snapshot or are in progress only
76-
file, err := os.Open(journal)
77-
if err != nil {
78-
return nil, err
75+
journal := rawdb.ReadSnapshotJournal(diskdb)
76+
if len(journal) == 0 {
77+
return nil, errors.New("missing or corrupted snapshot journal")
7978
}
80-
r := rlp.NewStream(file, 0)
79+
r := rlp.NewStream(bytes.NewReader(journal), 0)
8180

8281
// Read the snapshot generation progress for the disk layer
8382
var generator journalGenerator
@@ -162,9 +161,9 @@ func loadDiffLayer(parent snapshot, r *rlp.Stream) (snapshot, error) {
162161
return loadDiffLayer(newDiffLayer(parent, root, accountData, storageData), r)
163162
}
164163

165-
// Journal is the internal version of Journal that also returns the journal file
166-
// so subsequent layers know where to write to.
167-
func (dl *diskLayer) Journal(path string) (io.WriteCloser, common.Hash, error) {
164+
// Journal writes the persistent layer generator stats into a buffer to be stored
165+
// in the database as the snapshot journal.
166+
func (dl *diskLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
168167
// If the snapshot is currenty being generated, abort it
169168
var stats *generatorStats
170169
if dl.genAbort != nil {
@@ -180,12 +179,7 @@ func (dl *diskLayer) Journal(path string) (io.WriteCloser, common.Hash, error) {
180179
defer dl.lock.RUnlock()
181180

182181
if dl.stale {
183-
return nil, common.Hash{}, ErrSnapshotStale
184-
}
185-
// We've reached the bottom, open the journal
186-
file, err := os.Create(path)
187-
if err != nil {
188-
return nil, common.Hash{}, err
182+
return common.Hash{}, ErrSnapshotStale
189183
}
190184
// Write out the generator marker
191185
entry := journalGenerator{
@@ -198,44 +192,37 @@ func (dl *diskLayer) Journal(path string) (io.WriteCloser, common.Hash, error) {
198192
entry.Slots = stats.slots
199193
entry.Storage = uint64(stats.storage)
200194
}
201-
if err := rlp.Encode(file, entry); err != nil {
202-
file.Close()
203-
return nil, common.Hash{}, err
195+
if err := rlp.Encode(buffer, entry); err != nil {
196+
return common.Hash{}, err
204197
}
205-
return file, dl.root, nil
198+
return dl.root, nil
206199
}
207200

208-
// Journal is the internal version of Journal that also returns the journal file
209-
// so subsequent layers know where to write to.
210-
func (dl *diffLayer) Journal(path string) (io.WriteCloser, common.Hash, error) {
201+
// Journal writes the memory layer contents into a buffer to be stored in the
202+
// database as the snapshot journal.
203+
func (dl *diffLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
211204
// Journal the parent first
212-
writer, base, err := dl.parent.Journal(path)
205+
base, err := dl.parent.Journal(buffer)
213206
if err != nil {
214-
return nil, common.Hash{}, err
207+
return common.Hash{}, err
215208
}
216209
// Ensure the layer didn't get stale
217210
dl.lock.RLock()
218211
defer dl.lock.RUnlock()
219212

220213
if dl.stale {
221-
writer.Close()
222-
return nil, common.Hash{}, ErrSnapshotStale
214+
return common.Hash{}, ErrSnapshotStale
223215
}
224216
// Everything below was journalled, persist this layer too
225-
buf := bufio.NewWriter(writer)
226-
if err := rlp.Encode(buf, dl.root); err != nil {
227-
buf.Flush()
228-
writer.Close()
229-
return nil, common.Hash{}, err
217+
if err := rlp.Encode(buffer, dl.root); err != nil {
218+
return common.Hash{}, err
230219
}
231220
accounts := make([]journalAccount, 0, len(dl.accountData))
232221
for hash, blob := range dl.accountData {
233222
accounts = append(accounts, journalAccount{Hash: hash, Blob: blob})
234223
}
235-
if err := rlp.Encode(buf, accounts); err != nil {
236-
buf.Flush()
237-
writer.Close()
238-
return nil, common.Hash{}, err
224+
if err := rlp.Encode(buffer, accounts); err != nil {
225+
return common.Hash{}, err
239226
}
240227
storage := make([]journalStorage, 0, len(dl.storageData))
241228
for hash, slots := range dl.storageData {
@@ -247,11 +234,8 @@ func (dl *diffLayer) Journal(path string) (io.WriteCloser, common.Hash, error) {
247234
}
248235
storage = append(storage, journalStorage{Hash: hash, Keys: keys, Vals: vals})
249236
}
250-
if err := rlp.Encode(buf, storage); err != nil {
251-
buf.Flush()
252-
writer.Close()
253-
return nil, common.Hash{}, err
237+
if err := rlp.Encode(buffer, storage); err != nil {
238+
return common.Hash{}, err
254239
}
255-
buf.Flush()
256-
return writer, base, nil
240+
return base, nil
257241
}

‎core/state/snapshot/snapshot.go‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ import (
2121
"bytes"
2222
"errors"
2323
"fmt"
24-
"io"
2524
"sync"
2625

2726
"github.com/ethereum/go-ethereum/common"
@@ -112,10 +111,10 @@ type snapshot interface {
112111
// copying everything.
113112
Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer
114113

115-
// Journal commits an entire diff hierarchy to disk into a single journal file.
114+
// Journal commits an entire diff hierarchy to disk into a single journal entry.
116115
// This is meant to be used during shutdown to persist the snapshot without
117116
// flattening everything down (bad for reorgs).
118-
Journal(path string) (io.WriteCloser, common.Hash, error)
117+
Journal(buffer *bytes.Buffer) (common.Hash, error)
119118

120119
// Stale return whether this layer has become stale (was flattened across) or
121120
// if it's still live.
@@ -146,7 +145,7 @@ type Tree struct {
146145
// If the snapshot is missing or inconsistent, the entirety is deleted and will
147146
// be reconstructed from scratch based on the tries in the key-value store, on a
148147
// background thread.
149-
func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, journal string, cache int, root common.Hash) *Tree {
148+
func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash) *Tree {
150149
// Create a new, empty snapshot tree
151150
snap := &Tree{
152151
diskdb: diskdb,
@@ -155,7 +154,7 @@ func New(diskdb ethdb.KeyValueStore, triedb *trie.Database, journal string, cach
155154
layers: make(map[common.Hash]snapshot),
156155
}
157156
// Attempt to load a previously persisted snapshot and rebuild one if failed
158-
head, err := loadSnapshot(diskdb, triedb, journal, cache, root)
157+
head, err := loadSnapshot(diskdb, triedb, cache, root)
159158
if err != nil {
160159
log.Warn("Failed to load snapshot, regenerating", "err", err)
161160
snap.Rebuild(root)
@@ -401,6 +400,7 @@ func diffToDisk(bottom *diffLayer) *diskLayer {
401400
// Account was updated, push to disk
402401
rawdb.WriteAccountSnapshot(batch, hash, data)
403402
base.cache.Set(hash[:], data)
403+
snapshotCleanAccountWriteMeter.Mark(int64(len(data)))
404404

405405
if batch.ValueSize() > ethdb.IdealBatchSize {
406406
if err := batch.Write(); err != nil {
@@ -445,6 +445,7 @@ func diffToDisk(bottom *diffLayer) *diskLayer {
445445
if len(data) > 0 {
446446
rawdb.WriteStorageSnapshot(batch, accountHash, storageHash, data)
447447
base.cache.Set(append(accountHash[:], storageHash[:]...), data)
448+
snapshotCleanStorageWriteMeter.Mark(int64(len(data)))
448449
} else {
449450
rawdb.DeleteStorageSnapshot(batch, accountHash, storageHash)
450451
base.cache.Set(append(accountHash[:], storageHash[:]...), nil)
@@ -484,13 +485,13 @@ func diffToDisk(bottom *diffLayer) *diskLayer {
484485
return res
485486
}
486487

487-
// Journal commits an entire diff hierarchy to disk into a single journal file.
488+
// Journal commits an entire diff hierarchy to disk into a single journal entry.
488489
// This is meant to be used during shutdown to persist the snapshot without
489490
// flattening everything down (bad for reorgs).
490491
//
491492
// The method returns the root hash of the base layer that needs to be persisted
492493
// to disk as a trie too to allow continuing any pending generation op.
493-
func (t *Tree) Journal(root common.Hash, path string) (common.Hash, error) {
494+
func (t *Tree) Journal(root common.Hash) (common.Hash, error) {
494495
// Retrieve the head snapshot to journal from var snap snapshot
495496
snap := t.Snapshot(root)
496497
if snap == nil {
@@ -500,11 +501,14 @@ func (t *Tree) Journal(root common.Hash, path string) (common.Hash, error) {
500501
t.lock.Lock()
501502
defer t.lock.Unlock()
502503

503-
writer, base, err := snap.(snapshot).Journal(path)
504+
journal := new(bytes.Buffer)
505+
base, err := snap.(snapshot).Journal(journal)
504506
if err != nil {
505507
return common.Hash{}, err
506508
}
507-
return base, writer.Close()
509+
// Store the journal into the database and return
510+
rawdb.WriteSnapshotJournal(t.diskdb, journal.Bytes())
511+
return base, nil
508512
}
509513

510514
// Rebuild wipes all available snapshot data from the persistent database and

‎core/state/statedb.go‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -845,8 +845,8 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
845845
if err := s.snaps.Update(root, parent, s.snapAccounts, s.snapStorage); err != nil {
846846
log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
847847
}
848-
if err := s.snaps.Cap(root, 128); err != nil {
849-
log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err)
848+
if err := s.snaps.Cap(root, 127); err != nil { // Persistent layer is 128th, the last available trie
849+
log.Warn("Failed to cap snapshot tree", "root", root, "layers", 127, "err", err)
850850
}
851851
}
852852
s.snap, s.snapAccounts, s.snapStorage = nil, nil, nil

0 commit comments

Comments
 (0)