Skip to content

Commit

Permalink
refactor: improve cmd package and extract stamper to pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
gacevicljubisa committed Dec 13, 2024
1 parent b6ede3d commit 131ba6f
Show file tree
Hide file tree
Showing 18 changed files with 214 additions and 214 deletions.
28 changes: 17 additions & 11 deletions cmd/beekeeper/cmd/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,10 @@ import (
"github.com/spf13/cobra"
)

var errMissingClusterName = fmt.Errorf("cluster name not provided")

func (c *command) initCheckCmd() (err error) {
const (
optionNameClusterName = "cluster-name"
optionNameCreateCluster = "create-cluster"
optionNameChecks = "checks"
optionNameMetricsEnabled = "metrics-enabled"
Expand All @@ -34,18 +35,23 @@ func (c *command) initCheckCmd() (err error) {
ctx, cancel := context.WithTimeout(cmd.Context(), c.globalConfig.GetDuration(optionNameTimeout))
defer cancel()

checks := c.globalConfig.GetStringSlice(optionNameChecks)
if len(checks) == 0 {
return fmt.Errorf("no checks provided")
}

clusterName := c.globalConfig.GetString(optionNameClusterName)
if clusterName == "" {
return errMissingClusterName
}

// set cluster config
cfgCluster, ok := c.config.Clusters[c.globalConfig.GetString(optionNameClusterName)]
cfgCluster, ok := c.config.Clusters[clusterName]
if !ok {
return fmt.Errorf("cluster %s not defined", c.globalConfig.GetString(optionNameClusterName))
return fmt.Errorf("cluster %s not defined", clusterName)
}

// setup cluster
cluster, err := c.setupCluster(ctx,
c.globalConfig.GetString(optionNameClusterName),
c.config,
c.globalConfig.GetBool(optionNameCreateCluster),
)
cluster, err := c.setupCluster(ctx, clusterName, c.globalConfig.GetBool(optionNameCreateCluster))
if err != nil {
return fmt.Errorf("cluster setup: %w", err)
}
Expand Down Expand Up @@ -88,7 +94,7 @@ func (c *command) initCheckCmd() (err error) {
}

// run checks
for _, checkName := range c.globalConfig.GetStringSlice(optionNameChecks) {
for _, checkName := range checks {
checkName = strings.TrimSpace(checkName)
// get configuration
checkConfig, ok := c.config.Checks[checkName]
Expand Down Expand Up @@ -147,7 +153,7 @@ func (c *command) initCheckCmd() (err error) {
PreRunE: c.preRunE,
}

cmd.Flags().String(optionNameClusterName, "default", "cluster name")
cmd.Flags().String(optionNameClusterName, "", "cluster name. Required")
cmd.Flags().String(optionNameMetricsPusherAddress, "pushgateway.staging.internal", "prometheus metrics pusher address")
cmd.Flags().Bool(optionNameCreateCluster, false, "creates cluster before executing checks")
cmd.Flags().StringSlice(optionNameChecks, []string{"pingpong"}, "list of checks to execute")
Expand Down
17 changes: 13 additions & 4 deletions cmd/beekeeper/cmd/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ type nodeResult struct {
}

func (c *command) deleteCluster(ctx context.Context, clusterName string, cfg *config.Config, deleteStorage bool) (err error) {
if clusterName == "" {
return errMissingClusterName
}

clusterConfig, ok := cfg.Clusters[clusterName]
if !ok {
return fmt.Errorf("cluster %s not defined", clusterName)
Expand Down Expand Up @@ -108,8 +112,12 @@ func (c *command) deleteCluster(ctx context.Context, clusterName string, cfg *co
return
}

func (c *command) setupCluster(ctx context.Context, clusterName string, cfg *config.Config, startCluster bool) (cluster orchestration.Cluster, err error) {
clusterConfig, ok := cfg.Clusters[clusterName]
func (c *command) setupCluster(ctx context.Context, clusterName string, startCluster bool) (cluster orchestration.Cluster, err error) {
if clusterName == "" {
return nil, errMissingClusterName
}

clusterConfig, ok := c.config.Clusters[clusterName]
if !ok {
return nil, fmt.Errorf("cluster %s not defined", clusterName)
}
Expand Down Expand Up @@ -139,7 +147,7 @@ func (c *command) setupCluster(ctx context.Context, clusterName string, cfg *con
inCluster := c.globalConfig.GetBool(optionNameInCluster)

// setup bootnode node group
fundAddresses, bootnodes, err := setupNodes(ctx, clusterConfig, cfg, true, cluster, startCluster, inCluster, "", nodeResultChan)
fundAddresses, bootnodes, err := setupNodes(ctx, clusterConfig, c.config, true, cluster, startCluster, inCluster, "", nodeResultChan)
if err != nil {
return nil, fmt.Errorf("setup node group bootnode: %w", err)
}
Expand All @@ -153,7 +161,7 @@ func (c *command) setupCluster(ctx context.Context, clusterName string, cfg *con
}

// setup other node groups
fundAddresses, _, err = setupNodes(ctx, clusterConfig, cfg, false, cluster, startCluster, inCluster, bootnodes, nodeResultChan)
fundAddresses, _, err = setupNodes(ctx, clusterConfig, c.config, false, cluster, startCluster, inCluster, bootnodes, nodeResultChan)
if err != nil {
return nil, fmt.Errorf("setup other node groups: %w", err)
}
Expand All @@ -165,6 +173,7 @@ func (c *command) setupCluster(ctx context.Context, clusterName string, cfg *con
}
c.log.Infof("node groups funded")
}

c.log.WithField("use-static-endpoints", clusterConfig.IsUsingStaticEndpoints()).Infof("cluster %s setup completed", clusterName)

return cluster, nil
Expand Down
104 changes: 68 additions & 36 deletions cmd/beekeeper/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,10 @@ type command struct {
globalConfig *viper.Viper
globalConfigFile string
homeDir string
// configuration
config *config.Config
// kubernetes client
k8sClient *k8s.Client
// swap client
swapClient swap.Client
// log
log logging.Logger
config *config.Config // beekeeper clusters configuration (config dir)
k8sClient *k8s.Client // kubernetes client
swapClient swap.Client
log logging.Logger
}

type option func(*command)
Expand All @@ -72,7 +68,7 @@ func newCommand(opts ...option) (c *command, err error) {
SilenceErrors: true,
SilenceUsage: true,
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return c.initConfig()
return c.initConfig(cmd.Flags().Changed(optionNameClusterName))
},
},
}
Expand Down Expand Up @@ -112,7 +108,7 @@ func newCommand(opts ...option) (c *command, err error) {
return nil, err
}

if err := c.initStampFunderCmd(); err != nil {
if err := c.initStamperCmd(); err != nil {
return nil, err
}

Expand Down Expand Up @@ -143,6 +139,7 @@ func Execute() (err error) {
if err != nil {
return err
}

return c.Execute()
}

Expand All @@ -167,58 +164,90 @@ func (c *command) initGlobalFlags() {
globalFlags.String(optionNameKubeconfig, "~/.kube/config", "Path to the kubeconfig file")
}

func (c *command) bindGlobalFlags() (err error) {
for _, flag := range []string{optionNameConfigDir, optionNameConfigGitRepo, optionNameConfigGitBranch, optionNameConfigGitDir, optionNameConfigGitUsername, optionNameConfigGitPassword, optionNameLogVerbosity, optionNameLokiEndpoint} {
func (c *command) bindGlobalFlags() error {
for _, flag := range []string{
optionNameConfigDir,
optionNameConfigGitRepo,
optionNameConfigGitBranch,
optionNameConfigGitDir,
optionNameConfigGitUsername,
optionNameConfigGitPassword,
optionNameLogVerbosity,
optionNameLokiEndpoint,
} {
if err := c.globalConfig.BindPFlag(flag, c.root.PersistentFlags().Lookup(flag)); err != nil {
return err
return fmt.Errorf("binding %s flag: %w", flag, err)
}
}
return

return nil
}

func (c *command) initConfig() (err error) {
// set global configuration
func (c *command) initConfig(loadConfigDir bool) error {
if err := c.initGlobalConfig(); err != nil {
return fmt.Errorf("initializing global configuration: %w", err)
}

if err := c.initLogger(); err != nil {
return fmt.Errorf("initializing logger: %w", err)
}

if !loadConfigDir {
c.log.Debugf("Skipping loading configuration directory as the cluster name is not set")
return nil
}

if err := c.loadConfigDirectory(); err != nil {
return fmt.Errorf("loading configuration directory: %w", err)
}

return nil
}

func (c *command) initGlobalConfig() error {
cfg := viper.New()
cfgName := ".beekeeper"

if c.globalConfigFile != "" {
// Use config file from the flag.
cfg.SetConfigFile(c.globalConfigFile)
} else {
// Search config in home directory with name ".beekeeper" (without extension).
cfg.AddConfigPath(c.homeDir)
cfg.SetConfigName(cfgName)
}

// environment
cfg.SetEnvPrefix("beekeeper")
cfg.AutomaticEnv() // read in environment variables that match
cfg.AutomaticEnv()
cfg.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))

if c.homeDir != "" && c.globalConfigFile == "" {
c.globalConfigFile = filepath.Join(c.homeDir, cfgName+".yaml")
}

// if a config file is found, read it in.
if err := cfg.ReadInConfig(); err != nil {
var e viper.ConfigFileNotFoundError
if !errors.As(err, &e) {
if !errors.As(err, &viper.ConfigFileNotFoundError{}) {
return err
}
}

c.globalConfig = cfg
if err := c.bindGlobalFlags(); err != nil {
return err
}

// init logger
return c.bindGlobalFlags()
}

func (c *command) initLogger() error {
verbosity := c.globalConfig.GetString(optionNameLogVerbosity)
lokiEndpoint := c.globalConfig.GetString(optionNameLokiEndpoint)
c.log, err = newLogger(c.root, verbosity, lokiEndpoint)

log, err := newLogger(c.root, verbosity, lokiEndpoint)
if err != nil {
return fmt.Errorf("new logger: %w", err)
}

c.log = log
return nil
}

func (c *command) loadConfigDirectory() error {
if c.globalConfig.GetString(optionNameConfigGitRepo) != "" {
c.log.Debugf("using configuration from Git repository %s, branch %s, directory %s", c.globalConfig.GetString(optionNameConfigGitRepo), c.globalConfig.GetString(optionNameConfigGitBranch), c.globalConfig.GetString(optionNameConfigGitDir))
// read configuration from git repo
Expand Down Expand Up @@ -298,17 +327,19 @@ func (c *command) initConfig() (err error) {
}
}

return
return nil
}

func (c *command) setHomeDir() (err error) {
func (c *command) setHomeDir() error {
if c.homeDir != "" {
return
return nil
}

dir, err := os.UserHomeDir()
if err != nil {
return err
return fmt.Errorf("obtaining user's home dir: %w", err)
}

c.homeDir = dir
return nil
}
Expand All @@ -318,18 +349,17 @@ func (c *command) preRunE(cmd *cobra.Command, args []string) (err error) {
return err
}

// set Kubernetes client
if err := c.setK8S(); err != nil {
if err := c.setK8sClient(); err != nil {
return err
}
// set Swap client

if err := c.setSwapClient(); err != nil {
return err
}
return nil
}

func (c *command) setK8S() (err error) {
func (c *command) setK8sClient() (err error) {
if c.globalConfig.GetBool(optionNameEnableK8S) {
options := []k8s.ClientOption{
k8s.WithLogger(c.log),
Expand Down Expand Up @@ -369,6 +399,7 @@ func newLogger(cmd *cobra.Command, verbosity, lokiEndpoint string) (logging.Logg
logging.WithLokiOption(lokiEndpoint),
logging.WithMetricsOption(),
}

switch strings.ToLower(verbosity) {
case "0", "silent":
logger = logging.New(io.Discard, 0)
Expand All @@ -385,5 +416,6 @@ func newLogger(cmd *cobra.Command, verbosity, lokiEndpoint string) (logging.Logg
default:
return nil, fmt.Errorf("unknown %s level %q, use help to check flag usage options", optionNameLogVerbosity, verbosity)
}

return logger, nil
}
2 changes: 1 addition & 1 deletion cmd/beekeeper/cmd/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ func (c *command) initCreateCmd() (err error) {
},
}

cmd.AddCommand(c.initCreateK8SNamespace())
cmd.AddCommand(c.initCreateK8sNamespace())
cmd.AddCommand(c.initCreateBeeCluster())

c.root.AddCommand(cmd)
Expand Down
12 changes: 6 additions & 6 deletions cmd/beekeeper/cmd/create_bee_cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
)

const (
optionNameClusterName = "cluster-name"
optionNameChainNodeEndpoint = "geth-url"
optionNameWalletKey = "wallet-key"
optionNameTimeout = "timeout"
optionNameClusterName string = "cluster-name"
optionNameChainNodeEndpoint string = "geth-url"
optionNameWalletKey string = "wallet-key"
optionNameTimeout string = "timeout"
)

func (c *command) initCreateBeeCluster() *cobra.Command {
Expand All @@ -23,14 +23,14 @@ func (c *command) initCreateBeeCluster() *cobra.Command {
ctx, cancel := context.WithTimeout(cmd.Context(), c.globalConfig.GetDuration(optionNameTimeout))
defer cancel()
start := time.Now()
_, err = c.setupCluster(ctx, c.globalConfig.GetString(optionNameClusterName), c.config, true)
_, err = c.setupCluster(ctx, c.globalConfig.GetString(optionNameClusterName), true)
c.log.Infof("cluster setup took %s", time.Since(start))
return err
},
PreRunE: c.preRunE,
}

cmd.Flags().String(optionNameClusterName, "default", "cluster name")
cmd.Flags().String(optionNameClusterName, "", "cluster name")
cmd.Flags().String(optionNameChainNodeEndpoint, "", "Endpoint to chain node. Required.")
cmd.Flags().String(optionNameWalletKey, "", "Hex-encoded private key for the Bee node wallet. Required.")
cmd.Flags().Duration(optionNameTimeout, 30*time.Minute, "timeout")
Expand Down
Loading

0 comments on commit 131ba6f

Please sign in to comment.