Skip to content

Commit

Permalink
refact "cscli" root cmd (#2811)
Browse files Browse the repository at this point in the history
* refact "cscli" root cmd
* lint (naming, imports, whitespace)
  • Loading branch information
mmetc authored Feb 6, 2024
1 parent fdc5251 commit 4e724f6
Show file tree
Hide file tree
Showing 12 changed files with 199 additions and 140 deletions.
2 changes: 1 addition & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ linters-settings:

nestif:
# lower this after refactoring
min-complexity: 27
min-complexity: 28

nlreturn:
block-size: 4
Expand Down
10 changes: 5 additions & 5 deletions cmd/crowdsec-cli/bouncers.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,13 +36,13 @@ func askYesNo(message string, defaultAnswer bool) (bool, error) {
}

type cliBouncers struct {
db *database.Client
db *database.Client
cfg configGetter
}

func NewCLIBouncers(getconfig configGetter) *cliBouncers {
func NewCLIBouncers(cfg configGetter) *cliBouncers {
return &cliBouncers{
cfg: getconfig,
cfg: cfg,
}
}

Expand Down Expand Up @@ -197,13 +197,13 @@ cscli bouncers add MyBouncerName --key <random-key>`,
return cmd
}

func (cli *cliBouncers) deleteValid(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
func (cli *cliBouncers) deleteValid(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
bouncers, err := cli.db.ListBouncers()
if err != nil {
cobra.CompError("unable to list bouncers " + err.Error())
}

ret :=[]string{}
ret := []string{}

for _, bouncer := range bouncers {
if strings.Contains(bouncer.Name, toComplete) && !slices.Contains(args, bouncer.Name) {
Expand Down
9 changes: 7 additions & 2 deletions cmd/crowdsec-cli/config_restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,12 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
// Now we have config.yaml, we should regenerate config struct to have rights paths etc
ConfigFilePath = fmt.Sprintf("%s/config.yaml", csConfig.ConfigPaths.ConfigDir)

initConfig()
log.Debug("Reloading configuration")

csConfig, _, err = loadConfigFor("config")
if err != nil {
return fmt.Errorf("failed to reload configuration: %s", err)
}

backupCAPICreds := fmt.Sprintf("%s/online_api_credentials.yaml", dirPath)
if _, err = os.Stat(backupCAPICreds); err == nil {
Expand Down Expand Up @@ -227,7 +232,7 @@ func restoreConfigFromDirectory(dirPath string, oldBackup bool) error {
}
}

// if there is files in the acquis backup dir, restore them
// if there are files in the acquis backup dir, restore them
acquisBackupDir := filepath.Join(dirPath, "acquis", "*.yaml")
if acquisFiles, err := filepath.Glob(acquisBackupDir); err == nil {
for _, acquisFile := range acquisFiles {
Expand Down
24 changes: 14 additions & 10 deletions cmd/crowdsec-cli/dashboard.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"

"github.com/crowdsecurity/crowdsec/pkg/metabase"

"github.com/crowdsecurity/crowdsec/cmd/crowdsec-cli/require"
"github.com/crowdsecurity/crowdsec/pkg/metabase"
)

var (
metabaseUser = "[email protected]"
metabasePassword string
metabaseDbPath string
metabaseDBPath string
metabaseConfigPath string
metabaseConfigFolder = "metabase/"
metabaseConfigFile = "metabase.yaml"
Expand All @@ -43,13 +42,13 @@ var (
// information needed to set up a random password on user's behalf
)

type cliDashboard struct{
type cliDashboard struct {
cfg configGetter
}

func NewCLIDashboard(getconfig configGetter) *cliDashboard {
func NewCLIDashboard(cfg configGetter) *cliDashboard {
return &cliDashboard{
cfg: getconfig,
cfg: cfg,
}
}

Expand Down Expand Up @@ -99,6 +98,7 @@ cscli dashboard remove
metabaseContainerID = oldContainerID
}
}

return nil
},
}
Expand Down Expand Up @@ -127,8 +127,8 @@ cscli dashboard setup --listen 0.0.0.0
cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
`,
RunE: func(_ *cobra.Command, _ []string) error {
if metabaseDbPath == "" {
metabaseDbPath = cli.cfg().ConfigPaths.DataDir
if metabaseDBPath == "" {
metabaseDBPath = cli.cfg().ConfigPaths.DataDir
}

if metabasePassword == "" {
Expand All @@ -152,7 +152,7 @@ cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
if err = cli.chownDatabase(dockerGroup.Gid); err != nil {
return err
}
mb, err := metabase.SetupMetabase(cli.cfg().API.Server.DbConfig, metabaseListenAddress, metabaseListenPort, metabaseUser, metabasePassword, metabaseDbPath, dockerGroup.Gid, metabaseContainerID, metabaseImage)
mb, err := metabase.SetupMetabase(cli.cfg().API.Server.DbConfig, metabaseListenAddress, metabaseListenPort, metabaseUser, metabasePassword, metabaseDBPath, dockerGroup.Gid, metabaseContainerID, metabaseImage)
if err != nil {
return err
}
Expand All @@ -165,13 +165,14 @@ cscli dashboard setup -l 0.0.0.0 -p 443 --password <password>
fmt.Printf("\tURL : '%s'\n", mb.Config.ListenURL)
fmt.Printf("\tusername : '%s'\n", mb.Config.Username)
fmt.Printf("\tpassword : '%s'\n", mb.Config.Password)

return nil
},
}

flags := cmd.Flags()
flags.BoolVarP(&force, "force", "f", false, "Force setup : override existing files")
flags.StringVarP(&metabaseDbPath, "dir", "d", "", "Shared directory with metabase container")
flags.StringVarP(&metabaseDBPath, "dir", "d", "", "Shared directory with metabase container")
flags.StringVarP(&metabaseListenAddress, "listen", "l", metabaseListenAddress, "Listen address of container")
flags.StringVar(&metabaseImage, "metabase-image", metabaseImage, "Metabase image to use")
flags.StringVarP(&metabaseListenPort, "port", "p", metabaseListenPort, "Listen port of container")
Expand Down Expand Up @@ -203,6 +204,7 @@ func (cli *cliDashboard) newStartCmd() *cobra.Command {
}
log.Infof("Started metabase")
log.Infof("url : http://%s:%s", mb.Config.ListenAddr, mb.Config.ListenPort)

return nil
},
}
Expand Down Expand Up @@ -241,6 +243,7 @@ func (cli *cliDashboard) newShowPasswordCmd() *cobra.Command {
return err
}
log.Printf("'%s'", m.Config.Password)

return nil
},
}
Expand Down Expand Up @@ -313,6 +316,7 @@ cscli dashboard remove --force
}
}
}

