Skip to content

Commit

Permalink
chore: begin logging refactor
Browse files Browse the repository at this point in the history
* add logger interface
* add error logging
* add utility for making k1 directory that returns an error

Signed-off-by: nathan-nicholson <[email protected]>
  • Loading branch information
nathan-nicholson committed Dec 20, 2024
1 parent c4816c2 commit af8f242
Show file tree
Hide file tree
Showing 9 changed files with 185 additions and 76 deletions.
36 changes: 11 additions & 25 deletions cmd/aws/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/konstructio/kubefirst-api/pkg/constants"
"github.com/konstructio/kubefirst/internal/common"
"github.com/konstructio/kubefirst/internal/logger"
"github.com/spf13/cobra"
)

Expand Down Expand Up @@ -45,25 +44,8 @@ var (
supportedGitProtocolOverride = []string{"https", "ssh"}
)

type Printer interface {
AddWriter(w io.Writer)
Print(s string) error
}

type awsCommand struct {
logger logger.Logger
printer Printer
}

func NewAwsCommand(logger logger.Logger, printer Printer) *awsCommand {
return &awsCommand{
logger,
printer,
}
}

func NewCommand() *cobra.Command {
awsCmd := &cobra.Command{
func NewCommand(logger common.Logger, writer io.Writer) *cobra.Command {
cmd := &cobra.Command{
Use: "aws",
Short: "kubefirst aws installation",
Long: "kubefirst aws",
Expand All @@ -73,19 +55,23 @@ func NewCommand() *cobra.Command {
},
}

service := AwsService{
logger,
writer,
}

// wire up new commands
awsCmd.AddCommand(Create(), Destroy(), Quota(), RootCredentials())
cmd.AddCommand(Create(service), Destroy(), Quota(), RootCredentials())

return awsCmd
return cmd
}

func Create() *cobra.Command {
func Create(service AwsService) *cobra.Command {
createCmd := &cobra.Command{
Use: "create",
Short: "create the kubefirst platform running in aws",
TraverseChildren: true,
RunE: createAws,
// PreRun: common.CheckDocker,
RunE: service.createAws,
}

awsDefaults := constants.GetCloudDefaults().Aws
Expand Down
50 changes: 35 additions & 15 deletions cmd/aws/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,66 +27,85 @@ import (
"github.com/spf13/viper"
)

func createAws(cmd *cobra.Command, _ []string) error {
func (s *AwsService) createAws(cmd *cobra.Command, _ []string) error {
fmt.Fprintln(s.writer, "Starting to create AWS cluster")

cliFlags, err := utilities.GetFlags(cmd, "aws")
if err != nil {
progress.Error(err.Error())
return nil
s.logger.Error("failed to get flags", "error", err)
return fmt.Errorf("failed to get flags: %w", err)
}

progress.DisplayLogHints(40)
//TODO - Add progress steps

Check failure on line 39 in cmd/aws/create.go

View workflow job for this annotation

GitHub Actions / build

commentFormatting: put a space between `//` and comment text (gocritic)
//progress.DisplayLogHints(40)

isValid, catalogApps, err := catalog.ValidateCatalogApps(cliFlags.InstallCatalogApps)
if !isValid {
s.logger.Error("invalid catalog apps", "error", err)
return fmt.Errorf("invalid catalog apps: %w", err)
}

err = ValidateProvidedFlags(cliFlags.GitProvider)
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to validate provided flags", "error", err)
return fmt.Errorf("failed to validate provided flags: %w", err)
}

utilities.CreateK1ClusterDirectory(cliFlags.ClusterName)
// Create k1 cluster directory
homePath, err := os.UserHomeDir()

if err != nil {
s.logger.Error("failed to get user home directory", "error", err)
return fmt.Errorf("failed to get user home directory: %w", err)
}

err = utilities.CreateK1ClusterDirectoryE(homePath, cliFlags.ClusterName)

if err != nil {
s.logger.Error("failed to create k1 cluster directory", "error", err)
return fmt.Errorf("failed to create k1 cluster directory: %w", err)
}

// If cluster setup is complete, return
clusterSetupComplete := viper.GetBool("kubefirst-checks.cluster-install-complete")
if clusterSetupComplete {
err = fmt.Errorf("this cluster install process has already completed successfully")
progress.Error(err.Error())
s.logger.Info("cluster install process has already completed successfully")
fmt.Fprintln(s.writer, "Cluster install process has already completed successfully")
return nil
}

// Validate aws region
config, err := awsinternal.NewAwsV2(cloudRegionFlag)
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to validate AWS region", "error", err)
return fmt.Errorf("failed to validate AWS region: %w", err)
}

awsClient := &awsinternal.Configuration{Config: config}
creds, err := awsClient.Config.Credentials.Retrieve(aws.BackgroundContext())
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to retrieve AWS credentials", "error", err)
return fmt.Errorf("failed to retrieve AWS credentials: %w", err)
}

viper.Set("kubefirst.state-store-creds.access-key-id", creds.AccessKeyID)
viper.Set("kubefirst.state-store-creds.secret-access-key-id", creds.SecretAccessKey)
viper.Set("kubefirst.state-store-creds.token", creds.SessionToken)
if err := viper.WriteConfig(); err != nil {
s.logger.Error("failed to write config", "error", err)

return fmt.Errorf("failed to write config: %w", err)
}

_, err = awsClient.CheckAvailabilityZones(cliFlags.CloudRegion)
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to check availability zones", "error", err)
return fmt.Errorf("failed to check availability zones: %w", err)
}

gitAuth, err := gitShim.ValidateGitCredentials(cliFlags.GitProvider, cliFlags.GithubOrg, cliFlags.GitlabGroup)
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to validate Git credentials", "error", err)
return fmt.Errorf("failed to validate Git credentials: %w", err)
}

Expand All @@ -105,13 +124,14 @@ func createAws(cmd *cobra.Command, _ []string) error {

err = gitShim.InitializeGitProvider(&initGitParameters)
if err != nil {
progress.Error(err.Error())
s.logger.Error("failed to initialize Git provider", "error", err)
return fmt.Errorf("failed to initialize Git provider: %w", err)
}
}

viper.Set(fmt.Sprintf("kubefirst-checks.%s-credentials", cliFlags.GitProvider), true)
if err := viper.WriteConfig(); err != nil {
s.logger.Error("failed to write config", "error", err)
return fmt.Errorf("failed to write config: %w", err)
}

Expand All @@ -124,12 +144,12 @@ func createAws(cmd *cobra.Command, _ []string) error {

err = pkg.IsAppAvailable(fmt.Sprintf("%s/api/proxyHealth", cluster.GetConsoleIngressURL()), "kubefirst api")
if err != nil {
progress.Error("unable to start kubefirst api")
s.logger.Error("failed to check kubefirst API availability", "error", err)
return fmt.Errorf("failed to check kubefirst API availability: %w", err)
}

if err := provision.CreateMgmtCluster(gitAuth, cliFlags, catalogApps); err != nil {
progress.Error(err.Error())
s.logger.Error("failed to create management cluster", "error", err)
return fmt.Errorf("failed to create management cluster: %w", err)
}

Expand Down
12 changes: 12 additions & 0 deletions cmd/aws/types.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package aws

import (
"io"

"github.com/konstructio/kubefirst/internal/common"
)

type AwsService struct {

Check failure on line 9 in cmd/aws/types.go

View workflow job for this annotation

GitHub Actions / build

exported: type name will be used as aws.AwsService by other packages, and that stutters; consider calling this Service (revive)
logger common.Logger
writer io.Writer
}
6 changes: 3 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import (

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
func Execute(logger common.Logger) {
// rootCmd represents the base command when called without any subcommands
rootCmd := &cobra.Command{
Use: "kubefirst",
Expand All @@ -48,15 +48,15 @@ func Execute() {
rootCmd.SetOut(os.Stdout)

rootCmd.AddCommand(
betaCmd,
aws.NewCommand(),
aws.NewCommand(logger, os.Stderr),
civo.NewCommand(),
digitalocean.NewCommand(),
k3d.NewCommand(),
k3d.LocalCommandAlias(),
LaunchCommand(),
LetsEncryptCommand(),
TerraformCommand(),
betaCmd,
infoCmd,
versionCmd,
resetCmd,
Expand Down
8 changes: 8 additions & 0 deletions internal/common/logger.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package common

type Logger interface {
Debug(msg string, args ...any)
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
Loading

0 comments on commit af8f242

Please sign in to comment.