context.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. // Copyright 2022 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. "time"
  22. "github.com/ethereum/go-ethereum/common"
  23. "github.com/ethereum/go-ethereum/common/math"
  24. "github.com/ethereum/go-ethereum/core/rawdb"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  27. "github.com/ethereum/go-ethereum/log"
  28. )
  29. const (
  30. snapAccount = "account" // Identifier of account snapshot generation
  31. snapStorage = "storage" // Identifier of storage snapshot generation
  32. )
  33. // generatorStats is a collection of statistics gathered by the snapshot generator
  34. // for logging purposes.
  35. type generatorStats struct {
  36. origin uint64 // Origin prefix where generation started
  37. start time.Time // Timestamp when generation started
  38. accounts uint64 // Number of accounts indexed(generated or recovered)
  39. slots uint64 // Number of storage slots indexed(generated or recovered)
  40. dangling uint64 // Number of dangling storage slots
  41. storage common.StorageSize // Total account and storage slot size(generation or recovery)
  42. }
  43. // Log creates an contextual log with the given message and the context pulled
  44. // from the internally maintained statistics.
  45. func (gs *generatorStats) Log(msg string, root common.Hash, marker []byte) {
  46. var ctx []interface{}
  47. if root != (common.Hash{}) {
  48. ctx = append(ctx, []interface{}{"root", root}...)
  49. }
  50. // Figure out whether we're after or within an account
  51. switch len(marker) {
  52. case common.HashLength:
  53. ctx = append(ctx, []interface{}{"at", common.BytesToHash(marker)}...)
  54. case 2 * common.HashLength:
  55. ctx = append(ctx, []interface{}{
  56. "in", common.BytesToHash(marker[:common.HashLength]),
  57. "at", common.BytesToHash(marker[common.HashLength:]),
  58. }...)
  59. }
  60. // Add the usual measurements
  61. ctx = append(ctx, []interface{}{
  62. "accounts", gs.accounts,
  63. "slots", gs.slots,
  64. "storage", gs.storage,
  65. "dangling", gs.dangling,
  66. "elapsed", common.PrettyDuration(time.Since(gs.start)),
  67. }...)
  68. // Calculate the estimated indexing time based on current stats
  69. if len(marker) > 0 {
  70. if done := binary.BigEndian.Uint64(marker[:8]) - gs.origin; done > 0 {
  71. left := math.MaxUint64 - binary.BigEndian.Uint64(marker[:8])
  72. speed := done/uint64(time.Since(gs.start)/time.Millisecond+1) + 1 // +1s to avoid division by zero
  73. ctx = append(ctx, []interface{}{
  74. "eta", common.PrettyDuration(time.Duration(left/speed) * time.Millisecond),
  75. }...)
  76. }
  77. }
  78. log.Info(msg, ctx...)
  79. }
  80. // generatorContext carries a few global values to be shared by all generation functions.
  81. type generatorContext struct {
  82. stats *generatorStats // Generation statistic collection
  83. db ethdb.KeyValueStore // Key-value store containing the snapshot data
  84. account *holdableIterator // Iterator of account snapshot data
  85. storage *holdableIterator // Iterator of storage snapshot data
  86. batch ethdb.Batch // Database batch for writing batch data atomically
  87. logged time.Time // The timestamp when last generation progress was displayed
  88. }
  89. // newGeneratorContext initializes the context for generation.
  90. func newGeneratorContext(stats *generatorStats, db ethdb.KeyValueStore, accMarker []byte, storageMarker []byte) *generatorContext {
  91. ctx := &generatorContext{
  92. stats: stats,
  93. db: db,
  94. batch: db.NewBatch(),
  95. logged: time.Now(),
  96. }
  97. ctx.openIterator(snapAccount, accMarker)
  98. ctx.openIterator(snapStorage, storageMarker)
  99. return ctx
  100. }
  101. // openIterator constructs global account and storage snapshot iterators
  102. // at the interrupted position. These iterators should be reopened from time
  103. // to time to avoid blocking leveldb compaction for a long time.
  104. func (ctx *generatorContext) openIterator(kind string, start []byte) {
  105. if kind == snapAccount {
  106. iter := ctx.db.NewIterator(rawdb.SnapshotAccountPrefix, start)
  107. ctx.account = newHoldableIterator(rawdb.NewKeyLengthIterator(iter, 1+common.HashLength))
  108. return
  109. }
  110. iter := ctx.db.NewIterator(rawdb.SnapshotStoragePrefix, start)
  111. ctx.storage = newHoldableIterator(rawdb.NewKeyLengthIterator(iter, 1+2*common.HashLength))
  112. }
  113. // reopenIterator releases the specified snapshot iterator and re-open it
  114. // in the next position. It's aimed for not blocking leveldb compaction.
  115. func (ctx *generatorContext) reopenIterator(kind string) {
  116. // Shift iterator one more step, so that we can reopen
  117. // the iterator at the right position.
  118. var iter = ctx.account
  119. if kind == snapStorage {
  120. iter = ctx.storage
  121. }
  122. hasNext := iter.Next()
  123. if !hasNext {
  124. // Iterator exhausted, release forever and create an already exhausted virtual iterator
  125. iter.Release()
  126. if kind == snapAccount {
  127. ctx.account = newHoldableIterator(memorydb.New().NewIterator(nil, nil))
  128. return
  129. }
  130. ctx.storage = newHoldableIterator(memorydb.New().NewIterator(nil, nil))
  131. return
  132. }
  133. next := iter.Key()
  134. iter.Release()
  135. ctx.openIterator(kind, next[1:])
  136. }
  137. // close releases all the held resources.
  138. func (ctx *generatorContext) close() {
  139. ctx.account.Release()
  140. ctx.storage.Release()
  141. }
  142. // iterator returns the corresponding iterator specified by the kind.
  143. func (ctx *generatorContext) iterator(kind string) *holdableIterator {
  144. if kind == snapAccount {
  145. return ctx.account
  146. }
  147. return ctx.storage
  148. }
  149. // removeStorageBefore deletes all storage entries which are located before
  150. // the specified account. When the iterator touches the storage entry which
  151. // is located in or outside the given account, it stops and holds the current
  152. // iterated element locally.
  153. func (ctx *generatorContext) removeStorageBefore(account common.Hash) {
  154. var (
  155. count uint64
  156. start = time.Now()
  157. iter = ctx.storage
  158. )
  159. for iter.Next() {
  160. key := iter.Key()
  161. if bytes.Compare(key[1:1+common.HashLength], account.Bytes()) >= 0 {
  162. iter.Hold()
  163. break
  164. }
  165. count++
  166. ctx.batch.Delete(key)
  167. if ctx.batch.ValueSize() > ethdb.IdealBatchSize {
  168. ctx.batch.Write()
  169. ctx.batch.Reset()
  170. }
  171. }
  172. ctx.stats.dangling += count
  173. snapStorageCleanCounter.Inc(time.Since(start).Nanoseconds())
  174. }
  175. // removeStorageAt deletes all storage entries which are located in the specified
  176. // account. When the iterator touches the storage entry which is outside the given
  177. // account, it stops and holds the current iterated element locally. An error will
  178. // be returned if the initial position of iterator is not in the given account.
  179. func (ctx *generatorContext) removeStorageAt(account common.Hash) error {
  180. var (
  181. count int64
  182. start = time.Now()
  183. iter = ctx.storage
  184. )
  185. for iter.Next() {
  186. key := iter.Key()
  187. cmp := bytes.Compare(key[1:1+common.HashLength], account.Bytes())
  188. if cmp < 0 {
  189. return errors.New("invalid iterator position")
  190. }
  191. if cmp > 0 {
  192. iter.Hold()
  193. break
  194. }
  195. count++
  196. ctx.batch.Delete(key)
  197. if ctx.batch.ValueSize() > ethdb.IdealBatchSize {
  198. ctx.batch.Write()
  199. ctx.batch.Reset()
  200. }
  201. }
  202. snapWipedStorageMeter.Mark(count)
  203. snapStorageCleanCounter.Inc(time.Since(start).Nanoseconds())
  204. return nil
  205. }
  206. // removeStorageLeft deletes all storage entries which are located after
  207. // the current iterator position.
  208. func (ctx *generatorContext) removeStorageLeft() {
  209. var (
  210. count uint64
  211. start = time.Now()
  212. iter = ctx.storage
  213. )
  214. for iter.Next() {
  215. count++
  216. ctx.batch.Delete(iter.Key())
  217. if ctx.batch.ValueSize() > ethdb.IdealBatchSize {
  218. ctx.batch.Write()
  219. ctx.batch.Reset()
  220. }
  221. }
  222. ctx.stats.dangling += count
  223. snapDanglingStorageMeter.Mark(int64(count))
  224. snapStorageCleanCounter.Inc(time.Since(start).Nanoseconds())
  225. }