Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: introduce slog for zarf tools #3212

Merged
merged 11 commits into from
Nov 21, 2024
97 changes: 45 additions & 52 deletions src/cmd/tools/crane.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package tools

import (
"context"
"errors"
"fmt"
"os"
Expand All @@ -20,7 +21,7 @@ import (
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/packager/images"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/types"
)
Expand All @@ -39,6 +40,11 @@ func init() {
Aliases: []string{"r", "crane"},
Short: lang.CmdToolsRegistryShort,
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
// TODO (@austinabro321) once the code in cmd is simplified, we should change this to respect
// the log-format flag
l := logger.Default()
ctx := logger.WithContext(cmd.Context(), l)
cmd.SetContext(ctx)
// The crane options loading here comes from the rootCmd of crane
craneOptions = append(craneOptions, crane.WithContext(cmd.Context()))
// TODO(jonjohnsonjr): crane.Verbose option?
Expand All @@ -51,7 +57,6 @@ func init() {
if ndlayers {
craneOptions = append(craneOptions, crane.WithNondistributable())
}

var err error
var v1Platform *v1.Platform
if platform != "all" {
Expand Down Expand Up @@ -111,19 +116,19 @@ func zarfCraneCatalog(cranePlatformOptions *[]crane.Option) *cobra.Command {
originalCatalogFn := craneCatalog.RunE

craneCatalog.RunE = func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
l := logger.From(cmd.Context())
if len(args) > 0 {
return originalCatalogFn(cmd, args)
}

message.Note(lang.CmdToolsRegistryZarfState)
l.Info("retrieving registry information from Zarf state")

c, err := cluster.NewCluster()
if err != nil {
return err
}

ctx := cmd.Context()

zarfState, err := c.LoadZarfState(ctx)
if err != nil {
return err
Expand All @@ -139,7 +144,6 @@ func zarfCraneCatalog(cranePlatformOptions *[]crane.Option) *cobra.Command {
*cranePlatformOptions = append(*cranePlatformOptions, authOption)

if tunnel != nil {
message.Notef(lang.CmdToolsRegistryTunnel, registryEndpoint, zarfState.RegistryInfo.Address)
defer tunnel.Close()
return tunnel.Wrap(func() error { return originalCatalogFn(cmd, []string{registryEndpoint}) })
}
Expand All @@ -160,6 +164,8 @@ func zarfCraneInternalWrapper(commandToWrap func(*[]crane.Option) *cobra.Command
originalListFn := wrappedCommand.RunE

wrappedCommand.RunE = func(cmd *cobra.Command, args []string) error {
ctx := cmd.Context()
l := logger.From(ctx)
if len(args) < imageNameArgumentIndex+1 {
return errors.New("not have enough arguments specified for this command")
}
Expand All @@ -170,13 +176,11 @@ func zarfCraneInternalWrapper(commandToWrap func(*[]crane.Option) *cobra.Command
return originalListFn(cmd, args)
}

message.Note(lang.CmdToolsRegistryZarfState)

ctx := cmd.Context()
l.Info("retrieving registry information from Zarf state")

zarfState, err := c.LoadZarfState(ctx)
if err != nil {
message.Warnf("could not get Zarf state from Kubernetes cluster, continuing without state information %s", err.Error())
l.Warn("could not get Zarf state from Kubernetes cluster, continuing without state information", "error", err.Error())
return originalListFn(cmd, args)
}

Expand All @@ -195,7 +199,7 @@ func zarfCraneInternalWrapper(commandToWrap func(*[]crane.Option) *cobra.Command
*cranePlatformOptions = append(*cranePlatformOptions, authOption)

if tunnel != nil {
message.Notef(lang.CmdToolsRegistryTunnel, tunnel.Endpoint(), zarfState.RegistryInfo.Address)
l.Info("opening a tunnel to the Zarf registry", "local-endpoint", tunnel.Endpoint(), "cluster-address", zarfState.RegistryInfo.Address)

defer tunnel.Close()

Expand All @@ -219,6 +223,7 @@ func pruneImages(cmd *cobra.Command, _ []string) error {
}

ctx := cmd.Context()
l := logger.From(ctx)

zarfState, err := c.LoadZarfState(ctx)
if err != nil {
Expand All @@ -237,19 +242,19 @@ func pruneImages(cmd *cobra.Command, _ []string) error {
}

if tunnel != nil {
message.Notef(lang.CmdToolsRegistryTunnel, registryEndpoint, zarfState.RegistryInfo.Address)
l.Info("opening a tunnel to the Zarf registry", "local-endpoint", tunnel.Endpoint(), "cluster-address", zarfState.RegistryInfo.Address)
defer tunnel.Close()
return tunnel.Wrap(func() error { return doPruneImagesForPackages(zarfState, zarfPackages, registryEndpoint) })
return tunnel.Wrap(func() error { return doPruneImagesForPackages(ctx, zarfState, zarfPackages, registryEndpoint) })
}

return doPruneImagesForPackages(zarfState, zarfPackages, registryEndpoint)
return doPruneImagesForPackages(ctx, zarfState, zarfPackages, registryEndpoint)
}

func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.DeployedPackage, registryEndpoint string) error {
func doPruneImagesForPackages(ctx context.Context, zarfState *types.ZarfState, zarfPackages []types.DeployedPackage, registryEndpoint string) error {
l := logger.From(ctx)
authOption := images.WithPushAuth(zarfState.RegistryInfo)

spinner := message.NewProgressSpinner(lang.CmdToolsRegistryPruneLookup)
defer spinner.Stop()
l.Info("finding images to prune")

// Determine which image digests are currently used by Zarf packages
pkgImages := map[string]bool{}
Expand Down Expand Up @@ -278,8 +283,6 @@ func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.D
}
}

spinner.Updatef(lang.CmdToolsRegistryPruneCatalog)

// Find which images and tags are in the registry currently
imageCatalog, err := crane.Catalog(registryEndpoint, authOption)
if err != nil {
Expand All @@ -302,8 +305,6 @@ func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.D
}
}

spinner.Updatef(lang.CmdToolsRegistryPruneCalculate)

// Figure out which images are in the registry but not needed by packages
imageDigestsToPrune := map[string]bool{}
for digestRef, digest := range referenceToDigest {
Expand All @@ -317,44 +318,36 @@ func doPruneImagesForPackages(zarfState *types.ZarfState, zarfPackages []types.D
}
}

spinner.Success()
if len(imageDigestsToPrune) == 0 {
l.Info("there are no images to prune")
return nil
}

if len(imageDigestsToPrune) > 0 {
message.Note(lang.CmdToolsRegistryPruneImageList)
l.Info("the following image digests will be pruned from the registry:")
for digestRef := range imageDigestsToPrune {
l.Info(digestRef)
}

for digestRef := range imageDigestsToPrune {
message.Info(digestRef)
confirm := config.CommonOptions.Confirm
if !confirm {
prompt := &survey.Confirm{
Message: "continue with image prune?",
}

confirm := config.CommonOptions.Confirm

if confirm {
message.Note(lang.CmdConfirmProvided)
} else {
prompt := &survey.Confirm{
Message: lang.CmdConfirmContinue,
}
if err := survey.AskOne(prompt, &confirm); err != nil {
return fmt.Errorf("confirm selection canceled: %w", err)
}
if err := survey.AskOne(prompt, &confirm); err != nil {
return fmt.Errorf("confirm selection canceled: %w", err)
}
if confirm {
spinner := message.NewProgressSpinner(lang.CmdToolsRegistryPruneDelete)
defer spinner.Stop()
}
if confirm {
l.Info("pruning images")

// Delete the digest references that are to be pruned
for digestRef := range imageDigestsToPrune {
err = crane.Delete(digestRef, authOption)
if err != nil {
return err
}
// Delete the digest references that are to be pruned
for digestRef := range imageDigestsToPrune {
err = crane.Delete(digestRef, authOption)
if err != nil {
return err
}

spinner.Success()
l.Debug("image pruned", "name", digestRef)
}
} else {
message.Note(lang.CmdToolsRegistryPruneNoImages)
}

return nil
}
2 changes: 2 additions & 0 deletions src/cmd/tools/helm.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package tools
import (
"os"

"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"

"github.com/zarf-dev/zarf/src/cmd/tools/helm"
Expand All @@ -29,6 +30,7 @@ func init() {
helmCmd, err := helm.NewRootCmd(actionConfig, os.Stdout, helmArgs)
if err != nil {
message.Debug("Failed to initialize helm command", "error", err)
logger.Default().Debug("failed to initialize helm command", "error", err)
}
helmCmd.Short = lang.CmdToolsHelmShort
helmCmd.Long = lang.CmdToolsHelmLong
Expand Down
2 changes: 2 additions & 0 deletions src/cmd/tools/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/spf13/cobra"
"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
kubeCLI "k8s.io/component-base/cli"
kubeCmd "k8s.io/kubectl/pkg/cmd"
Expand All @@ -33,6 +34,7 @@ func init() {
if err := kubeCLI.RunNoErrOutput(kubectlCmd); err != nil {
// @todo(jeff-mccoy) - Kubectl gets mad about being a subcommand.
message.Debug(err)
logger.Default().Debug(err.Error())
}
}

Expand Down
24 changes: 16 additions & 8 deletions src/cmd/tools/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"github.com/zarf-dev/zarf/src/internal/packager/helm"
"github.com/zarf-dev/zarf/src/internal/packager/template"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/packager/sources"
"github.com/zarf-dev/zarf/src/pkg/pki"
Expand Down Expand Up @@ -74,7 +75,7 @@ var getCredsCmd = &cobra.Command{

if len(args) > 0 {
// If a component name is provided, only show that component's credentials
message.PrintComponentCredential(state, args[0])
message.PrintComponentCredential(ctx, state, args[0])
} else {
message.PrintCredentialTable(state, nil)
}
Expand All @@ -101,6 +102,7 @@ var updateCredsCmd = &cobra.Command{
}

ctx := cmd.Context()
l := logger.From(ctx)

timeoutCtx, cancel := context.WithTimeout(ctx, cluster.DefaultTimeout)
defer cancel()
Expand All @@ -122,13 +124,11 @@ var updateCredsCmd = &cobra.Command{
return fmt.Errorf("unable to update Zarf credentials: %w", err)
}

message.PrintCredentialUpdates(oldState, newState, args)
message.PrintCredentialUpdates(ctx, oldState, newState, args)

confirm := config.CommonOptions.Confirm

if confirm {
message.Note(lang.CmdToolsUpdateCredsConfirmProvided)
} else {
if !confirm {
prompt := &survey.Confirm{
Message: lang.CmdToolsUpdateCredsConfirmContinue,
}
Expand Down Expand Up @@ -180,6 +180,7 @@ var updateCredsCmd = &cobra.Command{
if err != nil {
// Warn if we couldn't actually update the registry (it might not be installed and we should try to continue)
message.Warnf(lang.CmdToolsUpdateCredsUnableUpdateRegistry, err.Error())
l.Warn("unable to update Zarf Registry values", "error", err.Error())
}
}
if slices.Contains(args, message.GitKey) && newState.GitServer.IsInternal() && internalGitServerExists {
Expand All @@ -193,6 +194,7 @@ var updateCredsCmd = &cobra.Command{
if err != nil {
// Warn if we couldn't actually update the agent (it might not be installed and we should try to continue)
message.Warnf(lang.CmdToolsUpdateCredsUnableUpdateAgent, err.Error())
l.Warn("unable to update Zarf Agent TLS secrets", "error", err.Error())
}
}
}
Expand All @@ -204,12 +206,14 @@ var clearCacheCmd = &cobra.Command{
Use: "clear-cache",
Aliases: []string{"c"},
Short: lang.CmdToolsClearCacheShort,
RunE: func(_ *cobra.Command, _ []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
l := logger.From(cmd.Context())
cachePath, err := config.GetAbsCachePath()
if err != nil {
return err
}
message.Notef(lang.CmdToolsClearCacheDir, cachePath)
l.Info("clearing cache", "path", cachePath)
if err := os.RemoveAll(cachePath); err != nil {
return fmt.Errorf("unable to clear the cache directory %s: %w", cachePath, err)
}
Expand Down Expand Up @@ -242,7 +246,7 @@ var generatePKICmd = &cobra.Command{
Aliases: []string{"pki"},
Short: lang.CmdToolsGenPkiShort,
Args: cobra.ExactArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) error {
pki, err := pki.GeneratePKI(args[0], subAltNames...)
if err != nil {
return err
Expand All @@ -257,6 +261,7 @@ var generatePKICmd = &cobra.Command{
return err
}
message.Successf(lang.CmdToolsGenPkiSuccess, args[0])
logger.From(cmd.Context()).Info("successfully created a chain of trust", "host", args[0])
return nil
},
}
Expand All @@ -265,7 +270,7 @@ var generateKeyCmd = &cobra.Command{
Use: "gen-key",
Aliases: []string{"key"},
Short: lang.CmdToolsGenKeyShort,
RunE: func(_ *cobra.Command, _ []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
// Utility function to prompt the user for the password to the private key
passwordFunc := func(bool) ([]byte, error) {
// perform the first prompt
Expand Down Expand Up @@ -329,6 +334,9 @@ var generateKeyCmd = &cobra.Command{
}

message.Successf(lang.CmdToolsGenKeySuccess, prvKeyFileName, pubKeyFileName)
logger.From(cmd.Context()).Info("Successfully generated key pair",
"private-key-path", prvKeyExistsErr,
"public-key-path", pubKeyFileName)
return nil
},
}
Expand Down
4 changes: 0 additions & 4 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,6 @@ const (

// Zarf CLI commands.
const (
// common command language
CmdConfirmProvided = "Confirm flag specified, continuing without prompting."
CmdConfirmContinue = "Continue with these changes?"

// root zarf command
RootCmdShort = "DevSecOps for Airgap"
RootCmdLong = "Zarf eliminates the complexity of air gap software delivery for Kubernetes clusters and cloud native workloads\n" +
Expand Down
2 changes: 2 additions & 0 deletions src/internal/packager/helm/chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ func (h *Helm) RemoveChart(ctx context.Context, namespace string, name string, s
func (h *Helm) UpdateReleaseValues(ctx context.Context, updatedValues map[string]interface{}) error {
spinner := message.NewProgressSpinner("Updating values for helm release %s", h.chart.ReleaseName)
defer spinner.Stop()
l := logger.From(ctx)
l.Debug("updating values for helm release", "name", h.chart.ReleaseName)

err := h.createActionConfig(ctx, h.chart.Namespace, spinner)
if err != nil {
Expand Down
Loading