Skip to content

Commit fe4fb0c

Browse files
lucaslopezfmergify[bot]
authored andcommitted
feat: Conditionally emit metrics based on enablement (#19903)
Co-authored-by: Aleksandr Bezobchuk <alexanderbez@users.noreply.github.com> (cherry picked from commit 2496cfd) # Conflicts: # CHANGELOG.md # x/circuit/module.go # x/crisis/module.go # x/distribution/abci.go # x/gov/keeper/abci.go # x/mint/abci.go # x/staking/keeper/abci.go # x/upgrade/abci.go
1 parent f76c659 commit fe4fb0c

File tree

15 files changed

+540
-16
lines changed

15 files changed

+540
-16
lines changed

CHANGELOG.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,11 +47,50 @@ Ref: https://keepachangelog.com/en/1.0.0/
4747

4848
### Improvements
4949

50+
<<<<<<< HEAD
5051
* (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Upgrade prometheus version and fix API breaking change due to prometheus bump.
5152
* (deps) [#19810](https://github.com/cosmos/cosmos-sdk/pull/19810) Bump `cosmossdk.io/store` to v1.1.0.
5253
* (server) [#19884](https://github.com/cosmos/cosmos-sdk/pull/19884) Add start customizability to start command options.
5354
* (x/gov) [#19853](https://github.com/cosmos/cosmos-sdk/pull/19853) Emit `depositor` in `EventTypeProposalDeposit`.
5455
* (x/gov) [#19844](https://github.com/cosmos/cosmos-sdk/pull/19844) Emit the proposer of governance proposals.
56+
=======
57+
* (telemetry) [#19903](https://github.com/cosmos/cosmos-sdk/pull/19903) Conditionally emit metrics based on enablement.
58+
* **Introduction of `Now` Function**: Added a new function called `Now` to the telemetry package. It returns the current system time if telemetry is enabled, or a zero time if telemetry is not enabled.
59+
* **Atomic Global Variable**: Implemented an atomic global variable to manage the state of telemetry's enablement. This ensures thread safety for the telemetry state.
60+
* **Conditional Telemetry Emission**: All telemetry functions have been updated to emit metrics only when telemetry is enabled. They perform a check with `isTelemetryEnabled()` and return early if telemetry is disabled, minimizing unnecessary operations and overhead.
61+
* (types) [#19869](https://github.com/cosmos/cosmos-sdk/pull/19869) Removed `Any` type from `codec/types` and replaced it with an alias for `cosmos/gogoproto/types/any`.
62+
* (server) [#19854](https://github.com/cosmos/cosmos-sdk/pull/19854) Add customizability to start command.
63+
* Add `StartCmdOptions` in `server.AddCommands` instead of `servertypes.ModuleInitFlags`. To set custom flags set them in the `StartCmdOptions` struct on the `AddFlags` field.
64+
* Add `StartCommandHandler` to `StartCmdOptions` to allow custom start command handlers. Users now have total control over how the app starts.
65+
* (types) [#19672](https://github.com/cosmos/cosmos-sdk/pull/19672) `PreBlock` now returns only an error for consistency with server/v2. The SDK has upgraded x/upgrade accordingly. `ResponsePreBlock` hence has been removed.
66+
* (server) [#19455](https://github.com/cosmos/cosmos-sdk/pull/19455) Allow calling back into the application struct in PostSetup.
67+
* (types) [#19512](https://github.com/cosmos/cosmos-sdk/pull/19512) The notion of basic manager does not exist anymore (and all related helpers).
68+
* The module manager now can do everything that the basic manager was doing.
69+
* `AppModuleBasic` has been deprecated for extension interfaces.
70+
* Modules can now implement `appmodule.HasRegisterInterfaces`, `modue.HasGRPCGateway` and `module.HasAminoCodec` when relevant.
71+
* SDK modules now directly implement those extension interfaces on `AppModule` instead of `AppModuleBasic`.
72+
* (client/keys) [#18950](https://github.com/cosmos/cosmos-sdk/pull/18950) Improve `<appd> keys add`, `<appd> keys import` and `<appd> keys rename` by checking name validation.
73+
* (client/keys) [#18745](https://github.com/cosmos/cosmos-sdk/pull/18745) Improve `<appd> keys export` and `<appd> keys mnemonic` by adding --yes option to skip interactive confirmation.
74+
* (client/keys) [#18743](https://github.com/cosmos/cosmos-sdk/pull/18743) Improve `<appd> keys add -i` by hiding inputting of bip39 passphrase.
75+
* (client/keys) [#18703](https://github.com/cosmos/cosmos-sdk/pull/18703) Improve `<appd> keys add` and `<appd> keys show` by checking whether there are duplicate keys in the multisig case.
76+
* Usage of `Must...` kind of functions are avoided in keeper methods.
77+
* (client/keys) [#18687](https://github.com/cosmos/cosmos-sdk/pull/18687) Improve `<appd> keys mnemonic` by displaying mnemonic discreetly on an alternate screen and adding `--indiscreet` option to disable it.
78+
* (client/keys) [#18684](https://github.com/cosmos/cosmos-sdk/pull/18684) Improve `<appd> keys export` by displaying unarmored hex private key discreetly on an alternate screen and adding `--indiscreet` option to disable it.
79+
* (client/keys) [#18663](https://github.com/cosmos/cosmos-sdk/pull/18663) Improve `<appd> keys add` by displaying mnemonic discreetly on an alternate screen and adding `--indiscreet` option to disable it.
80+
* (types) [#18440](https://github.com/cosmos/cosmos-sdk/pull/18440) Add `AmountOfNoValidation` to `sdk.DecCoins`.
81+
* (client) [#17503](https://github.com/cosmos/cosmos-sdk/pull/17503) Add `client.Context{}.WithAddressCodec`, `WithValidatorAddressCodec`, `WithConsensusAddressCodec` to provide address codecs to the client context. See the [UPGRADING.md](./UPGRADING.md) for more details.
82+
* (crypto/keyring) [#17503](https://github.com/cosmos/cosmos-sdk/pull/17503) Simplify keyring interfaces to use `[]byte` instead of `sdk.Address` for addresses.
83+
* (all) [#16537](https://github.com/cosmos/cosmos-sdk/pull/16537) Properly propagated `fmt.Errorf` errors and using `errors.New` where appropriate.
84+
* (rpc) [#17470](https://github.com/cosmos/cosmos-sdk/pull/17470) Avoid open 0.0.0.0 to public by default and add `listen-ip-address` argument for `testnet init-files` cmd.
85+
* (types) [#17670](https://github.com/cosmos/cosmos-sdk/pull/17670) Use `ctx.CometInfo` in place of `ctx.VoteInfos`
86+
* [#17733](https://github.com/cosmos/cosmos-sdk/pull/17733) Ensure `buf export` exports all proto dependencies
87+
* (crypto/keys) [#18026](https://github.com/cosmos/cosmos-sdk/pull/18026) Made public key generation constant time on `secp256k1`
88+
* (crypto | x/auth) [#14372](https://github.com/cosmos/cosmos-sdk/pull/18194) Key checks on signatures antehandle.
89+
* (types) [#18963](https://github.com/cosmos/cosmos-sdk/pull/18963) Swap out amino json encoding of `ABCIMessageLogs` for std lib json encoding
90+
* (x/auth) [#19651](https://github.com/cosmos/cosmos-sdk/pull/19651) Allow empty public keys in `GetSignBytesAdapter`.
91+
* (x/genutil) [#19735](https://github.com/cosmos/cosmos-sdk/pull/19735) Update genesis api to match new `appmodule.HasGenesis` interface.
92+
* (server) [#19966](https://github.com/cosmos/cosmos-sdk/pull/19966) Return BlockHeader by shallow copy in server Context.
93+
>>>>>>> 2496cfdf5 (feat: Conditionally emit metrics based on enablement (#19903))
5594
5695
## Bug Fixes
5796

server/start.go

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -536,10 +536,6 @@ func startAPIServer(
536536
}
537537

538538
func startTelemetry(cfg serverconfig.Config) (*telemetry.Metrics, error) {
539-
if !cfg.Telemetry.Enabled {
540-
return nil, nil
541-
}
542-
543539
return telemetry.New(cfg.Telemetry)
544540
}
545541

telemetry/metrics.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,15 @@ import (
1414
"github.com/prometheus/common/expfmt"
1515
)
1616

17+
// globalTelemetryEnabled is a private variable that stores the telemetry enabled state.
18+
// It is set on initialization and does not change for the lifetime of the program.
19+
var globalTelemetryEnabled bool
20+
21+
// IsTelemetryEnabled provides controlled access to check if telemetry is enabled.
22+
func IsTelemetryEnabled() bool {
23+
return globalTelemetryEnabled
24+
}
25+
1726
// globalLabels defines the set of global labels that will be applied to all
1827
// metrics emitted using the telemetry package function wrappers.
1928
var globalLabels = []metrics.Label{}
@@ -95,6 +104,7 @@ type GatherResponse struct {
95104

96105
// New creates a new instance of Metrics
97106
func New(cfg Config) (_ *Metrics, rerr error) {
107+
globalTelemetryEnabled = cfg.Enabled
98108
if !cfg.Enabled {
99109
return nil, nil
100110
}

telemetry/wrapper.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@ func NewLabel(name, value string) metrics.Label {
2424
// metric for a module with a given set of keys. If any global labels are defined,
2525
// they will be added to the module label.
2626
func ModuleMeasureSince(module string, start time.Time, keys ...string) {
27+
if !IsTelemetryEnabled() {
28+
return
29+
}
30+
2731
metrics.MeasureSinceWithLabels(
2832
keys,
2933
start.UTC(),
@@ -35,6 +39,10 @@ func ModuleMeasureSince(module string, start time.Time, keys ...string) {
3539
// module with a given set of keys. If any global labels are defined, they will
3640
// be added to the module label.
3741
func ModuleSetGauge(module string, val float32, keys ...string) {
42+
if !IsTelemetryEnabled() {
43+
return
44+
}
45+
3846
metrics.SetGaugeWithLabels(
3947
keys,
4048
val,
@@ -45,29 +53,58 @@ func ModuleSetGauge(module string, val float32, keys ...string) {
4553
// IncrCounter provides a wrapper functionality for emitting a counter metric with
4654
// global labels (if any).
4755
func IncrCounter(val float32, keys ...string) {
56+
if !IsTelemetryEnabled() {
57+
return
58+
}
59+
4860
metrics.IncrCounterWithLabels(keys, val, globalLabels)
4961
}
5062

5163
// IncrCounterWithLabels provides a wrapper functionality for emitting a counter
5264
// metric with global labels (if any) along with the provided labels.
5365
func IncrCounterWithLabels(keys []string, val float32, labels []metrics.Label) {
66+
if !IsTelemetryEnabled() {
67+
return
68+
}
69+
5470
metrics.IncrCounterWithLabels(keys, val, append(labels, globalLabels...))
5571
}
5672

5773
// SetGauge provides a wrapper functionality for emitting a gauge metric with
5874
// global labels (if any).
5975
func SetGauge(val float32, keys ...string) {
76+
if !IsTelemetryEnabled() {
77+
return
78+
}
79+
6080
metrics.SetGaugeWithLabels(keys, val, globalLabels)
6181
}
6282

6383
// SetGaugeWithLabels provides a wrapper functionality for emitting a gauge
6484
// metric with global labels (if any) along with the provided labels.
6585
func SetGaugeWithLabels(keys []string, val float32, labels []metrics.Label) {
86+
if !IsTelemetryEnabled() {
87+
return
88+
}
89+
6690
metrics.SetGaugeWithLabels(keys, val, append(labels, globalLabels...))
6791
}
6892

6993
// MeasureSince provides a wrapper functionality for emitting a a time measure
7094
// metric with global labels (if any).
7195
func MeasureSince(start time.Time, keys ...string) {
96+
if !IsTelemetryEnabled() {
97+
return
98+
}
99+
72100
metrics.MeasureSinceWithLabels(keys, start.UTC(), globalLabels)
73101
}
102+
103+
// Now return the current time if telemetry is enabled or a zero time if it's not
104+
func Now() time.Time {
105+
if !IsTelemetryEnabled() {
106+
return time.Time{}
107+
}
108+
109+
return time.Now()
110+
}

telemetry/wrapper_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package telemetry
2+
3+
import (
4+
"sync"
5+
"testing"
6+
"time"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
var mu sync.Mutex
12+
13+
func initTelemetry(v bool) {
14+
globalTelemetryEnabled = v
15+
}
16+
17+
// Reset the global state to a known disabled state before each test.
18+
func setupTest(t *testing.T) {
19+
t.Helper()
20+
mu.Lock() // Ensure no other test can modify global state at the same time.
21+
defer mu.Unlock()
22+
initTelemetry(false)
23+
}
24+
25+
// TestNow tests the Now function when telemetry is enabled and disabled.
26+
func TestNow(t *testing.T) {
27+
setupTest(t) // Locks the mutex to avoid race condition.
28+
29+
initTelemetry(true)
30+
telemetryTime := Now()
31+
assert.NotEqual(t, time.Time{}, telemetryTime, "Now() should not return zero time when telemetry is enabled")
32+
33+
setupTest(t) // Reset the global state and lock the mutex again.
34+
35+
initTelemetry(false)
36+
telemetryTime = Now()
37+
assert.Equal(t, time.Time{}, telemetryTime, "Now() should return zero time when telemetry is disabled")
38+
}
39+
40+
// TestIsTelemetryEnabled tests the IsTelemetryEnabled function.
41+
func TestIsTelemetryEnabled(t *testing.T) {
42+
setupTest(t) // Locks the mutex to avoid race condition.
43+
44+
initTelemetry(true)
45+
assert.True(t, IsTelemetryEnabled(), "IsTelemetryEnabled() should return true when globalTelemetryEnabled is set to true")
46+
47+
setupTest(t) // Reset the global state and lock the mutex again.
48+
49+
initTelemetry(false)
50+
assert.False(t, IsTelemetryEnabled(), "IsTelemetryEnabled() should return false when globalTelemetryEnabled is set to false")
51+
}

x/circuit/module.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"encoding/json"
66
"fmt"
7-
"time"
87

98
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
109

@@ -66,6 +65,7 @@ func (AppModuleBasic) ValidateGenesis(cdc codec.JSONCodec, _ client.TxEncodingCo
6665
return data.Validate()
6766
}
6867

68+
<<<<<<< HEAD
6969
// RegisterGRPCGatewayRoutes registers the gRPC Gateway routes for the circuit module.
7070
func (AppModuleBasic) RegisterGRPCGatewayRoutes(clientCtx client.Context, mux *gwruntime.ServeMux) {
7171
if err := types.RegisterQueryHandlerClient(context.Background(), mux, types.NewQueryClient(clientCtx)); err != nil {
@@ -112,6 +112,11 @@ func (AppModule) ConsensusVersion() uint64 { return ConsensusVersion }
112112
// no validator updates.
113113
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) {
114114
start := time.Now()
115+
=======
116+
// InitGenesis performs genesis initialization for the circuit module.
117+
func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error {
118+
start := telemetry.Now()
119+
>>>>>>> 2496cfdf5 (feat: Conditionally emit metrics based on enablement (#19903))
115120
var genesisState types.GenesisState
116121
cdc.MustUnmarshalJSON(data, &genesisState)
117122
telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal")

x/crisis/abci.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ package crisis
22

33
import (
44
"context"
5-
"time"
65

76
"github.com/cosmos/cosmos-sdk/telemetry"
87
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -12,7 +11,7 @@ import (
1211

1312
// check all registered invariants
1413
func EndBlocker(ctx context.Context, k keeper.Keeper) {
15-
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyEndBlocker)
14+
defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyEndBlocker)
1615

1716
sdkCtx := sdk.UnwrapSDKContext(ctx)
1817
if k.InvCheckPeriod() == 0 || sdkCtx.BlockHeight()%int64(k.InvCheckPeriod()) != 0 {

x/crisis/module.go

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"encoding/json"
66
"fmt"
7-
"time"
87

98
gwruntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
109
"github.com/spf13/cast"
@@ -136,13 +135,38 @@ func (am AppModule) RegisterServices(cfg module.Configurator) {
136135
}
137136
}
138137

138+
<<<<<<< HEAD
139139
// InitGenesis performs genesis initialization for the crisis module. It returns
140140
// no validator updates.
141141
func (am AppModule) InitGenesis(ctx sdk.Context, cdc codec.JSONCodec, data json.RawMessage) {
142142
start := time.Now()
143143
var genesisState types.GenesisState
144144
cdc.MustUnmarshalJSON(data, &genesisState)
145145
telemetry.MeasureSince(start, "InitGenesis", "crisis", "unmarshal")
146+
=======
147+
// DefaultGenesis returns default genesis state as raw bytes for the crisis module.
148+
func (am AppModule) DefaultGenesis() json.RawMessage {
149+
return am.cdc.MustMarshalJSON(types.DefaultGenesisState())
150+
}
151+
152+
// ValidateGenesis performs genesis state validation for the crisis module.
153+
func (am AppModule) ValidateGenesis(bz json.RawMessage) error {
154+
var data types.GenesisState
155+
if err := am.cdc.UnmarshalJSON(bz, &data); err != nil {
156+
return fmt.Errorf("failed to unmarshal %s genesis state: %w", types.ModuleName, err)
157+
}
158+
159+
return types.ValidateGenesis(&data)
160+
}
161+
162+
// InitGenesis performs genesis initialization for the crisis module.
163+
func (am AppModule) InitGenesis(ctx context.Context, data json.RawMessage) error {
164+
var genesisState types.GenesisState
165+
if err := am.cdc.UnmarshalJSON(data, &genesisState); err != nil {
166+
return err
167+
}
168+
telemetry.MeasureSince(telemetry.Now(), "InitGenesis", "crisis", "unmarshal")
169+
>>>>>>> 2496cfdf5 (feat: Conditionally emit metrics based on enablement (#19903))
146170

147171
am.keeper.InitGenesis(ctx, &genesisState)
148172
if !am.skipGenesisInvariants {

x/distribution/abci.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
package distribution
22

33
import (
4+
<<<<<<< HEAD:x/distribution/abci.go
45
"time"
6+
=======
7+
"cosmossdk.io/x/distribution/types"
8+
>>>>>>> 2496cfdf5 (feat: Conditionally emit metrics based on enablement (#19903)):x/distribution/keeper/abci.go
59

610
"github.com/cosmos/cosmos-sdk/telemetry"
711
sdk "github.com/cosmos/cosmos-sdk/types"
@@ -11,8 +15,14 @@ import (
1115

1216
// BeginBlocker sets the proposer for determining distribution during endblock
1317
// and distribute rewards for the previous block.
18+
<<<<<<< HEAD:x/distribution/abci.go
1419
func BeginBlocker(ctx sdk.Context, k keeper.Keeper) error {
1520
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker)
21+
=======
22+
// TODO: use context.Context after including the comet service
23+
func (k Keeper) BeginBlocker(ctx sdk.Context) error {
24+
defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyBeginBlocker)
25+
>>>>>>> 2496cfdf5 (feat: Conditionally emit metrics based on enablement (#19903)):x/distribution/keeper/abci.go
1626

1727
// determine the total power signing the block
1828
var previousTotalPower int64

x/evidence/keeper/abci.go

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package keeper
33
import (
44
"context"
55
"fmt"
6-
"time"
76

87
"cosmossdk.io/core/comet"
98
"cosmossdk.io/x/evidence/types"
@@ -15,7 +14,7 @@ import (
1514
// BeginBlocker iterates through and handles any newly discovered evidence of
1615
// misbehavior submitted by CometBFT. Currently, only equivocation is handled.
1716
func (k Keeper) BeginBlocker(ctx context.Context) error {
18-
defer telemetry.ModuleMeasureSince(types.ModuleName, time.Now(), telemetry.MetricKeyBeginBlocker)
17+
defer telemetry.ModuleMeasureSince(types.ModuleName, telemetry.Now(), telemetry.MetricKeyBeginBlocker)
1918

2019
bi := k.cometInfo.GetCometBlockInfo(ctx)
2120
if bi == nil {

0 commit comments

Comments
 (0)