Skip to content

Commit 86989e3

Browse files
authored
core: split out detailed trie access metrics from insertion time (#19316)
* core: split out detailed trie access metrics from insertion time * cmd, core, metrics: support expensive optional metrics
1 parent e852505 commit 86989e3

7 files changed

Lines changed: 132 additions & 38 deletions

File tree

‎cmd/geth/main.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,6 @@ var (
137137
utils.RPCCORSDomainFlag,
138138
utils.RPCVirtualHostsFlag,
139139
utils.EthStatsURLFlag,
140-
utils.MetricsEnabledFlag,
141140
utils.FakePoWFlag,
142141
utils.NoCompactionFlag,
143142
utils.GpoBlocksFlag,
@@ -174,6 +173,8 @@ var (
174173
}
175174

176175
metricsFlags = []cli.Flag{
176+
utils.MetricsEnabledFlag,
177+
utils.MetricsEnabledExpensiveFlag,
177178
utils.MetricsEnableInfluxDBFlag,
178179
utils.MetricsInfluxDBEndpointFlag,
179180
utils.MetricsInfluxDBDatabaseFlag,

‎cmd/geth/usage.go‎

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -225,16 +225,8 @@ var AppHelpFlagGroups = []flagGroup{
225225
}, debug.Flags...),
226226
},
227227
{
228-
Name: "METRICS AND STATS",
229-
Flags: []cli.Flag{
230-
utils.MetricsEnabledFlag,
231-
utils.MetricsEnableInfluxDBFlag,
232-
utils.MetricsInfluxDBEndpointFlag,
233-
utils.MetricsInfluxDBDatabaseFlag,
234-
utils.MetricsInfluxDBUsernameFlag,
235-
utils.MetricsInfluxDBPasswordFlag,
236-
utils.MetricsInfluxDBTagsFlag,
237-
},
228+
Name: "METRICS AND STATS",
229+
Flags: metricsFlags,
238230
},
239231
{
240232
Name: "WHISPER (EXPERIMENTAL)",

‎cmd/utils/flags.go‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ var (
226226
}
227227
// Dashboard settings
228228
DashboardEnabledFlag = cli.BoolFlag{
229-
Name: metrics.DashboardEnabledFlag,
229+
Name: "dashboard",
230230
Usage: "Enable the dashboard",
231231
}
232232
DashboardAddrFlag = cli.StringFlag{
@@ -644,9 +644,13 @@ var (
644644

645645
// Metrics flags
646646
MetricsEnabledFlag = cli.BoolFlag{
647-
Name: metrics.MetricsEnabledFlag,
647+
Name: "metrics",
648648
Usage: "Enable metrics collection and reporting",
649649
}
650+
MetricsEnabledExpensiveFlag = cli.BoolFlag{
651+
Name: "metrics.expensive",
652+
Usage: "Enable expensive metrics collection and reporting",
653+
}
650654
MetricsEnableInfluxDBFlag = cli.BoolFlag{
651655
Name: "metrics.influxdb",
652656
Usage: "Enable metrics export/push to an external InfluxDB database",

‎core/blockchain.go‎

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,16 @@ import (
4747
)
4848

4949
var (
50+
accountReadTimer = metrics.NewRegisteredTimer("chain/account/reads", nil)
51+
accountHashTimer = metrics.NewRegisteredTimer("chain/account/hashes", nil)
52+
accountUpdateTimer = metrics.NewRegisteredTimer("chain/account/updates", nil)
53+
accountCommitTimer = metrics.NewRegisteredTimer("chain/account/commits", nil)
54+
55+
storageReadTimer = metrics.NewRegisteredTimer("chain/storage/reads", nil)
56+
storageHashTimer = metrics.NewRegisteredTimer("chain/storage/hashes", nil)
57+
storageUpdateTimer = metrics.NewRegisteredTimer("chain/storage/updates", nil)
58+
storageCommitTimer = metrics.NewRegisteredTimer("chain/storage/commits", nil)
59+
5060
blockInsertTimer = metrics.NewRegisteredTimer("chain/inserts", nil)
5161
blockValidationTimer = metrics.NewRegisteredTimer("chain/validation", nil)
5262
blockExecutionTimer = metrics.NewRegisteredTimer("chain/execution", nil)
@@ -1249,10 +1259,26 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
12491259
if err != nil {
12501260
return it.index, events, coalescedLogs, err
12511261
}
1262+
1263+
// Update the metrics subsystem with all the measurements
1264+
accountReadTimer.Update(state.AccountReads)
1265+
accountHashTimer.Update(state.AccountHashes)
1266+
accountUpdateTimer.Update(state.AccountUpdates)
1267+
accountCommitTimer.Update(state.AccountCommits)
1268+
1269+
storageReadTimer.Update(state.StorageReads)
1270+
storageHashTimer.Update(state.StorageHashes)
1271+
storageUpdateTimer.Update(state.StorageUpdates)
1272+
storageCommitTimer.Update(state.StorageCommits)
1273+
1274+
trieAccess := state.AccountReads + state.AccountHashes + state.AccountUpdates + state.AccountCommits
1275+
trieAccess += state.StorageReads + state.StorageHashes + state.StorageUpdates + state.StorageCommits
1276+
12521277
blockInsertTimer.UpdateSince(start)
1253-
blockExecutionTimer.Update(t1.Sub(t0))
1278+
blockExecutionTimer.Update(t1.Sub(t0) - trieAccess)
12541279
blockValidationTimer.Update(t2.Sub(t1))
12551280
blockWriteTimer.Update(t3.Sub(t2))
1281+
12561282
switch status {
12571283
case CanonStatTy:
12581284
log.Debug("Inserted new block", "number", block.Number(), "hash", block.Hash(),
@@ -1274,7 +1300,6 @@ func (bc *BlockChain) insertChain(chain types.Blocks, verifySeals bool) (int, []
12741300
"root", block.Root())
12751301
events = append(events, ChainSideEvent{block})
12761302
}
1277-
blockInsertTimer.UpdateSince(start)
12781303
stats.processed++
12791304
stats.usedGas += usedGas
12801305

‎core/state/state_object.go‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,11 @@ import (
2121
"fmt"
2222
"io"
2323
"math/big"
24+
"time"
2425

2526
"github.com/ethereum/go-ethereum/common"
2627
"github.com/ethereum/go-ethereum/crypto"
28+
"github.com/ethereum/go-ethereum/metrics"
2729
"github.com/ethereum/go-ethereum/rlp"
2830
)
2931

@@ -177,6 +179,10 @@ func (self *stateObject) GetCommittedState(db Database, key common.Hash) common.
177179
if cached {
178180
return value
179181
}
182+
// Track the amount of time wasted on reading the storge trie
183+
if metrics.EnabledExpensive {
184+
defer func(start time.Time) { self.db.StorageReads += time.Since(start) }(time.Now())
185+
}
180186
// Otherwise load the value from the database
181187
enc, err := self.getTrie(db).TryGet(key[:])
182188
if err != nil {
@@ -216,6 +222,11 @@ func (self *stateObject) setState(key, value common.Hash) {
216222

217223
// updateTrie writes cached storage modifications into the object's storage trie.
218224
func (self *stateObject) updateTrie(db Database) Trie {
225+
// Track the amount of time wasted on updating the storge trie
226+
if metrics.EnabledExpensive {
227+
defer func(start time.Time) { self.db.StorageUpdates += time.Since(start) }(time.Now())
228+
}
229+
// Update all the dirty slots in the trie
219230
tr := self.getTrie(db)
220231
for key, value := range self.dirtyStorage {
221232
delete(self.dirtyStorage, key)
@@ -240,6 +251,11 @@ func (self *stateObject) updateTrie(db Database) Trie {
240251
// UpdateRoot sets the trie root to the current root hash of
241252
func (self *stateObject) updateRoot(db Database) {
242253
self.updateTrie(db)
254+
255+
// Track the amount of time wasted on hashing the storge trie
256+
if metrics.EnabledExpensive {
257+
defer func(start time.Time) { self.db.StorageHashes += time.Since(start) }(time.Now())
258+
}
243259
self.data.Root = self.trie.Hash()
244260
}
245261

@@ -250,6 +266,10 @@ func (self *stateObject) CommitTrie(db Database) error {
250266
if self.dbErr != nil {
251267
return self.dbErr
252268
}
269+
// Track the amount of time wasted on committing the storge trie
270+
if metrics.EnabledExpensive {
271+
defer func(start time.Time) { self.db.StorageCommits += time.Since(start) }(time.Now())
272+
}
253273
root, err := self.trie.Commit(nil)
254274
if err == nil {
255275
self.data.Root = root

‎core/state/statedb.go‎

Lines changed: 51 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -22,11 +22,13 @@ import (
2222
"fmt"
2323
"math/big"
2424
"sort"
25+
"time"
2526

2627
"github.com/ethereum/go-ethereum/common"
2728
"github.com/ethereum/go-ethereum/core/types"
2829
"github.com/ethereum/go-ethereum/crypto"
2930
"github.com/ethereum/go-ethereum/log"
31+
"github.com/ethereum/go-ethereum/metrics"
3032
"github.com/ethereum/go-ethereum/rlp"
3133
"github.com/ethereum/go-ethereum/trie"
3234
)
@@ -86,6 +88,16 @@ type StateDB struct {
8688
journal *journal
8789
validRevisions []revision
8890
nextRevisionId int
91+
92+
// Measurements gathered during execution for debugging purposes
93+
AccountReads time.Duration
94+
AccountHashes time.Duration
95+
AccountUpdates time.Duration
96+
AccountCommits time.Duration
97+
StorageReads time.Duration
98+
StorageHashes time.Duration
99+
StorageUpdates time.Duration
100+
StorageCommits time.Duration
89101
}
90102

91103
// Create a new state from a given trie.
@@ -386,46 +398,61 @@ func (self *StateDB) Suicide(addr common.Address) bool {
386398
//
387399

388400
// updateStateObject writes the given object to the trie.
389-
func (self *StateDB) updateStateObject(stateObject *stateObject) {
401+
func (s *StateDB) updateStateObject(stateObject *stateObject) {
402+
// Track the amount of time wasted on updating the account from the trie
403+
if metrics.EnabledExpensive {
404+
defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
405+
}
406+
// Encode the account and update the account trie
390407
addr := stateObject.Address()
408+
391409
data, err := rlp.EncodeToBytes(stateObject)
392410
if err != nil {
393411
panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
394412
}
395-
self.setError(self.trie.TryUpdate(addr[:], data))
413+
s.setError(s.trie.TryUpdate(addr[:], data))
396414
}
397415

398416
// deleteStateObject removes the given object from the state trie.
399-
func (self *StateDB) deleteStateObject(stateObject *stateObject) {
417+
func (s *StateDB) deleteStateObject(stateObject *stateObject) {
418+
// Track the amount of time wasted on deleting the account from the trie
419+
if metrics.EnabledExpensive {
420+
defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
421+
}
422+
// Delete the account from the trie
400423
stateObject.deleted = true
424+
401425
addr := stateObject.Address()
402-
self.setError(self.trie.TryDelete(addr[:]))
426+
s.setError(s.trie.TryDelete(addr[:]))
403427
}
404428

405429
// Retrieve a state object given by the address. Returns nil if not found.
406-
func (self *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
407-
// Prefer 'live' objects.
408-
if obj := self.stateObjects[addr]; obj != nil {
430+
func (s *StateDB) getStateObject(addr common.Address) (stateObject *stateObject) {
431+
// Prefer live objects
432+
if obj := s.stateObjects[addr]; obj != nil {
409433
if obj.deleted {
410434
return nil
411435
}
412436
return obj
413437
}
414-
415-
// Load the object from the database.
416-
enc, err := self.trie.TryGet(addr[:])
438+
// Track the amount of time wasted on loading the object from the database
439+
if metrics.EnabledExpensive {
440+
defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
441+
}
442+
// Load the object from the database
443+
enc, err := s.trie.TryGet(addr[:])
417444
if len(enc) == 0 {
418-
self.setError(err)
445+
s.setError(err)
419446
return nil
420447
}
421448
var data Account
422449
if err := rlp.DecodeBytes(enc, &data); err != nil {
423450
log.Error("Failed to decode state object", "addr", addr, "err", err)
424451
return nil
425452
}
426-
// Insert into the live set.
427-
obj := newObject(self, addr, data)
428-
self.setStateObject(obj)
453+
// Insert into the live set
454+
obj := newObject(s, addr, data)
455+
s.setStateObject(obj)
429456
return obj
430457
}
431458

@@ -600,6 +627,11 @@ func (s *StateDB) Finalise(deleteEmptyObjects bool) {
600627
// goes into transaction receipts.
601628
func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
602629
s.Finalise(deleteEmptyObjects)
630+
631+
// Track the amount of time wasted on hashing the account trie
632+
if metrics.EnabledExpensive {
633+
defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
634+
}
603635
return s.trie.Hash()
604636
}
605637

@@ -624,7 +656,7 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error)
624656
for addr := range s.journal.dirties {
625657
s.stateObjectsDirty[addr] = struct{}{}
626658
}
627-
// Commit objects to the trie.
659+
// Commit objects to the trie, measuring the elapsed time
628660
for addr, stateObject := range s.stateObjects {
629661
_, isDirty := s.stateObjectsDirty[addr]
630662
switch {
@@ -647,7 +679,10 @@ func (s *StateDB) Commit(deleteEmptyObjects bool) (root common.Hash, err error)
647679
}
648680
delete(s.stateObjectsDirty, addr)
649681
}
650-
// Write trie changes.
682+
// Write the account trie changes, measuing the amount of wasted time
683+
if metrics.EnabledExpensive {
684+
defer func(start time.Time) { s.AccountCommits += time.Since(start) }(time.Now())
685+
}
651686
root, err = s.trie.Commit(func(leaf []byte, parent common.Hash) error {
652687
var account Account
653688
if err := rlp.DecodeBytes(leaf, &account); err != nil {

‎metrics/metrics.go‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,41 @@ import (
1515
)
1616

1717
// Enabled is checked by the constructor functions for all of the
18-
// standard metrics. If it is true, the metric returned is a stub.
18+
// standard metrics. If it is true, the metric returned is a stub.
1919
//
2020
// This global kill-switch helps quantify the observer effect and makes
2121
// for less cluttered pprof profiles.
2222
var Enabled = false
2323

24-
// MetricsEnabledFlag is the CLI flag name to use to enable metrics collections.
25-
const MetricsEnabledFlag = "metrics"
26-
const DashboardEnabledFlag = "dashboard"
24+
// EnabledExpensive is a soft-flag meant for external packages to check if costly
25+
// metrics gathering is allowed or not. The goal is to separate standard metrics
26+
// for health monitoring and debug metrics that might impact runtime performance.
27+
var EnabledExpensive = false
28+
29+
// enablerFlags is the CLI flag names to use to enable metrics collections.
30+
var enablerFlags = []string{"metrics", "dashboard"}
31+
32+
// expensiveEnablerFlags is the CLI flag names to use to enable metrics collections.
33+
var expensiveEnablerFlags = []string{"metrics.expensive"}
2734

2835
// Init enables or disables the metrics system. Since we need this to run before
2936
// any other code gets to create meters and timers, we'll actually do an ugly hack
3037
// and peek into the command line args for the metrics flag.
3138
func init() {
3239
for _, arg := range os.Args {
33-
if flag := strings.TrimLeft(arg, "-"); flag == MetricsEnabledFlag || flag == DashboardEnabledFlag {
34-
log.Info("Enabling metrics collection")
35-
Enabled = true
40+
flag := strings.TrimLeft(arg, "-")
41+
42+
for _, enabler := range enablerFlags {
43+
if !Enabled && flag == enabler {
44+
log.Info("Enabling metrics collection")
45+
Enabled = true
46+
}
47+
}
48+
for _, enabler := range expensiveEnablerFlags {
49+
if !Enabled && flag == enabler {
50+
log.Info("Enabling expensive metrics collection")
51+
EnabledExpensive = true
52+
}
3653
}
3754
}
3855
}

0 commit comments

Comments
 (0)