return nil
},
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/crowdsec-cli/dashboard_unsupported.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ type cliDashboard struct{
cfg configGetter
}

func NewCLIDashboard(getconfig configGetter) *cliDashboard {
func NewCLIDashboard(cfg configGetter) *cliDashboard {
return &cliDashboard{
cfg: getconfig,
cfg: cfg,
}
}

Expand Down
8 changes: 5 additions & 3 deletions cmd/crowdsec-cli/decisions.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,14 +116,13 @@ func (cli *cliDecisions) decisionsToTable(alerts *models.GetAlertsResponse, prin
return nil
}


type cliDecisions struct {
cfg configGetter
}

func NewCLIDecisions(getconfig configGetter) *cliDecisions {
func NewCLIDecisions(cfg configGetter) *cliDecisions {
return &cliDecisions{
cfg: getconfig,
cfg: cfg,
}
}

Expand Down Expand Up @@ -157,6 +156,7 @@ func (cli *cliDecisions) NewCommand() *cobra.Command {
if err != nil {
return fmt.Errorf("creating api client: %w", err)
}

return nil
},
}
Expand Down Expand Up @@ -393,6 +393,7 @@ cscli decisions add --scope username --value foobar
}

log.Info("Decision successfully added")

return nil
},
}
Expand Down Expand Up @@ -499,6 +500,7 @@ cscli decisions delete --type captcha
}
}
log.Infof("%s decision(s) deleted", decisions.NbDeleted)

return nil
},
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/crowdsec-cli/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
)

type cliHub struct{
type cliHub struct {
cfg configGetter
}

func NewCLIHub(getconfig configGetter) *cliHub {
func NewCLIHub(cfg configGetter) *cliHub {
return &cliHub{
cfg: getconfig,
cfg: cfg,
}
}

Expand Down
21 changes: 11 additions & 10 deletions cmd/crowdsec-cli/machines.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"fmt"
"math/big"
"os"
"slices"
"strings"
"time"

Expand All @@ -17,7 +18,6 @@ import (
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"slices"

"github.com/crowdsecurity/machineid"

Expand Down Expand Up @@ -106,14 +106,14 @@ func getLastHeartbeat(m *ent.Machine) (string, bool) {
return hb, true
}

type cliMachines struct{
db *database.Client
type cliMachines struct {
db *database.Client
cfg configGetter
}

func NewCLIMachines(getconfig configGetter) *cliMachines {
func NewCLIMachines(cfg configGetter) *cliMachines {
return &cliMachines{
cfg: getconfig,
cfg: cfg,
}
}

Expand All @@ -136,6 +136,7 @@ Note: This command requires database direct access, so is intended to be run on
if err != nil {
return fmt.Errorf("unable to create new database client: %s", err)
}

return nil
},
}
Expand Down Expand Up @@ -249,7 +250,7 @@ cscli machines add -f- --auto > /tmp/mycreds.yaml`,

func (cli *cliMachines) add(args []string, machinePassword string, dumpFile string, apiURL string, interactive bool, autoAdd bool, force bool) error {
var (
err error
err error
machineID string
)

Expand Down Expand Up @@ -347,7 +348,7 @@ func (cli *cliMachines) add(args []string, machinePassword string, dumpFile stri
return nil
}

func (cli *cliMachines) deleteValid(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
func (cli *cliMachines) deleteValid(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
machines, err := cli.db.ListMachines()
if err != nil {
cobra.CompError("unable to list machines " + err.Error())
Expand Down Expand Up @@ -447,9 +448,9 @@ func (cli *cliMachines) prune(duration time.Duration, notValidOnly bool, force b

func (cli *cliMachines) newPruneCmd() *cobra.Command {
var (
duration time.Duration
notValidOnly bool
force bool
duration time.Duration
notValidOnly bool
force bool
)

const defaultDuration = 10 * time.Minute
Expand Down
Loading

0 comments on commit 4e724f6

Please sign in to comment.