cosmos-sdk/server/start.go

460 lines
15 KiB
Go
Raw Normal View History

package server
// DONTCOVER
import (
"fmt"
"net"
"net/http"
"os"
"runtime/pprof"
"time"
"github.com/spf13/cobra"
abciclient "github.com/tendermint/tendermint/abci/client"
"github.com/tendermint/tendermint/abci/server"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
tmos "github.com/tendermint/tendermint/libs/os"
tmservice "github.com/tendermint/tendermint/libs/service"
"github.com/tendermint/tendermint/node"
2020-06-15 10:39:09 -07:00
"github.com/tendermint/tendermint/rpc/client/local"
tmtypes "github.com/tendermint/tendermint/types"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
2020-06-15 10:39:09 -07:00
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/codec"
2020-06-15 10:39:09 -07:00
"github.com/cosmos/cosmos-sdk/server/api"
"github.com/cosmos/cosmos-sdk/server/config"
servergrpc "github.com/cosmos/cosmos-sdk/server/grpc"
"github.com/cosmos/cosmos-sdk/server/rosetta"
crgserver "github.com/cosmos/cosmos-sdk/server/rosetta/lib/server"
"github.com/cosmos/cosmos-sdk/server/types"
2020-06-22 13:31:33 -07:00
storetypes "github.com/cosmos/cosmos-sdk/store/types"
)
const (
// Tendermint full-node start flags
2020-06-22 13:31:33 -07:00
flagWithTendermint = "with-tendermint"
flagAddress = "address"
flagTransport = "transport"
2020-06-22 13:31:33 -07:00
flagTraceStore = "trace-store"
flagCPUProfile = "cpu-profile"
FlagMinGasPrices = "minimum-gas-prices"
FlagHaltHeight = "halt-height"
FlagHaltTime = "halt-time"
FlagInterBlockCache = "inter-block-cache"
FlagUnsafeSkipUpgrades = "unsafe-skip-upgrades"
FlagTrace = "trace"
FlagInvCheckPeriod = "inv-check-period"
2020-06-22 13:31:33 -07:00
FlagPruning = "pruning"
FlagPruningKeepRecent = "pruning-keep-recent"
FlagPruningInterval = "pruning-interval"
2020-08-20 09:19:16 -07:00
FlagIndexEvents = "index-events"
FlagMinRetainBlocks = "min-retain-blocks"
// state sync-related flags
FlagStateSyncSnapshotInterval = "state-sync.snapshot-interval"
FlagStateSyncSnapshotKeepRecent = "state-sync.snapshot-keep-recent"
feat: api server flags to start command (#11511) ## Description This PR will add api server flags to start command so we can enable api directly from command instead of modifying app.toml. --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2022-04-01 00:40:48 -07:00
// api-related flags
FlagAPIEnable = "api.enable"
FlagAPISwagger = "api.swagger"
FlagAPIAddress = "api.address"
FlagAPIMaxOpenConnections = "api.max-open-connections"
FlagRPCReadTimeout = "api.rpc-read-timeout"
FlagRPCWriteTimeout = "api.rpc-write-timeout"
FlagRPCMaxBodyBytes = "api.rpc-max-body-bytes"
FlagAPIEnableUnsafeCORS = "api.enabled-unsafe-cors"
// gRPC-related flags
flagGRPCOnly = "grpc-only"
flagGRPCEnable = "grpc.enable"
flagGRPCAddress = "grpc.address"
flagGRPCWebEnable = "grpc-web.enable"
flagGRPCWebAddress = "grpc-web.address"
)
// StartCmd runs the service passed in, either stand-alone or in-process with
// Tendermint.
func StartCmd(appCreator types.AppCreator, defaultNodeHome string) *cobra.Command {
cmd := &cobra.Command{
Use: "start",
Short: "Run the full node",
Long: `Run the full node application with Tendermint in or out of process. By
default, the application will run with Tendermint in process.
Pruning options can be provided via the '--pruning' flag or alternatively with '--pruning-keep-recent'
and 'pruning-interval' together.
2020-02-27 07:05:10 -08:00
For '--pruning' the options are as follows:
default: the last 362880 states are kept, pruning at 10 block intervals
nothing: all historic states will be saved, nothing will be deleted (i.e. archiving node)
2022-02-23 12:32:47 -08:00
everything: all saved states will be deleted, storing only the current and previous state; pruning at 10 block intervals
custom: allow pruning options to be manually specified through 'pruning-keep-recent' and 'pruning-interval'
Node halting configurations exist in the form of two flags: '--halt-height' and '--halt-time'. During
the ABCI Commit phase, the node will check if the current block height is greater than or equal to
the halt-height or if the current block time is greater than or equal to the halt-time. If so, the
node will attempt to gracefully shutdown and the block will not be committed. In addition, the node
will not be able to commit subsequent blocks.
For profiling and benchmarking purposes, CPU profiling can be enabled via the '--cpu-profile' flag
which accepts a path for the resulting pprof file.
The node may be started in a 'query only' mode where only the gRPC and JSON HTTP
API services are enabled via the 'grpc-only' flag. In this mode, Tendermint is
bypassed and can be used when legacy queries are needed after an on-chain upgrade
is performed. Note, when enabled, gRPC will also be automatically enabled.
`,
PreRunE: func(cmd *cobra.Command, _ []string) error {
serverCtx := GetServerContextFromCmd(cmd)
// Bind flags to the Context's Viper so the app construction can set
// options accordingly.
serverCtx.Viper.BindPFlags(cmd.Flags())
_, err := GetPruningOptionsFromFlags(serverCtx.Viper)
return err
},
RunE: func(cmd *cobra.Command, _ []string) error {
serverCtx := GetServerContextFromCmd(cmd)
clientCtx, err := client.GetClientQueryContext(cmd)
if err != nil {
return err
}
withTM, _ := cmd.Flags().GetBool(flagWithTendermint)
if !withTM {
serverCtx.Logger.Info("starting ABCI without Tendermint")
return startStandAlone(serverCtx, appCreator)
2018-04-21 19:26:46 -07:00
}
// amino is needed here for backwards compatibility of REST routes
err = startInProcess(serverCtx, clientCtx, appCreator)
errCode, ok := err.(ErrorCode)
if !ok {
return err
}
serverCtx.Logger.Debug(fmt.Sprintf("received quit signal: %d", errCode.Code))
return nil
2018-04-21 19:26:46 -07:00
},
}
2018-04-21 19:26:46 -07:00
cmd.Flags().String(flags.FlagHome, defaultNodeHome, "The application home directory")
cmd.Flags().Bool(flagWithTendermint, true, "Run abci app embedded in-process with tendermint")
cmd.Flags().String(flagAddress, "tcp://0.0.0.0:26658", "Listen address")
cmd.Flags().String(flagTransport, "socket", "Transport protocol: socket, grpc")
cmd.Flags().String(flagTraceStore, "", "Enable KVStore tracing to an output file")
cmd.Flags().String(FlagMinGasPrices, "", "Minimum gas prices to accept for transactions; Any fee in a tx must meet this minimum (e.g. 0.01photino;0.0001stake)")
cmd.Flags().IntSlice(FlagUnsafeSkipUpgrades, []int{}, "Skip a set of upgrade heights to continue the old binary")
cmd.Flags().Uint64(FlagHaltHeight, 0, "Block height at which to gracefully halt the chain and shutdown the node")
cmd.Flags().Uint64(FlagHaltTime, 0, "Minimum block time (in Unix seconds) at which to gracefully halt the chain and shutdown the node")
cmd.Flags().Bool(FlagInterBlockCache, true, "Enable inter-block caching")
cmd.Flags().String(flagCPUProfile, "", "Enable CPU profiling and write to the provided file")
cmd.Flags().Bool(FlagTrace, false, "Provide full stack traces for errors in ABCI Log")
2020-06-22 13:31:33 -07:00
cmd.Flags().String(FlagPruning, storetypes.PruningOptionDefault, "Pruning strategy (default|nothing|everything|custom)")
cmd.Flags().Uint64(FlagPruningKeepRecent, 0, "Number of recent heights to keep on disk (ignored if pruning is not 'custom')")
cmd.Flags().Uint64(FlagPruningInterval, 0, "Height interval at which pruned heights are removed from disk (ignored if pruning is not 'custom')")
cmd.Flags().Uint(FlagInvCheckPeriod, 0, "Assert registered invariants every N blocks")
cmd.Flags().Uint64(FlagMinRetainBlocks, 0, "Minimum block height offset during ABCI commit to prune Tendermint blocks")
feat: api server flags to start command (#11511) ## Description This PR will add api server flags to start command so we can enable api directly from command instead of modifying app.toml. --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [x] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [x] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [x] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2022-04-01 00:40:48 -07:00
cmd.Flags().Bool(FlagAPIEnable, false, "Define if the API server should be enabled")
cmd.Flags().Bool(FlagAPISwagger, false, "Define if swagger documentation should automatically be registered (Note: api must also be enabled.)")
cmd.Flags().String(FlagAPIAddress, config.DefaultAPIAddress, "the API server address to listen on")
cmd.Flags().Uint(FlagAPIMaxOpenConnections, 1000, "Define the number of maximum open connections")
cmd.Flags().Uint(FlagRPCReadTimeout, 10, "Define the Tendermint RPC read timeout (in seconds)")
cmd.Flags().Uint(FlagRPCWriteTimeout, 0, "Define the Tendermint RPC write timeout (in seconds)")
cmd.Flags().Uint(FlagRPCMaxBodyBytes, 1000000, "Define the Tendermint maximum response body (in bytes)")
cmd.Flags().Bool(FlagAPIEnableUnsafeCORS, false, "Define if CORS should be enabled (unsafe - use it at your own risk)")
cmd.Flags().Bool(flagGRPCOnly, false, "Start the node in gRPC query only mode (no Tendermint process is started)")
cmd.Flags().Bool(flagGRPCEnable, true, "Define if the gRPC server should be enabled")
cmd.Flags().String(flagGRPCAddress, config.DefaultGRPCAddress, "the gRPC server address to listen on")
cmd.Flags().Bool(flagGRPCWebEnable, true, "Define if the gRPC-Web server should be enabled. (Note: gRPC must also be enabled.)")
cmd.Flags().String(flagGRPCWebAddress, config.DefaultGRPCWebAddress, "The gRPC-Web server address to listen on")
cmd.Flags().Uint64(FlagStateSyncSnapshotInterval, 0, "State sync snapshot interval")
cmd.Flags().Uint32(FlagStateSyncSnapshotKeepRecent, 2, "State sync snapshot to keep")
// add support for all Tendermint-specific command line options
tcmd.AddNodeFlags(cmd)
return cmd
}
func startStandAlone(ctx *Context, appCreator types.AppCreator) error {
addr := ctx.Viper.GetString(flagAddress)
transport := ctx.Viper.GetString(flagTransport)
home := ctx.Viper.GetString(flags.FlagHome)
feat(types): Deprecate the DBBackend variable in favor of new app-db-backend config entry (#11188) * [10948]: Add changelog entry. * [10948]: Deprecate the types.DBBackend variable and the NewLevelDB function. Create a NewDB function to replace them. * [10948]: Add a DBBackend string to the simulation config and a flag for setting it. Update the simulation setup to use that instead of the compile-time DBBackend variable. * [10948]: Update the mock app creator to use the NewDB function. Not sure what to do about the db backend in that case though. * [10948]: Update changelog to reflect new db-backend field name. * [10948]: Use the tendermint db-backend type for the snapshot db. * [10948]: Update the last use of NewLevelDB by adding a parameter to openDB and uppdating calls to that to provide the db type to use. * [10948]: Upddate the NewDB function to also have a default db backend type if an empty string is provided there. * [10948]: Remove the new TODO in mock.NewApp. After looking through it's uses, there doesn't seem to be any desire to change it, and there's no easy way to communicate it. * [10948]: Enhance the NewDB defer function to also add info to any err that is being returned. * [10948]: Add some unit tests for NewDB. * [10948]: Lint fixes. * [10948]: Add a changelog entry to the deprecated section. * [10948]: Update the makefile to no longer set the types.DBBackend value. * [10948]: Use memdb for the mock app instead of goleveldb. I know it was a goleveldb before, but for a mock app, a memdb feels like a better choice (assuming 'mock' and 'mem' mean what I assume they mean). * [10948]: Fix the store benchmark tests (had some index-out-of-range issues). * [10948]: Fix cachekv store bench test calling iter.Key() before checking iter.Valid(). * [10948]: Remove the panic recovery from types.NewDB since dbm.NewDB returns an error now (it didn't originally, when NewLevelDB was first written). * [10948]: Add changlog entry indicationg an API breaking change due to the DBBackend change. * [10948]: Get rid of the types.NewDB function in favor of just using the tm-db version of it. * [10948]: Fix Update the codeql-analysis github action to use go v1.17. * [10948]: Add config file option for the app db backend type. * [10948]: Adjust the comment on the app-db-backend config entry to clarify fallback behavior. * [10948]: Add a default of GoLevelDBBackend to GetAppDBBackend. The old DBBackend variable defaulted to that, and some unit tests assume that behavior still exists. * [10948]: Add the missing quotes around the app-db-backend value. * [10948]: Small tweak to the changelog's deprecated entry. * Add the go version declaration back into the codeql-analysis github action. * [10948]: Update new use of openDB. * [10948]: Put a brief delay after closing the test network. Hopefully that helps with address-in-use and non-empty directory errors. Co-authored-by: Marko <marbar3778@yahoo.com>
2022-03-18 02:26:20 -07:00
db, err := openDB(home, GetAppDBBackend(ctx.Viper))
2018-02-21 09:56:04 -08:00
if err != nil {
return err
}
traceWriterFile := ctx.Viper.GetString(flagTraceStore)
traceWriter, err := openTraceWriter(traceWriterFile)
if err != nil {
return err
}
app := appCreator(ctx.Logger, db, traceWriter, ctx.Viper)
2018-02-21 09:56:04 -08:00
svr, err := server.NewServer(addr, transport, app)
if err != nil {
return fmt.Errorf("error creating listener: %v", err)
}
2018-04-21 19:26:46 -07:00
svr.SetLogger(ctx.Logger.With("module", "abci-server"))
err = svr.Start()
if err != nil {
tmos.Exit(err.Error())
}
defer func() {
if err = svr.Stop(); err != nil {
tmos.Exit(err.Error())
}
}()
// Wait for SIGINT or SIGTERM signal
return WaitForQuitSignals()
}
func startInProcess(ctx *Context, clientCtx client.Context, appCreator types.AppCreator) error {
2018-04-21 19:26:46 -07:00
cfg := ctx.Config
2018-02-21 09:56:04 -08:00
home := cfg.RootDir
var cpuProfileCleanup func()
if cpuProfile := ctx.Viper.GetString(flagCPUProfile); cpuProfile != "" {
f, err := os.Create(cpuProfile)
if err != nil {
return err
}
ctx.Logger.Info("starting CPU profiler", "profile", cpuProfile)
if err := pprof.StartCPUProfile(f); err != nil {
return err
}
cpuProfileCleanup = func() {
ctx.Logger.Info("stopping CPU profiler", "profile", cpuProfile)
pprof.StopCPUProfile()
f.Close()
}
}
feat(types): Deprecate the DBBackend variable in favor of new app-db-backend config entry (#11188) * [10948]: Add changelog entry. * [10948]: Deprecate the types.DBBackend variable and the NewLevelDB function. Create a NewDB function to replace them. * [10948]: Add a DBBackend string to the simulation config and a flag for setting it. Update the simulation setup to use that instead of the compile-time DBBackend variable. * [10948]: Update the mock app creator to use the NewDB function. Not sure what to do about the db backend in that case though. * [10948]: Update changelog to reflect new db-backend field name. * [10948]: Use the tendermint db-backend type for the snapshot db. * [10948]: Update the last use of NewLevelDB by adding a parameter to openDB and uppdating calls to that to provide the db type to use. * [10948]: Upddate the NewDB function to also have a default db backend type if an empty string is provided there. * [10948]: Remove the new TODO in mock.NewApp. After looking through it's uses, there doesn't seem to be any desire to change it, and there's no easy way to communicate it. * [10948]: Enhance the NewDB defer function to also add info to any err that is being returned. * [10948]: Add some unit tests for NewDB. * [10948]: Lint fixes. * [10948]: Add a changelog entry to the deprecated section. * [10948]: Update the makefile to no longer set the types.DBBackend value. * [10948]: Use memdb for the mock app instead of goleveldb. I know it was a goleveldb before, but for a mock app, a memdb feels like a better choice (assuming 'mock' and 'mem' mean what I assume they mean). * [10948]: Fix the store benchmark tests (had some index-out-of-range issues). * [10948]: Fix cachekv store bench test calling iter.Key() before checking iter.Valid(). * [10948]: Remove the panic recovery from types.NewDB since dbm.NewDB returns an error now (it didn't originally, when NewLevelDB was first written). * [10948]: Add changlog entry indicationg an API breaking change due to the DBBackend change. * [10948]: Get rid of the types.NewDB function in favor of just using the tm-db version of it. * [10948]: Fix Update the codeql-analysis github action to use go v1.17. * [10948]: Add config file option for the app db backend type. * [10948]: Adjust the comment on the app-db-backend config entry to clarify fallback behavior. * [10948]: Add a default of GoLevelDBBackend to GetAppDBBackend. The old DBBackend variable defaulted to that, and some unit tests assume that behavior still exists. * [10948]: Add the missing quotes around the app-db-backend value. * [10948]: Small tweak to the changelog's deprecated entry. * Add the go version declaration back into the codeql-analysis github action. * [10948]: Update new use of openDB. * [10948]: Put a brief delay after closing the test network. Hopefully that helps with address-in-use and non-empty directory errors. Co-authored-by: Marko <marbar3778@yahoo.com>
2022-03-18 02:26:20 -07:00
db, err := openDB(home, GetAppDBBackend(ctx.Viper))
2018-02-21 09:56:04 -08:00
if err != nil {
return err
2018-02-21 09:56:04 -08:00
}
feat(types): Deprecate the DBBackend variable in favor of new app-db-backend config entry (#11188) * [10948]: Add changelog entry. * [10948]: Deprecate the types.DBBackend variable and the NewLevelDB function. Create a NewDB function to replace them. * [10948]: Add a DBBackend string to the simulation config and a flag for setting it. Update the simulation setup to use that instead of the compile-time DBBackend variable. * [10948]: Update the mock app creator to use the NewDB function. Not sure what to do about the db backend in that case though. * [10948]: Update changelog to reflect new db-backend field name. * [10948]: Use the tendermint db-backend type for the snapshot db. * [10948]: Update the last use of NewLevelDB by adding a parameter to openDB and uppdating calls to that to provide the db type to use. * [10948]: Upddate the NewDB function to also have a default db backend type if an empty string is provided there. * [10948]: Remove the new TODO in mock.NewApp. After looking through it's uses, there doesn't seem to be any desire to change it, and there's no easy way to communicate it. * [10948]: Enhance the NewDB defer function to also add info to any err that is being returned. * [10948]: Add some unit tests for NewDB. * [10948]: Lint fixes. * [10948]: Add a changelog entry to the deprecated section. * [10948]: Update the makefile to no longer set the types.DBBackend value. * [10948]: Use memdb for the mock app instead of goleveldb. I know it was a goleveldb before, but for a mock app, a memdb feels like a better choice (assuming 'mock' and 'mem' mean what I assume they mean). * [10948]: Fix the store benchmark tests (had some index-out-of-range issues). * [10948]: Fix cachekv store bench test calling iter.Key() before checking iter.Valid(). * [10948]: Remove the panic recovery from types.NewDB since dbm.NewDB returns an error now (it didn't originally, when NewLevelDB was first written). * [10948]: Add changlog entry indicationg an API breaking change due to the DBBackend change. * [10948]: Get rid of the types.NewDB function in favor of just using the tm-db version of it. * [10948]: Fix Update the codeql-analysis github action to use go v1.17. * [10948]: Add config file option for the app db backend type. * [10948]: Adjust the comment on the app-db-backend config entry to clarify fallback behavior. * [10948]: Add a default of GoLevelDBBackend to GetAppDBBackend. The old DBBackend variable defaulted to that, and some unit tests assume that behavior still exists. * [10948]: Add the missing quotes around the app-db-backend value. * [10948]: Small tweak to the changelog's deprecated entry. * Add the go version declaration back into the codeql-analysis github action. * [10948]: Update new use of openDB. * [10948]: Put a brief delay after closing the test network. Hopefully that helps with address-in-use and non-empty directory errors. Co-authored-by: Marko <marbar3778@yahoo.com>
2022-03-18 02:26:20 -07:00
traceWriterFile := ctx.Viper.GetString(flagTraceStore)
traceWriter, err := openTraceWriter(traceWriterFile)
if err != nil {
return err
}
feat: Non-zero Default Fees (#9371) <!-- < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < ☺ v ✰ Thanks for creating a PR! ✰ v Before smashing the submit button please review the checkboxes. v If a checkbox is n/a - please still include it but + a little note why ☺ > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > > --> ## Description <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> closes: #9106 --- Before we can merge this PR, please make sure that all the following items have been checked off. If any of the checklist items are not applicable, please leave them but write a little note why. - [x] Targeted PR against correct branch (see [CONTRIBUTING.md](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] Linked to Github issue with discussion and accepted design OR link to spec that describes this work. - [ ] Code follows the [module structure standards](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules/structure.md). - [ ] Wrote unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] Updated relevant documentation (`docs/`) or specification (`x/<module>/spec/`) - [ ] Added relevant `godoc` [comments](https://blog.golang.org/godoc-documenting-go-code). - [ ] Added a relevant changelog entry to the `Unreleased` section in `CHANGELOG.md` - [ ] Re-reviewed `Files changed` in the Github PR explorer - [ ] Review `Codecov Report` in the comment section below once CI passes
2021-06-25 03:41:32 -07:00
config := config.GetConfig(ctx.Viper)
if err := config.ValidateBasic(); err != nil {
return err
}
app := appCreator(ctx.Logger, db, traceWriter, ctx.Viper)
2018-02-21 09:56:04 -08:00
genDoc, err := tmtypes.GenesisDocFromFile(cfg.GenesisFile())
if err != nil {
return err
}
var (
tmNode tmservice.Service
gRPCOnly = ctx.Viper.GetBool(flagGRPCOnly)
)
if gRPCOnly {
ctx.Logger.Info("starting node in gRPC only mode; Tendermint is disabled")
config.GRPC.Enable = true
} else {
ctx.Logger.Info("starting node with ABCI Tendermint in-process")
tmNode, err = node.New(cfg, ctx.Logger, abciclient.NewLocalCreator(app), genDoc)
if err != nil {
return err
}
if err := tmNode.Start(); err != nil {
return err
}
}
// Add the tx service to the gRPC router. We only need to register this
// service if API or gRPC is enabled, and avoid doing so in the general
// case, because it spawns a new local tendermint RPC client.
if (config.API.Enable || config.GRPC.Enable) && tmNode != nil {
node, ok := tmNode.(local.NodeService)
if !ok {
return fmt.Errorf("unable to set node type; please try re-installing the binary")
}
localNode, err := local.New(node)
if err != nil {
return err
}
clientCtx = clientCtx.WithClient(localNode)
app.RegisterTxService(clientCtx)
app.RegisterTendermintService(clientCtx)
}
var apiSrv *api.Server
if config.API.Enable {
genDoc, err := tmtypes.GenesisDocFromFile(cfg.GenesisFile())
2020-06-15 10:39:09 -07:00
if err != nil {
return err
}
clientCtx := clientCtx.WithHomeDir(home).WithChainID(genDoc.ChainID)
2020-06-15 10:39:09 -07:00
if config.GRPC.Enable {
_, port, err := net.SplitHostPort(config.GRPC.Address)
if err != nil {
return err
}
grpcAddress := fmt.Sprintf("127.0.0.1:%s", port)
// If grpc is enabled, configure grpc client for grpc gateway.
grpcClient, err := grpc.Dial(
grpcAddress,
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithDefaultCallOptions(grpc.ForceCodec(codec.NewProtoCodec(clientCtx.InterfaceRegistry).GRPCCodec())),
)
if err != nil {
return err
}
clientCtx = clientCtx.WithGRPCClient(grpcClient)
ctx.Logger.Debug("grpc client assigned to client context", "target", grpcAddress)
}
apiSrv = api.New(clientCtx, ctx.Logger.With("module", "api-server"))
app.RegisterAPIRoutes(apiSrv, config.API)
errCh := make(chan error)
go func() {
if err := apiSrv.Start(config); err != nil {
errCh <- err
}
}()
select {
case err := <-errCh:
2020-06-15 10:39:09 -07:00
return err
fix: start GRPCWebServer in goroutine (#9704) so it don't block other code from executing. Closes #9703 <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-07-18 18:20:55 -07:00
case <-time.After(types.ServerStartTime): // assume server started successfully
2020-06-15 10:39:09 -07:00
}
}
var (
grpcSrv *grpc.Server
grpcWebSrv *http.Server
)
if config.GRPC.Enable {
grpcSrv, err = servergrpc.StartGRPCServer(clientCtx, app, config.GRPC.Address)
if err != nil {
return err
}
if config.GRPCWeb.Enable {
grpcWebSrv, err = servergrpc.StartGRPCWeb(grpcSrv, config)
if err != nil {
ctx.Logger.Error("failed to start grpc-web http server: ", err)
return err
}
}
}
// At this point it is safe to block the process if we're in gRPC only mode as
// we do not need to start Rosetta or handle any Tendermint related processes.
if gRPCOnly {
// wait for signal capture and gracefully return
return WaitForQuitSignals()
}
var rosettaSrv crgserver.Server
if config.Rosetta.Enable {
offlineMode := config.Rosetta.Offline
// If GRPC is not enabled rosetta cannot work in online mode, so it works in
// offline mode.
if !config.GRPC.Enable {
offlineMode = true
}
conf := &rosetta.Config{
Blockchain: config.Rosetta.Blockchain,
Network: config.Rosetta.Network,
TendermintRPC: ctx.Config.RPC.ListenAddress,
GRPCEndpoint: config.GRPC.Address,
Addr: config.Rosetta.Address,
Retries: config.Rosetta.Retries,
Offline: offlineMode,
Codec: clientCtx.Codec.(*codec.ProtoCodec),
InterfaceRegistry: clientCtx.InterfaceRegistry,
}
rosettaSrv, err = rosetta.ServerFromConfig(conf)
if err != nil {
return err
}
errCh := make(chan error)
go func() {
if err := rosettaSrv.Start(); err != nil {
errCh <- err
}
}()
select {
case err := <-errCh:
return err
fix: start GRPCWebServer in goroutine (#9704) so it don't block other code from executing. Closes #9703 <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-07-18 18:20:55 -07:00
case <-time.After(types.ServerStartTime): // assume server started successfully
}
}
defer func() {
if tmNode.IsRunning() {
_ = tmNode.Stop()
}
if cpuProfileCleanup != nil {
cpuProfileCleanup()
}
if apiSrv != nil {
_ = apiSrv.Close()
}
if grpcSrv != nil {
grpcSrv.Stop()
if grpcWebSrv != nil {
grpcWebSrv.Close()
}
}
ctx.Logger.Info("exiting...")
}()
// wait for signal capture and gracefully return
return WaitForQuitSignals()
}