Skip to content

Commit

Permalink
refactor: replace message.Debug with context logger
Browse files Browse the repository at this point in the history
Signed-off-by: Philip Laine <philip.laine@gmail.com>
  • Loading branch information
phillebaba committed Aug 7, 2024
1 parent e9c756b commit 3ed9004
Show file tree
Hide file tree
Showing 46 changed files with 277 additions and 158 deletions.
8 changes: 4 additions & 4 deletions src/cmd/dev.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ var devDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -78,7 +78,7 @@ var devGenerateCmd = &cobra.Command{
pkgConfig.CreateOpts.BaseDir = "."
pkgConfig.FindImagesOpts.RepoHelmChartPath = pkgConfig.GenerateOpts.GitPath

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -229,7 +229,7 @@ var devFindImagesCmd = &cobra.Command{
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -276,7 +276,7 @@ var devLintCmd = &cobra.Command{
pkgConfig.CreateOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ var initCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down
23 changes: 12 additions & 11 deletions src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (

"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/packager/sources"
"github.com/zarf-dev/zarf/src/types"
Expand Down Expand Up @@ -54,7 +55,7 @@ var packageCreateCmd = &cobra.Command{
pkgConfig.CreateOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgCreateSet), pkgConfig.CreateOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -84,7 +85,7 @@ var packageDeployCmd = &cobra.Command{
pkgConfig.PkgOpts.SetVariables = helpers.TransformAndMergeMap(
v.GetStringMapString(common.VPkgDeploySet), pkgConfig.PkgOpts.SetVariables, strings.ToUpper)

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -112,7 +113,7 @@ var packageMirrorCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -136,11 +137,11 @@ var packageInspectCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
src, err := identifyAndFallbackToClusterSource()
src, err := identifyAndFallbackToClusterSource(cmd.Context())
if err != nil {
return err
}
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down Expand Up @@ -208,11 +209,11 @@ var packageRemoveCmd = &cobra.Command{
return err
}
pkgConfig.PkgOpts.PackageSource = packageSource
src, err := identifyAndFallbackToClusterSource()
src, err := identifyAndFallbackToClusterSource(cmd.Context())
if err != nil {
return err
}
pkgClient, err := packager.New(&pkgConfig, packager.WithSource(src))
pkgClient, err := packager.New(cmd.Context(), &pkgConfig, packager.WithSource(src))
if err != nil {
return err
}
Expand Down Expand Up @@ -253,7 +254,7 @@ var packagePublishCmd = &cobra.Command{

pkgConfig.PublishOpts.PackageDestination = ref.String()

pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand All @@ -273,7 +274,7 @@ var packagePullCmd = &cobra.Command{
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
pkgConfig.PkgOpts.PackageSource = args[0]
pkgClient, err := packager.New(&pkgConfig)
pkgClient, err := packager.New(cmd.Context(), &pkgConfig)
if err != nil {
return err
}
Expand Down Expand Up @@ -311,10 +312,10 @@ func choosePackage(args []string) (string, error) {
}

// TODO: This code does not seem to do what it was intended.
func identifyAndFallbackToClusterSource() (sources.PackageSource, error) {
func identifyAndFallbackToClusterSource(ctx context.Context) (sources.PackageSource, error) {
identifiedSrc := sources.Identify(pkgConfig.PkgOpts.PackageSource)
if identifiedSrc == "" {
message.Debugf(lang.CmdPackageClusterSourceFallback, pkgConfig.PkgOpts.PackageSource)
logging.FromContextOrDiscard(ctx).Debug("package source does not satisfy any current sources, assuming it is a package deployed to a cluster", "source", pkgConfig.PkgOpts.PackageSource)
src, err := sources.NewClusterSource(&pkgConfig.PkgOpts)
if err != nil {
return nil, fmt.Errorf("unable to identify source from %s: %w", pkgConfig.PkgOpts.PackageSource, err)
Expand Down
6 changes: 6 additions & 0 deletions src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package cmd
import (
"context"
"fmt"
"log/slog"
"os"
"slices"
"strings"
Expand All @@ -19,6 +20,7 @@ import (
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/layout"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/types"
)
Expand Down Expand Up @@ -87,6 +89,10 @@ var rootCmd = &cobra.Command{

// Execute is the entrypoint for the CLI.
func Execute(ctx context.Context) {
handler := logging.NewPtermHandler()
log := slog.New(handler)
ctx = logging.NewContext(ctx, log)

cmd, err := rootCmd.ExecuteContextC(ctx)
if err == nil {
return
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/tools/wait.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var waitForCmd = &cobra.Command{
Long: lang.CmdToolsWaitForLong,
Example: lang.CmdToolsWaitForExample,
Args: cobra.MinimumNArgs(1),
RunE: func(_ *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, args []string) error {
// Parse the timeout string
timeout, err := time.ParseDuration(waitTimeout)
if err != nil {
Expand All @@ -51,7 +51,7 @@ var waitForCmd = &cobra.Command{
}

// Execute the wait command.
if err := utils.ExecuteWait(waitTimeout, waitNamespace, condition, kind, identifier, timeout); err != nil {
if err := utils.ExecuteWait(cmd.Context(), waitTimeout, waitNamespace, condition, kind, identifier, timeout); err != nil {
return err
}
return err
Expand Down
5 changes: 2 additions & 3 deletions src/config/lang/english.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,9 +314,8 @@ $ zarf package pull oci://ghcr.io/defenseunicorns/packages/dos-games:1.0.0 -a ar
$ zarf package pull oci://ghcr.io/defenseunicorns/packages/dos-games:1.0.0 -a skeleton`
CmdPackagePullFlagOutputDirectory = "Specify the output directory for the pulled Zarf package"

CmdPackageChoose = "Choose or type the package file"
CmdPackageClusterSourceFallback = "%q does not satisfy any current sources, assuming it is a package deployed to a cluster"
CmdPackageInvalidSource = "Unable to identify source from %q: %s"
CmdPackageChoose = "Choose or type the package file"
CmdPackageInvalidSource = "Unable to identify source from %q: %s"

// zarf dev (prepare is an alias for dev)
CmdDevShort = "Commands useful for developing packages"
Expand Down
4 changes: 0 additions & 4 deletions src/internal/agent/hooks/argocd-application.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/agent/operations"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/types"
v1 "k8s.io/api/admission/v1"
Expand Down Expand Up @@ -65,8 +64,6 @@ func mutateApplication(ctx context.Context, r *v1.AdmissionRequest, cluster *clu
return nil, err
}

message.Debugf("Using the url of (%s) to mutate the ArgoCD Application", state.GitServer.Address)

app := Application{}
if err = json.Unmarshal(r.Object.Raw, &app); err != nil {
return nil, fmt.Errorf(lang.ErrUnmarshal, err)
Expand Down Expand Up @@ -125,7 +122,6 @@ func getPatchedRepoURL(repoURL string, gs types.GitServerInfo, r *v1.AdmissionRe
return "", fmt.Errorf("%s: %w", AgentErrTransformGitURL, err)
}
patchedURL = transformedURL.String()
message.Debugf("original repoURL of (%s) got mutated to (%s)", repoURL, patchedURL)
}

return patchedURL, nil
Expand Down
1 change: 0 additions & 1 deletion src/internal/agent/hooks/argocd-repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,6 @@ func mutateRepositorySecret(ctx context.Context, r *v1.AdmissionRequest, cluster
return nil, fmt.Errorf("unable the git url: %w", err)
}
patchedURL = transformedURL.String()
message.Debugf("original url of (%s) got mutated to (%s)", repoCreds.URL, patchedURL)
}

patches := populateArgoRepositoryPatchOperations(patchedURL, state.GitServer)
Expand Down
4 changes: 0 additions & 4 deletions src/internal/agent/hooks/flux-gitrepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/internal/agent/operations"
"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/transform"
v1 "k8s.io/api/admission/v1"
)
Expand Down Expand Up @@ -51,8 +50,6 @@ func mutateGitRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster
return nil, err
}

message.Debugf("Using the url of (%s) to mutate the flux repository", state.GitServer.Address)

repo := flux.GitRepository{}
if err = json.Unmarshal(r.Object.Raw, &repo); err != nil {
return nil, fmt.Errorf(lang.ErrUnmarshal, err)
Expand All @@ -78,7 +75,6 @@ func mutateGitRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster
return nil, fmt.Errorf("%s: %w", AgentErrTransformGitURL, err)
}
patchedURL = transformedURL.String()
message.Debugf("original git URL of (%s) got mutated to (%s)", repo.Spec.URL, patchedURL)
}

// Patch updates of the repo spec
Expand Down
4 changes: 0 additions & 4 deletions src/internal/agent/hooks/flux-helmrepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,6 @@ func mutateHelmRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluste
return nil, err
}

message.Debugf("Using the url of (%s) to mutate the flux HelmRepository", registryAddress)

patchedSrc, err := transform.ImageTransformHost(registryAddress, src.Spec.URL)
if err != nil {
return nil, fmt.Errorf("unable to transform the HelmRepo URL: %w", err)
Expand All @@ -78,8 +76,6 @@ func mutateHelmRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluste
}
patchedURL := helpers.OCIURLPrefix + patchedRefInfo.Name

message.Debugf("original HelmRepo URL of (%s) got mutated to (%s)", src.Spec.URL, patchedURL)

patches := populateHelmRepoPatchOperations(patchedURL, zarfState.RegistryInfo.IsInternal())

patches = append(patches, getLabelPatch(src.Labels))
Expand Down
6 changes: 1 addition & 5 deletions src/internal/agent/hooks/flux-ocirepo.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func mutateOCIRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster
src.Spec.Reference = &flux.OCIRepositoryRef{}
}

// If we have a semver we want to continue since we wil still have the upstream tag
// If we have a semver we want to continue since we will still have the upstream tag
// but should warn that we can't guarantee there won't be collisions
if src.Spec.Reference.SemVer != "" {
message.Warnf(lang.AgentWarnSemVerRef, src.Spec.Reference.SemVer)
Expand All @@ -69,8 +69,6 @@ func mutateOCIRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster
}

// For the internal registry this will be the ip & port of the service, it may look like 10.43.36.151:5000
message.Debugf("Using the url of (%s) to mutate the flux OCIRepository", registryAddress)

ref := src.Spec.URL
if src.Spec.Reference.Digest != "" {
ref = fmt.Sprintf("%s@%s", ref, src.Spec.Reference.Digest)
Expand All @@ -97,8 +95,6 @@ func mutateOCIRepo(ctx context.Context, r *v1.AdmissionRequest, cluster *cluster
patchedRef.Tag = patchedRefInfo.Tag
}

message.Debugf("original OCIRepo URL of (%s) got mutated to (%s)", src.Spec.URL, patchedURL)

patches := populateOCIRepoPatchOperations(patchedURL, zarfState.RegistryInfo.IsInternal(), patchedRef)

patches = append(patches, getLabelPatch(src.Labels))
Expand Down
11 changes: 7 additions & 4 deletions src/internal/agent/http/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package http

import (
"context"
"crypto/tls"
"fmt"
"io"
Expand All @@ -14,25 +15,27 @@ import (
"strings"

"github.com/zarf-dev/zarf/src/pkg/cluster"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/types"
)

// ProxyHandler constructs a new httputil.ReverseProxy and returns an http handler.
func ProxyHandler(cluster *cluster.Cluster) http.HandlerFunc {
func ProxyHandler(ctx context.Context, cluster *cluster.Cluster) http.HandlerFunc {
log := logging.FromContextOrDiscard(ctx)

return func(w http.ResponseWriter, r *http.Request) {
state, err := cluster.LoadZarfState(r.Context())
if err != nil {
message.Debugf("%#v", err)
log.Debug("load zarf state failed", "error", err)
w.WriteHeader(http.StatusInternalServerError)
//nolint: errcheck // ignore
w.Write([]byte("unable to load Zarf state, see the Zarf HTTP proxy logs for more details"))
return
}
err = proxyRequestTransform(r, state)
if err != nil {
message.Debugf("%#v", err)
log.Debug("proxy request transporm failed", "error", err)
w.WriteHeader(http.StatusInternalServerError)
//nolint: errcheck // ignore
w.Write([]byte("unable to transform the provided request, see the Zarf HTTP proxy logs for more details"))
Expand Down
2 changes: 1 addition & 1 deletion src/internal/agent/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func StartWebhook(ctx context.Context, cluster *cluster.Cluster) error {
// StartHTTPProxy launches the zarf agent proxy in the cluster.
func StartHTTPProxy(ctx context.Context, cluster *cluster.Cluster) error {
mux := http.NewServeMux()
mux.Handle("/", agentHttp.ProxyHandler(cluster))
mux.Handle("/", agentHttp.ProxyHandler(ctx, cluster))
return startServer(ctx, httpPort, mux)
}

Expand Down
11 changes: 7 additions & 4 deletions src/internal/git/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"

"github.com/zarf-dev/zarf/src/pkg/logging"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/pkg/transform"
"github.com/zarf-dev/zarf/src/pkg/utils"
Expand Down Expand Up @@ -146,6 +147,8 @@ func (r *Repository) Path() string {

// Push pushes the repository to the remote git server.
func (r *Repository) Push(ctx context.Context, address, username, password string) error {
log := logging.FromContextOrDiscard(ctx)

repo, err := git.PlainOpen(r.path)
if err != nil {
return fmt.Errorf("not a valid git repo or unable to open: %w", err)
Expand Down Expand Up @@ -194,11 +197,11 @@ func (r *Repository) Push(ctx context.Context, address, username, password strin
}
err = repo.FetchContext(ctx, fetchOptions)
if errors.Is(err, transport.ErrRepositoryNotFound) {
message.Debugf("Repo not yet available offline, skipping fetch...")
log.Debug("repository not yet available offling, skipping fetch")
} else if errors.Is(err, git.ErrForceNeeded) {
message.Debugf("Repo fetch requires force, skipping fetch...")
log.Debug("repositoy fetch requires force, skipping fetch")
} else if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debugf("Repo already up-to-date, skipping fetch...")
log.Debug("repository already update-to date, skipping fetch")
} else if err != nil {
return fmt.Errorf("unable to fetch the git repo prior to push: %w", err)
}
Expand All @@ -216,7 +219,7 @@ func (r *Repository) Push(ctx context.Context, address, username, password strin
},
})
if errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debug("Repo already up-to-date")
logging.FromContextOrDiscard(ctx).Debug("Repository already up-to-date")
} else if errors.Is(err, plumbing.ErrObjectNotFound) {
return fmt.Errorf("unable to push repo due to likely shallow clone: %s", err.Error())
} else if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions src/internal/packager/helm/chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -195,8 +195,7 @@ func (h *Helm) RemoveChart(namespace string, name string, spinner *message.Spinn
// Establish a new actionConfig for the namespace.
_ = h.createActionConfig(namespace, spinner)
// Perform the uninstall.
response, err := h.uninstallChart(name)
message.Debug(response)
_, err := h.uninstallChart(name)
return err
}

Expand Down
Loading

0 comments on commit 3ed9004

Please sign in to comment.