journal.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Copyright 2019 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package snapshot
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "errors"
  21. "fmt"
  22. "io"
  23. "time"
  24. "github.com/VictoriaMetrics/fastcache"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/ethdb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/ethereum/go-ethereum/rlp"
  30. "github.com/ethereum/go-ethereum/trie"
  31. )
  32. // journalGenerator is a disk layer entry containing the generator progress marker.
  33. type journalGenerator struct {
  34. Wiping bool // Whether the database was in progress of being wiped
  35. Done bool // Whether the generator finished creating the snapshot
  36. Marker []byte
  37. Accounts uint64
  38. Slots uint64
  39. Storage uint64
  40. }
  41. // journalAccount is an account entry in a diffLayer's disk journal.
  42. type journalAccount struct {
  43. Hash common.Hash
  44. Blob []byte
  45. }
  46. // journalStorage is an account's storage map in a diffLayer's disk journal.
  47. type journalStorage struct {
  48. Hash common.Hash
  49. Keys []common.Hash
  50. Vals [][]byte
  51. }
  52. // loadSnapshot loads a pre-existing state snapshot backed by a key-value store.
  53. func loadSnapshot(diskdb ethdb.KeyValueStore, triedb *trie.Database, cache int, root common.Hash) (snapshot, error) {
  54. // Retrieve the block number and hash of the snapshot, failing if no snapshot
  55. // is present in the database (or crashed mid-update).
  56. baseRoot := rawdb.ReadSnapshotRoot(diskdb)
  57. if baseRoot == (common.Hash{}) {
  58. return nil, errors.New("missing or corrupted snapshot")
  59. }
  60. base := &diskLayer{
  61. diskdb: diskdb,
  62. triedb: triedb,
  63. cache: fastcache.New(cache * 1024 * 1024),
  64. root: baseRoot,
  65. }
  66. // Retrieve the journal, it must exist since even for 0 layer it stores whether
  67. // we've already generated the snapshot or are in progress only
  68. journal := rawdb.ReadSnapshotJournal(diskdb)
  69. if len(journal) == 0 {
  70. return nil, errors.New("missing or corrupted snapshot journal")
  71. }
  72. r := rlp.NewStream(bytes.NewReader(journal), 0)
  73. // Read the snapshot generation progress for the disk layer
  74. var generator journalGenerator
  75. if err := r.Decode(&generator); err != nil {
  76. return nil, fmt.Errorf("failed to load snapshot progress marker: %v", err)
  77. }
  78. // Load all the snapshot diffs from the journal
  79. snapshot, err := loadDiffLayer(base, r)
  80. if err != nil {
  81. return nil, err
  82. }
  83. // Entire snapshot journal loaded, sanity check the head and return
  84. // Journal doesn't exist, don't worry if it's not supposed to
  85. if head := snapshot.Root(); head != root {
  86. return nil, fmt.Errorf("head doesn't match snapshot: have %#x, want %#x", head, root)
  87. }
  88. // Everything loaded correctly, resume any suspended operations
  89. if !generator.Done {
  90. // If the generator was still wiping, restart one from scratch (fine for
  91. // now as it's rare and the wiper deletes the stuff it touches anyway, so
  92. // restarting won't incur a lot of extra database hops.
  93. var wiper chan struct{}
  94. if generator.Wiping {
  95. log.Info("Resuming previous snapshot wipe")
  96. wiper = wipeSnapshot(diskdb, false)
  97. }
  98. // Whether or not wiping was in progress, load any generator progress too
  99. base.genMarker = generator.Marker
  100. if base.genMarker == nil {
  101. base.genMarker = []byte{}
  102. }
  103. base.genAbort = make(chan chan *generatorStats)
  104. var origin uint64
  105. if len(generator.Marker) >= 8 {
  106. origin = binary.BigEndian.Uint64(generator.Marker)
  107. }
  108. go base.generate(&generatorStats{
  109. wiping: wiper,
  110. origin: origin,
  111. start: time.Now(),
  112. accounts: generator.Accounts,
  113. slots: generator.Slots,
  114. storage: common.StorageSize(generator.Storage),
  115. })
  116. }
  117. return snapshot, nil
  118. }
  119. // loadDiffLayer reads the next sections of a snapshot journal, reconstructing a new
  120. // diff and verifying that it can be linked to the requested parent.
  121. func loadDiffLayer(parent snapshot, r *rlp.Stream) (snapshot, error) {
  122. // Read the next diff journal entry
  123. var root common.Hash
  124. if err := r.Decode(&root); err != nil {
  125. // The first read may fail with EOF, marking the end of the journal
  126. if err == io.EOF {
  127. return parent, nil
  128. }
  129. return nil, fmt.Errorf("load diff root: %v", err)
  130. }
  131. var accounts []journalAccount
  132. if err := r.Decode(&accounts); err != nil {
  133. return nil, fmt.Errorf("load diff accounts: %v", err)
  134. }
  135. accountData := make(map[common.Hash][]byte)
  136. for _, entry := range accounts {
  137. accountData[entry.Hash] = entry.Blob
  138. }
  139. var storage []journalStorage
  140. if err := r.Decode(&storage); err != nil {
  141. return nil, fmt.Errorf("load diff storage: %v", err)
  142. }
  143. storageData := make(map[common.Hash]map[common.Hash][]byte)
  144. for _, entry := range storage {
  145. slots := make(map[common.Hash][]byte)
  146. for i, key := range entry.Keys {
  147. slots[key] = entry.Vals[i]
  148. }
  149. storageData[entry.Hash] = slots
  150. }
  151. return loadDiffLayer(newDiffLayer(parent, root, accountData, storageData), r)
  152. }
  153. // Journal writes the persistent layer generator stats into a buffer to be stored
  154. // in the database as the snapshot journal.
  155. func (dl *diskLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
  156. // If the snapshot is currenty being generated, abort it
  157. var stats *generatorStats
  158. if dl.genAbort != nil {
  159. abort := make(chan *generatorStats)
  160. dl.genAbort <- abort
  161. if stats = <-abort; stats != nil {
  162. stats.Log("Journalling in-progress snapshot", dl.genMarker)
  163. }
  164. }
  165. // Ensure the layer didn't get stale
  166. dl.lock.RLock()
  167. defer dl.lock.RUnlock()
  168. if dl.stale {
  169. return common.Hash{}, ErrSnapshotStale
  170. }
  171. // Write out the generator marker
  172. entry := journalGenerator{
  173. Done: dl.genMarker == nil,
  174. Marker: dl.genMarker,
  175. }
  176. if stats != nil {
  177. entry.Wiping = (stats.wiping != nil)
  178. entry.Accounts = stats.accounts
  179. entry.Slots = stats.slots
  180. entry.Storage = uint64(stats.storage)
  181. }
  182. if err := rlp.Encode(buffer, entry); err != nil {
  183. return common.Hash{}, err
  184. }
  185. return dl.root, nil
  186. }
  187. // Journal writes the memory layer contents into a buffer to be stored in the
  188. // database as the snapshot journal.
  189. func (dl *diffLayer) Journal(buffer *bytes.Buffer) (common.Hash, error) {
  190. // Journal the parent first
  191. base, err := dl.parent.Journal(buffer)
  192. if err != nil {
  193. return common.Hash{}, err
  194. }
  195. // Ensure the layer didn't get stale
  196. dl.lock.RLock()
  197. defer dl.lock.RUnlock()
  198. if dl.stale {
  199. return common.Hash{}, ErrSnapshotStale
  200. }
  201. // Everything below was journalled, persist this layer too
  202. if err := rlp.Encode(buffer, dl.root); err != nil {
  203. return common.Hash{}, err
  204. }
  205. accounts := make([]journalAccount, 0, len(dl.accountData))
  206. for hash, blob := range dl.accountData {
  207. accounts = append(accounts, journalAccount{Hash: hash, Blob: blob})
  208. }
  209. if err := rlp.Encode(buffer, accounts); err != nil {
  210. return common.Hash{}, err
  211. }
  212. storage := make([]journalStorage, 0, len(dl.storageData))
  213. for hash, slots := range dl.storageData {
  214. keys := make([]common.Hash, 0, len(slots))
  215. vals := make([][]byte, 0, len(slots))
  216. for key, val := range slots {
  217. keys = append(keys, key)
  218. vals = append(vals, val)
  219. }
  220. storage = append(storage, journalStorage{Hash: hash, Keys: keys, Vals: vals})
  221. }
  222. if err := rlp.Encode(buffer, storage); err != nil {
  223. return common.Hash{}, err
  224. }
  225. return base, nil
  226. }