server

package
v3.1.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 10, 2024 License: Apache-2.0 Imports: 77 Imported by: 0

README

Server

The server package is responsible for providing the mechanisms necessary to start an ABCI CometBFT application and provides the CLI framework (based on cobra) necessary to fully bootstrap an application. The package exposes two core functions: StartCmd and ExportCmd which creates commands to start the application and export state respectively.

Preliminary

The root command of an application typically is constructed with:

  • command to start an application binary
  • three meta commands: query, tx, and a few auxiliary commands such as genesis. utilities.

It is vital that the root command of an application uses PersistentPreRun() cobra command property for executing the command, so all child commands have access to the server and client contexts. These contexts are set as their default values initially and may be modified, scoped to the command, in their respective PersistentPreRun() functions. Note that the client.Context is typically pre-populated with "default" values that may be useful for all commands to inherit and override if necessary.

Example:

var (
	initClientCtx  = client.Context{...}

	rootCmd = &cobra.Command{
		Use:   "simd",
		Short: "simulation app",
		PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
			if err := client.SetCmdClientContextHandler(initClientCtx, cmd); err != nil {
				return err
			}

			return server.InterceptConfigsPreRunHandler(cmd)
		},
	}
    // add root sub-commands ...
)

The SetCmdClientContextHandler call reads persistent flags via ReadPersistentCommandFlags which creates a client.Context and sets that on the root command's Context.

The InterceptConfigsPreRunHandler call creates a viper literal, default server.Context, and a logger and sets that on the root command's Context. The server.Context will be modified and saved to disk via the internal interceptConfigs call, which either reads or creates a CometBFT configuration based on the home path provided. In addition, interceptConfigs also reads and loads the application configuration, app.toml, and binds that to the server.Context viper literal. This is vital so the application can get access to not only the CLI flags, but also to the application configuration values provided by this file.

StartCmd

The StartCmd accepts an AppCreator function which returns an Application. The AppCreator is responsible for constructing the application based on the options provided to it via AppOptions. The AppOptions interface type defines a single method, Get() interface{}, and is implemented as a viper literal that exists in the server.Context. All the possible options an application may use and provide to the construction process are defined by the StartCmd and by the application's config file, app.toml.

The application can either be started in-process or as an external process. The former creates a CometBFT service and the latter creates a CometBFT Node.

Under the hood, StartCmd will call GetServerContextFromCmd, which provides the command access to a server.Context. This context provides access to the viper literal, the CometBFT config and logger. This allows flags to be bound the viper literal and passed to the application construction.

Example:

func newApp(logger log.Logger, db dbm.DB, traceStore io.Writer, appOpts servertypes.AppOptions) servertypes.Application {
	baseappOptions := server.DefaultBaseappOptions(appOpts)
	return simapp.NewSimApp(
		logger, db, traceStore, true,
		appOpts,
		baseappOptions...,
	)
}

Note, some of the options provided are exposed via CLI flags in the start command and some are also allowed to be set in the application's app.toml. It is recommend to use the cast package for type safety guarantees and due to the limitations of CLI flag types.

Documentation

Overview

Package server The commands from the SDK are defined with `cobra` and configured with the `viper` package.

This takes place in the `InterceptConfigsPreRunHandler` function. Since the `viper` package is used for configuration the precedence is dictated by that package. That is

1. Command line switches 2. Environment variables 3. Files from configuration values 4. Default values

The global configuration instance exposed by the `viper` package is not used by Cosmos SDK in this function. A new instance of `viper.Viper` is created and the following is performed. The environmental variable prefix is set to the current program name. Environmental variables consider the underscore to be equivalent to the `.` or `-` character. This means that an configuration value called `rpc.laddr` would be read from an environmental variable called `MYTOOL_RPC_LADDR` if the current program name is `mytool`.

Running the `InterceptConfigsPreRunHandler` also reads `app.toml` and `config.toml` from the home directory under the `config` directory. If `config.toml` or `app.toml` do not exist then those files are created and populated with default values. `InterceptConfigsPreRunHandler` takes two parameters to set/update a custom template to create custom `app.toml`. If these parameters are empty, the server then creates a default template provided by the SDK.

Index

Constants

