github.com/aswedchain/aswed@v1.0.1/trie/database.go (about) 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 17 package trie 18 19 import ( 20 "errors" 21 "fmt" 22 "io" 23 "reflect" 24 "runtime" 25 "sync" 26 "time" 27 28 "github.com/VictoriaMetrics/fastcache" 29 "github.com/aswedchain/aswed/common" 30 "github.com/aswedchain/aswed/core/rawdb" 31 "github.com/aswedchain/aswed/ethdb" 32 "github.com/aswedchain/aswed/log" 33 "github.com/aswedchain/aswed/metrics" 34 "github.com/aswedchain/aswed/rlp" 35 ) 36 37 var ( 38 memcacheCleanHitMeter = metrics.NewRegisteredMeter("trie/memcache/clean/hit", nil) 39 memcacheCleanMissMeter = metrics.NewRegisteredMeter("trie/memcache/clean/miss", nil) 40 memcacheCleanReadMeter = metrics.NewRegisteredMeter("trie/memcache/clean/read", nil) 41 memcacheCleanWriteMeter = metrics.NewRegisteredMeter("trie/memcache/clean/write", nil) 42 43 memcacheDirtyHitMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/hit", nil) 44 memcacheDirtyMissMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/miss", nil) 45 memcacheDirtyReadMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/read", nil) 46 memcacheDirtyWriteMeter = metrics.NewRegisteredMeter("trie/memcache/dirty/write", nil) 47 48 memcacheFlushTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/flush/time", nil) 49 memcacheFlushNodesMeter = metrics.NewRegisteredMeter("trie/memcache/flush/nodes", nil) 50 memcacheFlushSizeMeter = metrics.NewRegisteredMeter("trie/memcache/flush/size", nil) 51 52 memcacheGCTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/gc/time", nil) 53 memcacheGCNodesMeter = metrics.NewRegisteredMeter("trie/memcache/gc/nodes", nil) 54 memcacheGCSizeMeter = metrics.NewRegisteredMeter("trie/memcache/gc/size", nil) 55 56 memcacheCommitTimeTimer = metrics.NewRegisteredResettingTimer("trie/memcache/commit/time", nil) 57 memcacheCommitNodesMeter = metrics.NewRegisteredMeter("trie/memcache/commit/nodes", nil) 58 memcacheCommitSizeMeter = metrics.NewRegisteredMeter("trie/memcache/commit/size", nil) 59 ) 60 61 // Database is an intermediate write layer between the trie data structures and 62 // the disk database. The aim is to accumulate trie writes in-memory and only 63 // periodically flush a couple tries to disk, garbage collecting the remainder. 64 // 65 // Note, the trie Database is **not** thread safe in its mutations, but it **is** 66 // thread safe in providing individual, independent node access. The rationale 67 // behind this split design is to provide read access to RPC handlers and sync 68 // servers even while the trie is executing expensive garbage collection. 69 type Database struct { 70 diskdb ethdb.KeyValueStore // Persistent storage for matured trie nodes 71 72 cleans *fastcache.Cache // GC friendly memory cache of clean node RLPs 73 dirties map[common.Hash]*cachedNode // Data and references relationships of dirty trie nodes 74 oldest common.Hash // Oldest tracked node, flush-list head 75 newest common.Hash // Newest tracked node, flush-list tail 76 77 preimages map[common.Hash][]byte // Preimages of nodes from the secure trie 78 79 gctime time.Duration // Time spent on garbage collection since last commit 80 gcnodes uint64 // Nodes garbage collected since last commit 81 gcsize common.StorageSize // Data storage garbage collected since last commit 82 83 flushtime time.Duration // Time spent on data flushing since last commit 84 flushnodes uint64 // Nodes flushed since last commit 85 flushsize common.StorageSize // Data storage flushed since last commit 86 87 dirtiesSize common.StorageSize // Storage size of the dirty node cache (exc. metadata) 88 childrenSize common.StorageSize // Storage size of the external children tracking 89 preimagesSize common.StorageSize // Storage size of the preimages cache 90 91 lock sync.RWMutex 92 } 93 94 // rawNode is a simple binary blob used to differentiate between collapsed trie 95 // nodes and already encoded RLP binary blobs (while at the same time store them 96 // in the same cache fields). 97 type rawNode []byte 98 99 func (n rawNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") } 100 func (n rawNode) fstring(ind string) string { panic("this should never end up in a live trie") } 101 102 func (n rawNode) EncodeRLP(w io.Writer) error { 103 _, err := w.Write([]byte(n)) 104 return err 105 } 106 107 // rawFullNode represents only the useful data content of a full node, with the 108 // caches and flags stripped out to minimize its data storage. This type honors 109 // the same RLP encoding as the original parent. 110 type rawFullNode [17]node 111 112 func (n rawFullNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") } 113 func (n rawFullNode) fstring(ind string) string { panic("this should never end up in a live trie") } 114 115 func (n rawFullNode) EncodeRLP(w io.Writer) error { 116 var nodes [17]node 117 118 for i, child := range n { 119 if child != nil { 120 nodes[i] = child 121 } else { 122 nodes[i] = nilValueNode 123 } 124 } 125 return rlp.Encode(w, nodes) 126 } 127 128 // rawShortNode represents only the useful data content of a short node, with the 129 // caches and flags stripped out to minimize its data storage. This type honors 130 // the same RLP encoding as the original parent. 131 type rawShortNode struct { 132 Key []byte 133 Val node 134 } 135 136 func (n rawShortNode) cache() (hashNode, bool) { panic("this should never end up in a live trie") } 137 func (n rawShortNode) fstring(ind string) string { panic("this should never end up in a live trie") } 138 139 // cachedNode is all the information we know about a single cached trie node 140 // in the memory database write layer. 141 type cachedNode struct { 142 node node // Cached collapsed trie node, or raw rlp data 143 size uint16 // Byte size of the useful cached data 144 145 parents uint32 // Number of live nodes referencing this one 146 children map[common.Hash]uint16 // External children referenced by this node 147 148 flushPrev common.Hash // Previous node in the flush-list 149 flushNext common.Hash // Next node in the flush-list 150 } 151 152 // cachedNodeSize is the raw size of a cachedNode data structure without any 153 // node data included. It's an approximate size, but should be a lot better 154 // than not counting them. 155 var cachedNodeSize = int(reflect.TypeOf(cachedNode{}).Size()) 156 157 // cachedNodeChildrenSize is the raw size of an initialized but empty external 158 // reference map. 159 const cachedNodeChildrenSize = 48 160 161 // rlp returns the raw rlp encoded blob of the cached trie node, either directly 162 // from the cache, or by regenerating it from the collapsed node. 163 func (n *cachedNode) rlp() []byte { 164 if node, ok := n.node.(rawNode); ok { 165 return node 166 } 167 blob, err := rlp.EncodeToBytes(n.node) 168 if err != nil { 169 panic(err) 170 } 171 return blob 172 } 173 174 // obj returns the decoded and expanded trie node, either directly from the cache, 175 // or by regenerating it from the rlp encoded blob. 176 func (n *cachedNode) obj(hash common.Hash) node { 177 if node, ok := n.node.(rawNode); ok { 178 return mustDecodeNode(hash[:], node) 179 } 180 return expandNode(hash[:], n.node) 181 } 182 183 // forChilds invokes the callback for all the tracked children of this node, 184 // both the implicit ones from inside the node as well as the explicit ones 185 // from outside the node. 186 func (n *cachedNode) forChilds(onChild func(hash common.Hash)) { 187 for child := range n.children { 188 onChild(child) 189 } 190 if _, ok := n.node.(rawNode); !ok { 191 forGatherChildren(n.node, onChild) 192 } 193 } 194 195 // forGatherChildren traverses the node hierarchy of a collapsed storage node and 196 // invokes the callback for all the hashnode children. 197 func forGatherChildren(n node, onChild func(hash common.Hash)) { 198 switch n := n.(type) { 199 case *rawShortNode: 200 forGatherChildren(n.Val, onChild) 201 case rawFullNode: 202 for i := 0; i < 16; i++ { 203 forGatherChildren(n[i], onChild) 204 } 205 case hashNode: 206 onChild(common.BytesToHash(n)) 207 case valueNode, nil, rawNode: 208 default: 209 panic(fmt.Sprintf("unknown node type: %T", n)) 210 } 211 } 212 213 // simplifyNode traverses the hierarchy of an expanded memory node and discards 214 // all the internal caches, returning a node that only contains the raw data. 215 func simplifyNode(n node) node { 216 switch n := n.(type) { 217 case *shortNode: 218 // Short nodes discard the flags and cascade 219 return &rawShortNode{Key: n.Key, Val: simplifyNode(n.Val)} 220 221 case *fullNode: 222 // Full nodes discard the flags and cascade 223 node := rawFullNode(n.Children) 224 for i := 0; i < len(node); i++ { 225 if node[i] != nil { 226 node[i] = simplifyNode(node[i]) 227 } 228 } 229 return node 230 231 case valueNode, hashNode, rawNode: 232 return n 233 234 default: 235 panic(fmt.Sprintf("unknown node type: %T", n)) 236 } 237 } 238 239 // expandNode traverses the node hierarchy of a collapsed storage node and converts 240 // all fields and keys into expanded memory form. 241 func expandNode(hash hashNode, n node) node { 242 switch n := n.(type) { 243 case *rawShortNode: 244 // Short nodes need key and child expansion 245 return &shortNode{ 246 Key: compactToHex(n.Key), 247 Val: expandNode(nil, n.Val), 248 flags: nodeFlag{ 249 hash: hash, 250 }, 251 } 252 253 case rawFullNode: 254 // Full nodes need child expansion 255 node := &fullNode{ 256 flags: nodeFlag{ 257 hash: hash, 258 }, 259 } 260 for i := 0; i < len(node.Children); i++ { 261 if n[i] != nil { 262 node.Children[i] = expandNode(nil, n[i]) 263 } 264 } 265 return node 266 267 case valueNode, hashNode: 268 return n 269 270 default: 271 panic(fmt.Sprintf("unknown node type: %T", n)) 272 } 273 } 274 275 // NewDatabase creates a new trie database to store ephemeral trie content before 276 // its written out to disk or garbage collected. No read cache is created, so all 277 // data retrievals will hit the underlying disk database. 278 func NewDatabase(diskdb ethdb.KeyValueStore) *Database { 279 return NewDatabaseWithCache(diskdb, 0, "") 280 } 281 282 // NewDatabaseWithCache creates a new trie database to store ephemeral trie content 283 // before its written out to disk or garbage collected. It also acts as a read cache 284 // for nodes loaded from disk. 285 func NewDatabaseWithCache(diskdb ethdb.KeyValueStore, cache int, journal string) *Database { 286 var cleans *fastcache.Cache 287 if cache > 0 { 288 if journal == "" { 289 cleans = fastcache.New(cache * 1024 * 1024) 290 } else { 291 cleans = fastcache.LoadFromFileOrNew(journal, cache*1024*1024) 292 } 293 } 294 return &Database{ 295 diskdb: diskdb, 296 cleans: cleans, 297 dirties: map[common.Hash]*cachedNode{{}: { 298 children: make(map[common.Hash]uint16), 299 }}, 300 preimages: make(map[common.Hash][]byte), 301 } 302 } 303 304 // DiskDB retrieves the persistent storage backing the trie database. 305 func (db *Database) DiskDB() ethdb.KeyValueStore { 306 return db.diskdb 307 } 308 309 // insert inserts a collapsed trie node into the memory database. 310 // The blob size must be specified to allow proper size tracking. 311 // All nodes inserted by this function will be reference tracked 312 // and in theory should only used for **trie nodes** insertion. 313 func (db *Database) insert(hash common.Hash, size int, node node) { 314 // If the node's already cached, skip 315 if _, ok := db.dirties[hash]; ok { 316 return 317 } 318 memcacheDirtyWriteMeter.Mark(int64(size)) 319 320 // Create the cached entry for this node 321 entry := &cachedNode{ 322 node: simplifyNode(node), 323 size: uint16(size), 324 flushPrev: db.newest, 325 } 326 entry.forChilds(func(child common.Hash) { 327 if c := db.dirties[child]; c != nil { 328 c.parents++ 329 } 330 }) 331 db.dirties[hash] = entry 332 333 // Update the flush-list endpoints 334 if db.oldest == (common.Hash{}) { 335 db.oldest, db.newest = hash, hash 336 } else { 337 db.dirties[db.newest].flushNext, db.newest = hash, hash 338 } 339 db.dirtiesSize += common.StorageSize(common.HashLength + entry.size) 340 } 341 342 // insertPreimage writes a new trie node pre-image to the memory database if it's 343 // yet unknown. The method will NOT make a copy of the slice, 344 // only use if the preimage will NOT be changed later on. 345 // 346 // Note, this method assumes that the database's lock is held! 347 func (db *Database) insertPreimage(hash common.Hash, preimage []byte) { 348 if _, ok := db.preimages[hash]; ok { 349 return 350 } 351 db.preimages[hash] = preimage 352 db.preimagesSize += common.StorageSize(common.HashLength + len(preimage)) 353 } 354 355 // node retrieves a cached trie node from memory, or returns nil if none can be 356 // found in the memory cache. 357 func (db *Database) node(hash common.Hash) node { 358 // Retrieve the node from the clean cache if available 359 if db.cleans != nil { 360 if enc := db.cleans.Get(nil, hash[:]); enc != nil { 361 memcacheCleanHitMeter.Mark(1) 362 memcacheCleanReadMeter.Mark(int64(len(enc))) 363 return mustDecodeNode(hash[:], enc) 364 } 365 } 366 // Retrieve the node from the dirty cache if available 367 db.lock.RLock() 368 dirty := db.dirties[hash] 369 db.lock.RUnlock() 370 371 if dirty != nil { 372 memcacheDirtyHitMeter.Mark(1) 373 memcacheDirtyReadMeter.Mark(int64(dirty.size)) 374 return dirty.obj(hash) 375 } 376 memcacheDirtyMissMeter.Mark(1) 377 378 // Content unavailable in memory, attempt to retrieve from disk 379 enc, err := db.diskdb.Get(hash[:]) 380 if err != nil || enc == nil { 381 return nil 382 } 383 if db.cleans != nil { 384 db.cleans.Set(hash[:], enc) 385 memcacheCleanMissMeter.Mark(1) 386 memcacheCleanWriteMeter.Mark(int64(len(enc))) 387 } 388 return mustDecodeNode(hash[:], enc) 389 } 390 391 // Node retrieves an encoded cached trie node from memory. If it cannot be found 392 // cached, the method queries the persistent database for the content. 393 func (db *Database) Node(hash common.Hash) ([]byte, error) { 394 // It doesn't make sense to retrieve the metaroot 395 if hash == (common.Hash{}) { 396 return nil, errors.New("not found") 397 } 398 // Retrieve the node from the clean cache if available 399 if db.cleans != nil { 400 if enc := db.cleans.Get(nil, hash[:]); enc != nil { 401 memcacheCleanHitMeter.Mark(1) 402 memcacheCleanReadMeter.Mark(int64(len(enc))) 403 return enc, nil 404 } 405 } 406 // Retrieve the node from the dirty cache if available 407 db.lock.RLock() 408 dirty := db.dirties[hash] 409 db.lock.RUnlock() 410 411 if dirty != nil { 412 memcacheDirtyHitMeter.Mark(1) 413 memcacheDirtyReadMeter.Mark(int64(dirty.size)) 414 return dirty.rlp(), nil 415 } 416 memcacheDirtyMissMeter.Mark(1) 417 418 // Content unavailable in memory, attempt to retrieve from disk 419 enc := rawdb.ReadTrieNode(db.diskdb, hash) 420 if len(enc) != 0 { 421 if db.cleans != nil { 422 db.cleans.Set(hash[:], enc) 423 memcacheCleanMissMeter.Mark(1) 424 memcacheCleanWriteMeter.Mark(int64(len(enc))) 425 } 426 return enc, nil 427 } 428 return nil, errors.New("not found") 429 } 430 431 // preimage retrieves a cached trie node pre-image from memory. If it cannot be 432 // found cached, the method queries the persistent database for the content. 433 func (db *Database) preimage(hash common.Hash) []byte { 434 // Retrieve the node from cache if available 435 db.lock.RLock() 436 preimage := db.preimages[hash] 437 db.lock.RUnlock() 438 439 if preimage != nil { 440 return preimage 441 } 442 return rawdb.ReadPreimage(db.diskdb, hash) 443 } 444 445 // Nodes retrieves the hashes of all the nodes cached within the memory database. 446 // This method is extremely expensive and should only be used to validate internal 447 // states in test code. 448 func (db *Database) Nodes() []common.Hash { 449 db.lock.RLock() 450 defer db.lock.RUnlock() 451 452 var hashes = make([]common.Hash, 0, len(db.dirties)) 453 for hash := range db.dirties { 454 if hash != (common.Hash{}) { // Special case for "root" references/nodes 455 hashes = append(hashes, hash) 456 } 457 } 458 return hashes 459 } 460 461 // Reference adds a new reference from a parent node to a child node. 462 // This function is used to add reference between internal trie node 463 // and external node(e.g. storage trie root), all internal trie nodes 464 // are referenced together by database itself. 465 func (db *Database) Reference(child common.Hash, parent common.Hash) { 466 db.lock.Lock() 467 defer db.lock.Unlock() 468 469 db.reference(child, parent) 470 } 471 472 // reference is the private locked version of Reference. 473 func (db *Database) reference(child common.Hash, parent common.Hash) { 474 // If the node does not exist, it's a node pulled from disk, skip 475 node, ok := db.dirties[child] 476 if !ok { 477 return 478 } 479 // If the reference already exists, only duplicate for roots 480 if db.dirties[parent].children == nil { 481 db.dirties[parent].children = make(map[common.Hash]uint16) 482 db.childrenSize += cachedNodeChildrenSize 483 } else if _, ok = db.dirties[parent].children[child]; ok && parent != (common.Hash{}) { 484 return 485 } 486 node.parents++ 487 db.dirties[parent].children[child]++ 488 if db.dirties[parent].children[child] == 1 { 489 db.childrenSize += common.HashLength + 2 // uint16 counter 490 } 491 } 492 493 // Dereference removes an existing reference from a root node. 494 func (db *Database) Dereference(root common.Hash) { 495 // Sanity check to ensure that the meta-root is not removed 496 if root == (common.Hash{}) { 497 log.Error("Attempted to dereference the trie cache meta root") 498 return 499 } 500 db.lock.Lock() 501 defer db.lock.Unlock() 502 503 nodes, storage, start := len(db.dirties), db.dirtiesSize, time.Now() 504 db.dereference(root, common.Hash{}) 505 506 db.gcnodes += uint64(nodes - len(db.dirties)) 507 db.gcsize += storage - db.dirtiesSize 508 db.gctime += time.Since(start) 509 510 memcacheGCTimeTimer.Update(time.Since(start)) 511 memcacheGCSizeMeter.Mark(int64(storage - db.dirtiesSize)) 512 memcacheGCNodesMeter.Mark(int64(nodes - len(db.dirties))) 513 514 log.Debug("Dereferenced trie from memory database", "nodes", nodes-len(db.dirties), "size", storage-db.dirtiesSize, "time", time.Since(start), 515 "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize) 516 } 517 518 // dereference is the private locked version of Dereference. 519 func (db *Database) dereference(child common.Hash, parent common.Hash) { 520 // Dereference the parent-child 521 node := db.dirties[parent] 522 523 if node.children != nil && node.children[child] > 0 { 524 node.children[child]-- 525 if node.children[child] == 0 { 526 delete(node.children, child) 527 db.childrenSize -= (common.HashLength + 2) // uint16 counter 528 } 529 } 530 // If the child does not exist, it's a previously committed node. 531 node, ok := db.dirties[child] 532 if !ok { 533 return 534 } 535 // If there are no more references to the child, delete it and cascade 536 if node.parents > 0 { 537 // This is a special cornercase where a node loaded from disk (i.e. not in the 538 // memcache any more) gets reinjected as a new node (short node split into full, 539 // then reverted into short), causing a cached node to have no parents. That is 540 // no problem in itself, but don't make maxint parents out of it. 541 node.parents-- 542 } 543 if node.parents == 0 { 544 // Remove the node from the flush-list 545 switch child { 546 case db.oldest: 547 db.oldest = node.flushNext 548 db.dirties[node.flushNext].flushPrev = common.Hash{} 549 case db.newest: 550 db.newest = node.flushPrev 551 db.dirties[node.flushPrev].flushNext = common.Hash{} 552 default: 553 db.dirties[node.flushPrev].flushNext = node.flushNext 554 db.dirties[node.flushNext].flushPrev = node.flushPrev 555 } 556 // Dereference all children and delete the node 557 node.forChilds(func(hash common.Hash) { 558 db.dereference(hash, child) 559 }) 560 delete(db.dirties, child) 561 db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size)) 562 if node.children != nil { 563 db.childrenSize -= cachedNodeChildrenSize 564 } 565 } 566 } 567 568 // Cap iteratively flushes old but still referenced trie nodes until the total 569 // memory usage goes below the given threshold. 570 // 571 // Note, this method is a non-synchronized mutator. It is unsafe to call this 572 // concurrently with other mutators. 573 func (db *Database) Cap(limit common.StorageSize) error { 574 // Create a database batch to flush persistent data out. It is important that 575 // outside code doesn't see an inconsistent state (referenced data removed from 576 // memory cache during commit but not yet in persistent storage). This is ensured 577 // by only uncaching existing data when the database write finalizes. 578 nodes, storage, start := len(db.dirties), db.dirtiesSize, time.Now() 579 batch := db.diskdb.NewBatch() 580 581 // db.dirtiesSize only contains the useful data in the cache, but when reporting 582 // the total memory consumption, the maintenance metadata is also needed to be 583 // counted. 584 size := db.dirtiesSize + common.StorageSize((len(db.dirties)-1)*cachedNodeSize) 585 size += db.childrenSize - common.StorageSize(len(db.dirties[common.Hash{}].children)*(common.HashLength+2)) 586 587 // If the preimage cache got large enough, push to disk. If it's still small 588 // leave for later to deduplicate writes. 589 flushPreimages := db.preimagesSize > 4*1024*1024 590 if flushPreimages { 591 rawdb.WritePreimages(batch, db.preimages) 592 if batch.ValueSize() > ethdb.IdealBatchSize { 593 if err := batch.Write(); err != nil { 594 return err 595 } 596 batch.Reset() 597 } 598 } 599 // Keep committing nodes from the flush-list until we're below allowance 600 oldest := db.oldest 601 for size > limit && oldest != (common.Hash{}) { 602 // Fetch the oldest referenced node and push into the batch 603 node := db.dirties[oldest] 604 rawdb.WriteTrieNode(batch, oldest, node.rlp()) 605 606 // If we exceeded the ideal batch size, commit and reset 607 if batch.ValueSize() >= ethdb.IdealBatchSize { 608 if err := batch.Write(); err != nil { 609 log.Error("Failed to write flush list to disk", "err", err) 610 return err 611 } 612 batch.Reset() 613 } 614 // Iterate to the next flush item, or abort if the size cap was achieved. Size 615 // is the total size, including the useful cached data (hash -> blob), the 616 // cache item metadata, as well as external children mappings. 617 size -= common.StorageSize(common.HashLength + int(node.size) + cachedNodeSize) 618 if node.children != nil { 619 size -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2)) 620 } 621 oldest = node.flushNext 622 } 623 // Flush out any remainder data from the last batch 624 if err := batch.Write(); err != nil { 625 log.Error("Failed to write flush list to disk", "err", err) 626 return err 627 } 628 // Write successful, clear out the flushed data 629 db.lock.Lock() 630 defer db.lock.Unlock() 631 632 if flushPreimages { 633 db.preimages, db.preimagesSize = make(map[common.Hash][]byte), 0 634 } 635 for db.oldest != oldest { 636 node := db.dirties[db.oldest] 637 delete(db.dirties, db.oldest) 638 db.oldest = node.flushNext 639 640 db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size)) 641 if node.children != nil { 642 db.childrenSize -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2)) 643 } 644 } 645 if db.oldest != (common.Hash{}) { 646 db.dirties[db.oldest].flushPrev = common.Hash{} 647 } 648 db.flushnodes += uint64(nodes - len(db.dirties)) 649 db.flushsize += storage - db.dirtiesSize 650 db.flushtime += time.Since(start) 651 652 memcacheFlushTimeTimer.Update(time.Since(start)) 653 memcacheFlushSizeMeter.Mark(int64(storage - db.dirtiesSize)) 654 memcacheFlushNodesMeter.Mark(int64(nodes - len(db.dirties))) 655 656 log.Debug("Persisted nodes from memory database", "nodes", nodes-len(db.dirties), "size", storage-db.dirtiesSize, "time", time.Since(start), 657 "flushnodes", db.flushnodes, "flushsize", db.flushsize, "flushtime", db.flushtime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize) 658 659 return nil 660 } 661 662 // Commit iterates over all the children of a particular node, writes them out 663 // to disk, forcefully tearing down all references in both directions. As a side 664 // effect, all pre-images accumulated up to this point are also written. 665 // 666 // Note, this method is a non-synchronized mutator. It is unsafe to call this 667 // concurrently with other mutators. 668 func (db *Database) Commit(node common.Hash, report bool, callback func(common.Hash)) error { 669 // Create a database batch to flush persistent data out. It is important that 670 // outside code doesn't see an inconsistent state (referenced data removed from 671 // memory cache during commit but not yet in persistent storage). This is ensured 672 // by only uncaching existing data when the database write finalizes. 673 start := time.Now() 674 batch := db.diskdb.NewBatch() 675 676 // Move all of the accumulated preimages into a write batch 677 rawdb.WritePreimages(batch, db.preimages) 678 if batch.ValueSize() > ethdb.IdealBatchSize { 679 if err := batch.Write(); err != nil { 680 return err 681 } 682 batch.Reset() 683 } 684 // Since we're going to replay trie node writes into the clean cache, flush out 685 // any batched pre-images before continuing. 686 if err := batch.Write(); err != nil { 687 return err 688 } 689 batch.Reset() 690 691 // Move the trie itself into the batch, flushing if enough data is accumulated 692 nodes, storage := len(db.dirties), db.dirtiesSize 693 694 uncacher := &cleaner{db} 695 if err := db.commit(node, batch, uncacher, callback); err != nil { 696 log.Error("Failed to commit trie from trie database", "err", err) 697 return err 698 } 699 // Trie mostly committed to disk, flush any batch leftovers 700 if err := batch.Write(); err != nil { 701 log.Error("Failed to write trie to disk", "err", err) 702 return err 703 } 704 // Uncache any leftovers in the last batch 705 db.lock.Lock() 706 defer db.lock.Unlock() 707 708 batch.Replay(uncacher) 709 batch.Reset() 710 711 // Reset the storage counters and bumpd metrics 712 db.preimages, db.preimagesSize = make(map[common.Hash][]byte), 0 713 714 memcacheCommitTimeTimer.Update(time.Since(start)) 715 memcacheCommitSizeMeter.Mark(int64(storage - db.dirtiesSize)) 716 memcacheCommitNodesMeter.Mark(int64(nodes - len(db.dirties))) 717 718 logger := log.Info 719 if !report { 720 logger = log.Debug 721 } 722 logger("Persisted trie from memory database", "nodes", nodes-len(db.dirties)+int(db.flushnodes), "size", storage-db.dirtiesSize+db.flushsize, "time", time.Since(start)+db.flushtime, 723 "gcnodes", db.gcnodes, "gcsize", db.gcsize, "gctime", db.gctime, "livenodes", len(db.dirties), "livesize", db.dirtiesSize) 724 725 // Reset the garbage collection statistics 726 db.gcnodes, db.gcsize, db.gctime = 0, 0, 0 727 db.flushnodes, db.flushsize, db.flushtime = 0, 0, 0 728 729 return nil 730 } 731 732 // commit is the private locked version of Commit. 733 func (db *Database) commit(hash common.Hash, batch ethdb.Batch, uncacher *cleaner, callback func(common.Hash)) error { 734 // If the node does not exist, it's a previously committed node 735 node, ok := db.dirties[hash] 736 if !ok { 737 return nil 738 } 739 var err error 740 node.forChilds(func(child common.Hash) { 741 if err == nil { 742 err = db.commit(child, batch, uncacher, callback) 743 } 744 }) 745 if err != nil { 746 return err 747 } 748 // If we've reached an optimal batch size, commit and start over 749 rawdb.WriteTrieNode(batch, hash, node.rlp()) 750 if callback != nil { 751 callback(hash) 752 } 753 if batch.ValueSize() >= ethdb.IdealBatchSize { 754 if err := batch.Write(); err != nil { 755 return err 756 } 757 db.lock.Lock() 758 batch.Replay(uncacher) 759 batch.Reset() 760 db.lock.Unlock() 761 } 762 return nil 763 } 764 765 // cleaner is a database batch replayer that takes a batch of write operations 766 // and cleans up the trie database from anything written to disk. 767 type cleaner struct { 768 db *Database 769 } 770 771 // Put reacts to database writes and implements dirty data uncaching. This is the 772 // post-processing step of a commit operation where the already persisted trie is 773 // removed from the dirty cache and moved into the clean cache. The reason behind 774 // the two-phase commit is to ensure ensure data availability while moving from 775 // memory to disk. 776 func (c *cleaner) Put(key []byte, rlp []byte) error { 777 hash := common.BytesToHash(key) 778 779 // If the node does not exist, we're done on this path 780 node, ok := c.db.dirties[hash] 781 if !ok { 782 return nil 783 } 784 // Node still exists, remove it from the flush-list 785 switch hash { 786 case c.db.oldest: 787 c.db.oldest = node.flushNext 788 c.db.dirties[node.flushNext].flushPrev = common.Hash{} 789 case c.db.newest: 790 c.db.newest = node.flushPrev 791 c.db.dirties[node.flushPrev].flushNext = common.Hash{} 792 default: 793 c.db.dirties[node.flushPrev].flushNext = node.flushNext 794 c.db.dirties[node.flushNext].flushPrev = node.flushPrev 795 } 796 // Remove the node from the dirty cache 797 delete(c.db.dirties, hash) 798 c.db.dirtiesSize -= common.StorageSize(common.HashLength + int(node.size)) 799 if node.children != nil { 800 c.db.dirtiesSize -= common.StorageSize(cachedNodeChildrenSize + len(node.children)*(common.HashLength+2)) 801 } 802 // Move the flushed node into the clean cache to prevent insta-reloads 803 if c.db.cleans != nil { 804 c.db.cleans.Set(hash[:], rlp) 805 memcacheCleanWriteMeter.Mark(int64(len(rlp))) 806 } 807 return nil 808 } 809 810 func (c *cleaner) Delete(key []byte) error { 811 panic("not implemented") 812 } 813 814 // Size returns the current storage size of the memory cache in front of the 815 // persistent database layer. 816 func (db *Database) Size() (common.StorageSize, common.StorageSize) { 817 db.lock.RLock() 818 defer db.lock.RUnlock() 819 820 // db.dirtiesSize only contains the useful data in the cache, but when reporting 821 // the total memory consumption, the maintenance metadata is also needed to be 822 // counted. 823 var metadataSize = common.StorageSize((len(db.dirties) - 1) * cachedNodeSize) 824 var metarootRefs = common.StorageSize(len(db.dirties[common.Hash{}].children) * (common.HashLength + 2)) 825 return db.dirtiesSize + db.childrenSize + metadataSize - metarootRefs, db.preimagesSize 826 } 827 828 // saveCache saves clean state cache to given directory path 829 // using specified CPU cores. 830 func (db *Database) saveCache(dir string, threads int) error { 831 if db.cleans == nil { 832 return nil 833 } 834 log.Info("Writing clean trie cache to disk", "path", dir, "threads", threads) 835 836 start := time.Now() 837 err := db.cleans.SaveToFileConcurrent(dir, threads) 838 if err != nil { 839 log.Error("Failed to persist clean trie cache", "error", err) 840 return err 841 } 842 log.Info("Persisted the clean trie cache", "path", dir, "elapsed", common.PrettyDuration(time.Since(start))) 843 return nil 844 } 845 846 // SaveCache atomically saves fast cache data to the given dir using all 847 // available CPU cores. 848 func (db *Database) SaveCache(dir string) error { 849 return db.saveCache(dir, runtime.GOMAXPROCS(0)) 850 } 851 852 // SaveCachePeriodically atomically saves fast cache data to the given dir with 853 // the specified interval. All dump operation will only use a single CPU core. 854 func (db *Database) SaveCachePeriodically(dir string, interval time.Duration, stopCh <-chan struct{}) { 855 ticker := time.NewTicker(interval) 856 defer ticker.Stop() 857 858 for { 859 select { 860 case <-ticker.C: 861 db.saveCache(dir, 1) 862 case <-stopCh: 863 return 864 } 865 } 866 }