From 74a2246b3e0c834d45eae4ff12904773df3cc0db Mon Sep 17 00:00:00 2001 From: Christopher Goes Date: Wed, 4 Apr 2018 13:39:13 +0200 Subject: [PATCH] Pass logger and config through CLI context (closes #725) --- examples/basecoin/cmd/basecoind/main.go | 40 +++++++++++++++++++------ examples/democoin/cmd/democoind/main.go | 40 +++++++++++++++++++------ examples/gaia/gaiad/main.go | 35 ++++++++++++++++++---- server/context.go | 15 ++++++++++ server/init.go | 26 +++++++--------- server/init_test.go | 8 +++-- server/reset.go | 14 ++++----- server/show_node_id.go | 13 +++----- server/show_validator.go | 13 +++----- server/start.go | 24 +++++++-------- server/start_test.go | 7 +++-- server/test_helpers.go | 11 +++++-- 12 files changed, 158 insertions(+), 88 deletions(-) create mode 100644 server/context.go diff --git a/examples/basecoin/cmd/basecoind/main.go b/examples/basecoin/cmd/basecoind/main.go index 395667671..ad26d08c4 100644 --- a/examples/basecoin/cmd/basecoind/main.go +++ b/examples/basecoin/cmd/basecoind/main.go @@ -7,9 +7,13 @@ import ( "path/filepath" "github.com/spf13/cobra" + "github.com/spf13/viper" abci "github.com/tendermint/abci/types" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tmlibs/cli" + tmflags "github.com/tendermint/tmlibs/cli/flags" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -21,9 +25,31 @@ import ( // basecoindCmd is the entry point for this binary var ( + context = server.NewContext(nil, nil) basecoindCmd = &cobra.Command{ Use: "gaiad", Short: "Gaia Daemon (server)", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if cmd.Name() == version.VersionCmd.Name() { + return nil + } + config, err := tcmd.ParseConfig() + if err != nil { + return err + } + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel()) + if err != nil { + return err + } + if viper.GetBool(cli.TraceFlag) { + logger = log.NewTracingLogger(logger) + } + logger = logger.With("module", "main") + context.Config = config + context.Logger = logger + return nil + }, } ) @@ -76,16 +102,12 @@ func generateApp(rootDir string, logger log.Logger) (abci.Application, error) { } func main() { - // TODO: set logger through CLI - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). - With("module", "main") - basecoindCmd.AddCommand( - server.InitCmd(defaultOptions, logger), - server.StartCmd(generateApp, logger), - server.UnsafeResetAllCmd(logger), - server.ShowNodeIdCmd(logger), - server.ShowValidatorCmd(logger), + server.InitCmd(defaultOptions, context), + server.StartCmd(generateApp, context), + server.UnsafeResetAllCmd(context), + server.ShowNodeIdCmd(context), + server.ShowValidatorCmd(context), version.VersionCmd, ) diff --git a/examples/democoin/cmd/democoind/main.go b/examples/democoin/cmd/democoind/main.go index a7af708a1..114c28d0f 100644 --- a/examples/democoin/cmd/democoind/main.go +++ b/examples/democoin/cmd/democoind/main.go @@ -7,9 +7,13 @@ import ( "path/filepath" "github.com/spf13/cobra" + "github.com/spf13/viper" abci "github.com/tendermint/abci/types" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tmlibs/cli" + tmflags "github.com/tendermint/tmlibs/cli/flags" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tmlibs/log" @@ -21,9 +25,31 @@ import ( // democoindCmd is the entry point for this binary var ( + context = server.NewContext(nil, nil) democoindCmd = &cobra.Command{ Use: "democoind", Short: "Gaia Daemon (server)", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if cmd.Name() == version.VersionCmd.Name() { + return nil + } + config, err := tcmd.ParseConfig() + if err != nil { + return err + } + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel()) + if err != nil { + return err + } + if viper.GetBool(cli.TraceFlag) { + logger = log.NewTracingLogger(logger) + } + logger = logger.With("module", "main") + context.Config = config + context.Logger = logger + return nil + }, } ) @@ -82,16 +108,12 @@ func generateApp(rootDir string, logger log.Logger) (abci.Application, error) { } func main() { - // TODO: set logger through CLI - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). - With("module", "main") - democoindCmd.AddCommand( - server.InitCmd(defaultOptions, logger), - server.StartCmd(generateApp, logger), - server.UnsafeResetAllCmd(logger), - server.ShowNodeIdCmd(logger), - server.ShowValidatorCmd(logger), + server.InitCmd(defaultOptions, context), + server.StartCmd(generateApp, context), + server.UnsafeResetAllCmd(context), + server.ShowNodeIdCmd(context), + server.ShowValidatorCmd(context), version.VersionCmd, ) diff --git a/examples/gaia/gaiad/main.go b/examples/gaia/gaiad/main.go index 70a44d8cb..f42452135 100644 --- a/examples/gaia/gaiad/main.go +++ b/examples/gaia/gaiad/main.go @@ -6,9 +6,13 @@ import ( "os" "github.com/spf13/cobra" + "github.com/spf13/viper" abci "github.com/tendermint/abci/types" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tmlibs/cli" + tmflags "github.com/tendermint/tmlibs/cli/flags" cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/log" @@ -19,9 +23,31 @@ import ( // gaiadCmd is the entry point for this binary var ( + context = server.NewContext(nil, nil) gaiadCmd = &cobra.Command{ Use: "gaiad", Short: "Gaia Daemon (server)", + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + if cmd.Name() == version.VersionCmd.Name() { + return nil + } + config, err := tcmd.ParseConfig() + if err != nil { + return err + } + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel()) + if err != nil { + return err + } + if viper.GetBool(cli.TraceFlag) { + logger = log.NewTracingLogger(logger) + } + logger = logger.With("module", "main") + context.Config = config + context.Logger = logger + return nil + }, } ) @@ -56,13 +82,10 @@ func generateApp(rootDir string, logger log.Logger) (abci.Application, error) { } func main() { - logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)). - With("module", "main") - gaiadCmd.AddCommand( - server.InitCmd(defaultOptions, logger), - server.StartCmd(generateApp, logger), - server.UnsafeResetAllCmd(logger), + server.InitCmd(defaultOptions, context), + server.StartCmd(generateApp, context), + server.UnsafeResetAllCmd(context), version.VersionCmd, ) diff --git a/server/context.go b/server/context.go new file mode 100644 index 000000000..def2eddb4 --- /dev/null +++ b/server/context.go @@ -0,0 +1,15 @@ +package server + +import ( + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tmlibs/log" +) + +type Context struct { + Config *cfg.Config + Logger log.Logger +} + +func NewContext(config *cfg.Config, logger log.Logger) *Context { + return &Context{config, logger} +} diff --git a/server/init.go b/server/init.go index 435895081..4e0049ed4 100644 --- a/server/init.go +++ b/server/init.go @@ -7,13 +7,10 @@ import ( "github.com/spf13/cobra" - cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/log" - - tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p" tmtypes "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" ) type testnetInformation struct { @@ -29,10 +26,10 @@ type testnetInformation struct { // The application can pass in a function to generate // proper state. And may want to use GenerateCoinKey // to create default account(s). -func InitCmd(gen GenAppState, logger log.Logger) *cobra.Command { +func InitCmd(gen GenAppState, ctx *Context) *cobra.Command { cmd := initCmd{ genAppState: gen, - logger: logger, + context: ctx, } cobraCmd := cobra.Command{ Use: "init", @@ -50,7 +47,7 @@ type GenAppState func(args []string) (json.RawMessage, string, cmn.HexBytes, err type initCmd struct { genAppState GenAppState - logger log.Logger + context *Context } func (c initCmd) run(cmd *cobra.Command, args []string) error { @@ -59,11 +56,8 @@ func (c initCmd) run(cmd *cobra.Command, args []string) error { // Run the basic tendermint initialization, // set up a default genesis with no app_options - config, err := tcmd.ParseConfig() - if err != nil { - return err - } - err = c.initTendermintFiles(config, &testnetInfo) + config := c.context.Config + err := c.initTendermintFiles(config, &testnetInfo) if err != nil { return err } @@ -109,17 +103,17 @@ func (c initCmd) initTendermintFiles(config *cfg.Config, info *testnetInformatio var privValidator *tmtypes.PrivValidatorFS if cmn.FileExists(privValFile) { privValidator = tmtypes.LoadPrivValidatorFS(privValFile) - c.logger.Info("Found private validator", "path", privValFile) + c.context.Logger.Info("Found private validator", "path", privValFile) } else { privValidator = tmtypes.GenPrivValidatorFS(privValFile) privValidator.Save() - c.logger.Info("Generated private validator", "path", privValFile) + c.context.Logger.Info("Generated private validator", "path", privValFile) } // genesis file genFile := config.GenesisFile() if cmn.FileExists(genFile) { - c.logger.Info("Found genesis file", "path", genFile) + c.context.Logger.Info("Found genesis file", "path", genFile) } else { genDoc := tmtypes.GenesisDoc{ ChainID: cmn.Fmt("test-chain-%v", cmn.RandStr(6)), @@ -132,7 +126,7 @@ func (c initCmd) initTendermintFiles(config *cfg.Config, info *testnetInformatio if err := genDoc.SaveAs(genFile); err != nil { return err } - c.logger.Info("Generated genesis file", "path", genFile) + c.context.Logger.Info("Generated genesis file", "path", genFile) } // reload the config file and find our validator info diff --git a/server/init_test.go b/server/init_test.go index 0abb18040..19e669519 100644 --- a/server/init_test.go +++ b/server/init_test.go @@ -8,13 +8,17 @@ import ( "github.com/tendermint/tmlibs/log" "github.com/cosmos/cosmos-sdk/mock" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" ) func TestInit(t *testing.T) { defer setupViper(t)() logger := log.NewNopLogger() - cmd := InitCmd(mock.GenInitOptions, logger) - err := cmd.RunE(nil, nil) + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := NewContext(cfg, logger) + cmd := InitCmd(mock.GenInitOptions, ctx) + err = cmd.RunE(nil, nil) require.NoError(t, err) } diff --git a/server/reset.go b/server/reset.go index 5c70bbdac..2cff9169f 100644 --- a/server/reset.go +++ b/server/reset.go @@ -4,12 +4,11 @@ import ( "github.com/spf13/cobra" tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" - "github.com/tendermint/tmlibs/log" ) // UnsafeResetAllCmd - extension of the tendermint command, resets initialization -func UnsafeResetAllCmd(logger log.Logger) *cobra.Command { - cmd := resetAll{logger} +func UnsafeResetAllCmd(ctx *Context) *cobra.Command { + cmd := resetAll{ctx} return &cobra.Command{ Use: "unsafe_reset_all", Short: "Reset all blockchain data", @@ -18,14 +17,11 @@ func UnsafeResetAllCmd(logger log.Logger) *cobra.Command { } type resetAll struct { - logger log.Logger + context *Context } func (r resetAll) run(cmd *cobra.Command, args []string) error { - cfg, err := tcmd.ParseConfig() - if err != nil { - return err - } - tcmd.ResetAll(cfg.DBDir(), cfg.PrivValidatorFile(), r.logger) + cfg := r.context.Config + tcmd.ResetAll(cfg.DBDir(), cfg.PrivValidatorFile(), r.context.Logger) return nil } diff --git a/server/show_node_id.go b/server/show_node_id.go index f8d9f3f81..8c81d734f 100644 --- a/server/show_node_id.go +++ b/server/show_node_id.go @@ -5,14 +5,12 @@ import ( "github.com/spf13/cobra" - tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/p2p" - "github.com/tendermint/tmlibs/log" ) // ShowNodeIdCmd - ported from Tendermint, dump node ID to stdout -func ShowNodeIdCmd(logger log.Logger) *cobra.Command { - cmd := showNodeId{logger} +func ShowNodeIdCmd(ctx *Context) *cobra.Command { + cmd := showNodeId{ctx} return &cobra.Command{ Use: "show_node_id", Short: "Show this node's ID", @@ -21,14 +19,11 @@ func ShowNodeIdCmd(logger log.Logger) *cobra.Command { } type showNodeId struct { - logger log.Logger + context *Context } func (s showNodeId) run(cmd *cobra.Command, args []string) error { - cfg, err := tcmd.ParseConfig() - if err != nil { - return err - } + cfg := s.context.Config nodeKey, err := p2p.LoadOrGenNodeKey(cfg.NodeKeyFile()) if err != nil { return err diff --git a/server/show_validator.go b/server/show_validator.go index d2c7705d6..9f0cd9419 100644 --- a/server/show_validator.go +++ b/server/show_validator.go @@ -6,14 +6,12 @@ import ( "github.com/spf13/cobra" "github.com/tendermint/go-wire/data" - tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tmlibs/log" ) // ShowValidator - ported from Tendermint, show this node's validator info -func ShowValidatorCmd(logger log.Logger) *cobra.Command { - cmd := showValidator{logger} +func ShowValidatorCmd(ctx *Context) *cobra.Command { + cmd := showValidator{ctx} return &cobra.Command{ Use: "show_validator", Short: "Show this node's validator info", @@ -22,14 +20,11 @@ func ShowValidatorCmd(logger log.Logger) *cobra.Command { } type showValidator struct { - logger log.Logger + context *Context } func (s showValidator) run(cmd *cobra.Command, args []string) error { - cfg, err := tcmd.ParseConfig() - if err != nil { - return err - } + cfg := s.context.Config privValidator := types.LoadOrGenPrivValidatorFS(cfg.PrivValidatorFile()) pubKeyJSONBytes, err := data.ToJSON(privValidator.PubKey) if err != nil { diff --git a/server/start.go b/server/start.go index c8d9fc4d1..574e1584e 100644 --- a/server/start.go +++ b/server/start.go @@ -27,10 +27,10 @@ type appCreator func(string, log.Logger) (abci.Application, error) // StartCmd runs the service passed in, either // stand-alone, or in-process with tendermint -func StartCmd(app appCreator, logger log.Logger) *cobra.Command { +func StartCmd(app appCreator, ctx *Context) *cobra.Command { start := startCmd{ appCreator: app, - logger: logger, + context: ctx, } cmd := &cobra.Command{ Use: "start", @@ -49,15 +49,15 @@ func StartCmd(app appCreator, logger log.Logger) *cobra.Command { type startCmd struct { appCreator appCreator - logger log.Logger + context *Context } func (s startCmd) run(cmd *cobra.Command, args []string) error { if !viper.GetBool(flagWithTendermint) { - s.logger.Info("Starting ABCI without Tendermint") + s.context.Logger.Info("Starting ABCI without Tendermint") return s.startStandAlone() } - s.logger.Info("Starting ABCI with Tendermint") + s.context.Logger.Info("Starting ABCI with Tendermint") return s.startInProcess() } @@ -65,7 +65,7 @@ func (s startCmd) startStandAlone() error { // Generate the app in the proper dir addr := viper.GetString(flagAddress) home := viper.GetString("home") - app, err := s.appCreator(home, s.logger) + app, err := s.appCreator(home, s.context.Logger) if err != nil { return err } @@ -74,7 +74,7 @@ func (s startCmd) startStandAlone() error { if err != nil { return errors.Errorf("Error creating listener: %v\n", err) } - svr.SetLogger(s.logger.With("module", "abci-server")) + svr.SetLogger(s.context.Logger.With("module", "abci-server")) svr.Start() // Wait forever @@ -86,13 +86,9 @@ func (s startCmd) startStandAlone() error { } func (s startCmd) startInProcess() error { - cfg, err := tcmd.ParseConfig() - if err != nil { - return err - } - + cfg := s.context.Config home := cfg.RootDir - app, err := s.appCreator(home, s.logger) + app, err := s.appCreator(home, s.context.Logger) if err != nil { return err } @@ -103,7 +99,7 @@ func (s startCmd) startInProcess() error { proxy.NewLocalClientCreator(app), node.DefaultGenesisDocProviderFunc(cfg), node.DefaultDBProvider, - s.logger.With("module", "node")) + s.context.Logger.With("module", "node")) if err != nil { return err } diff --git a/server/start_test.go b/server/start_test.go index b2716da24..40f7a0aab 100644 --- a/server/start_test.go +++ b/server/start_test.go @@ -11,6 +11,7 @@ import ( "github.com/cosmos/cosmos-sdk/mock" "github.com/tendermint/abci/server" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tmlibs/log" ) @@ -21,7 +22,10 @@ func TestStartStandAlone(t *testing.T) { }() logger := log.NewNopLogger() - initCmd := InitCmd(mock.GenInitOptions, logger) + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + ctx := NewContext(cfg, logger) + initCmd := InitCmd(mock.GenInitOptions, ctx) err = initCmd.RunE(nil, nil) require.NoError(t, err) @@ -37,7 +41,6 @@ func TestStartStandAlone(t *testing.T) { case <-timer.C: svr.Stop() } - } func TestStartWithTendermint(t *testing.T) { diff --git a/server/test_helpers.go b/server/test_helpers.go index 103af7c33..f226ba1b1 100644 --- a/server/test_helpers.go +++ b/server/test_helpers.go @@ -12,6 +12,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/stretchr/testify/require" + tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands" "github.com/tendermint/tmlibs/cli" "github.com/tendermint/tmlibs/log" ) @@ -44,14 +45,18 @@ func setupViper(t *testing.T) func() { func StartServer(t *testing.T) chan error { defer setupViper(t)() + cfg, err := tcmd.ParseConfig() + require.Nil(t, err) + // init server - initCmd := InitCmd(mock.GenInitOptions, log.NewNopLogger()) - err := initCmd.RunE(nil, nil) + ctx := NewContext(cfg, log.NewNopLogger()) + initCmd := InitCmd(mock.GenInitOptions, ctx) + err = initCmd.RunE(nil, nil) require.NoError(t, err) // start server viper.Set(flagWithTendermint, true) - startCmd := StartCmd(mock.NewApp, log.NewNopLogger()) + startCmd := StartCmd(mock.NewApp, ctx) startCmd.Flags().Set(flagAddress, FreeTCPAddr(t)) // set to a new free address startCmd.Flags().Set("rpc.laddr", FreeTCPAddr(t)) // set to a new free address timeout := time.Duration(3) * time.Second