View Source
const (
	FlagMinGasPrices       = "minimum-gas-prices"
	FlagQueryGasLimit      = "query-gas-limit"
	FlagHaltHeight         = "halt-height"
	FlagHaltTime           = "halt-time"
	FlagInterBlockCache    = "inter-block-cache"
	FlagUnsafeSkipUpgrades = "unsafe-skip-upgrades"
	FlagTrace              = "trace"
	FlagInvCheckPeriod     = "inv-check-period"

	FlagPruning             = "pruning"
	FlagPruningKeepRecent   = "pruning-keep-recent"
	FlagPruningInterval     = "pruning-interval"
	FlagIndexEvents         = "index-events"
	FlagMinRetainBlocks     = "min-retain-blocks"
	FlagIAVLCacheSize       = "iavl-cache-size"
	FlagDisableIAVLFastNode = "iavl-disable-fastnode"
	FlagShutdownGrace       = "shutdown-grace"

	FlagStateSyncSnapshotInterval   = "state-sync.snapshot-interval"
	FlagStateSyncSnapshotKeepRecent = "state-sync.snapshot-keep-recent"

	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"

	FlagMempoolMaxTxs = "mempool.max-txs"

	KeyIsTestnet             = "is-testnet"
	KeyNewChainID            = "new-chain-ID"
	KeyNewOpAddr             = "new-operator-addr"
	KeyNewValAddr            = "new-validator-addr"
	KeyUserPubKey            = "user-pub-key"
	KeyTriggerTestnetUpgrade = "trigger-testnet-upgrade"
)
View Source
const ServerContextKey = sdk.ContextKey("server.context")

ServerContextKey defines the context key used to retrieve a server.Context from a command's Context.

Variables

This section is empty.

Functions

func AddCommands

func AddCommands[T types.Application](rootCmd *cobra.Command, appCreator types.AppCreator[T], opts StartCmdOptions[T])

AddCommands add server commands

func AddCommandsWithStartCmdOptions

func AddCommandsWithStartCmdOptions[T types.Application](rootCmd *cobra.Command, appCreator types.AppCreator[T], opts StartCmdOptions[T])

AddCommandsWithStartCmdOptions adds server commands with the provided StartCmdOptions. Deprecated: Use AddCommands directly instead.

func AddTestnetCreatorCommand

func AddTestnetCreatorCommand[T types.Application](rootCmd *cobra.Command, appCreator types.AppCreator[T])

AddTestnetCreatorCommand allows chains to create a testnet from the state existing in their node's data directory.

func BootstrapStateCmd

func BootstrapStateCmd[T types.Application](appCreator types.AppCreator[T]) *cobra.Command

func CreateSDKLogger

func CreateSDKLogger(ctx *Context, out io.Writer) (log.Logger, error)

CreateSDKLogger creates a the default SDK logger. It reads the log level and format from the server context.

func DefaultBaseappOptions

func DefaultBaseappOptions(appOpts types.AppOptions) []func(*baseapp.BaseApp)

DefaultBaseappOptions returns the default baseapp options provided by the Cosmos SDK

func ExternalIP

func ExternalIP() (string, error)

ExternalIP https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go TODO there must be a better way to get external IP

func GetAppDBBackend

func GetAppDBBackend(opts types.AppOptions) dbm.BackendType

GetAppDBBackend gets the backend type to use for the application DBs.

func GetPruningOptionsFromFlags

func GetPruningOptionsFromFlags(appOpts types.AppOptions) (pruningtypes.PruningOptions, error)

GetPruningOptionsFromFlags parses command flags and returns the correct PruningOptions. If a pruning strategy is provided, that will be parsed and returned, otherwise, it is assumed custom pruning options are provided.

func GetSnapshotStore

func GetSnapshotStore(appOpts types.AppOptions) (*snapshots.Store, error)

func InPlaceTestnetCreator

func InPlaceTestnetCreator[T types.Application](testnetAppCreator types.AppCreator[T]) *cobra.Command

InPlaceTestnetCreator utilizes the provided chainID and operatorAddress as well as the local private validator key to control the network represented in the data folder. This is useful to create testnets nearly identical to your mainnet environment.

func InterceptConfigsPreRunHandler

func InterceptConfigsPreRunHandler(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig interface{}, cmtConfig *cmtcfg.Config) error

InterceptConfigsPreRunHandler is identical to InterceptConfigsAndCreateContext except it also sets the server context on the command and the server logger.

func ListenForQuitSignals

func ListenForQuitSignals(g *errgroup.Group, block bool, cancelFn context.CancelFunc, logger log.Logger)

ListenForQuitSignals listens for SIGINT and SIGTERM. When a signal is received, the cleanup function is called, indicating the caller can gracefully exit or return.

Note, the blocking behavior of this depends on the block argument. The caller must ensure the corresponding context derived from the cancelFn is used correctly.

func NewCometABCIWrapper

func NewCometABCIWrapper(app servertypes.ABCI) abci.Application

func NewRollbackCmd

func NewRollbackCmd[T types.Application](appCreator types.AppCreator[T]) *cobra.Command

NewRollbackCmd creates a command to rollback CometBFT and multistore state by one height.

func OpenDB

func OpenDB(rootDir string, backendType dbm.BackendType) (dbm.DB, error)

OpenDB opens the application database using the appropriate driver.

func QueryBlockCmd

func QueryBlockCmd() *cobra.Command

QueryBlockCmd implements the default command for a Block query.

func QueryBlockResultsCmd

func QueryBlockResultsCmd() *cobra.Command

