9045b79bc2
This PR modifies how the metrics library handles `Enabled`: previously, the package `init` decided whether to serve real metrics or just dummy-types. This has several drawbacks: - During pkg init, we need to determine whether metrics are enabled or not. So we first hacked in a check if certain geth-specific commandline-flags were enabled. Then we added a similar check for geth-env-vars. Then we almost added a very elaborate check for toml-config-file, plus toml parsing. - Using "real" types and dummy types interchangeably means that everything is hidden behind interfaces. This has a performance penalty, and also it just adds a lot of code. This PR removes the interface stuff, uses concrete types, and allows for the setting of Enabled to happen later. It is still assumed that `metrics.Enable()` is invoked early on. The somewhat 'heavy' operations, such as ticking meters and exp-decay, now checks the enable-flag to prevent resource leak. The change may be large, but it's mostly pretty trivial, and from the last time I gutted the metrics, I ensured that we have fairly good test coverage. --------- Co-authored-by: Felix Lange <fjl@twurst.com>
59 lines
1.4 KiB
Go
59 lines
1.4 KiB
Go
package metrics
|
|
|
|
import (
|
|
"sync/atomic"
|
|
)
|
|
|
|
// GetOrRegisterCounter returns an existing Counter or constructs and registers
|
|
// a new Counter.
|
|
func GetOrRegisterCounter(name string, r Registry) *Counter {
|
|
if r == nil {
|
|
r = DefaultRegistry
|
|
}
|
|
return r.GetOrRegister(name, NewCounter).(*Counter)
|
|
}
|
|
|
|
// NewCounter constructs a new Counter.
|
|
func NewCounter() *Counter {
|
|
return new(Counter)
|
|
}
|
|
|
|
// NewRegisteredCounter constructs and registers a new Counter.
|
|
func NewRegisteredCounter(name string, r Registry) *Counter {
|
|
c := NewCounter()
|
|
if r == nil {
|
|
r = DefaultRegistry
|
|
}
|
|
r.Register(name, c)
|
|
return c
|
|
}
|
|
|
|
// CounterSnapshot is a read-only copy of a Counter.
|
|
type CounterSnapshot int64
|
|
|
|
// Count returns the count at the time the snapshot was taken.
|
|
func (c CounterSnapshot) Count() int64 { return int64(c) }
|
|
|
|
// Counter hold an int64 value that can be incremented and decremented.
|
|
type Counter atomic.Int64
|
|
|
|
// Clear sets the counter to zero.
|
|
func (c *Counter) Clear() {
|
|
(*atomic.Int64)(c).Store(0)
|
|
}
|
|
|
|
// Dec decrements the counter by the given amount.
|
|
func (c *Counter) Dec(i int64) {
|
|
(*atomic.Int64)(c).Add(-i)
|
|
}
|
|
|
|
// Inc increments the counter by the given amount.
|
|
func (c *Counter) Inc(i int64) {
|
|
(*atomic.Int64)(c).Add(i)
|
|
}
|
|
|
|
// Snapshot returns a read-only copy of the counter.
|
|
func (c *Counter) Snapshot() CounterSnapshot {
|
|
return CounterSnapshot((*atomic.Int64)(c).Load())
|
|
}
|