database.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Copyright 2018 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 rawdb
  17. import (
  18. "bytes"
  19. "errors"
  20. "fmt"
  21. "os"
  22. "sync/atomic"
  23. "time"
  24. "github.com/ethereum/go-ethereum/common"
  25. "github.com/ethereum/go-ethereum/ethdb"
  26. "github.com/ethereum/go-ethereum/ethdb/leveldb"
  27. "github.com/ethereum/go-ethereum/ethdb/memorydb"
  28. "github.com/ethereum/go-ethereum/log"
  29. "github.com/olekukonko/tablewriter"
  30. )
  31. // freezerdb is a database wrapper that enabled freezer data retrievals.
  32. type freezerdb struct {
  33. ethdb.KeyValueStore
  34. ethdb.AncientStore
  35. }
  36. // Close implements io.Closer, closing both the fast key-value store as well as
  37. // the slow ancient tables.
  38. func (frdb *freezerdb) Close() error {
  39. var errs []error
  40. if err := frdb.AncientStore.Close(); err != nil {
  41. errs = append(errs, err)
  42. }
  43. if err := frdb.KeyValueStore.Close(); err != nil {
  44. errs = append(errs, err)
  45. }
  46. if len(errs) != 0 {
  47. return fmt.Errorf("%v", errs)
  48. }
  49. return nil
  50. }
  51. // Freeze is a helper method used for external testing to trigger and block until
  52. // a freeze cycle completes, without having to sleep for a minute to trigger the
  53. // automatic background run.
  54. func (frdb *freezerdb) Freeze(threshold uint64) {
  55. // Set the freezer threshold to a temporary value
  56. defer func(old uint64) {
  57. atomic.StoreUint64(&frdb.AncientStore.(*freezer).threshold, old)
  58. }(atomic.LoadUint64(&frdb.AncientStore.(*freezer).threshold))
  59. atomic.StoreUint64(&frdb.AncientStore.(*freezer).threshold, threshold)
  60. // Trigger a freeze cycle and block until it's done
  61. trigger := make(chan struct{}, 1)
  62. frdb.AncientStore.(*freezer).trigger <- trigger
  63. <-trigger
  64. }
  65. // nofreezedb is a database wrapper that disables freezer data retrievals.
  66. type nofreezedb struct {
  67. ethdb.KeyValueStore
  68. }
  69. // HasAncient returns an error as we don't have a backing chain freezer.
  70. func (db *nofreezedb) HasAncient(kind string, number uint64) (bool, error) {
  71. return false, errNotSupported
  72. }
  73. // Ancient returns an error as we don't have a backing chain freezer.
  74. func (db *nofreezedb) Ancient(kind string, number uint64) ([]byte, error) {
  75. return nil, errNotSupported
  76. }
  77. // Ancients returns an error as we don't have a backing chain freezer.
  78. func (db *nofreezedb) Ancients() (uint64, error) {
  79. return 0, errNotSupported
  80. }
  81. // AncientSize returns an error as we don't have a backing chain freezer.
  82. func (db *nofreezedb) AncientSize(kind string) (uint64, error) {
  83. return 0, errNotSupported
  84. }
  85. // AppendAncient returns an error as we don't have a backing chain freezer.
  86. func (db *nofreezedb) AppendAncient(number uint64, hash, header, body, receipts, td []byte) error {
  87. return errNotSupported
  88. }
  89. // TruncateAncients returns an error as we don't have a backing chain freezer.
  90. func (db *nofreezedb) TruncateAncients(items uint64) error {
  91. return errNotSupported
  92. }
  93. // Sync returns an error as we don't have a backing chain freezer.
  94. func (db *nofreezedb) Sync() error {
  95. return errNotSupported
  96. }
  97. // NewDatabase creates a high level database on top of a given key-value data
  98. // store without a freezer moving immutable chain segments into cold storage.
  99. func NewDatabase(db ethdb.KeyValueStore) ethdb.Database {
  100. return &nofreezedb{
  101. KeyValueStore: db,
  102. }
  103. }
  104. // NewDatabaseWithFreezer creates a high level database on top of a given key-
  105. // value data store with a freezer moving immutable chain segments into cold
  106. // storage.
  107. func NewDatabaseWithFreezer(db ethdb.KeyValueStore, freezer string, namespace string) (ethdb.Database, error) {
  108. // Create the idle freezer instance
  109. frdb, err := newFreezer(freezer, namespace)
  110. if err != nil {
  111. return nil, err
  112. }
  113. // Since the freezer can be stored separately from the user's key-value database,
  114. // there's a fairly high probability that the user requests invalid combinations
  115. // of the freezer and database. Ensure that we don't shoot ourselves in the foot
  116. // by serving up conflicting data, leading to both datastores getting corrupted.
  117. //
  118. // - If both the freezer and key-value store is empty (no genesis), we just
  119. // initialized a new empty freezer, so everything's fine.
  120. // - If the key-value store is empty, but the freezer is not, we need to make
  121. // sure the user's genesis matches the freezer. That will be checked in the
  122. // blockchain, since we don't have the genesis block here (nor should we at
  123. // this point care, the key-value/freezer combo is valid).
  124. // - If neither the key-value store nor the freezer is empty, cross validate
  125. // the genesis hashes to make sure they are compatible. If they are, also
  126. // ensure that there's no gap between the freezer and sunsequently leveldb.
  127. // - If the key-value store is not empty, but the freezer is we might just be
  128. // upgrading to the freezer release, or we might have had a small chain and
  129. // not frozen anything yet. Ensure that no blocks are missing yet from the
  130. // key-value store, since that would mean we already had an old freezer.
  131. // If the genesis hash is empty, we have a new key-value store, so nothing to
  132. // validate in this method. If, however, the genesis hash is not nil, compare
  133. // it to the freezer content.
  134. if kvgenesis, _ := db.Get(headerHashKey(0)); len(kvgenesis) > 0 {
  135. if frozen, _ := frdb.Ancients(); frozen > 0 {
  136. // If the freezer already contains something, ensure that the genesis blocks
  137. // match, otherwise we might mix up freezers across chains and destroy both
  138. // the freezer and the key-value store.
  139. frgenesis, err := frdb.Ancient(freezerHashTable, 0)
  140. if err != nil {
  141. return nil, fmt.Errorf("failed to retrieve genesis from ancient %v", err)
  142. } else if !bytes.Equal(kvgenesis, frgenesis) {
  143. return nil, fmt.Errorf("genesis mismatch: %#x (leveldb) != %#x (ancients)", kvgenesis, frgenesis)
  144. }
  145. // Key-value store and freezer belong to the same network. Ensure that they
  146. // are contiguous, otherwise we might end up with a non-functional freezer.
  147. if kvhash, _ := db.Get(headerHashKey(frozen)); len(kvhash) == 0 {
  148. // Subsequent header after the freezer limit is missing from the database.
  149. // Reject startup is the database has a more recent head.
  150. if *ReadHeaderNumber(db, ReadHeadHeaderHash(db)) > frozen-1 {
  151. return nil, fmt.Errorf("gap (#%d) in the chain between ancients and leveldb", frozen)
  152. }
  153. // Database contains only older data than the freezer, this happens if the
  154. // state was wiped and reinited from an existing freezer.
  155. }
  156. // Otherwise, key-value store continues where the freezer left off, all is fine.
  157. // We might have duplicate blocks (crash after freezer write but before key-value
  158. // store deletion, but that's fine).
  159. } else {
  160. // If the freezer is empty, ensure nothing was moved yet from the key-value
  161. // store, otherwise we'll end up missing data. We check block #1 to decide
  162. // if we froze anything previously or not, but do take care of databases with
  163. // only the genesis block.
  164. if ReadHeadHeaderHash(db) != common.BytesToHash(kvgenesis) {
  165. // Key-value store contains more data than the genesis block, make sure we
  166. // didn't freeze anything yet.
  167. if kvblob, _ := db.Get(headerHashKey(1)); len(kvblob) == 0 {
  168. return nil, errors.New("ancient chain segments already extracted, please set --datadir.ancient to the correct path")
  169. }
  170. // Block #1 is still in the database, we're allowed to init a new feezer
  171. }
  172. // Otherwise, the head header is still the genesis, we're allowed to init a new
  173. // feezer.
  174. }
  175. }
  176. // Freezer is consistent with the key-value database, permit combining the two
  177. go frdb.freeze(db)
  178. return &freezerdb{
  179. KeyValueStore: db,
  180. AncientStore: frdb,
  181. }, nil
  182. }
  183. // NewMemoryDatabase creates an ephemeral in-memory key-value database without a
  184. // freezer moving immutable chain segments into cold storage.
  185. func NewMemoryDatabase() ethdb.Database {
  186. return NewDatabase(memorydb.New())
  187. }
  188. // NewMemoryDatabaseWithCap creates an ephemeral in-memory key-value database
  189. // with an initial starting capacity, but without a freezer moving immutable
  190. // chain segments into cold storage.
  191. func NewMemoryDatabaseWithCap(size int) ethdb.Database {
  192. return NewDatabase(memorydb.NewWithCap(size))
  193. }
  194. // NewLevelDBDatabase creates a persistent key-value database without a freezer
  195. // moving immutable chain segments into cold storage.
  196. func NewLevelDBDatabase(file string, cache int, handles int, namespace string) (ethdb.Database, error) {
  197. db, err := leveldb.New(file, cache, handles, namespace)
  198. if err != nil {
  199. return nil, err
  200. }
  201. return NewDatabase(db), nil
  202. }
  203. // NewLevelDBDatabaseWithFreezer creates a persistent key-value database with a
  204. // freezer moving immutable chain segments into cold storage.
  205. func NewLevelDBDatabaseWithFreezer(file string, cache int, handles int, freezer string, namespace string) (ethdb.Database, error) {
  206. kvdb, err := leveldb.New(file, cache, handles, namespace)
  207. if err != nil {
  208. return nil, err
  209. }
  210. frdb, err := NewDatabaseWithFreezer(kvdb, freezer, namespace)
  211. if err != nil {
  212. kvdb.Close()
  213. return nil, err
  214. }
  215. return frdb, nil
  216. }
  217. type counter uint64
  218. func (c counter) String() string {
  219. return fmt.Sprintf("%d", c)
  220. }
  221. func (c counter) Percentage(current uint64) string {
  222. return fmt.Sprintf("%d", current*100/uint64(c))
  223. }
  224. // stat stores sizes and count for a parameter
  225. type stat struct {
  226. size common.StorageSize
  227. count counter
  228. }
  229. // Add size to the stat and increase the counter by 1
  230. func (s *stat) Add(size common.StorageSize) {
  231. s.size += size
  232. s.count++
  233. }
  234. func (s *stat) Size() string {
  235. return s.size.String()
  236. }
  237. func (s *stat) Count() string {
  238. return s.count.String()
  239. }
  240. // InspectDatabase traverses the entire database and checks the size
  241. // of all different categories of data.
  242. func InspectDatabase(db ethdb.Database, keyPrefix, keyStart []byte) error {
  243. it := db.NewIterator(keyPrefix, keyStart)
  244. defer it.Release()
  245. var (
  246. count int64
  247. start = time.Now()
  248. logged = time.Now()
  249. // Key-value store statistics
  250. headers stat
  251. bodies stat
  252. receipts stat
  253. tds stat
  254. numHashPairings stat
  255. hashNumPairings stat
  256. tries stat
  257. codes stat
  258. txLookups stat
  259. accountSnaps stat
  260. storageSnaps stat
  261. preimages stat
  262. bloomBits stat
  263. cliqueSnaps stat
  264. // Ancient store statistics
  265. ancientHeadersSize common.StorageSize
  266. ancientBodiesSize common.StorageSize
  267. ancientReceiptsSize common.StorageSize
  268. ancientTdsSize common.StorageSize
  269. ancientHashesSize common.StorageSize
  270. // Les statistic
  271. chtTrieNodes stat
  272. bloomTrieNodes stat
  273. // Meta- and unaccounted data
  274. metadata stat
  275. unaccounted stat
  276. shutdownInfo stat
  277. // Totals
  278. total common.StorageSize
  279. )
  280. // Inspect key-value database first.
  281. for it.Next() {
  282. var (
  283. key = it.Key()
  284. size = common.StorageSize(len(key) + len(it.Value()))
  285. )
  286. total += size
  287. switch {
  288. case bytes.HasPrefix(key, headerPrefix) && len(key) == (len(headerPrefix)+8+common.HashLength):
  289. headers.Add(size)
  290. case bytes.HasPrefix(key, blockBodyPrefix) && len(key) == (len(blockBodyPrefix)+8+common.HashLength):
  291. bodies.Add(size)
  292. case bytes.HasPrefix(key, blockReceiptsPrefix) && len(key) == (len(blockReceiptsPrefix)+8+common.HashLength):
  293. receipts.Add(size)
  294. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerTDSuffix):
  295. tds.Add(size)
  296. case bytes.HasPrefix(key, headerPrefix) && bytes.HasSuffix(key, headerHashSuffix):
  297. numHashPairings.Add(size)
  298. case bytes.HasPrefix(key, headerNumberPrefix) && len(key) == (len(headerNumberPrefix)+common.HashLength):
  299. hashNumPairings.Add(size)
  300. case len(key) == common.HashLength:
  301. tries.Add(size)
  302. case bytes.HasPrefix(key, CodePrefix) && len(key) == len(CodePrefix)+common.HashLength:
  303. codes.Add(size)
  304. case bytes.HasPrefix(key, txLookupPrefix) && len(key) == (len(txLookupPrefix)+common.HashLength):
  305. txLookups.Add(size)
  306. case bytes.HasPrefix(key, SnapshotAccountPrefix) && len(key) == (len(SnapshotAccountPrefix)+common.HashLength):
  307. accountSnaps.Add(size)
  308. case bytes.HasPrefix(key, SnapshotStoragePrefix) && len(key) == (len(SnapshotStoragePrefix)+2*common.HashLength):
  309. storageSnaps.Add(size)
  310. case bytes.HasPrefix(key, preimagePrefix) && len(key) == (len(preimagePrefix)+common.HashLength):
  311. preimages.Add(size)
  312. case bytes.HasPrefix(key, bloomBitsPrefix) && len(key) == (len(bloomBitsPrefix)+10+common.HashLength):
  313. bloomBits.Add(size)
  314. case bytes.HasPrefix(key, BloomBitsIndexPrefix):
  315. bloomBits.Add(size)
  316. case bytes.HasPrefix(key, []byte("clique-")) && len(key) == 7+common.HashLength:
  317. cliqueSnaps.Add(size)
  318. case bytes.HasPrefix(key, []byte("cht-")) ||
  319. bytes.HasPrefix(key, []byte("chtIndexV2-")) ||
  320. bytes.HasPrefix(key, []byte("chtRootV2-")): // Canonical hash trie
  321. chtTrieNodes.Add(size)
  322. case bytes.HasPrefix(key, []byte("blt-")) ||
  323. bytes.HasPrefix(key, []byte("bltIndex-")) ||
  324. bytes.HasPrefix(key, []byte("bltRoot-")): // Bloomtrie sub
  325. bloomTrieNodes.Add(size)
  326. case bytes.Equal(key, uncleanShutdownKey):
  327. shutdownInfo.Add(size)
  328. default:
  329. var accounted bool
  330. for _, meta := range [][]byte{
  331. databaseVersionKey, headHeaderKey, headBlockKey, headFastBlockKey, lastPivotKey,
  332. fastTrieProgressKey, snapshotRootKey, snapshotJournalKey, snapshotGeneratorKey,
  333. snapshotRecoveryKey, txIndexTailKey, fastTxLookupLimitKey, uncleanShutdownKey,
  334. badBlockKey,
  335. } {
  336. if bytes.Equal(key, meta) {
  337. metadata.Add(size)
  338. accounted = true
  339. break
  340. }
  341. }
  342. if !accounted {
  343. unaccounted.Add(size)
  344. }
  345. }
  346. count++
  347. if count%1000 == 0 && time.Since(logged) > 8*time.Second {
  348. log.Info("Inspecting database", "count", count, "elapsed", common.PrettyDuration(time.Since(start)))
  349. logged = time.Now()
  350. }
  351. }
  352. // Inspect append-only file store then.
  353. ancientSizes := []*common.StorageSize{&ancientHeadersSize, &ancientBodiesSize, &ancientReceiptsSize, &ancientHashesSize, &ancientTdsSize}
  354. for i, category := range []string{freezerHeaderTable, freezerBodiesTable, freezerReceiptTable, freezerHashTable, freezerDifficultyTable} {
  355. if size, err := db.AncientSize(category); err == nil {
  356. *ancientSizes[i] += common.StorageSize(size)
  357. total += common.StorageSize(size)
  358. }
  359. }
  360. // Get number of ancient rows inside the freezer
  361. ancients := counter(0)
  362. if count, err := db.Ancients(); err == nil {
  363. ancients = counter(count)
  364. }
  365. // Display the database statistic.
  366. stats := [][]string{
  367. {"Key-Value store", "Headers", headers.Size(), headers.Count()},
  368. {"Key-Value store", "Bodies", bodies.Size(), bodies.Count()},
  369. {"Key-Value store", "Receipt lists", receipts.Size(), receipts.Count()},
  370. {"Key-Value store", "Difficulties", tds.Size(), tds.Count()},
  371. {"Key-Value store", "Block number->hash", numHashPairings.Size(), numHashPairings.Count()},
  372. {"Key-Value store", "Block hash->number", hashNumPairings.Size(), hashNumPairings.Count()},
  373. {"Key-Value store", "Transaction index", txLookups.Size(), txLookups.Count()},
  374. {"Key-Value store", "Bloombit index", bloomBits.Size(), bloomBits.Count()},
  375. {"Key-Value store", "Contract codes", codes.Size(), codes.Count()},
  376. {"Key-Value store", "Trie nodes", tries.Size(), tries.Count()},
  377. {"Key-Value store", "Trie preimages", preimages.Size(), preimages.Count()},
  378. {"Key-Value store", "Account snapshot", accountSnaps.Size(), accountSnaps.Count()},
  379. {"Key-Value store", "Storage snapshot", storageSnaps.Size(), storageSnaps.Count()},
  380. {"Key-Value store", "Clique snapshots", cliqueSnaps.Size(), cliqueSnaps.Count()},
  381. {"Key-Value store", "Singleton metadata", metadata.Size(), metadata.Count()},
  382. {"Key-Value store", "Shutdown metadata", shutdownInfo.Size(), shutdownInfo.Count()},
  383. {"Ancient store", "Headers", ancientHeadersSize.String(), ancients.String()},
  384. {"Ancient store", "Bodies", ancientBodiesSize.String(), ancients.String()},
  385. {"Ancient store", "Receipt lists", ancientReceiptsSize.String(), ancients.String()},
  386. {"Ancient store", "Difficulties", ancientTdsSize.String(), ancients.String()},
  387. {"Ancient store", "Block number->hash", ancientHashesSize.String(), ancients.String()},
  388. {"Light client", "CHT trie nodes", chtTrieNodes.Size(), chtTrieNodes.Count()},
  389. {"Light client", "Bloom trie nodes", bloomTrieNodes.Size(), bloomTrieNodes.Count()},
  390. }
  391. table := tablewriter.NewWriter(os.Stdout)
  392. table.SetHeader([]string{"Database", "Category", "Size", "Items"})
  393. table.SetFooter([]string{"", "Total", total.String(), " "})
  394. table.AppendBulk(stats)
  395. table.Render()
  396. if unaccounted.size > 0 {
  397. log.Error("Database contains unaccounted data", "size", unaccounted.size, "count", unaccounted.count)
  398. }
  399. return nil
  400. }