Skip to content

Commit

Permalink
refactor(cli): silence containercreation and rework logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Szilveszter committed Nov 16, 2022
1 parent 4243e59 commit b878212
Show file tree
Hide file tree
Showing 9 changed files with 88 additions and 118 deletions.
2 changes: 1 addition & 1 deletion golang/cmd/crane/crane.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func loadConfiguration() (*config.Configuration, error) {

commonConfig.InjectSecret(secret, &cfg.CommonConfiguration)

log.Print("Configuration loaded.")
log.Info().Msg("Configuration loaded.")
return cfg, nil
}

Expand Down
2 changes: 1 addition & 1 deletion golang/cmd/dagent/dagent.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@ func main() {
log.Panic().Err(err).Msg("failed to parse env GRPC_TOKEN")
}
commonConfig.InjectSecret(string(cfg.SecretPrivateKeyFile), &cfg.CommonConfiguration)
log.Print("Configuration loaded.")
log.Info().Msg("Configuration loaded.")
dagent.Serve(&cfg)
}
10 changes: 5 additions & 5 deletions golang/internal/config/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,15 @@ import (
)

func CheckGenerateKeys(secretPath string) (string, error) {
log.Printf("Checking key file: %v", secretPath)
log.Info().Msgf("Checking key file: %v", secretPath)
fileContent, err := os.ReadFile(secretPath) //#nosec G304 -- secret path comes from an env

if errors.Is(err, syscall.EISDIR) {
return "", fmt.Errorf("key path is a directory: %w", err)
}

if errors.Is(err, os.ErrNotExist) {
log.Printf("Key file does not exist: %v", secretPath)
log.Debug().Msgf("Key file does not exist: %v", secretPath)
return generateKey(secretPath)
} else if err != nil {
return "", fmt.Errorf("key file can't be read: %w", err)
Expand All @@ -44,12 +44,12 @@ func CheckGenerateKeys(secretPath string) (string, error) {

return keyStr, keyErr
}
log.Printf("Key file is expired: %v", secretPath)
log.Debug().Msgf("Key file is expired: %v", secretPath)
return generateKey(secretPath)
}

func GenerateKeyString() (string, error) {
log.Printf("Generating new key file...")
log.Info().Msgf("Generating new key file...")
const (
name = "dyrector.io agent"
email = "hello@dyrector.io"
Expand Down Expand Up @@ -78,7 +78,7 @@ func generateKey(secretPath string) (string, error) {
if fileErr != nil {
return "", fileErr
}
log.Printf("New key is generated and saved")
log.Info().Msgf("New key is generated and saved")

return keyStr, nil
}
Expand Down
5 changes: 3 additions & 2 deletions golang/pkg/builder/container/container_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"log"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
Expand All @@ -15,7 +16,6 @@ import (
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
"github.com/rs/zerolog/log"

dockerHelper "github.com/dyrector-io/dyrectorio/golang/internal/helper/docker"
)
Expand Down Expand Up @@ -481,7 +481,8 @@ func attachNetworks(dc *DockerContainerBuilder) {
Aliases: dc.networkAliases,
}

if err := dc.client.NetworkConnect(dc.ctx, networkID, *dc.containerID, endpointSettings); err != nil {
err := dc.client.NetworkConnect(dc.ctx, networkID, *dc.containerID, endpointSettings)
if err != nil {
logWrite(dc, fmt.Sprintln("Container network attach error: ", err))
}
}
Expand Down
9 changes: 4 additions & 5 deletions golang/pkg/builder/container/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ import (
"errors"
"fmt"
"io"
"log"
"time"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/client"
"github.com/rs/zerolog/log"
)

func registryAuthBase64(user, password string) string {
Expand All @@ -26,7 +26,7 @@ func registryAuthBase64(user, password string) string {
}
encodedJSON, err := json.Marshal(authConfig)
if err != nil {
log.Error().Stack().Err(err).Send()
log.Println(err)
return ""
}
return base64.URLEncoding.EncodeToString(encodedJSON)
Expand Down Expand Up @@ -112,7 +112,7 @@ func pullImage(ctx context.Context, logger io.StringWriter, fullyQualifiedImageN
err = nil
break
} else if err != nil {
log.Error().Stack().Err(err).Msg("decode error")
log.Println("decode error: " + err.Error())
break
}

Expand Down Expand Up @@ -144,7 +144,6 @@ type defaultLogger struct {
}

func (logger *defaultLogger) WriteString(s string) (int, error) {
//nolint
fmt.Println(s)
fmt.Println(s) //nolint
return len(s), nil
}
12 changes: 12 additions & 0 deletions golang/pkg/cli/cli.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"github.com/rs/zerolog"
ucli "github.com/urfave/cli/v2"

"github.com/dyrector-io/dyrectorio/golang/internal/version"
Expand Down Expand Up @@ -51,6 +52,12 @@ func InitCLI() *ucli.App {
Usage: "enables writing configuration, storing current state",
Required: false,
},
&ucli.BoolFlag{
Name: "debug",
Value: false,
Usage: "enables debug messages",
Required: false,
},
&ucli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Expand All @@ -64,6 +71,11 @@ func InitCLI() *ucli.App {
}

func run(cCtx *ucli.Context) error {
zerolog.SetGlobalLevel(zerolog.InfoLevel)
if cCtx.Bool("debug") {
zerolog.SetGlobalLevel(zerolog.DebugLevel)
}

state := Settings{
SettingsWrite: cCtx.Bool("write"),
SettingsFilePath: SettingsFileLocation(cCtx.String("config")),
Expand Down
35 changes: 21 additions & 14 deletions golang/pkg/cli/config_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -273,16 +273,6 @@ func PodmanInfo() {
}

func DisabledServiceSettings(settings *Settings) *Settings {
if settings.Containers.Crux.Disabled && settings.Command == UpCommand {
// TODO(c3ppc3pp): log these at the end of the executable. also we should print out the mailslurper address
log.Info().Msg("Do not forget to add your DATABASE_URL to your crux environment.")
log.Info().Msgf("DATABASE_URL=postgresql://%s:%s@localhost:%d/%s?schema=public",
settings.SettingsFile.CruxPostgresUser,
settings.SettingsFile.CruxPostgresPassword,
settings.SettingsFile.CruxPostgresPort,
settings.SettingsFile.CruxPostgresDB)
}

if settings.Containers.CruxUI.Disabled {
settings.CruxUI.CruxAddr = "localhost"
} else {
Expand All @@ -294,26 +284,43 @@ func DisabledServiceSettings(settings *Settings) *Settings {

func PrintInfo(settings *Settings) {
log.Warn().Msg("🦩🦩🦩 Use the CLI tool only for NON-PRODUCTION purpose. 🦩🦩🦩")
log.Info().Str("path", settings.SettingsFilePath).Msg("Platform configuration file location")

if settings.Containers.Crux.Disabled {
log.Info().Msg("Do not forget to add your environmental variables to your .env files or export them!")
log.Info().Msgf("DATABASE_URL=postgresql://%s:%s@localhost:%d/%s?schema=public",
settings.SettingsFile.CruxPostgresUser,
settings.SettingsFile.CruxPostgresPassword,
settings.SettingsFile.CruxPostgresPort,
settings.SettingsFile.CruxPostgresDB)
}

log.Info().Msgf("Stack is ready. The UI should be available at http://localhost:%d location.",
settings.SettingsFile.Options.TraefikWebPort)
log.Info().Msgf("The e-mail service should be available at http://localhost:%d location.",
settings.SettingsFile.Options.MailSlurperWebPort)
log.Info().Msg("Happy deploying! 🎬")
}

// Save the settings
func SaveSettings(settings *Settings) {
if settings.SettingsWrite {
userConfDir, _ := os.UserConfigDir()
userConfDir, err := os.UserConfigDir()
if err != nil {
log.Fatal().Err(err).Stack().Send()
}
settingspath := fmt.Sprintf("%s/%s/%s", userConfDir, SettingsFileDir, SettingsFileName)

// If settingspath is default, we create the directory for it
if settings.SettingsFilePath == settingspath {
if _, err := os.Stat(userConfDir); errors.Is(err, os.ErrNotExist) {
if _, err = os.Stat(userConfDir); errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(userConfDir, DirPerms)
if err != nil {
log.Fatal().Err(err).Stack().Send()
}
} else if err != nil {
log.Fatal().Err(err).Stack().Send()
}
if _, err := os.Stat(filepath.Dir(settingspath)); errors.Is(err, os.ErrNotExist) {
if _, err = os.Stat(filepath.Dir(settingspath)); errors.Is(err, os.ErrNotExist) {
err = os.Mkdir(filepath.Dir(settingspath), DirPerms)
if err != nil {
log.Fatal().Err(err).Stack().Send()
Expand Down
8 changes: 8 additions & 0 deletions golang/pkg/cli/container_defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const (
func GetCrux(settings *Settings) *containerbuilder.DockerContainerBuilder {
crux := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(fmt.Sprintf("%s:%s", settings.Crux.Image, settings.SettingsFile.Version)).
WithLogWriter(nil).
WithName(settings.Containers.Crux.Name).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
WithoutConflict().
Expand Down Expand Up @@ -80,6 +81,7 @@ func GetCrux(settings *Settings) *containerbuilder.DockerContainerBuilder {
func GetCruxMigrate(settings *Settings) *containerbuilder.DockerContainerBuilder {
cruxMigrate := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(fmt.Sprintf("%s:%s", settings.Crux.Image, settings.SettingsFile.Version)).
WithLogWriter(nil).
WithName(settings.Containers.CruxMigrate.Name).
WithoutConflict().
WithForcePullImage().
Expand Down Expand Up @@ -107,6 +109,7 @@ func GetCruxUI(settings *Settings) *containerbuilder.DockerContainerBuilder {

cruxUI := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(fmt.Sprintf("%s:%s", settings.CruxUI.Image, settings.SettingsFile.Version)).
WithLogWriter(nil).
WithName(settings.Containers.CruxUI.Name).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
WithoutConflict().
Expand Down Expand Up @@ -177,6 +180,7 @@ func GetTraefik(settings *Settings) *containerbuilder.DockerContainerBuilder {

traefik := containerbuilder.NewDockerBuilder(context.Background()).
WithImage("docker.io/library/traefik:v2.8.8").
WithLogWriter(nil).
WithName(settings.Containers.Traefik.Name).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
WithoutConflict().
Expand Down Expand Up @@ -206,6 +210,7 @@ func GetTraefik(settings *Settings) *containerbuilder.DockerContainerBuilder {
func GetKratos(settings *Settings) *containerbuilder.DockerContainerBuilder {
kratos := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(fmt.Sprintf("%s:%s", settings.Kratos.Image, settings.SettingsFile.Version)).
WithLogWriter(nil).
WithName(settings.Containers.Kratos.Name).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
WithoutConflict().
Expand Down Expand Up @@ -265,6 +270,7 @@ func GetKratos(settings *Settings) *containerbuilder.DockerContainerBuilder {
func GetKratosMigrate(settings *Settings) *containerbuilder.DockerContainerBuilder {
kratosMigrate := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(fmt.Sprintf("%s:%s", settings.Kratos.Image, settings.SettingsFile.Version)).
WithLogWriter(nil).
WithName(settings.Containers.KratosMigrate.Name).
WithoutConflict().
WithForcePullImage().
Expand All @@ -288,6 +294,7 @@ func GetKratosMigrate(settings *Settings) *containerbuilder.DockerContainerBuild
func GetMailSlurper(settings *Settings) *containerbuilder.DockerContainerBuilder {
mailslurper := containerbuilder.NewDockerBuilder(context.Background()).
WithImage(MailSlurperImage).
WithLogWriter(nil).
WithName(settings.Containers.MailSlurper.Name).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
WithoutConflict().
Expand Down Expand Up @@ -367,6 +374,7 @@ func GetKratosPostgres(settings *Settings) *containerbuilder.DockerContainerBuil
func GetBasePostgres(settings *Settings) *containerbuilder.DockerContainerBuilder {
basePostgres := containerbuilder.
NewDockerBuilder(context.Background()).
WithLogWriter(nil).
WithImage(PostgresImage).
WithNetworks([]string{settings.SettingsFile.Network}).
WithRestartPolicy(containerbuilder.AlwaysRestartPolicy).
Expand Down
Loading

0 comments on commit b878212

Please sign in to comment.