From 5aaff2109642ace58c72d7d68413a024a0de2baf Mon Sep 17 00:00:00 2001 From: Julien Robert Date: Tue, 25 Jun 2024 20:53:57 +0200 Subject: [PATCH] feat: parse home flag earlier (#20771) --- CHANGELOG.md | 1 + client/config/config.go | 20 ----------------- client/v2/CHANGELOG.md | 1 + client/v2/helpers/home.go | 36 +++++++++++++++++++++++++++++++ docs/learn/advanced/07-cli.md | 4 ++-- scripts/init-simapp.sh | 2 +- scripts/simapp-v2-init.sh | 3 ++- server/v2/cometbft/flags/flags.go | 3 --- server/v2/commands.go | 3 ++- simapp/CHANGELOG.md | 1 + simapp/app.go | 8 +++---- simapp/app_di.go | 7 +++--- simapp/simd/cmd/commands.go | 19 ---------------- simapp/simd/cmd/root.go | 4 ++-- simapp/simd/cmd/root_di.go | 8 ++----- simapp/v2/app_di.go | 18 +++++++--------- simapp/v2/simdv2/cmd/commands.go | 15 ++----------- simapp/v2/simdv2/cmd/root_di.go | 2 +- x/upgrade/CHANGELOG.md | 1 + x/upgrade/depinject.go | 12 +++++++++-- x/upgrade/go.mod | 2 +- x/upgrade/keeper/keeper.go | 16 ++++++-------- 22 files changed, 87 insertions(+), 99 deletions(-) create mode 100644 client/v2/helpers/home.go diff --git a/CHANGELOG.md b/CHANGELOG.md index d4c1e59256bb..d0915fbb45ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -102,6 +102,7 @@ Every module contains its own CHANGELOG.md. Please refer to the module you are i * (proto) [#20098](https://github.com/cosmos/cosmos-sdk/pull/20098) Use cosmos_proto added_in annotation instead of // Since comments. * (baseapp) [#20208](https://github.com/cosmos/cosmos-sdk/pull/20208) Skip running validateBasic for rechecking txs. * (baseapp) [#20380](https://github.com/cosmos/cosmos-sdk/pull/20380) Enhanced OfferSnapshot documentation. +* (client) [#20771](https://github.com/cosmos/cosmos-sdk/pull/20771) Remove `ReadDefaultValuesFromDefaultClientConfig` from `client` package. (It was introduced in `v0.50.6` as a quick fix). ### Bug Fixes diff --git a/client/config/config.go b/client/config/config.go index 893ddd7df886..d850b04dc39b 100644 --- a/client/config/config.go +++ b/client/config/config.go @@ -53,26 +53,6 @@ func ReadFromClientConfig(ctx client.Context) (client.Context, error) { return CreateClientConfig(ctx, "", nil) } -// ReadDefaultValuesFromDefaultClientConfig reads default values from default client.toml file and updates them in client.Context -// The client.toml is then discarded. -func ReadDefaultValuesFromDefaultClientConfig(ctx client.Context, customClientTemplate string, customConfig interface{}) (client.Context, error) { - prevHomeDir := ctx.HomeDir - dir, err := os.MkdirTemp("", "simapp") - if err != nil { - return ctx, fmt.Errorf("couldn't create temp dir: %w", err) - } - defer os.RemoveAll(dir) - - ctx.HomeDir = dir - ctx, err = CreateClientConfig(ctx, customClientTemplate, customConfig) - if err != nil { - return ctx, fmt.Errorf("couldn't create client config: %w", err) - } - - ctx.HomeDir = prevHomeDir - return ctx, nil -} - // CreateClientConfig reads the client.toml file and returns a new populated client.Context // If the client.toml file does not exist, it creates one with default values. // It takes a customClientTemplate and customConfig as input that can be used to overwrite the default config and enhance the client.toml file. diff --git a/client/v2/CHANGELOG.md b/client/v2/CHANGELOG.md index 02700494da35..17567723dd0c 100644 --- a/client/v2/CHANGELOG.md +++ b/client/v2/CHANGELOG.md @@ -42,6 +42,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ * [#18626](https://github.com/cosmos/cosmos-sdk/pull/18626) Support for off-chain signing and verification of a file. * [#18461](https://github.com/cosmos/cosmos-sdk/pull/18461) Support governance proposals. +* [#20771](https://github.com/cosmos/cosmos-sdk/pull/20771) Add `GetNodeHomeDirectory` helper. ### API Breaking Changes diff --git a/client/v2/helpers/home.go b/client/v2/helpers/home.go new file mode 100644 index 000000000000..f62ff30490e9 --- /dev/null +++ b/client/v2/helpers/home.go @@ -0,0 +1,36 @@ +package helpers + +import ( + "os" + "path/filepath" + "strings" +) + +// GetNodeHomeDirectory gets the home directory of the node (where the config is located). +// It parses the home flag if set if the `NODE_HOME` environment variable if set (and ignores name). +// Otherwise, it returns the default home directory given its name. +func GetNodeHomeDirectory(name string) (string, error) { + // get the home directory from the flag + args := os.Args + for i := 0; i < len(args); i++ { + if args[i] == "--home" && i+1 < len(args) { + return filepath.Clean(args[i+1]), nil + } else if strings.HasPrefix(args[i], "--home=") { + return filepath.Clean(args[i][7:]), nil + } + } + + // get the home directory from the environment variable + homeDir := os.Getenv("NODE_HOME") + if homeDir != "" { + return filepath.Clean(homeDir), nil + } + + // return the default home directory + userHomeDir, err := os.UserHomeDir() + if err != nil { + return "", err + } + + return filepath.Join(userHomeDir, name), nil +} diff --git a/docs/learn/advanced/07-cli.md b/docs/learn/advanced/07-cli.md index 77c2fe861bfa..b4932ad4c90d 100644 --- a/docs/learn/advanced/07-cli.md +++ b/docs/learn/advanced/07-cli.md @@ -172,7 +172,7 @@ Flags are added to commands directly (generally in the [module's CLI file](../.. ## Environment variables -Each flag is bound to its respective named environment variable. Then name of the environment variable consist of two parts - capital case `basename` followed by flag name of the flag. `-` must be substituted with `_`. For example flag `--home` for application with basename `GAIA` is bound to `GAIA_HOME`. It allows reducing the amount of flags typed for routine operations. For example instead of: +Each flag is bound to its respective named environment variable. Then name of the environment variable consist of two parts - capital case `basename` followed by flag name of the flag. `-` must be substituted with `_`. For example flag `--node` for application with basename `GAIA` is bound to `GAIA_NODE`. It allows reducing the amount of flags typed for routine operations. For example instead of: ```shell gaia --home=./ --node= --chain-id="testchain-1" --keyring-backend=test tx ... --from= @@ -182,7 +182,7 @@ this will be more convenient: ```shell # define env variables in .env, .envrc etc -GAIA_HOME= +NODE_HOME= GAIA_NODE= GAIA_CHAIN_ID="testchain-1" GAIA_KEYRING_BACKEND="test" diff --git a/scripts/init-simapp.sh b/scripts/init-simapp.sh index f6babfedf042..b7f08949564b 100755 --- a/scripts/init-simapp.sh +++ b/scripts/init-simapp.sh @@ -4,7 +4,7 @@ SIMD_BIN=${SIMD_BIN:=$(which simd 2>/dev/null)} if [ -z "$SIMD_BIN" ]; then echo "SIMD_BIN is not set. Make sure to run make install before"; exit 1; fi echo "using $SIMD_BIN" -if [ -d "$($SIMD_BIN config home)" ]; then rm -r $($SIMD_BIN config home); fi +if [ -d "$($SIMD_BIN config home)" ]; then rm -rv $($SIMD_BIN config home); fi $SIMD_BIN config set client chain-id demo $SIMD_BIN config set client keyring-backend test $SIMD_BIN config set client keyring-default-keyname alice diff --git a/scripts/simapp-v2-init.sh b/scripts/simapp-v2-init.sh index a41cfba08245..d13960d2d80e 100755 --- a/scripts/simapp-v2-init.sh +++ b/scripts/simapp-v2-init.sh @@ -11,7 +11,7 @@ CONFIG="${CONFIG:-$HOME/.simappv2/config}" COSMOS_BUILD_OPTIONS=v2 make build -if [ -d "$($SIMD config home)" ]; then rm -r $($SIMD config home); fi +if [ -d "$($SIMD config home)" ]; then rm -rv $($SIMD config home); fi $SIMD init simapp-v2-node --chain-id simapp-v2-chain @@ -26,6 +26,7 @@ jq '.app_state.mint.minter.inflation = "0.300000000000000000"' genesis.json > te # change the initial height to 2 to work around store/v2 and iavl limitations with a genesis block jq '.initial_height = 2' genesis.json > temp.json && mv temp.json genesis.json +$SIMD config set client chain-id simapp-v2-chain $SIMD keys add test_validator --indiscreet VALIDATOR_ADDRESS=$($SIMD keys show test_validator -a --keyring-backend test) diff --git a/server/v2/cometbft/flags/flags.go b/server/v2/cometbft/flags/flags.go index 37003dcdce21..878cc9c28227 100644 --- a/server/v2/cometbft/flags/flags.go +++ b/server/v2/cometbft/flags/flags.go @@ -9,9 +9,6 @@ const ( ) const ( - FlagHome = "home" - FlagKeyringDir = "keyring-dir" - FlagUseLedger = "ledger" FlagChainID = "chain-id" FlagNode = "node" FlagGRPC = "grpc-addr" diff --git a/server/v2/commands.go b/server/v2/commands.go index 47c6ea797e0a..a6059388ad2a 100644 --- a/server/v2/commands.go +++ b/server/v2/commands.go @@ -109,7 +109,8 @@ func AddCommands(rootCmd *cobra.Command, newApp AppCreator[transaction.Tx], logg // configHandle writes the default config to the home directory if it does not exist and sets the server context func configHandle(s *Server, home string, cmd *cobra.Command) error { - if _, err := os.Stat(filepath.Join(home, "config")); os.IsNotExist(err) { + // we need to check app.toml as the config folder can already exist for the client.toml + if _, err := os.Stat(filepath.Join(home, "config", "app.toml")); os.IsNotExist(err) { if err = s.WriteConfig(filepath.Join(home, "config")); err != nil { return err } diff --git a/simapp/CHANGELOG.md b/simapp/CHANGELOG.md index 6b279ddfa2ce..2daff48a15f2 100644 --- a/simapp/CHANGELOG.md +++ b/simapp/CHANGELOG.md @@ -35,6 +35,7 @@ Always refer to the [UPGRADING.md](https://github.com/cosmos/cosmos-sdk/blob/mai * [#20409](https://github.com/cosmos/cosmos-sdk/pull/20409) Add `tx` as `SkipStoreKeys` in `app_config.go`. * [#20485](https://github.com/cosmos/cosmos-sdk/pull/20485) The signature of `x/upgrade/types.UpgradeHandler` has changed to accept `appmodule.VersionMap` from `module.VersionMap`. These types are interchangeable, but usages of `UpradeKeeper.SetUpgradeHandler` may need to adjust their usages to match the new signature. * [#20740](https://github.com/cosmos/cosmos-sdk/pull/20740) Update `genutilcli.Commands` to use the genutil modules from the module manager. +* [#20771](https://github.com/cosmos/cosmos-sdk/pull/20771) Use client/v2 `GetNodeHomeDirectory` helper in `app.go` and use the `DefaultNodeHome` constant everywhere in the app. diff --git a/simapp/app.go b/simapp/app.go index c441659f18c1..d5a0269f8197 100644 --- a/simapp/app.go +++ b/simapp/app.go @@ -18,6 +18,7 @@ import ( autocliv1 "cosmossdk.io/api/cosmos/autocli/v1" reflectionv1 "cosmossdk.io/api/cosmos/reflection/v1" "cosmossdk.io/client/v2/autocli" + clienthelpers "cosmossdk.io/client/v2/helpers" "cosmossdk.io/core/log" storetypes "cosmossdk.io/store/types" "cosmossdk.io/x/accounts" @@ -183,12 +184,11 @@ type SimApp struct { } func init() { - userHomeDir, err := os.UserHomeDir() + var err error + DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory(".simapp") if err != nil { panic(err) } - - DefaultNodeHome = filepath.Join(userHomeDir, ".simapp") } // NewSimApp returns a reference to an initialized SimApp. @@ -536,7 +536,7 @@ func NewSimApp( app.sm = module.NewSimulationManagerFromAppModules(app.ModuleManager.Modules, overrideModules) // create, start, and load the unordered tx manager - utxDataDir := filepath.Join(cast.ToString(appOpts.Get(flags.FlagHome)), "data") + utxDataDir := filepath.Join(homePath, "data") app.UnorderedTxManager = unorderedtx.NewManager(utxDataDir) app.UnorderedTxManager.Start() diff --git a/simapp/app_di.go b/simapp/app_di.go index d2b27c7eefdc..ac73c5af53fb 100644 --- a/simapp/app_di.go +++ b/simapp/app_di.go @@ -6,12 +6,12 @@ import ( _ "embed" "fmt" "io" - "os" "path/filepath" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cast" + clienthelpers "cosmossdk.io/client/v2/helpers" "cosmossdk.io/core/legacy" "cosmossdk.io/depinject" "cosmossdk.io/log" @@ -100,12 +100,11 @@ type SimApp struct { } func init() { - userHomeDir, err := os.UserHomeDir() + var err error + DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory(".simapp") if err != nil { panic(err) } - - DefaultNodeHome = filepath.Join(userHomeDir, ".simapp") } // AppConfig returns the default app config. diff --git a/simapp/simd/cmd/commands.go b/simapp/simd/cmd/commands.go index 4bb204e522fe..84c691a225f5 100644 --- a/simapp/simd/cmd/commands.go +++ b/simapp/simd/cmd/commands.go @@ -3,7 +3,6 @@ package cmd import ( "errors" "io" - "os" dbm "github.com/cosmos/cosmos-db" "github.com/spf13/cobra" @@ -18,7 +17,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/pruning" "github.com/cosmos/cosmos-sdk/client/rpc" @@ -143,13 +141,6 @@ func appExport( appOpts servertypes.AppOptions, modulesToExport []string, ) (servertypes.ExportedApp, error) { - // this check is necessary as we use the flag in x/upgrade. - // we can exit more gracefully by checking the flag here. - homePath, ok := appOpts.Get(flags.FlagHome).(string) - if !ok || homePath == "" { - return servertypes.ExportedApp{}, errors.New("application home not set") - } - viperAppOpts, ok := appOpts.(*viper.Viper) if !ok { return servertypes.ExportedApp{}, errors.New("appOpts is not viper.Viper") @@ -172,13 +163,3 @@ func appExport( return simApp.ExportAppStateAndValidators(forZeroHeight, jailAllowedAddrs, modulesToExport) } - -var tempDir = func() string { - dir, err := os.MkdirTemp("", "simapp") - if err != nil { - dir = simapp.DefaultNodeHome - } - defer os.RemoveAll(dir) - - return dir -} diff --git a/simapp/simd/cmd/root.go b/simapp/simd/cmd/root.go index 9367365676ac..007bdd5b9382 100644 --- a/simapp/simd/cmd/root.go +++ b/simapp/simd/cmd/root.go @@ -30,7 +30,7 @@ import ( func NewRootCmd() *cobra.Command { // we "pre"-instantiate the application for getting the injected/configured encoding configuration // note, this is not necessary when using app wiring, as depinject can be directly used (see root_v2.go) - tempApp := simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(tempDir())) + tempApp := simapp.NewSimApp(log.NewNopLogger(), dbm.NewMemDB(), nil, true, simtestutil.NewAppOptionsWithFlagHome(simapp.DefaultNodeHome)) encodingConfig := params.EncodingConfig{ InterfaceRegistry: tempApp.InterfaceRegistry(), Codec: tempApp.AppCodec(), @@ -114,7 +114,7 @@ func NewRootCmd() *cobra.Command { // autocli opts customClientTemplate, customClientConfig := initClientConfig() var err error - initClientCtx, err = config.ReadDefaultValuesFromDefaultClientConfig(initClientCtx, customClientTemplate, customClientConfig) + initClientCtx, err = config.CreateClientConfig(initClientCtx, customClientTemplate, customClientConfig) if err != nil { panic(err) } diff --git a/simapp/simd/cmd/root_di.go b/simapp/simd/cmd/root_di.go index 2302ace1a3fd..4ed5437d1637 100644 --- a/simapp/simd/cmd/root_di.go +++ b/simapp/simd/cmd/root_di.go @@ -24,7 +24,6 @@ import ( "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" "github.com/cosmos/cosmos-sdk/server" - simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims" "github.com/cosmos/cosmos-sdk/types/module" ) @@ -38,10 +37,7 @@ func NewRootCmd() *cobra.Command { if err := depinject.Inject( depinject.Configs(simapp.AppConfig(), - depinject.Supply( - log.NewNopLogger(), - simtestutil.NewAppOptionsWithFlagHome(tempDir()), - ), + depinject.Supply(log.NewNopLogger()), depinject.Provide( ProvideClientContext, ), @@ -128,7 +124,7 @@ func ProvideClientContext( // Read the config to overwrite the default values with the values from the config file customClientTemplate, customClientConfig := initClientConfig() - clientCtx, err = config.ReadDefaultValuesFromDefaultClientConfig(clientCtx, customClientTemplate, customClientConfig) + clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) if err != nil { panic(err) } diff --git a/simapp/v2/app_di.go b/simapp/v2/app_di.go index a91de00b55f9..a55d9ec3289b 100644 --- a/simapp/v2/app_di.go +++ b/simapp/v2/app_di.go @@ -2,16 +2,17 @@ package simapp import ( _ "embed" - "os" "path/filepath" "github.com/spf13/viper" + clienthelpers "cosmossdk.io/client/v2/helpers" coreapp "cosmossdk.io/core/app" "cosmossdk.io/core/legacy" "cosmossdk.io/core/log" "cosmossdk.io/depinject" "cosmossdk.io/runtime/v2" + serverv2 "cosmossdk.io/server/v2" "cosmossdk.io/store/v2" "cosmossdk.io/store/v2/commitment/iavl" "cosmossdk.io/store/v2/db" @@ -36,10 +37,8 @@ import ( upgradekeeper "cosmossdk.io/x/upgrade/keeper" "github.com/cosmos/cosmos-sdk/client" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/codec" codectypes "github.com/cosmos/cosmos-sdk/codec/types" - servertypes "github.com/cosmos/cosmos-sdk/server/types" "github.com/cosmos/cosmos-sdk/std" ) @@ -77,12 +76,11 @@ type SimApp struct { } func init() { - userHomeDir, err := os.UserHomeDir() + var err error + DefaultNodeHome, err = clienthelpers.GetNodeHomeDirectory(".simappv2") if err != nil { panic(err) } - - DefaultNodeHome = filepath.Join(userHomeDir, ".simappv2") } // AppConfig returns the default app config. @@ -97,8 +95,8 @@ func NewSimApp( logger log.Logger, viper *viper.Viper, ) *SimApp { - homeDir := viper.Get(flags.FlagHome).(string) // TODO - scRawDb, err := db.NewGoLevelDB("application", filepath.Join(homeDir, "data"), nil) + viper.Set(serverv2.FlagHome, DefaultNodeHome) // TODO possibly set earlier when viper is created + scRawDb, err := db.NewGoLevelDB("application", filepath.Join(DefaultNodeHome, "data"), nil) if err != nil { panic(err) } @@ -113,7 +111,7 @@ func NewSimApp( logger, &root.FactoryOptions{ Logger: logger, - RootDir: homeDir, + RootDir: DefaultNodeHome, SSType: 0, SCType: 0, SCPruneOptions: &store.PruneOptions{ @@ -126,7 +124,7 @@ func NewSimApp( }, SCRawDB: scRawDb, }, - servertypes.AppOptions(viper), + viper, // ADVANCED CONFIGURATION diff --git a/simapp/v2/simdv2/cmd/commands.go b/simapp/v2/simdv2/cmd/commands.go index b8c2988aa72c..b4b186c0f01f 100644 --- a/simapp/v2/simdv2/cmd/commands.go +++ b/simapp/v2/simdv2/cmd/commands.go @@ -22,7 +22,6 @@ import ( "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/debug" - "github.com/cosmos/cosmos-sdk/client/flags" "github.com/cosmos/cosmos-sdk/client/keys" "github.com/cosmos/cosmos-sdk/client/rpc" "github.com/cosmos/cosmos-sdk/server" @@ -49,12 +48,8 @@ func (t *temporaryTxDecoder) DecodeJSON(bz []byte) (transaction.Tx, error) { return t.txConfig.TxJSONDecoder()(bz) } -func newApp( - logger log.Logger, - viper *viper.Viper, -) serverv2.AppI[transaction.Tx] { - sa := simapp.NewSimApp(logger, viper) - return sa +func newApp(logger log.Logger, viper *viper.Viper) serverv2.AppI[transaction.Tx] { + return simapp.NewSimApp(logger, viper) } func initRootCmd( @@ -184,12 +179,6 @@ func appExport( viper *viper.Viper, modulesToExport []string, ) (servertypes.ExportedApp, error) { - // this check is necessary as we use the flag in x/upgrade. - // we can exit more gracefully by checking the flag here. - homePath, ok := viper.Get(flags.FlagHome).(string) - if !ok || homePath == "" { - return servertypes.ExportedApp{}, errors.New("application home not set") - } // overwrite the FlagInvCheckPeriod viper.Set(server.FlagInvCheckPeriod, 1) diff --git a/simapp/v2/simdv2/cmd/root_di.go b/simapp/v2/simdv2/cmd/root_di.go index c8937e1bf2e9..51c873be570b 100644 --- a/simapp/v2/simdv2/cmd/root_di.go +++ b/simapp/v2/simdv2/cmd/root_di.go @@ -121,7 +121,7 @@ func ProvideClientContext( // Read the config to overwrite the default values with the values from the config file customClientTemplate, customClientConfig := initClientConfig() - clientCtx, err = config.ReadDefaultValuesFromDefaultClientConfig(clientCtx, customClientTemplate, customClientConfig) + clientCtx, err = config.CreateClientConfig(clientCtx, customClientTemplate, customClientConfig) if err != nil { panic(err) } diff --git a/x/upgrade/CHANGELOG.md b/x/upgrade/CHANGELOG.md index c098e5a24827..ffa9529fa65f 100644 --- a/x/upgrade/CHANGELOG.md +++ b/x/upgrade/CHANGELOG.md @@ -28,6 +28,7 @@ Ref: https://keepachangelog.com/en/1.0.0/ ### Improvements * [#19672](https://github.com/cosmos/cosmos-sdk/pull/19672) Follow latest `cosmossdk.io/core` `PreBlock` simplification. +* [#20771](https://github.com/cosmos/cosmos-sdk/pull/20771) Create upgrade directory only when necessary (upgrade flow and not init flow). ### API Breaking Changes diff --git a/x/upgrade/depinject.go b/x/upgrade/depinject.go index 08d00cdf843f..be1187c3f684 100644 --- a/x/upgrade/depinject.go +++ b/x/upgrade/depinject.go @@ -2,6 +2,7 @@ package upgrade import ( "github.com/spf13/cast" + "github.com/spf13/viper" modulev1 "cosmossdk.io/api/cosmos/upgrade/module/v1" "cosmossdk.io/core/address" @@ -41,7 +42,8 @@ type ModuleInputs struct { AddressCodec address.Codec AppVersionModifier app.VersionModifier - AppOpts servertypes.AppOptions `optional:"true"` + AppOpts servertypes.AppOptions `optional:"true"` // server v0 + Viper *viper.Viper `optional:"true"` // server v2 } type ModuleOutputs struct { @@ -57,7 +59,13 @@ func ProvideModule(in ModuleInputs) ModuleOutputs { skipUpgradeHeights = make(map[int64]bool) ) - if in.AppOpts != nil { + if in.Viper != nil { // viper takes precedence over app options + for _, h := range in.Viper.GetIntSlice(server.FlagUnsafeSkipUpgrades) { + skipUpgradeHeights[int64(h)] = true + } + + homePath = in.Viper.GetString(flags.FlagHome) + } else if in.AppOpts != nil { for _, h := range cast.ToIntSlice(in.AppOpts.Get(server.FlagUnsafeSkipUpgrades)) { skipUpgradeHeights[int64(h)] = true } diff --git a/x/upgrade/go.mod b/x/upgrade/go.mod index de0fcd51cb60..38a394cbe544 100644 --- a/x/upgrade/go.mod +++ b/x/upgrade/go.mod @@ -26,6 +26,7 @@ require ( github.com/spf13/cast v1.6.0 github.com/spf13/cobra v1.8.1 github.com/spf13/pflag v1.0.5 + github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.9.0 google.golang.org/genproto/googleapis/api v0.0.0-20240617180043-68d350f18fd4 google.golang.org/grpc v1.64.0 @@ -160,7 +161,6 @@ require ( github.com/sasha-s/go-deadlock v0.3.1 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.11.0 // indirect - github.com/spf13/viper v1.19.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect github.com/supranational/blst v0.3.11 // indirect github.com/syndtr/goleveldb v1.0.1-0.20220721030215-126854af5e6d // indirect diff --git a/x/upgrade/keeper/keeper.go b/x/upgrade/keeper/keeper.go index 89aa35c98d1c..237ee21fb202 100644 --- a/x/upgrade/keeper/keeper.go +++ b/x/upgrade/keeper/keeper.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "os" - "path" "path/filepath" "sort" "strconv" @@ -65,8 +64,8 @@ func NewKeeper( authority: authority, } - if upgradePlan, err := k.ReadUpgradeInfoFromDisk(); err == nil && upgradePlan.Height > 0 { - telemetry.SetGaugeWithLabels([]string{"server", "info"}, 1, []metrics.Label{telemetry.NewLabel("upgrade_height", strconv.FormatInt(upgradePlan.Height, 10))}) + if homePath == "" { + k.Logger.Warn("homePath is empty; upgrade info will be written to the current directory") } return k @@ -488,7 +487,7 @@ func (k Keeper) DumpUpgradeInfoToDisk(height int64, p types.Plan) error { // GetUpgradeInfoPath returns the upgrade info file path func (k Keeper) GetUpgradeInfoPath() (string, error) { - upgradeInfoFileDir := path.Join(k.getHomeDir(), "data") + upgradeInfoFileDir := filepath.Join(k.homePath, "data") if err := os.MkdirAll(upgradeInfoFileDir, os.ModePerm); err != nil { return "", fmt.Errorf("could not create directory %q: %w", upgradeInfoFileDir, err) } @@ -496,11 +495,6 @@ func (k Keeper) GetUpgradeInfoPath() (string, error) { return filepath.Join(upgradeInfoFileDir, types.UpgradeInfoFilename), nil } -// getHomeDir returns the height at which the given upgrade was executed -func (k Keeper) getHomeDir() string { - return k.homePath -} - // ReadUpgradeInfoFromDisk returns the name and height of the upgrade which is // written to disk by the old binary when panicking. An error is returned if // the upgrade path directory cannot be created or if the file exists and @@ -531,6 +525,10 @@ func (k Keeper) ReadUpgradeInfoFromDisk() (types.Plan, error) { return upgradeInfo, err } + if upgradeInfo.Height > 0 { + telemetry.SetGaugeWithLabels([]string{"server", "info"}, 1, []metrics.Label{telemetry.NewLabel("upgrade_height", strconv.FormatInt(upgradeInfo.Height, 10))}) + } + return upgradeInfo, nil }