Add Goland Standard "cmd" Pattern for Beacon-Chain Binaries (#8540)

* beacon chain cmd pattern

* imports spacing

* more import fix

* edit build file

* e2e viz

* amend e2e
This commit is contained in:
Raul Jordan
2021-03-02 13:36:03 -06:00
committed by GitHub
parent cdea2debc9
commit 090fbbf18c
50 changed files with 218 additions and 182 deletions

View File

@@ -0,0 +1,148 @@
load("@prysm//tools/go:def.bzl", "go_library")
load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_test")
load("@io_bazel_rules_docker//go:image.bzl", "go_image")
load("@io_bazel_rules_docker//container:container.bzl", "container_bundle", "container_image")
load("//tools:go_image.bzl", "go_image_alpine", "go_image_debug")
load("@io_bazel_rules_docker//contrib:push-all.bzl", "docker_push")
go_library(
name = "go_default_library",
srcs = [
"log.go",
"main.go",
"usage.go",
],
importpath = "github.com/prysmaticlabs/prysm/cmd/beacon-chain",
visibility = ["//beacon-chain:__subpackages__"],
deps = [
"//beacon-chain/db:go_default_library",
"//beacon-chain/node:go_default_library",
"//cmd/beacon-chain/flags:go_default_library",
"//shared/cmd:go_default_library",
"//shared/debug:go_default_library",
"//shared/featureconfig:go_default_library",
"//shared/fileutil:go_default_library",
"//shared/journald:go_default_library",
"//shared/logutil:go_default_library",
"//shared/maxprocs:go_default_library",
"//shared/tos:go_default_library",
"//shared/version:go_default_library",
"@com_github_ethereum_go_ethereum//log:go_default_library",
"@com_github_ipfs_go_log_v2//:go_default_library",
"@com_github_joonix_log//:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
"@com_github_x_cray_logrus_prefixed_formatter//:go_default_library",
],
)
go_image(
name = "image",
base = select({
"//tools:base_image_alpine": "//tools:alpine_cc_image",
"//tools:base_image_cc": "//tools:cc_image",
"//conditions:default": "//tools:cc_image",
}),
binary = ":beacon-chain",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
container_image(
name = "image_with_creation_time",
base = "image",
stamp = True,
visibility = ["//beacon-chain:__pkg__"],
)
container_bundle(
name = "image_bundle",
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest": ":image_with_creation_time",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}": ":image_with_creation_time",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest": ":image_with_creation_time",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}": ":image_with_creation_time",
},
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
go_image_debug(
name = "image_debug",
image = ":image",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
container_bundle(
name = "image_bundle_debug",
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest-debug": ":image_debug",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}-debug": ":image_debug",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest-debug": ":image_debug",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}-debug": ":image_debug",
},
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
go_image_alpine(
name = "image_alpine",
image = ":image",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
container_bundle(
name = "image_bundle_alpine",
images = {
"gcr.io/prysmaticlabs/prysm/beacon-chain:latest-alpine": ":image_alpine",
"gcr.io/prysmaticlabs/prysm/beacon-chain:{DOCKER_TAG}-alpine": ":image_alpine",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:latest-alpine": ":image_alpine",
"index.docker.io/prysmaticlabs/prysm-beacon-chain:{DOCKER_TAG}-alpine": ":image_alpine",
},
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
docker_push(
name = "push_images",
bundle = ":image_bundle",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
docker_push(
name = "push_images_debug",
bundle = ":image_bundle_debug",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
docker_push(
name = "push_images_alpine",
bundle = ":image_bundle_alpine",
tags = ["manual"],
visibility = ["//beacon-chain:__pkg__"],
)
go_binary(
name = "beacon-chain",
embed = [":go_default_library"],
visibility = [
"//beacon-chain:__subpackages__",
"//endtoend:__pkg__",
],
)
go_test(
name = "go_default_test",
size = "small",
srcs = ["usage_test.go"],
embed = [":go_default_library"],
visibility = ["//beacon-chain:__pkg__"],
deps = [
"//shared/featureconfig:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
],
)

View File

@@ -0,0 +1,22 @@
load("@prysm//tools/go:def.bzl", "go_library")
go_library(
name = "go_default_library",
srcs = [
"base.go",
"config.go",
"interop.go",
"log.go",
],
importpath = "github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags",
visibility = [
"//beacon-chain:__subpackages__",
"//cmd/beacon-chain:__subpackages__",
],
deps = [
"//shared/cmd:go_default_library",
"//shared/params:go_default_library",
"@com_github_sirupsen_logrus//:go_default_library",
"@com_github_urfave_cli_v2//:go_default_library",
],
)

View File

@@ -0,0 +1,169 @@
// Package flags defines beacon-node specific runtime flags for
// setting important values such as ports, eth1 endpoints, and more.
package flags
import (
"github.com/prysmaticlabs/prysm/shared/params"
"github.com/urfave/cli/v2"
)
var (
// HTTPWeb3ProviderFlag provides an HTTP access endpoint to an ETH 1.0 RPC.
HTTPWeb3ProviderFlag = &cli.StringFlag{
Name: "http-web3provider",
Usage: "A mainchain web3 provider string http endpoint. This is our primary web3 provider",
}
FallbackWeb3ProviderFlag = &cli.StringSliceFlag{
Name: "fallback-web3provider",
Usage: "A mainchain web3 provider string http endpoint. This is our fallback web3 provider, this flag maybe used multiple times.",
}
// DepositContractFlag defines a flag for the deposit contract address.
DepositContractFlag = &cli.StringFlag{
Name: "deposit-contract",
Usage: "Deposit contract address. Beacon chain node will listen logs coming from the deposit contract to determine when validator is eligible to participate.",
Value: params.BeaconConfig().DepositContractAddress,
}
// RPCHost defines the host on which the RPC server should listen.
RPCHost = &cli.StringFlag{
Name: "rpc-host",
Usage: "Host on which the RPC server should listen",
Value: "127.0.0.1",
}
// RPCPort defines a beacon node RPC port to open.
RPCPort = &cli.IntFlag{
Name: "rpc-port",
Usage: "RPC port exposed by a beacon node",
Value: 4000,
}
// MonitoringPortFlag defines the http port used to serve prometheus metrics.
MonitoringPortFlag = &cli.IntFlag{
Name: "monitoring-port",
Usage: "Port used to listening and respond metrics for prometheus.",
Value: 8080,
}
// CertFlag defines a flag for the node's TLS certificate.
CertFlag = &cli.StringFlag{
Name: "tls-cert",
Usage: "Certificate for secure gRPC. Pass this and the tls-key flag in order to use gRPC securely.",
}
// KeyFlag defines a flag for the node's TLS key.
KeyFlag = &cli.StringFlag{
Name: "tls-key",
Usage: "Key for secure gRPC. Pass this and the tls-cert flag in order to use gRPC securely.",
}
// DisableGRPCGateway for JSON-HTTP requests to the beacon node.
DisableGRPCGateway = &cli.BoolFlag{
Name: "disable-grpc-gateway",
Usage: "Disable the gRPC gateway for JSON-HTTP requests",
}
// GRPCGatewayHost specifies a gRPC gateway host for Prysm.
GRPCGatewayHost = &cli.StringFlag{
Name: "grpc-gateway-host",
Usage: "The host on which the gateway server runs on",
Value: "127.0.0.1",
}
// GRPCGatewayPort enables a gRPC gateway to be exposed for Prysm.
GRPCGatewayPort = &cli.IntFlag{
Name: "grpc-gateway-port",
Usage: "Enable gRPC gateway for JSON requests",
Value: 3500,
}
// GPRCGatewayCorsDomain serves preflight requests when serving gRPC JSON gateway.
GPRCGatewayCorsDomain = &cli.StringFlag{
Name: "grpc-gateway-corsdomain",
Usage: "Comma separated list of domains from which to accept cross origin requests " +
"(browser enforced). This flag has no effect if not used with --grpc-gateway-port.",
Value: "http://localhost:4200,http://localhost:7500,http://127.0.0.1:4200,http://127.0.0.1:7500,http://0.0.0.0:4200,http://0.0.0.0:7500",
}
// MinSyncPeers specifies the required number of successful peer handshakes in order
// to start syncing with external peers.
MinSyncPeers = &cli.IntFlag{
Name: "min-sync-peers",
Usage: "The required number of valid peers to connect with before syncing.",
Value: 3,
}
// ContractDeploymentBlock is the block in which the eth1 deposit contract was deployed.
ContractDeploymentBlock = &cli.IntFlag{
Name: "contract-deployment-block",
Usage: "The eth1 block in which the deposit contract was deployed.",
Value: 11184524,
}
// SetGCPercent is the percentage of current live allocations at which the garbage collector is to run.
SetGCPercent = &cli.IntFlag{
Name: "gc-percent",
Usage: "The percentage of freshly allocated data to live data on which the gc will be run again.",
Value: 100,
}
// HeadSync starts the beacon node from the previously saved head state and syncs from there.
HeadSync = &cli.BoolFlag{
Name: "head-sync",
Usage: "Starts the beacon node with the previously saved head state instead of finalized state.",
}
// SlotsPerArchivedPoint specifies the number of slots between the archived points, to save beacon state in the cold
// section of DB.
SlotsPerArchivedPoint = &cli.IntFlag{
Name: "slots-per-archive-point",
Usage: "The slot durations of when an archived state gets saved in the DB.",
Value: 2048,
}
// DisableDiscv5 disables running discv5.
DisableDiscv5 = &cli.BoolFlag{
Name: "disable-discv5",
Usage: "Does not run the discoveryV5 dht.",
}
// BlockBatchLimit specifies the requested block batch size.
BlockBatchLimit = &cli.IntFlag{
Name: "block-batch-limit",
Usage: "The amount of blocks the local peer is bounded to request and respond to in a batch.",
Value: 64,
}
// BlockBatchLimitBurstFactor specifies the factor by which block batch size may increase.
BlockBatchLimitBurstFactor = &cli.IntFlag{
Name: "block-batch-limit-burst-factor",
Usage: "The factor by which block batch limit may increase on burst.",
Value: 10,
}
// DisableSync disables a node from syncing at start-up. Instead the node enters regular sync
// immediately.
DisableSync = &cli.BoolFlag{
Name: "disable-sync",
Usage: "Starts the beacon node without entering initial sync and instead exits to regular sync immediately.",
}
// EnableDebugRPCEndpoints as /v1/beacon/state.
EnableDebugRPCEndpoints = &cli.BoolFlag{
Name: "enable-debug-rpc-endpoints",
Usage: "Enables the debug rpc service, containing utility endpoints such as /eth/v1alpha1/beacon/state.",
}
SubscribeToAllSubnets = &cli.BoolFlag{
Name: "subscribe-all-subnets",
Usage: "Subscribe to all possible attestation subnets.",
}
// HistoricalSlasherNode is a set of beacon node flags required for performing historical detection with a slasher.
HistoricalSlasherNode = &cli.BoolFlag{
Name: "historical-slasher-node",
Usage: "Enables required flags for serving historical data to a slasher client. Results in additional storage usage",
}
// ChainID defines a flag to set the chain id. If none is set, it derives this value from NetworkConfig
ChainID = &cli.Uint64Flag{
Name: "chain-id",
Usage: "Sets the chain id of the beacon chain",
}
// NetworkID defines a flag to set the network id. If none is set, it derives this value from NetworkConfig
NetworkID = &cli.Uint64Flag{
Name: "network-id",
Usage: "Sets the network id of the beacon chain.",
}
// WeakSubjectivityCheckpt defines the weak subjectivity checkpoint the node must sync through to defend against long range attacks.
WeakSubjectivityCheckpt = &cli.StringFlag{
Name: "weak-subjectivity-checkpoint",
Usage: "Input in `block_root:epoch_number` format. This guarantee that syncing leads to the given Weak Subjectivity Checkpoint being in the canonical chain. " +
"If such a sync is not possible, the node will treat it a critical and irrecoverable failure",
Value: "",
}
// Eth1HeaderReqLimit defines a flag to set the maximum number of headers that a deposit log query can fetch. If none is set, 1000 will be the limit.
Eth1HeaderReqLimit = &cli.Uint64Flag{
Name: "eth1-header-req-limit",
Usage: "Sets the maximum number of headers that a deposit log query can fetch.",
Value: uint64(1000),
}
)

View File

@@ -0,0 +1,66 @@
package flags
import (
"github.com/prysmaticlabs/prysm/shared/cmd"
"github.com/urfave/cli/v2"
)
// GlobalFlags specifies all the global flags for the
// beacon node.
type GlobalFlags struct {
HeadSync bool
DisableSync bool
DisableDiscv5 bool
SubscribeToAllSubnets bool
MinimumSyncPeers int
BlockBatchLimit int
BlockBatchLimitBurstFactor int
}
var globalConfig *GlobalFlags
// Get retrieves the global config.
func Get() *GlobalFlags {
if globalConfig == nil {
return &GlobalFlags{}
}
return globalConfig
}
// Init sets the global config equal to the config that is passed in.
func Init(c *GlobalFlags) {
globalConfig = c
}
// ConfigureGlobalFlags initializes the global config.
// based on the provided cli context.
func ConfigureGlobalFlags(ctx *cli.Context) {
cfg := &GlobalFlags{}
if ctx.Bool(HeadSync.Name) {
log.Warn("Using Head Sync flag, it starts syncing from last saved head.")
cfg.HeadSync = true
}
if ctx.Bool(DisableSync.Name) {
log.Warn("Using Disable Sync flag, using this flag on a live network might lead to adverse consequences.")
cfg.DisableSync = true
}
if ctx.Bool(SubscribeToAllSubnets.Name) {
log.Warn("Subscribing to All Attestation Subnets")
cfg.SubscribeToAllSubnets = true
}
cfg.DisableDiscv5 = ctx.Bool(DisableDiscv5.Name)
cfg.BlockBatchLimit = ctx.Int(BlockBatchLimit.Name)
cfg.BlockBatchLimitBurstFactor = ctx.Int(BlockBatchLimitBurstFactor.Name)
configureMinimumPeers(ctx, cfg)
Init(cfg)
}
func configureMinimumPeers(ctx *cli.Context, cfg *GlobalFlags) {
cfg.MinimumSyncPeers = ctx.Int(MinSyncPeers.Name)
maxPeers := ctx.Int(cmd.P2PMaxPeers.Name)
if cfg.MinimumSyncPeers > maxPeers {
log.Warnf("Changing Minimum Sync Peers to %d", maxPeers)
cfg.MinimumSyncPeers = maxPeers
}
}

View File

@@ -0,0 +1,30 @@
package flags
import (
"github.com/urfave/cli/v2"
)
var (
// InteropGenesisStateFlag defines a flag for the beacon node to load genesis state via file.
InteropGenesisStateFlag = &cli.StringFlag{
Name: "interop-genesis-state",
Usage: "The genesis state file (.SSZ) to load from",
}
// InteropMockEth1DataVotesFlag enables mocking the eth1 proof-of-work chain data put into blocks by proposers.
InteropMockEth1DataVotesFlag = &cli.BoolFlag{
Name: "interop-eth1data-votes",
Usage: "Enable mocking of eth1 data votes for proposers to package into blocks",
}
// InteropGenesisTimeFlag specifies genesis time for state generation.
InteropGenesisTimeFlag = &cli.Uint64Flag{
Name: "interop-genesis-time",
Usage: "Specify the genesis time for interop genesis state generation. Must be used with " +
"--interop-num-validators",
}
// InteropNumValidatorsFlag specifies number of genesis validators for state generation.
InteropNumValidatorsFlag = &cli.Uint64Flag{
Name: "interop-num-validators",
Usage: "Specify number of genesis validators to generate for interop. Must be used with --interop-genesis-time",
}
)

View File

@@ -0,0 +1,5 @@
package flags
import "github.com/sirupsen/logrus"
var log = logrus.WithField("prefix", "flags")

5
cmd/beacon-chain/log.go Normal file
View File

@@ -0,0 +1,5 @@
package main
import "github.com/sirupsen/logrus"
var log = logrus.WithField("prefix", "main")

227
cmd/beacon-chain/main.go Normal file
View File

@@ -0,0 +1,227 @@
// Package beacon-chain defines the entire runtime of an eth2 beacon node.
package main
import (
"fmt"
"os"
"path/filepath"
"runtime"
runtimeDebug "runtime/debug"
gethlog "github.com/ethereum/go-ethereum/log"
golog "github.com/ipfs/go-log/v2"
joonix "github.com/joonix/log"
"github.com/prysmaticlabs/prysm/beacon-chain/db"
"github.com/prysmaticlabs/prysm/beacon-chain/node"
"github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags"
"github.com/prysmaticlabs/prysm/shared/cmd"
"github.com/prysmaticlabs/prysm/shared/debug"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/prysmaticlabs/prysm/shared/fileutil"
"github.com/prysmaticlabs/prysm/shared/journald"
"github.com/prysmaticlabs/prysm/shared/logutil"
_ "github.com/prysmaticlabs/prysm/shared/maxprocs"
"github.com/prysmaticlabs/prysm/shared/tos"
"github.com/prysmaticlabs/prysm/shared/version"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
prefixed "github.com/x-cray/logrus-prefixed-formatter"
)
var appFlags = []cli.Flag{
flags.DepositContractFlag,
flags.HTTPWeb3ProviderFlag,
flags.FallbackWeb3ProviderFlag,
flags.RPCHost,
flags.RPCPort,
flags.CertFlag,
flags.KeyFlag,
flags.DisableGRPCGateway,
flags.GRPCGatewayHost,
flags.GRPCGatewayPort,
flags.GPRCGatewayCorsDomain,
flags.MinSyncPeers,
flags.ContractDeploymentBlock,
flags.SetGCPercent,
flags.HeadSync,
flags.DisableSync,
flags.DisableDiscv5,
flags.BlockBatchLimit,
flags.BlockBatchLimitBurstFactor,
flags.InteropMockEth1DataVotesFlag,
flags.InteropGenesisStateFlag,
flags.InteropNumValidatorsFlag,
flags.InteropGenesisTimeFlag,
flags.SlotsPerArchivedPoint,
flags.EnableDebugRPCEndpoints,
flags.SubscribeToAllSubnets,
flags.HistoricalSlasherNode,
flags.ChainID,
flags.NetworkID,
flags.WeakSubjectivityCheckpt,
flags.Eth1HeaderReqLimit,
cmd.EnableBackupWebhookFlag,
cmd.BackupWebhookOutputDir,
cmd.MinimalConfigFlag,
cmd.E2EConfigFlag,
cmd.RPCMaxPageSizeFlag,
cmd.BootstrapNode,
cmd.NoDiscovery,
cmd.StaticPeers,
cmd.RelayNode,
cmd.P2PUDPPort,
cmd.P2PTCPPort,
cmd.P2PIP,
cmd.P2PHost,
cmd.P2PHostDNS,
cmd.P2PMaxPeers,
cmd.P2PPrivKey,
cmd.P2PMetadata,
cmd.P2PAllowList,
cmd.P2PDenyList,
cmd.DataDirFlag,
cmd.VerbosityFlag,
cmd.EnableTracingFlag,
cmd.TracingProcessNameFlag,
cmd.TracingEndpointFlag,
cmd.TraceSampleFractionFlag,
cmd.MonitoringHostFlag,
flags.MonitoringPortFlag,
cmd.DisableMonitoringFlag,
cmd.ClearDB,
cmd.ForceClearDB,
cmd.LogFormat,
cmd.MaxGoroutines,
debug.PProfFlag,
debug.PProfAddrFlag,
debug.PProfPortFlag,
debug.MemProfileRateFlag,
debug.CPUProfileFlag,
debug.TraceFlag,
debug.BlockProfileRateFlag,
debug.MutexProfileFractionFlag,
cmd.LogFileName,
cmd.EnableUPnPFlag,
cmd.ConfigFileFlag,
cmd.ChainConfigFileFlag,
cmd.GrpcMaxCallRecvMsgSizeFlag,
cmd.AcceptTosFlag,
cmd.RestoreSourceFileFlag,
cmd.RestoreTargetDirFlag,
cmd.BoltMMapInitialSizeFlag,
}
func init() {
appFlags = cmd.WrapFlags(append(appFlags, featureconfig.BeaconChainFlags...))
}
func main() {
app := cli.App{}
app.Name = "beacon-chain"
app.Usage = "this is a beacon chain implementation for Ethereum 2.0"
app.Action = startNode
app.Version = version.Version()
app.Commands = []*cli.Command{
db.DatabaseCommands,
}
app.Flags = appFlags
app.Before = func(ctx *cli.Context) error {
// Load flags from config file, if specified.
if err := cmd.LoadFlagsFromConfig(ctx, app.Flags); err != nil {
return err
}
format := ctx.String(cmd.LogFormat.Name)
switch format {
case "text":
formatter := new(prefixed.TextFormatter)
formatter.TimestampFormat = "2006-01-02 15:04:05"
formatter.FullTimestamp = true
// If persistent log files are written - we disable the log messages coloring because
// the colors are ANSI codes and seen as gibberish in the log files.
formatter.DisableColors = ctx.String(cmd.LogFileName.Name) != ""
logrus.SetFormatter(formatter)
case "fluentd":
f := joonix.NewFormatter()
if err := joonix.DisableTimestampFormat(f); err != nil {
panic(err)
}
logrus.SetFormatter(f)
case "json":
logrus.SetFormatter(&logrus.JSONFormatter{})
case "journald":
if err := journald.Enable(); err != nil {
return err
}
default:
return fmt.Errorf("unknown log format %s", format)
}
logFileName := ctx.String(cmd.LogFileName.Name)
if logFileName != "" {
if err := logutil.ConfigurePersistentLogging(logFileName); err != nil {
log.WithError(err).Error("Failed to configuring logging to disk.")
}
}
if err := cmd.ExpandSingleEndpointIfFile(ctx, flags.HTTPWeb3ProviderFlag); err != nil {
return err
}
if err := cmd.ExpandWeb3EndpointsIfFile(ctx, flags.FallbackWeb3ProviderFlag); err != nil {
return err
}
if ctx.IsSet(flags.SetGCPercent.Name) {
runtimeDebug.SetGCPercent(ctx.Int(flags.SetGCPercent.Name))
}
runtime.GOMAXPROCS(runtime.NumCPU())
return debug.Setup(ctx)
}
defer func() {
if x := recover(); x != nil {
log.Errorf("Runtime panic: %v\n%v", x, string(runtimeDebug.Stack()))
panic(x)
}
}()
if err := app.Run(os.Args); err != nil {
log.Error(err.Error())
}
}
func startNode(ctx *cli.Context) error {
// Fix data dir for Windows users.
outdatedDataDir := filepath.Join(fileutil.HomeDir(), "AppData", "Roaming", "Eth2")
currentDataDir := ctx.String(cmd.DataDirFlag.Name)
if err := cmd.FixDefaultDataDir(outdatedDataDir, currentDataDir); err != nil {
return err
}
// verify if ToS accepted
if err := tos.VerifyTosAcceptedOrPrompt(ctx); err != nil {
return err
}
verbosity := ctx.String(cmd.VerbosityFlag.Name)
level, err := logrus.ParseLevel(verbosity)
if err != nil {
return err
}
logrus.SetLevel(level)
if level == logrus.TraceLevel {
// libp2p specific logging.
golog.SetAllLoggers(golog.LevelDebug)
// Geth specific logging.
glogger := gethlog.NewGlogHandler(gethlog.StreamHandler(os.Stderr, gethlog.TerminalFormat(true)))
glogger.Verbosity(gethlog.LvlTrace)
gethlog.Root().SetHandler(glogger)
}
beacon, err := node.New(ctx)
if err != nil {
return err
}
beacon.Start()
return nil
}

180
cmd/beacon-chain/usage.go Normal file
View File

@@ -0,0 +1,180 @@
// This code was adapted from https://github.com/ethereum/go-ethereum/blob/master/cmd/geth/usage.go
package main
import (
"io"
"sort"
"github.com/prysmaticlabs/prysm/cmd/beacon-chain/flags"
"github.com/prysmaticlabs/prysm/shared/cmd"
"github.com/prysmaticlabs/prysm/shared/debug"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/urfave/cli/v2"
)
var appHelpTemplate = `NAME:
{{.App.Name}} - {{.App.Usage}}
USAGE:
{{.App.HelpName}} [options]{{if .App.Commands}} command [command options]{{end}} {{if .App.ArgsUsage}}{{.App.ArgsUsage}}{{else}}[arguments...]{{end}}
{{if .App.Version}}
AUTHOR:
{{range .App.Authors}}{{ . }}{{end}}
{{end}}{{if .App.Commands}}
GLOBAL OPTIONS:
{{range .App.Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}}
{{end}}{{end}}{{if .FlagGroups}}
{{range .FlagGroups}}{{.Name}} OPTIONS:
{{range .Flags}}{{.}}
{{end}}
{{end}}{{end}}{{if .App.Copyright }}
COPYRIGHT:
{{.App.Copyright}}
VERSION:
{{.App.Version}}
{{end}}{{if len .App.Authors}}
{{end}}
`
type flagGroup struct {
Name string
Flags []cli.Flag
}
var appHelpFlagGroups = []flagGroup{
{
Name: "cmd",
Flags: []cli.Flag{
cmd.MinimalConfigFlag,
cmd.E2EConfigFlag,
cmd.RPCMaxPageSizeFlag,
cmd.NoDiscovery,
cmd.BootstrapNode,
cmd.RelayNode,
cmd.P2PUDPPort,
cmd.P2PTCPPort,
cmd.DataDirFlag,
cmd.VerbosityFlag,
cmd.EnableTracingFlag,
cmd.TracingProcessNameFlag,
cmd.TracingEndpointFlag,
cmd.TraceSampleFractionFlag,
cmd.MonitoringHostFlag,
cmd.BackupWebhookOutputDir,
cmd.EnableBackupWebhookFlag,
flags.MonitoringPortFlag,
cmd.DisableMonitoringFlag,
cmd.MaxGoroutines,
cmd.ForceClearDB,
cmd.ClearDB,
cmd.ConfigFileFlag,
cmd.ChainConfigFileFlag,
cmd.GrpcMaxCallRecvMsgSizeFlag,
cmd.AcceptTosFlag,
cmd.RestoreSourceFileFlag,
cmd.RestoreTargetDirFlag,
cmd.BoltMMapInitialSizeFlag,
},
},
{
Name: "debug",
Flags: []cli.Flag{
debug.PProfFlag,
debug.PProfAddrFlag,
debug.PProfPortFlag,
debug.MemProfileRateFlag,
debug.CPUProfileFlag,
debug.TraceFlag,
debug.BlockProfileRateFlag,
debug.MutexProfileFractionFlag,
},
},
{
Name: "beacon-chain",
Flags: []cli.Flag{
flags.InteropMockEth1DataVotesFlag,
flags.InteropGenesisStateFlag,
flags.DepositContractFlag,
flags.ContractDeploymentBlock,
flags.RPCHost,
flags.RPCPort,
flags.CertFlag,
flags.KeyFlag,
flags.DisableGRPCGateway,
flags.GRPCGatewayHost,
flags.GRPCGatewayPort,
flags.GPRCGatewayCorsDomain,
flags.HTTPWeb3ProviderFlag,
flags.FallbackWeb3ProviderFlag,
flags.SetGCPercent,
flags.HeadSync,
flags.DisableSync,
flags.SlotsPerArchivedPoint,
flags.DisableDiscv5,
flags.BlockBatchLimit,
flags.BlockBatchLimitBurstFactor,
flags.EnableDebugRPCEndpoints,
flags.SubscribeToAllSubnets,
flags.HistoricalSlasherNode,
flags.ChainID,
flags.NetworkID,
flags.WeakSubjectivityCheckpt,
flags.Eth1HeaderReqLimit,
},
},
{
Name: "p2p",
Flags: []cli.Flag{
cmd.P2PIP,
cmd.P2PHost,
cmd.P2PHostDNS,
cmd.P2PMaxPeers,
cmd.P2PPrivKey,
cmd.P2PMetadata,
cmd.P2PAllowList,
cmd.P2PDenyList,
cmd.StaticPeers,
cmd.EnableUPnPFlag,
flags.MinSyncPeers,
},
},
{
Name: "log",
Flags: []cli.Flag{
cmd.LogFormat,
cmd.LogFileName,
},
},
{
Name: "features",
Flags: featureconfig.ActiveFlags(featureconfig.BeaconChainFlags),
},
{
Name: "interop",
Flags: []cli.Flag{
flags.InteropGenesisStateFlag,
flags.InteropGenesisTimeFlag,
flags.InteropNumValidatorsFlag,
},
},
}
func init() {
cli.AppHelpTemplate = appHelpTemplate
type helpData struct {
App interface{}
FlagGroups []flagGroup
}
originalHelpPrinter := cli.HelpPrinter
cli.HelpPrinter = func(w io.Writer, tmpl string, data interface{}) {
if tmpl == appHelpTemplate {
for _, group := range appHelpFlagGroups {
sort.Sort(cli.FlagsByName(group.Flags))
}
originalHelpPrinter(w, tmpl, helpData{data, appHelpFlagGroups})
} else {
originalHelpPrinter(w, tmpl, data)
}
}
}

View File

@@ -0,0 +1,44 @@
package main
import (
"testing"
"github.com/prysmaticlabs/prysm/shared/featureconfig"
"github.com/urfave/cli/v2"
)
func TestAllFlagsExistInHelp(t *testing.T) {
// If this test is failing, it is because you've recently added/removed a
// flag in beacon chain main.go, but did not add/remove it to the usage.go
// flag grouping (appHelpFlagGroups).
var helpFlags []cli.Flag
for _, group := range appHelpFlagGroups {
helpFlags = append(helpFlags, group.Flags...)
}
helpFlags = featureconfig.ActiveFlags(helpFlags)
appFlags = featureconfig.ActiveFlags(appFlags)
for _, flag := range appFlags {
if !doesFlagExist(flag, helpFlags) {
t.Errorf("Flag %s does not exist in help/usage flags.", flag.Names()[0])
}
}
for _, flag := range helpFlags {
if !doesFlagExist(flag, appFlags) {
t.Errorf("Flag %s does not exist in main.go, "+
"but exists in help flags", flag.Names()[0])
}
}
}
func doesFlagExist(flag cli.Flag, flags []cli.Flag) bool {
for _, f := range flags {
if f.String() == flag.String() {
return true
}
}
return false
}