QueryBlockResultsCmd implements the default command for a BlockResults query.

func QueryBlocksCmd

func QueryBlocksCmd() *cobra.Command

QueryBlocksCmd returns a command to search through blocks by events.

func RegisterSwaggerAPI

func RegisterSwaggerAPI(_ client.Context, rtr *mux.Router, swaggerEnabled bool) error

RegisterSwaggerAPI provides a common function which registers swagger route with API Server

func SetCmdServerContext

func SetCmdServerContext(cmd *cobra.Command, serverCtx *Context) error

SetCmdServerContext sets a command's Context value to the provided argument. If the context has not been set, set the given context as the default.

func SetupTraceWriter

func SetupTraceWriter(logger log.Logger, traceWriterFile string) (traceWriter io.WriteCloser, cleanup func(), err error)

SetupTraceWriter sets up the trace writer and returns a cleanup function.

func ShowAddressCmd

func ShowAddressCmd() *cobra.Command

ShowAddressCmd - show this node's validator address

func ShowNodeIDCmd

func ShowNodeIDCmd() *cobra.Command

ShowNodeIDCmd - ported from CometBFT, dump node ID to stdout

func ShowValidatorCmd

func ShowValidatorCmd() *cobra.Command

ShowValidatorCmd - ported from CometBFT, show this node's validator info

func StartCmd

func StartCmd[T types.Application](appCreator types.AppCreator[T]) *cobra.Command

StartCmd runs the service passed in, either stand-alone or in-process with CometBFT.

func StartCmdWithOptions

func StartCmdWithOptions[T types.Application](appCreator types.AppCreator[T], opts StartCmdOptions[T]) *cobra.Command

StartCmdWithOptions runs the service passed in, either stand-alone or in-process with CometBFT.

func StatusCommand

func StatusCommand() *cobra.Command

StatusCommand returns the command to return the status of the network.

func VersionCmd

func VersionCmd() *cobra.Command

VersionCmd prints CometBFT and ABCI version numbers.

Types

type Context

type Context struct {
	Viper  *viper.Viper
	Config *cmtcfg.Config
	Logger corelog.Logger
}

Context server context Deprecated: Do not use since we use viper to track all config

func GetServerContextFromCmd

func GetServerContextFromCmd(cmd *cobra.Command) *Context

GetServerContextFromCmd returns a Context from a command or an empty Context if it has not been set.

func InterceptConfigsAndCreateContext

func InterceptConfigsAndCreateContext(cmd *cobra.Command, customAppConfigTemplate string, customAppConfig interface{}, cmtConfig *cmtcfg.Config) (*Context, error)

InterceptConfigsAndCreateContext performs a pre-run function for the root daemon application command. It will create a Viper literal and a default server Context. The server CometBFT configuration will either be read and parsed or created and saved to disk, where the server Context is updated to reflect the CometBFT configuration. It takes custom app config template and config settings to create a custom CometBFT configuration. If the custom template is empty, it uses default-template provided by the server. The Viper literal is used to read and parse the application configuration. Command handlers can fetch the server Context to get the CometBFT configuration or to get access to Viper.

func NewContext

func NewContext(v *viper.Viper, config *cmtcfg.Config, logger log.Logger) *Context

func NewDefaultContext

func NewDefaultContext() *Context

type StartCmdOptions

type StartCmdOptions[T types.Application] struct {
	// DBOpener can be used to customize db opening, for example customize db options or support different db backends,
	// default to the builtin db opener.
	DBOpener func(rootDir string, backendType dbm.BackendType) (dbm.DB, error)
	// PostSetup can be used to setup extra services under the same cancellable context,
	// it's not called in stand-alone mode, only for in-process mode.
	PostSetup func(app T, svrCtx *Context, clientCtx client.Context, ctx context.Context, g *errgroup.Group) error
	// PostSetupStandalone can be used to setup extra services under the same cancellable context,
	PostSetupStandalone func(app T, svrCtx *Context, clientCtx client.Context, ctx context.Context, g *errgroup.Group) error
	// AddFlags add custom flags to start cmd
	AddFlags func(cmd *cobra.Command)
	// StartCommandHanlder can be used to customize the start command handler
	StartCommandHandler func(svrCtx *Context, clientCtx client.Context, appCreator types.AppCreator[T], inProcessConsensus bool, opts StartCmdOptions[T]) error
}

StartCmdOptions defines options that can be customized in `StartCmdWithOptions`,

Directories

Path Synopsis
gogoreflection
Package gogoreflection implements gRPC reflection for gogoproto consumers the normal reflection library does not work as it points to a different singleton registry.
Package gogoreflection implements gRPC reflection for gogoproto consumers the normal reflection library does not work as it points to a different singleton registry.
reflection/v2alpha1
Package v2alpha1 is a reverse proxy.
Package v2alpha1 is a reverse proxy.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL