Skip to content

Commit

Permalink
feat: refactored with cobra + viper
Browse files Browse the repository at this point in the history
  • Loading branch information
freak12techno committed May 1, 2021
1 parent 2f439f7 commit 19ed4fe
Show file tree
Hide file tree
Showing 6 changed files with 92 additions and 77 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,7 @@ By default, if not specified, it defaults to the next values (as it works this w

An example of the network where you have to specify all the prefixes manually is Iris, check out the flags example below.

Additionally, you can pass a `--config` flag with a path to your config file (I use `.toml`, but anything supported by [viper](https://github.com/spf13/viper) should work).

## Which networks this is guaranteed to work?

Expand Down
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,8 @@ require (
github.com/google/uuid v1.2.0
github.com/prometheus/client_golang v1.8.0
github.com/rs/zerolog v1.20.0
github.com/spf13/cobra v1.1.1
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.7.1
google.golang.org/grpc v1.35.0
)
149 changes: 80 additions & 69 deletions main.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package main

import (
"flag"
"fmt"
"net/http"
"os"

Expand All @@ -10,90 +10,82 @@ import (
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/rs/zerolog"
)

var PrefixFlag = flag.String("bech-prefix", "persistence", "Bech32 global prefix")

// some networks, like Iris, have the different prefixes for address, validator and consensus node
var AccountPrefixFlag = flag.String("bech-account-prefix", "", "Bech32 account prefix")
var AccountPubkeyPrefixFlag = flag.String("bech-account-pubkey-prefix", "", "Bech32 pubkey account prefix")
var ValidatorPrefixFlag = flag.String("bech-validator-prefix", "", "Bech32 validator prefix")
var ValidatorPubkeyPrefixFlag = flag.String("bech-validator-pubkey-prefix", "", "Bech32 pubkey validator prefix")
var ConsensusNodePrefixFlag = flag.String("bech-consensus-node-prefix", "", "Bech32 consensus node prefix")
var ConsensusNodePubkeyPrefixFlag = flag.String("bech-consensus-node-pubkey-prefix", "", "Bech32 pubkey consensus node prefix")
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)

var Denom = flag.String("denom", "uxprt", "Cosmos coin denom")
var ListenAddress = flag.String("listen-address", ":9300", "The address this exporter would listen on")
var NodeAddress = flag.String("node", "localhost:9090", "RPC node address")
var LogLevel = flag.String("log-level", "info", "Logging level")
var Limit = flag.Uint64("limit", 1000, "Pagination limit for gRPC requests")
var (
ConfigPath string

Denom string
ListenAddress string
NodeAddress string
LogLevel string
Limit uint64

Prefix string
AccountPrefix string
AccountPubkeyPrefix string
ValidatorPrefix string
ValidatorPubkeyPrefix string
ConsensusNodePrefix string
ConsensusNodePubkeyPrefix string
)

var log = zerolog.New(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()

var AccountPrefix string
var AccountPubkeyPrefix string
var ValidatorPrefix string
var ValidatorPubkeyPrefix string
var ConsensusNodePrefix string
var ConsensusNodePubkeyPrefix string

func main() {
flag.Parse()
var rootCmd = &cobra.Command{
Use: "missed-blocks-checker",
Long: "Tool to monitor missed blocks for Cosmos-chain validators",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if ConfigPath == "" {
return nil
}

viper.SetConfigFile(ConfigPath)
if err := viper.ReadInConfig(); err != nil {
log.Info().Err(err).Msg("Error reading config file")
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return err
}
}

// Credits to https://carolynvanslyck.com/blog/2020/08/sting-of-the-viper/
cmd.Flags().VisitAll(func(f *pflag.Flag) {
if !f.Changed && viper.IsSet(f.Name) {
val := viper.Get(f.Name)
if err := cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val)); err != nil {
log.Fatal().Err(err).Msg("Could not set flag")
}
}
})

return nil
},
Run: Execute,
}

logLevel, err := zerolog.ParseLevel(*LogLevel)
func Execute(cmd *cobra.Command, args []string) {
logLevel, err := zerolog.ParseLevel(LogLevel)
if err != nil {
log.Fatal().Err(err).Msg("Could not parse log level")
}

zerolog.SetGlobalLevel(logLevel)

if *AccountPrefixFlag == "" {
AccountPrefix = *PrefixFlag
} else {
AccountPrefix = *AccountPrefixFlag
}

if *AccountPubkeyPrefixFlag == "" {
AccountPubkeyPrefix = *PrefixFlag + "pub"
} else {
AccountPubkeyPrefix = *PrefixFlag
}

if *ValidatorPrefixFlag == "" {
ValidatorPrefix = *PrefixFlag + "valoper"
} else {
ValidatorPrefix = *ValidatorPrefixFlag
}

if *ValidatorPubkeyPrefixFlag == "" {
ValidatorPubkeyPrefix = *PrefixFlag + "valoperpub"
} else {
ValidatorPubkeyPrefix = *ValidatorPubkeyPrefixFlag
}

if *ConsensusNodePrefixFlag == "" {
ConsensusNodePrefix = *PrefixFlag + "valcons"
} else {
ConsensusNodePrefix = *ConsensusNodePrefixFlag
}

if *ConsensusNodePubkeyPrefixFlag == "" {
ConsensusNodePubkeyPrefix = *PrefixFlag + "valconspub"
} else {
ConsensusNodePubkeyPrefix = *ConsensusNodePrefixFlag
}

log.Info().
Str("--bech-account-prefix", AccountPrefix).
Str("--bech-account-pubkey-prefix", AccountPubkeyPrefix).
Str("--bech-validator-prefix", ValidatorPrefix).
Str("--bech-validator-pubkey-prefix", ValidatorPubkeyPrefix).
Str("--bech-consensus-node-prefix", ConsensusNodePrefix).
Str("--bech-consensus-node-pubkey-prefix", ConsensusNodePubkeyPrefix).
Str("--denom", *Denom).
Str("--listen-address", *ListenAddress).
Str("--node", *NodeAddress).
Str("--log-level", *LogLevel).
Str("--denom", Denom).
Str("--listen-address", ListenAddress).
Str("--node", NodeAddress).
Str("--log-level", LogLevel).
Msg("Started with following parameters")

config := sdk.GetConfig()
Expand All @@ -103,7 +95,7 @@ func main() {
config.Seal()

grpcConn, err := grpc.Dial(
*NodeAddress,
NodeAddress,
grpc.WithInsecure(),
)
if err != nil {
Expand All @@ -124,9 +116,28 @@ func main() {
ValidatorsHandler(w, r, grpcConn)
})

log.Info().Str("address", *ListenAddress).Msg("Listening")
err = http.ListenAndServe(*ListenAddress, nil)
log.Info().Str("address", ListenAddress).Msg("Listening")
err = http.ListenAndServe(ListenAddress, nil)
if err != nil {
log.Fatal().Err(err).Msg("Could not start application")
}
}

func main() {
rootCmd.PersistentFlags().StringVar(&Denom, "denom", "uxprt", "Cosmos coin denom")
rootCmd.PersistentFlags().StringVar(&ListenAddress, "listen-address", ":9300", "The address this exporter would listen on")
rootCmd.PersistentFlags().StringVar(&NodeAddress, "node", "localhost:9090", "RPC node address")
rootCmd.PersistentFlags().StringVar(&LogLevel, "log-level", "info", "Logging level")
rootCmd.PersistentFlags().Uint64Var(&Limit, "limit", 1000, "Pagination limit for gRPC requests")

// some networks, like Iris, have the different prefixes for address, validator and consensus node
rootCmd.PersistentFlags().StringVar(&Prefix, "bech-prefix", "persistence", "Bech32 global prefix")
rootCmd.PersistentFlags().StringVar(&ValidatorPrefix, "bech-validator-prefix", Prefix+"valoper", "Bech32 validator prefix")
rootCmd.PersistentFlags().StringVar(&ValidatorPubkeyPrefix, "bech-validator-pubkey-prefix", Prefix+"valoperpub", "Bech32 pubkey validator prefix")
rootCmd.PersistentFlags().StringVar(&ConsensusNodePrefix, "bech-consensus-node-prefix", Prefix+"valcons", "Bech32 consensus node prefix")
rootCmd.PersistentFlags().StringVar(&ConsensusNodePubkeyPrefix, "bech-consensus-node-pubkey-prefix", Prefix+"valconspub", "Bech32 pubkey consensus node prefix")

if err := rootCmd.Execute(); err != nil {
log.Fatal().Err(err).Msg("Could not start application")
}
}
4 changes: 2 additions & 2 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ func ValidatorHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Cli
validatorUnbondingsGauge.With(prometheus.Labels{
"address": unbonding.ValidatorAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": *Denom, // unbonding does not have denom in response for some reason
"denom": Denom, // unbonding does not have denom in response for some reason
"unbonded_by": unbonding.DelegatorAddress,
}).Set(sum)
}
Expand Down Expand Up @@ -308,7 +308,7 @@ func ValidatorHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Cli
validatorRedelegationsGauge.With(prometheus.Labels{
"address": redelegation.Redelegation.ValidatorSrcAddress,
"moniker": validator.Validator.Description.Moniker,
"denom": *Denom, // redelegation does not have denom in response for some reason
"denom": Denom, // redelegation does not have denom in response for some reason
"redelegated_by": redelegation.Redelegation.DelegatorAddress,
"redelegated_to": redelegation.Redelegation.ValidatorDstAddress,
}).Set(sum)
Expand Down
6 changes: 3 additions & 3 deletions validators.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func ValidatorsHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Cl
context.Background(),
&stakingtypes.QueryValidatorsRequest{
Pagination: &querytypes.PageRequest{
Limit: *Limit,
Limit: Limit,
},
},
)
Expand All @@ -122,7 +122,7 @@ func ValidatorsHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Cl
context.Background(),
&slashingtypes.QuerySigningInfosRequest{
Pagination: &querytypes.PageRequest{
Limit: *Limit,
Limit: Limit,
},
},
)
Expand Down Expand Up @@ -154,7 +154,7 @@ func ValidatorsHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Cl
validatorsCommissionGauge.With(prometheus.Labels{
"address": validator.OperatorAddress,
"moniker": validator.Description.Moniker,
"denom": *Denom,
"denom": Denom,
}).Set(rate)
}

Expand Down
6 changes: 3 additions & 3 deletions wallet.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ func WalletHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Client
bankClient := banktypes.NewQueryClient(grpcConn)
bankRes, err := bankClient.Balance(
context.Background(),
&banktypes.QueryBalanceRequest{Address: myAddress.String(), Denom: *Denom},
&banktypes.QueryBalanceRequest{Address: myAddress.String(), Denom: Denom},
)

if err != nil {
Expand Down Expand Up @@ -186,7 +186,7 @@ func WalletHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Client

walletUnbondingsGauge.With(prometheus.Labels{
"address": unbonding.DelegatorAddress,
"denom": *Denom, // unbonding does not have denom in response for some reason
"denom": Denom, // unbonding does not have denom in response for some reason
"unbonded_from": unbonding.ValidatorAddress,
}).Set(sum)
}
Expand Down Expand Up @@ -227,7 +227,7 @@ func WalletHandler(w http.ResponseWriter, r *http.Request, grpcConn *grpc.Client

walletRedelegationGauge.With(prometheus.Labels{
"address": redelegation.Redelegation.DelegatorAddress,
"denom": *Denom, // redelegation does not have denom in response for some reason
"denom": Denom, // redelegation does not have denom in response for some reason
"redelegated_from": redelegation.Redelegation.ValidatorSrcAddress,
"redelegated_to": redelegation.Redelegation.ValidatorDstAddress,
}).Set(sum)
Expand Down

0 comments on commit 19ed4fe

Please sign in to comment.