From e26e868db0e96fd76c26b35d196c188ece5e90e6 Mon Sep 17 00:00:00 2001 From: Marlon Gamez Date: Mon, 16 Aug 2021 15:51:28 -0700 Subject: [PATCH] Change `logrus` calls in `pkg/` and `cmd/` to use `log.Entry(ctx)` (#6419) * helper function and context setting * update logrus calls to use log.Entry() * fix imports in integration/ * revert unneeded changes * revert more unnecessary changes * fix wrapper_windows.go --- cmd/skaffold/app/cmd/cmd.go | 23 +++---- cmd/skaffold/app/cmd/config/util.go | 12 ++-- cmd/skaffold/app/cmd/dev.go | 6 +- cmd/skaffold/app/cmd/flags.go | 5 +- cmd/skaffold/app/cmd/runner.go | 7 +- cmd/skaffold/app/skaffold.go | 4 +- cmd/skaffold/skaffold.go | 7 +- hack/versions/pkg/schema/check.go | 2 +- pkg/diag/validator/pod.go | 22 +++---- pkg/skaffold/build/bazel/dependencies.go | 7 +- pkg/skaffold/build/build_problems.go | 10 +-- pkg/skaffold/build/builder_mux.go | 11 ++-- pkg/skaffold/build/buildpacks/lifecycle.go | 10 +-- pkg/skaffold/build/cache/cache.go | 6 +- pkg/skaffold/build/cache/hash.go | 5 +- pkg/skaffold/build/cache/lookup.go | 11 ++-- pkg/skaffold/build/cache/retrieve.go | 11 ++-- pkg/skaffold/build/cluster/kaniko.go | 4 +- pkg/skaffold/build/cluster/logs.go | 3 +- pkg/skaffold/build/cluster/pod.go | 5 +- pkg/skaffold/build/cluster/secret.go | 10 +-- pkg/skaffold/build/custom/script.go | 5 +- pkg/skaffold/build/gcb/buildpacks.go | 5 +- pkg/skaffold/build/gcb/cloud_build.go | 16 ++--- pkg/skaffold/build/jib/errors.go | 6 +- pkg/skaffold/build/jib/gradle.go | 7 +- pkg/skaffold/build/jib/init.go | 8 +-- pkg/skaffold/build/jib/jib.go | 6 +- pkg/skaffold/build/jib/jvm.go | 6 +- pkg/skaffold/build/jib/maven.go | 7 +- pkg/skaffold/build/jib/sync.go | 5 +- pkg/skaffold/build/local/local.go | 5 +- pkg/skaffold/build/local/prune.go | 24 +++---- pkg/skaffold/build/local/types.go | 7 +- pkg/skaffold/build/misc/graceful.go | 6 +- pkg/skaffold/build/result.go | 5 +- pkg/skaffold/build/scheduler.go | 2 +- pkg/skaffold/cluster/minikube.go | 21 +++--- pkg/skaffold/config/portforward.go | 6 +- pkg/skaffold/config/util.go | 21 +++--- pkg/skaffold/constants/constants.go | 4 ++ pkg/skaffold/debug/apply_transforms.go | 13 ++-- pkg/skaffold/debug/cnb.go | 5 +- pkg/skaffold/debug/transform.go | 31 ++++----- pkg/skaffold/debug/transform_go.go | 9 +-- pkg/skaffold/debug/transform_jvm.go | 5 +- pkg/skaffold/debug/transform_netcore.go | 5 +- pkg/skaffold/debug/transform_nodejs.go | 9 +-- pkg/skaffold/debug/transform_python.go | 13 ++-- pkg/skaffold/deploy/deploy_mux.go | 2 +- pkg/skaffold/deploy/docker/deploy.go | 8 +-- pkg/skaffold/deploy/docker/port.go | 4 +- pkg/skaffold/deploy/helm/args.go | 5 +- pkg/skaffold/deploy/helm/deploy.go | 16 ++--- pkg/skaffold/deploy/helm/parse.go | 11 ++-- pkg/skaffold/deploy/helm/util.go | 4 +- pkg/skaffold/deploy/kpt/kpt.go | 4 +- pkg/skaffold/deploy/kubectl/cli.go | 7 +- pkg/skaffold/deploy/kubectl/kubectl.go | 8 +-- pkg/skaffold/deploy/kustomize/kustomize.go | 4 +- pkg/skaffold/deploy/label/labels.go | 8 +-- pkg/skaffold/docker/auth.go | 6 +- pkg/skaffold/docker/build_args.go | 6 +- pkg/skaffold/docker/client.go | 8 +-- pkg/skaffold/docker/docker_init.go | 5 +- pkg/skaffold/docker/image.go | 16 ++--- pkg/skaffold/docker/image_util.go | 5 +- pkg/skaffold/docker/logger/log.go | 7 +- pkg/skaffold/docker/parse.go | 12 ++-- pkg/skaffold/docker/remote.go | 7 +- pkg/skaffold/event/v2/event.go | 2 - pkg/skaffold/filemon/changes.go | 11 ++-- pkg/skaffold/gcp/auth.go | 16 ++--- pkg/skaffold/hooks/host.go | 7 +- pkg/skaffold/initializer/analyze/analyze.go | 5 +- pkg/skaffold/initializer/config.go | 6 +- pkg/skaffold/initializer/deploy/kustomize.go | 6 +- pkg/skaffold/initializer/kompose.go | 5 +- .../init/microservices/leeroy-web/web.go | 3 +- .../testdata/init/windows/apps/web/web.go | 3 +- pkg/skaffold/instrumentation/export.go | 22 +++---- pkg/skaffold/instrumentation/new.go | 7 +- pkg/skaffold/instrumentation/trace.go | 5 +- pkg/skaffold/instrumentation/types.go | 6 +- pkg/skaffold/kubernetes/context/context.go | 10 +-- .../kubernetes/debugging/container_manager.go | 4 +- pkg/skaffold/kubernetes/logger/log.go | 8 +-- pkg/skaffold/kubernetes/manifest/images.go | 11 ++-- pkg/skaffold/kubernetes/manifest/labels.go | 6 +- pkg/skaffold/kubernetes/owner.go | 4 +- .../kubernetes/portforward/entry_manager.go | 2 +- .../portforward/forwarder_manager.go | 8 +-- .../portforward/kubectl_forwarder.go | 31 ++++----- .../kubernetes/portforward/pod_forwarder.go | 4 +- .../portforward/port_forward_integration.go | 6 +- .../portforward/resource_forwarder.go | 4 +- .../kubernetes/status/resource/deployment.go | 7 +- .../kubernetes/status/status_check.go | 8 +-- pkg/skaffold/kubernetes/util.go | 5 +- pkg/skaffold/kubernetes/wait.go | 9 +-- pkg/skaffold/kubernetes/watcher.go | 4 +- pkg/skaffold/log/stream/stream.go | 5 +- pkg/skaffold/output/color.go | 5 +- pkg/skaffold/output/log/log.go | 53 +++++++++++++++ pkg/skaffold/output/log/log_test.go | 66 +++++++++++++++++++ pkg/skaffold/output/output.go | 34 +++------- pkg/skaffold/output/output_test.go | 36 +--------- pkg/skaffold/parser/config.go | 12 ++-- pkg/skaffold/render/generate/generate.go | 7 +- pkg/skaffold/render/renderer/renderer.go | 4 +- pkg/skaffold/runner/build.go | 13 ++-- pkg/skaffold/runner/builder.go | 10 +-- pkg/skaffold/runner/listen.go | 7 +- pkg/skaffold/runner/runcontext/context.go | 7 +- pkg/skaffold/runner/timings.go | 13 ++-- pkg/skaffold/runner/v1/deploy.go | 9 ++- pkg/skaffold/runner/v1/dev.go | 29 ++++---- pkg/skaffold/runner/v1/new.go | 11 ++-- pkg/skaffold/schema/defaults/defaults.go | 7 +- pkg/skaffold/schema/profiles.go | 11 ++-- pkg/skaffold/schema/v1alpha1/upgrade.go | 5 +- pkg/skaffold/schema/v1beta9/upgrade.go | 6 +- pkg/skaffold/schema/v2beta16/upgrade.go | 5 +- pkg/skaffold/schema/validation/validation.go | 4 +- pkg/skaffold/schema/versions.go | 5 +- pkg/skaffold/server/server.go | 12 ++-- pkg/skaffold/survey/survey.go | 6 +- pkg/skaffold/sync/docker.go | 7 +- pkg/skaffold/sync/sync.go | 14 ++-- pkg/skaffold/tag/custom_template.go | 6 +- pkg/skaffold/tag/git_commit.go | 6 +- pkg/skaffold/tag/input_digest.go | 5 +- pkg/skaffold/tags/paths.go | 9 +-- pkg/skaffold/test/structure/structure.go | 5 +- pkg/skaffold/timeutil/util.go | 5 +- pkg/skaffold/trigger/fsnotify/trigger.go | 4 +- pkg/skaffold/trigger/triggers.go | 7 +- pkg/skaffold/update/update.go | 7 +- pkg/skaffold/util/cmd.go | 11 ++-- pkg/skaffold/util/config.go | 7 +- pkg/skaffold/util/env_template.go | 5 +- pkg/skaffold/util/gsutil.go | 4 +- pkg/skaffold/util/port.go | 25 +++---- pkg/skaffold/util/regex.go | 5 +- pkg/skaffold/util/tar.go | 6 +- pkg/skaffold/util/util.go | 6 +- pkg/skaffold/util/wrapper_unix.go | 4 +- pkg/skaffold/yamltags/tags.go | 10 +-- 148 files changed, 729 insertions(+), 642 deletions(-) create mode 100644 pkg/skaffold/output/log/log.go create mode 100644 pkg/skaffold/output/log/log_test.go diff --git a/cmd/skaffold/app/cmd/cmd.go b/cmd/skaffold/app/cmd/cmd.go index 7efea94f357..99574776d6b 100644 --- a/cmd/skaffold/app/cmd/cmd.go +++ b/cmd/skaffold/app/cmd/cmd.go @@ -36,6 +36,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation/prompt" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/server" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/survey" @@ -107,9 +108,9 @@ func NewSkaffoldCommand(out, errOut io.Writer) *cobra.Command { // Print version versionInfo := version.Get() version.SetClient(opts.User) - logrus.Infof("Skaffold %+v", versionInfo) + log.Entry(context.Background()).Infof("Skaffold %+v", versionInfo) if !isHouseKeepingMessagesAllowed(cmd) { - logrus.Debugf("Disable housekeeping messages for command explicitly") + log.Entry(context.Background()).Debug("Disable housekeeping messages for command explicitly") return nil } s = survey.New(opts.GlobalConfig, opts.ConfigurationFile, opts.Command) @@ -128,7 +129,7 @@ func NewSkaffoldCommand(out, errOut io.Writer) *cobra.Command { select { case msg := <-updateMsg: if err := config.UpdateMsgDisplayed(opts.GlobalConfig); err != nil { - logrus.Debugf("could not update the 'last-prompted' config for 'update-config' section due to %s", err) + log.Entry(context.Background()).Debugf("could not update the 'last-prompted' config for 'update-config' section due to %s", err) } fmt.Fprintf(cmd.OutOrStderr(), "%s\n", msg) default: @@ -235,7 +236,7 @@ func setFlagsFromEnvVariables(rootCmd *cobra.Command) { // special case for backward compatibility. if f.Name == "namespace" { if val, present := os.LookupEnv("SKAFFOLD_DEPLOY_NAMESPACE"); present { - logrus.Warnln("Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.") + log.Entry(context.Background()).Warn("Using SKAFFOLD_DEPLOY_NAMESPACE env variable is deprecated. Please use SKAFFOLD_NAMESPACE instead.") cmd.Flags().Set(f.Name, val) } } @@ -262,7 +263,7 @@ func setUpLogs(stdErr io.Writer, level string, timestamp bool) error { logrus.SetFormatter(&logrus.TextFormatter{ FullTimestamp: timestamp, }) - logrus.AddHook(event.NewLogHook(constants.DevLoop, event.SubtaskIDNone)) + logrus.AddHook(event.NewLogHook(constants.DevLoop, constants.SubtaskIDNone)) return nil } @@ -310,13 +311,13 @@ func preReleaseVersion(s string) bool { func isQuietMode() bool { switch { case !interactive: - logrus.Debug("Update check prompt, survey prompt and telemetry prompt disabled in non-interactive mode") + log.Entry(context.Background()).Debug("Update check prompt, survey prompt and telemetry prompt disabled in non-interactive mode") return true case quietFlag: - logrus.Debug("Update check prompt, survey prompt and telemetry prompt disabled in quiet mode") + log.Entry(context.Background()).Debug("Update check prompt, survey prompt and telemetry prompt disabled in quiet mode") return true case analyze: - logrus.Debug("Update check prompt, survey prompt and telemetry prompt disabled when running `init --analyze`") + log.Entry(context.Background()).Debug("Update check prompt, survey prompt and telemetry prompt disabled when running `init --analyze`") return true default: return false @@ -334,16 +335,16 @@ func apiServerShutdownHook(err error) error { func updateCheckForReleasedVersionsIfNotDisabled(s string) string { if preReleaseVersion(s) { - logrus.Debug("Skipping update check for pre-release version") + log.Entry(context.Background()).Debug("Skipping update check for pre-release version") return "" } if !update.EnableCheck { - logrus.Debug("Skipping update check for flag `--update-check` set to false") + log.Entry(context.Background()).Debug("Skipping update check for flag `--update-check` set to false") return "" } msg, err := updateCheck(opts.GlobalConfig) if err != nil { - logrus.Infof("update check failed: %s", err) + log.Entry(context.Background()).Infof("update check failed: %s", err) } return msg } diff --git a/cmd/skaffold/app/cmd/config/util.go b/cmd/skaffold/app/cmd/config/util.go index 46460a4e317..c69d4d4cf5b 100644 --- a/cmd/skaffold/app/cmd/config/util.go +++ b/cmd/skaffold/app/cmd/config/util.go @@ -17,12 +17,12 @@ limitations under the License. package config import ( + "context" "fmt" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + kctx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -31,13 +31,13 @@ func resolveKubectlContext() { return } - config, err := context.CurrentConfig() + config, err := kctx.CurrentConfig() switch { case err != nil: - logrus.Warn("unable to retrieve current kubectl context, using global values") + log.Entry(context.Background()).Warn("unable to retrieve current kubectl context, using global values") global = true case config.CurrentContext == "": - logrus.Infof("no kubectl context currently set, using global values") + log.Entry(context.Background()).Info("no kubectl context currently set, using global values") global = true default: kubecontext = config.CurrentContext diff --git a/cmd/skaffold/app/cmd/dev.go b/cmd/skaffold/app/cmd/dev.go index 34111c3b1ec..d6d6f349fba 100644 --- a/cmd/skaffold/app/cmd/dev.go +++ b/cmd/skaffold/app/cmd/dev.go @@ -21,9 +21,9 @@ import ( "errors" "io" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" @@ -73,7 +73,7 @@ func runDev(ctx context.Context, out io.Writer) error { if r.HasDeployed() { cleanup = func() { if err := r.Cleanup(context.Background(), out); err != nil { - logrus.Warnln("deployer cleanup:", err) + log.Entry(ctx).Warn("deployer cleanup:", err) } } } @@ -81,7 +81,7 @@ func runDev(ctx context.Context, out io.Writer) error { if r.HasBuilt() { prune = func() { if err := r.Prune(context.Background(), out); err != nil { - logrus.Warnln("builder cleanup:", err) + log.Entry(ctx).Warn("builder cleanup:", err) } } } diff --git a/cmd/skaffold/app/cmd/flags.go b/cmd/skaffold/app/cmd/flags.go index 3a53f8fac72..2bf62d1e203 100644 --- a/cmd/skaffold/app/cmd/flags.go +++ b/cmd/skaffold/app/cmd/flags.go @@ -17,17 +17,18 @@ limitations under the License. package cmd import ( + "context" "fmt" "reflect" "time" - "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/flags" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) var ( @@ -660,7 +661,7 @@ func setDefaultValues(v interface{}, fl *Flag, cmdName string) { } else if val, ok := v.(pflag.Value); ok { val.Set(fmt.Sprintf("%v", d)) } else { - logrus.Fatalf("%s --%s: unhandled value type: %v (%T)", cmdName, fl.Name, v, v) + log.Entry(context.Background()).Fatalf("%s --%s: unhandled value type: %v (%T)", cmdName, fl.Name, v, v) } } diff --git a/cmd/skaffold/app/cmd/runner.go b/cmd/skaffold/app/cmd/runner.go index 64feed3dc3d..6f48c8de569 100644 --- a/cmd/skaffold/app/cmd/runner.go +++ b/cmd/skaffold/app/cmd/runner.go @@ -22,8 +22,6 @@ import ( "fmt" "io" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" @@ -32,6 +30,7 @@ import ( initConfig "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/parser" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" @@ -153,10 +152,10 @@ func setDefaultDeployer(configs parser.SkaffoldConfigSet) { func warnIfUpdateIsAvailable() { warning, err := update.CheckVersionOnError(opts.GlobalConfig) if err != nil { - logrus.Infof("update check failed: %s", err) + log.Entry(context.Background()).Infof("update check failed: %s", err) return } if warning != "" { - logrus.Warn(warning) + log.Entry(context.Background()).Warn(warning) } } diff --git a/cmd/skaffold/app/skaffold.go b/cmd/skaffold/app/skaffold.go index d4774d9b0cd..053e8486399 100644 --- a/cmd/skaffold/app/skaffold.go +++ b/cmd/skaffold/app/skaffold.go @@ -23,9 +23,9 @@ import ( "os" shell "github.com/kballard/go-shellquote" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/cmd" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) func Run(out, stderr io.Writer) error { @@ -41,7 +41,7 @@ func Run(out, stderr io.Writer) error { return fmt.Errorf("SKAFFOLD_CMDLINE is invalid: %w", err) } // XXX logged before logrus.SetLevel is called in NewSkaffoldCommand's PersistentPreRunE - logrus.Debugf("Retrieving command line from SKAFFOLD_CMDLINE: %q", parsed) + log.Entry(ctx).Debugf("Retrieving command line from SKAFFOLD_CMDLINE: %q", parsed) c.SetArgs(parsed) } err := c.ExecuteContext(ctx) diff --git a/cmd/skaffold/skaffold.go b/cmd/skaffold/skaffold.go index f2909c83658..30833782c65 100644 --- a/cmd/skaffold/skaffold.go +++ b/cmd/skaffold/skaffold.go @@ -19,15 +19,14 @@ package main import ( "context" "errors" - "log" "os" "cloud.google.com/go/profiler" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/version" ) @@ -44,13 +43,13 @@ func main() { ServiceVersion: version.Get().Version, }) if err != nil { - log.Fatalf("failed to start the profiler: %v", err) + log.Entry(context.Background()).Fatalf("failed to start the profiler: %v", err) } } var code int if err := app.Run(os.Stdout, os.Stderr); err != nil { if errors.Is(err, context.Canceled) { - logrus.Debugln("ignore error since context is cancelled:", err) + log.Entry(context.Background()).Debugln("ignore error since context is cancelled:", err) } else { // As we allow some color setup using CLI flags for the main run, we can't run SetupColors() // for the entire skaffold run here. It's possible SetupColors() was never called, so call it again diff --git a/hack/versions/pkg/schema/check.go b/hack/versions/pkg/schema/check.go index 3dd9d535eec..b0c40841975 100644 --- a/hack/versions/pkg/schema/check.go +++ b/hack/versions/pkg/schema/check.go @@ -95,7 +95,7 @@ func RunSchemaCheckOnChangedFiles() error { continue } - logrus.Warnf("Detected changes to the latest config. Checking on Github if it's released...") + logrus.Warn("Detected changes to the latest config. Checking on Github if it's released...") latestVersion, isReleased := GetLatestVersion() if !isReleased { logrus.Infof("Schema %q is not yet released. Changes are ok.", latestVersion) diff --git a/pkg/diag/validator/pod.go b/pkg/diag/validator/pod.go index 46d51b58344..b6e9c916192 100644 --- a/pkg/diag/validator/pod.go +++ b/pkg/diag/validator/pod.go @@ -23,7 +23,6 @@ import ( "regexp" "strings" - "github.com/sirupsen/logrus" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -33,6 +32,7 @@ import ( deploymentutil "k8s.io/kubectl/pkg/util/deployment" "github.com/GoogleContainerTools/skaffold/pkg/diag/recommender" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -89,10 +89,10 @@ func NewPodValidator(k kubernetes.Interface, d appsv1.Deployment) *PodValidator func (p *PodValidator) Validate(ctx context.Context, ns string, opts metav1.ListOptions) ([]Resource, error) { _, _, controller, err := getReplicaSet(&p.depObj, p.k.AppsV1()) if err != nil { - logrus.Debugf("could not fetch deployment replica set %s", err) + log.Entry(ctx).Debugf("could not fetch deployment replica set %s", err) return []Resource{}, err } else if controller == nil { - logrus.Debugf("deployment replica set not created yet.") + log.Entry(ctx).Debugf("deployment replica set not created yet.") return []Resource{}, nil } @@ -144,14 +144,14 @@ func getPodStatus(pod *v1.Pod) (proto.StatusCode, []string, error) { } // If the event type PodScheduled with status False is found then we check if it is due to taints and tolerations. if c, ok := isPodNotScheduled(pod); ok { - logrus.Debugf("Pod %q not scheduled: checking tolerations", pod.Name) + log.Entry(context.Background()).Debugf("Pod %q not scheduled: checking tolerations", pod.Name) sc, err := getUntoleratedTaints(c.Reason, c.Message) return sc, nil, err } // we can check the container status if the pod has been scheduled successfully. This can be determined by having the event // PodScheduled with status True, or a ContainerReady or PodReady event with status False. if isPodScheduledButNotReady(pod) { - logrus.Debugf("Pod %q scheduled but not ready: checking container statuses", pod.Name) + log.Entry(context.Background()).Debugf("Pod %q scheduled but not ready: checking container statuses", pod.Name) // TODO(dgageot): Add EphemeralContainerStatuses cs := append(pod.Status.InitContainerStatuses, pod.Status.ContainerStatuses...) // See https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-states @@ -171,11 +171,11 @@ func getPodStatus(pod *v1.Pod) (proto.StatusCode, []string, error) { } if c, ok := isPodStatusUnknown(pod); ok { - logrus.Debugf("Pod %q condition status of type %s is unknown", pod.Name, c.Type) + log.Entry(context.Background()).Debugf("Pod %q condition status of type %s is unknown", pod.Name, c.Type) return proto.StatusCode_STATUSCHECK_UNKNOWN, nil, fmt.Errorf(c.Message) } - logrus.Debugf("Unable to determine current service state of pod %q", pod.Name) + log.Entry(context.Background()).Debugf("Unable to determine current service state of pod %q", pod.Name) return proto.StatusCode_STATUSCHECK_UNKNOWN, nil, fmt.Errorf("unable to determine current service state of pod %q", pod.Name) } @@ -288,13 +288,13 @@ func processPodEvents(e corev1.EventInterface, pod v1.Pod, ps *podStatus) { if _, ok := unknownConditionsOrSuccess[ps.ae.ErrCode]; !ok { return } - logrus.Debugf("Fetching events for pod %q", pod.Name) + log.Entry(context.Background()).Debugf("Fetching events for pod %q", pod.Name) // Get pod events. scheme := runtime.NewScheme() scheme.AddKnownTypes(v1.SchemeGroupVersion, &pod) events, err := e.Search(scheme, &pod) if err != nil { - logrus.Debugf("Could not fetch events for resource %q due to %v", pod.Name, err) + log.Entry(context.Background()).Debugf("Could not fetch events for resource %q due to %v", pod.Name, err) return } // find the latest failed event. @@ -385,7 +385,7 @@ func extractErrorMessageFromWaitingContainerStatus(po *v1.Pod, c v1.ContainerSta return proto.StatusCode_STATUSCHECK_RUN_CONTAINER_ERR, nil, fmt.Errorf("container %s in error: %s", c.Name, trimSpace(match[3])) } } - logrus.Debugf("Unknown waiting reason for container %q: %v", c.Name, c.State) + log.Entry(context.Background()).Debugf("Unknown waiting reason for container %q: %v", c.Name, c.State) return proto.StatusCode_STATUSCHECK_CONTAINER_WAITING_UNKNOWN, nil, fmt.Errorf("container %s in error: %v", c.Name, c.State.Waiting) } @@ -405,7 +405,7 @@ func trimSpace(msg string) string { } func getPodLogs(po *v1.Pod, c string, sc proto.StatusCode) (proto.StatusCode, []string) { - logrus.Debugf("Fetching logs for container %s/%s", po.Name, c) + log.Entry(context.Background()).Debugf("Fetching logs for container %s/%s", po.Name, c) logCommand := []string{"kubectl", "logs", po.Name, "-n", po.Namespace, "-c", c} logs, err := runCli(logCommand[0], logCommand[1:]) if err != nil { diff --git a/pkg/skaffold/build/bazel/dependencies.go b/pkg/skaffold/build/bazel/dependencies.go index aec42cd8a6e..c85d1867dab 100644 --- a/pkg/skaffold/build/bazel/dependencies.go +++ b/pkg/skaffold/build/bazel/dependencies.go @@ -27,8 +27,7 @@ import ( "sync" "time" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -49,7 +48,7 @@ func GetDependencies(ctx context.Context, dir string, a *latestV1.BazelArtifact) go func() { <-timer.C - once.Do(func() { logrus.Warnln("Retrieving Bazel dependencies can take a long time the first time") }) + once.Do(func() { log.Entry(ctx).Warn("Retrieving Bazel dependencies can take a long time the first time") }) }() topLevelFolder, err := findWorkspace(dir) @@ -95,7 +94,7 @@ func GetDependencies(ctx context.Context, dir string, a *latestV1.BazelArtifact) } deps = append(deps, rel) - logrus.Debugf("Found dependencies for bazel artifact: %v", deps) + log.Entry(ctx).Debugf("Found dependencies for bazel artifact: %v", deps) return deps, nil } diff --git a/pkg/skaffold/build/build_problems.go b/pkg/skaffold/build/build_problems.go index 465b0cc1828..f198178fa1a 100644 --- a/pkg/skaffold/build/build_problems.go +++ b/pkg/skaffold/build/build_problems.go @@ -17,14 +17,14 @@ limitations under the License. package build import ( + "context" "fmt" "regexp" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -49,7 +49,7 @@ var ( Regexp: re(fmt.Sprintf(".*%s.* denied: .*", PushImageErr)), ErrCode: proto.StatusCode_BUILD_PUSH_ACCESS_DENIED, Description: func(err error) string { - logrus.Tracef("error building %s", err) + log.Entry(context.Background()).Tracef("error building %s", err) return "Build Failed. No push access to specified image repository" }, Suggestion: suggestBuildPushAccessDeniedAction, @@ -65,7 +65,7 @@ var ( { Regexp: re(unknownProjectErr), Description: func(err error) string { - logrus.Tracef("error building %s", err) + log.Entry(context.Background()).Tracef("error building %s", err) matchExp := re(unknownProjectErr) if match := matchExp.FindStringSubmatch(err.Error()); len(match) >= 2 { return fmt.Sprintf("Build Failed. %s", match[1]) @@ -84,7 +84,7 @@ var ( Regexp: re(dockerConnectionFailed), ErrCode: proto.StatusCode_BUILD_DOCKER_DAEMON_NOT_RUNNING, Description: func(err error) string { - logrus.Tracef("error building %s", err) + log.Entry(context.Background()).Tracef("error building %s", err) matchExp := re(dockerConnectionFailed) if match := matchExp.FindStringSubmatch(err.Error()); len(match) >= 2 { return fmt.Sprintf("Build Failed. %s", match[1]) diff --git a/pkg/skaffold/build/builder_mux.go b/pkg/skaffold/build/builder_mux.go index f9e2574d5ad..631248c977f 100644 --- a/pkg/skaffold/build/builder_mux.go +++ b/pkg/skaffold/build/builder_mux.go @@ -22,10 +22,9 @@ import ( "io" "reflect" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/hooks" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" ) @@ -70,16 +69,16 @@ func NewBuilderMux(cfg Config, store ArtifactStore, builder func(p latestV1.Pipe switch { case minConcurrency < 0: minConcurrency = concurrency - logrus.Infof("build concurrency first set to %d parsed from %s[%d]", minConcurrency, reflect.TypeOf(b).String(), i) + log.Entry(context.Background()).Infof("build concurrency first set to %d parsed from %s[%d]", minConcurrency, reflect.TypeOf(b).String(), i) case concurrency > 0 && (minConcurrency == 0 || concurrency < minConcurrency): minConcurrency = concurrency - logrus.Infof("build concurrency updated to %d parsed from %s[%d]", minConcurrency, reflect.TypeOf(b).String(), i) + log.Entry(context.Background()).Infof("build concurrency updated to %d parsed from %s[%d]", minConcurrency, reflect.TypeOf(b).String(), i) default: - logrus.Infof("build concurrency value %d parsed from %s[%d] is ignored since it's not less than previously set value %d", concurrency, reflect.TypeOf(b).String(), i, minConcurrency) + log.Entry(context.Background()).Infof("build concurrency value %d parsed from %s[%d] is ignored since it's not less than previously set value %d", concurrency, reflect.TypeOf(b).String(), i, minConcurrency) } } } - logrus.Infof("final build concurrency value is %d", minConcurrency) + log.Entry(context.Background()).Infof("final build concurrency value is %d", minConcurrency) return &BuilderMux{builders: pb, byImageName: m, store: store, concurrency: minConcurrency}, nil } diff --git a/pkg/skaffold/build/buildpacks/lifecycle.go b/pkg/skaffold/build/buildpacks/lifecycle.go index 8ce2381bf69..090adfca472 100644 --- a/pkg/skaffold/build/buildpacks/lifecycle.go +++ b/pkg/skaffold/build/buildpacks/lifecycle.go @@ -30,10 +30,10 @@ import ( "github.com/buildpacks/pack" packcfg "github.com/buildpacks/pack/config" "github.com/buildpacks/pack/project" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -202,14 +202,14 @@ func resolveDependencyImages(artifact *latestV1.BuildpackArtifact, r ArtifactRes if builderImage == d.Alias { builderImage, found = r.GetImageTag(d.ImageName) if !found { - logrus.Fatalf("failed to resolve build result for required artifact %q", d.ImageName) + log.Entry(context.Background()).Fatalf("failed to resolve build result for required artifact %q", d.ImageName) } builderImageLocal = true } if runImage == d.Alias { runImage, found = r.GetImageTag(d.ImageName) if !found { - logrus.Fatalf("failed to resolve build result for required artifact %q", d.ImageName) + log.Entry(context.Background()).Fatalf("failed to resolve build result for required artifact %q", d.ImageName) } runImageLocal = true } @@ -224,10 +224,10 @@ func resolveDependencyImages(artifact *latestV1.BuildpackArtifact, r ArtifactRes // if remote image pull is disabled then the image that is not fetched from the required artifacts might not be latestV1. if !pushImages && builderImageLocal { - logrus.Warnln("Disabled remote image pull since builder image is built locally. Buildpacks run image may not be latestV1.") + log.Entry(context.Background()).Warn("Disabled remote image pull since builder image is built locally. Buildpacks run image may not be latestV1.") } if !pushImages && runImageLocal { - logrus.Warnln("Disabled remote image pull since run image is built locally. Buildpacks builder image may not be latestV1.") + log.Entry(context.Background()).Warn("Disabled remote image pull since run image is built locally. Buildpacks builder image may not be latestV1.") } } diff --git a/pkg/skaffold/build/cache/cache.go b/pkg/skaffold/build/cache/cache.go index a7ae8e4845c..5826a5bdce6 100644 --- a/pkg/skaffold/build/cache/cache.go +++ b/pkg/skaffold/build/cache/cache.go @@ -24,13 +24,13 @@ import ( "sync" "github.com/mitchellh/go-homedir" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" @@ -81,13 +81,13 @@ func NewCache(cfg Config, isLocalImage func(imageName string) (bool, error), dep cacheFile, err := resolveCacheFile(cfg.CacheFile()) if err != nil { - logrus.Warnf("Error resolving cache file, not using skaffold cache: %v", err) + log.Entry(context.Background()).Warnf("Error resolving cache file, not using skaffold cache: %v", err) return &noCache{}, nil } artifactCache, err := retrieveArtifactCache(cacheFile) if err != nil { - logrus.Warnf("Error retrieving artifact cache, not using skaffold cache: %v", err) + log.Entry(context.Background()).Warnf("Error retrieving artifact cache, not using skaffold cache: %v", err) return &noCache{}, nil } diff --git a/pkg/skaffold/build/cache/hash.go b/pkg/skaffold/build/cache/hash.go index 3a99b1bd681..8b5537ca8e6 100644 --- a/pkg/skaffold/build/cache/hash.go +++ b/pkg/skaffold/build/cache/hash.go @@ -27,13 +27,12 @@ import ( "os" "sort" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/buildpacks" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -134,7 +133,7 @@ func singleArtifactHash(ctx context.Context, depLister DependencyLister, a *late h, err := fileHasherFunc(d) if err != nil { if os.IsNotExist(err) { - logrus.Tracef("skipping dependency for artifact cache calculation, file not found %s: %s", d, err) + log.Entry(ctx).Tracef("skipping dependency for artifact cache calculation, file not found %s: %s", d, err) continue // Ignore files that don't exist } diff --git a/pkg/skaffold/build/cache/lookup.go b/pkg/skaffold/build/cache/lookup.go index b90e6b079ce..f87ab1e3ead 100644 --- a/pkg/skaffold/build/cache/lookup.go +++ b/pkg/skaffold/build/cache/lookup.go @@ -22,10 +22,9 @@ import ( "io/ioutil" "sync" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" ) @@ -69,7 +68,7 @@ func (c *cache) lookup(ctx context.Context, a *latestV1.Artifact, tag string, h c.cacheMutex.RUnlock() if !cacheHit { if entry, err = c.tryImport(ctx, a, tag, hash); err != nil { - logrus.Debugf("Could not import artifact from Docker, building instead (%s)", err) + log.Entry(ctx).Debugf("Could not import artifact from Docker, building instead (%s)", err) return needsBuilding{hash: hash} } } @@ -141,13 +140,13 @@ func (c *cache) tryImport(ctx context.Context, a *latestV1.Artifact, tag string, } if !c.client.ImageExists(ctx, tag) { - logrus.Debugf("Importing artifact %s from docker registry", tag) + log.Entry(ctx).Debugf("Importing artifact %s from docker registry", tag) err := c.client.Pull(ctx, ioutil.Discard, tag) if err != nil { return entry, err } } else { - logrus.Debugf("Importing artifact %s from local docker", tag) + log.Entry(ctx).Debugf("Importing artifact %s from local docker", tag) } imageID, err := c.client.ImageID(ctx, tag) @@ -160,7 +159,7 @@ func (c *cache) tryImport(ctx context.Context, a *latestV1.Artifact, tag string, } if digest, err := docker.RemoteDigest(tag, c.cfg); err == nil { - logrus.Debugf("Added digest for %s to cache entry", tag) + log.Entry(ctx).Debugf("Added digest for %s to cache entry", tag) entry.Digest = digest } diff --git a/pkg/skaffold/build/cache/retrieve.go b/pkg/skaffold/build/cache/retrieve.go index b04257bcc08..5170de2363e 100644 --- a/pkg/skaffold/build/cache/retrieve.go +++ b/pkg/skaffold/build/cache/retrieve.go @@ -22,8 +22,6 @@ import ( "io" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" @@ -32,6 +30,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -62,7 +61,7 @@ func (c *cache) Build(ctx context.Context, out io.Writer, tags tag.ImageTags, ar var alreadyBuilt []graph.Artifact for i, artifact := range artifacts { eventV2.CacheCheckInProgress(artifact.ImageName) - out := output.WithEventContext(out, constants.Build, artifact.ImageName) + out, ctx := output.WithEventContext(ctx, out, constants.Build, artifact.ImageName) output.Default.Fprintf(out, " - %s: ", artifact.ImageName) result := results[i] @@ -139,7 +138,7 @@ func (c *cache) Build(ctx context.Context, out io.Writer, tags tag.ImageTags, ar }) } - logrus.Infoln("Cache check completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Info("Cache check completed in", util.ShowHumanizeTime(time.Since(start))) bRes, err := buildAndTest(ctx, out, tags, needToBuild) if err != nil { @@ -148,12 +147,12 @@ func (c *cache) Build(ctx context.Context, out io.Writer, tags tag.ImageTags, ar } if err := c.addArtifacts(ctx, bRes, hashByName); err != nil { - logrus.Warnf("error adding artifacts to cache; caching may not work as expected: %v", err) + log.Entry(ctx).Warnf("error adding artifacts to cache; caching may not work as expected: %v", err) return append(bRes, alreadyBuilt...), nil } if err := saveArtifactCache(c.cacheFile, c.artifactCache); err != nil { - logrus.Warnf("error saving cache file; caching may not work as expected: %v", err) + log.Entry(ctx).Warnf("error saving cache file; caching may not work as expected: %v", err) return append(bRes, alreadyBuilt...), nil } diff --git a/pkg/skaffold/build/cluster/kaniko.go b/pkg/skaffold/build/cluster/kaniko.go index 52cbf99b266..1634e7baa86 100644 --- a/pkg/skaffold/build/cluster/kaniko.go +++ b/pkg/skaffold/build/cluster/kaniko.go @@ -22,7 +22,6 @@ import ( "fmt" "io" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" @@ -31,6 +30,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -73,7 +73,7 @@ func (b *Builder) buildWithKaniko(ctx context.Context, out io.Writer, workspace if err := pods.Delete(ctx, pod.Name, metav1.DeleteOptions{ GracePeriodSeconds: new(int64), }); err != nil { - logrus.Fatalf("deleting pod: %s", err) + log.Entry(ctx).Fatalf("deleting pod: %s", err) } }() diff --git a/pkg/skaffold/build/cluster/logs.go b/pkg/skaffold/build/cluster/logs.go index 76175e95576..3836193ade2 100644 --- a/pkg/skaffold/build/cluster/logs.go +++ b/pkg/skaffold/build/cluster/logs.go @@ -30,6 +30,7 @@ import ( corev1 "k8s.io/client-go/kubernetes/typed/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/kaniko" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // logLevel makes sure kaniko logs at least at Info level and at most Debug level (trace doesn't work with Kaniko) @@ -59,7 +60,7 @@ func streamLogs(ctx context.Context, out io.Writer, name string, pods corev1.Pod Container: kaniko.DefaultContainerName, }).Stream(ctx) if err != nil { - logrus.Debugln("unable to get kaniko pod logs:", err) + log.Entry(ctx).Debug("unable to get kaniko pod logs:", err) time.Sleep(1 * time.Second) continue } diff --git a/pkg/skaffold/build/cluster/pod.go b/pkg/skaffold/build/cluster/pod.go index 2773a5f9ac9..3f4cf49cfcd 100644 --- a/pkg/skaffold/build/cluster/pod.go +++ b/pkg/skaffold/build/cluster/pod.go @@ -17,15 +17,16 @@ limitations under the License. package cluster import ( + "context" "fmt" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/resource" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/kaniko" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/version" ) @@ -254,7 +255,7 @@ func kanikoArgs(artifact *latestV1.KanikoArtifact, tag string, insecureRegistrie return nil, fmt.Errorf("unable build kaniko args: %w", err) } - logrus.Trace("kaniko arguments are ", strings.Join(args, " ")) + log.Entry(context.Background()).Trace("kaniko arguments are ", strings.Join(args, " ")) return args, nil } diff --git a/pkg/skaffold/build/cluster/secret.go b/pkg/skaffold/build/cluster/secret.go index 15f50670bf5..17bc1ac9121 100644 --- a/pkg/skaffold/build/cluster/secret.go +++ b/pkg/skaffold/build/cluster/secret.go @@ -22,7 +22,6 @@ import ( "io" "io/ioutil" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" typedV1 "k8s.io/client-go/kubernetes/typed/core/v1" @@ -30,6 +29,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/kaniko" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const ( @@ -57,7 +57,7 @@ func (b *Builder) setupPullSecret(ctx context.Context, out io.Writer) (func(), e } if b.PullSecretPath == "" { // TODO: Remove the warning when pod health check can display pod failure errors. - logrus.Warnf("Assuming the secret %s is mounted inside Kaniko pod with the filename %s. If your secret is mounted at different path, please specify using config key `pullSecretPath`.\nSee https://skaffold.dev/docs/references/yaml/#build-cluster-pullSecretPath", b.PullSecretName, defaultKanikoSecretPath) + log.Entry(ctx).Warnf("Assuming the secret %s is mounted inside Kaniko pod with the filename %s. If your secret is mounted at different path, please specify using config key `pullSecretPath`.\nSee https://skaffold.dev/docs/references/yaml/#build-cluster-pullSecretPath", b.PullSecretName, defaultKanikoSecretPath) b.PullSecretPath = defaultKanikoSecretPath return func() {}, nil } @@ -85,7 +85,7 @@ func (b *Builder) createSecretFromFile(ctx context.Context, secrets typedV1.Secr return func() { if err := secrets.Delete(ctx, b.PullSecretName, metav1.DeleteOptions{}); err != nil { - logrus.Warnf("deleting pull secret") + log.Entry(ctx).Warn("deleting pull secret") } }, nil } @@ -105,7 +105,7 @@ func (b *Builder) setupDockerConfigSecret(ctx context.Context, out io.Writer) (f secrets := client.CoreV1().Secrets(b.Namespace) if b.DockerConfig.Path == "" { - logrus.Debug("No docker config specified. Checking for one in the cluster.") + log.Entry(ctx).Debug("No docker config specified. Checking for one in the cluster.") if _, err := secrets.Get(ctx, b.DockerConfig.SecretName, metav1.GetOptions{}); err != nil { return nil, fmt.Errorf("checking for existing kaniko secret: %w", err) @@ -135,7 +135,7 @@ func (b *Builder) setupDockerConfigSecret(ctx context.Context, out io.Writer) (f return func() { if err := secrets.Delete(ctx, b.DockerConfig.SecretName, metav1.DeleteOptions{}); err != nil { - logrus.Warnf("deleting docker config secret") + log.Entry(ctx).Warn("deleting docker config secret") } }, nil } diff --git a/pkg/skaffold/build/custom/script.go b/pkg/skaffold/build/custom/script.go index a5026016df9..2dec229302a 100644 --- a/pkg/skaffold/build/custom/script.go +++ b/pkg/skaffold/build/custom/script.go @@ -24,11 +24,10 @@ import ( "path/filepath" "runtime" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/misc" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -44,7 +43,7 @@ func (b *Builder) runBuildScript(ctx context.Context, out io.Writer, a *latestV1 return fmt.Errorf("retrieving cmd: %w", err) } - logrus.Debugf("Running command: %s", cmd.Args) + log.Entry(ctx).Debugf("Running command: %s", cmd.Args) if err := cmd.Start(); err != nil { return fmt.Errorf("starting cmd: %w", err) } diff --git a/pkg/skaffold/build/gcb/buildpacks.go b/pkg/skaffold/build/gcb/buildpacks.go index c5bda7867a2..f9d55cbd5fb 100644 --- a/pkg/skaffold/build/gcb/buildpacks.go +++ b/pkg/skaffold/build/gcb/buildpacks.go @@ -17,14 +17,15 @@ limitations under the License. package gcb import ( + "context" "fmt" - "github.com/sirupsen/logrus" "google.golang.org/api/cloudbuild/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/misc" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -71,7 +72,7 @@ func fromRequiredArtifacts(imageName string, r docker.ArtifactResolver, deps []* if imageName == d.Alias { image, found := r.GetImageTag(d.ImageName) if !found { - logrus.Fatalf("failed to resolve build result for required artifact %q", d.ImageName) + log.Entry(context.Background()).Fatalf("failed to resolve build result for required artifact %q", d.ImageName) } return image } diff --git a/pkg/skaffold/build/gcb/cloud_build.go b/pkg/skaffold/build/gcb/cloud_build.go index 1ae80ece729..a803f4d930b 100644 --- a/pkg/skaffold/build/gcb/cloud_build.go +++ b/pkg/skaffold/build/gcb/cloud_build.go @@ -28,7 +28,6 @@ import ( cstorage "cloud.google.com/go/storage" "github.com/google/uuid" - "github.com/sirupsen/logrus" "google.golang.org/api/cloudbuild/v1" "google.golang.org/api/googleapi" "google.golang.org/api/iterator" @@ -40,6 +39,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/gcp" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sources" ) @@ -148,7 +148,7 @@ watch: for { var cb *cloudbuild.Build var err error - logrus.Debugf("current offset %d", offset) + log.Entry(ctx).Debugf("current offset %d", offset) backoff := NewStatusBackoff() if waitErr := wait.Poll(backoff.Duration, RetryTimeout, func() (bool, error) { time.Sleep(backoff.Step()) @@ -201,9 +201,9 @@ watch: } if err := c.Bucket(cbBucket).Object(buildObject).Delete(ctx); err != nil { - logrus.Warnf("Unable to deleting source archive after build: %q: %v", buildObject, err) + log.Entry(ctx).Warnf("Unable to deleting source archive after build: %q: %v", buildObject, err) } else { - logrus.Infof("Deleted source archive %s", buildObject) + log.Entry(ctx).Infof("Deleted source archive %s", buildObject) } return build.TagWithDigest(tag, digest), nil @@ -241,12 +241,12 @@ func (b *Builder) getLogs(ctx context.Context, c *cstorage.Client, offset int64, switch gerr.Code { // case http. case 404, 416, 429, 503: - logrus.Debugf("Status Code: %d, %s", gerr.Code, gerr.Body) + log.Entry(ctx).Debugf("Status Code: %d, %s", gerr.Code, gerr.Body) return nil, nil } } if err == cstorage.ErrObjectNotExist { - logrus.Debugf("Logs for %s %s not uploaded yet...", bucket, objectName) + log.Entry(ctx).Debugf("Logs for %s %s not uploaded yet...", bucket, objectName) return nil, nil } return nil, fmt.Errorf("unknown error: %w", err) @@ -294,7 +294,7 @@ func (b *Builder) createBucketIfNotExists(ctx context.Context, c *cstorage.Clien if e, ok := err.(*googleapi.Error); ok { if e.Code == http.StatusConflict { // 409 errors are ok, there could have been a race condition or eventual consistency. - logrus.Debugf("Not creating bucket, got a 409 error indicating it already exists.") + log.Entry(ctx).Debug("Not creating bucket, got a 409 error indicating it already exists.") return nil } } @@ -302,6 +302,6 @@ func (b *Builder) createBucketIfNotExists(ctx context.Context, c *cstorage.Clien if err != nil { return err } - logrus.Debugf("Created bucket %s in %s", bucket, projectID) + log.Entry(ctx).Debugf("Created bucket %s in %s", bucket, projectID) return nil } diff --git a/pkg/skaffold/build/jib/errors.go b/pkg/skaffold/build/jib/errors.go index e9522498b60..14223046a29 100644 --- a/pkg/skaffold/build/jib/errors.go +++ b/pkg/skaffold/build/jib/errors.go @@ -17,11 +17,11 @@ limitations under the License. package jib import ( + "context" "fmt" - "github.com/sirupsen/logrus" - sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -61,7 +61,7 @@ func dependencyErr(pType PluginType, workspace string, err error) error { case JibGradle: code = proto.StatusCode_BUILD_JIB_GRADLE_DEP_ERR default: - logrus.Fatal("Unknown jib build type", pType) + log.Entry(context.Background()).Fatal("Unknown jib build type", pType) } return sErrors.NewError(err, proto.ActionableErr{ diff --git a/pkg/skaffold/build/jib/gradle.go b/pkg/skaffold/build/jib/gradle.go index 913c422486d..07182e6b176 100644 --- a/pkg/skaffold/build/jib/gradle.go +++ b/pkg/skaffold/build/jib/gradle.go @@ -22,10 +22,9 @@ import ( "io" "os/exec" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -67,7 +66,7 @@ func (b *Builder) runGradleCommand(ctx context.Context, out io.Writer, workspace cmd.Stdout = out cmd.Stderr = out - logrus.Infof("Building %s: %s, %v", workspace, cmd.Path, cmd.Args) + log.Entry(ctx).Infof("Building %s: %s, %v", workspace, cmd.Path, cmd.Args) if err := util.RunCmd(&cmd); err != nil { return fmt.Errorf("gradle build failed: %w", err) } @@ -83,7 +82,7 @@ func getDependenciesGradle(ctx context.Context, workspace string, a *latestV1.Ji if err != nil { return nil, dependencyErr(JibGradle, workspace, err) } - logrus.Debugf("Found dependencies for jib-gradle artifact: %v", deps) + log.Entry(ctx).Debugf("Found dependencies for jib-gradle artifact: %v", deps) return deps, nil } diff --git a/pkg/skaffold/build/jib/init.go b/pkg/skaffold/build/jib/init.go index b292fd9360c..7547667a2ca 100644 --- a/pkg/skaffold/build/jib/init.go +++ b/pkg/skaffold/build/jib/init.go @@ -18,6 +18,7 @@ package jib import ( "bytes" + "context" "encoding/json" "fmt" "io/ioutil" @@ -26,8 +27,7 @@ import ( "regexp" "strings" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -86,7 +86,7 @@ type jibJSON struct { // validate checks if a file is a valid Jib configuration. Returns the list of Config objects corresponding to each Jib project built by the file, or nil if Jib is not configured. func validate(path string, enableGradleAnalysis bool) []ArtifactConfig { if !JVMFound() { - logrus.Debugf("Skipping Jib for init for %q: no functioning Java VM", path) + log.Entry(context.Background()).Debugf("Skipping Jib for init for %q: no functioning Java VM", path) return nil } // Determine whether maven or gradle @@ -140,7 +140,7 @@ func validate(path string, enableGradleAnalysis bool) []ArtifactConfig { line := bytes.ReplaceAll(match[1], []byte(`\`), []byte(`\\`)) parsedJSON := jibJSON{} if err := json.Unmarshal(line, &parsedJSON); err != nil { - logrus.Warnf("failed to parse jib json: %s", err.Error()) + log.Entry(context.Background()).Warnf("failed to parse jib json: %s", err.Error()) return nil } diff --git a/pkg/skaffold/build/jib/jib.go b/pkg/skaffold/build/jib/jib.go index 4fd61224bac..157ffd4d462 100644 --- a/pkg/skaffold/build/jib/jib.go +++ b/pkg/skaffold/build/jib/jib.go @@ -31,9 +31,9 @@ import ( "time" "github.com/google/go-containerregistry/pkg/name" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/walk" @@ -233,7 +233,7 @@ func walkFiles(workspace string, watchedFiles []string, ignoredFiles []string, c info, err := os.Stat(dep) if err != nil { if os.IsNotExist(err) { - logrus.Debugf("could not stat dependency: %s", err) + log.Entry(context.Background()).Debugf("could not stat dependency: %s", err) continue // Ignore files that don't exist } return fmt.Errorf("unable to stat file %q: %w", dep, err) @@ -341,7 +341,7 @@ func baseImageArg(a *latestV1.JibArtifact, r ArtifactResolver, deps []*latestV1. } img, found := r.GetImageTag(d.ImageName) if !found { - logrus.Fatalf("failed to resolve build result for required artifact %q", d.ImageName) + log.Entry(context.Background()).Fatalf("failed to resolve build result for required artifact %q", d.ImageName) } if pushImages { // pull image from the registry (prefix `registry://` is optional) diff --git a/pkg/skaffold/build/jib/jvm.go b/pkg/skaffold/build/jib/jvm.go index 67528946e69..163c1c9c310 100644 --- a/pkg/skaffold/build/jib/jvm.go +++ b/pkg/skaffold/build/jib/jvm.go @@ -17,11 +17,11 @@ limitations under the License. package jib import ( + "context" "os/exec" "sync" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -54,7 +54,7 @@ func resolveJVM() bool { cmd := exec.Command("java", "-version") err := util.RunCmd(cmd) if err != nil { - logrus.Warnf("Skipping Jib: no JVM: %v failed: %v", cmd.Args, err) + log.Entry(context.Background()).Warnf("Skipping Jib: no JVM: %v failed: %v", cmd.Args, err) } return err == nil } diff --git a/pkg/skaffold/build/jib/maven.go b/pkg/skaffold/build/jib/maven.go index e7a09d36e04..7965c8d2bf1 100644 --- a/pkg/skaffold/build/jib/maven.go +++ b/pkg/skaffold/build/jib/maven.go @@ -22,10 +22,9 @@ import ( "io" "os/exec" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -67,7 +66,7 @@ func (b *Builder) runMavenCommand(ctx context.Context, out io.Writer, workspace cmd.Stdout = out cmd.Stderr = out - logrus.Infof("Building %s: %s, %v", workspace, cmd.Path, cmd.Args) + log.Entry(ctx).Infof("Building %s: %s, %v", workspace, cmd.Path, cmd.Args) if err := util.RunCmd(&cmd); err != nil { return fmt.Errorf("maven build failed: %w", err) } @@ -82,7 +81,7 @@ func getDependenciesMaven(ctx context.Context, workspace string, a *latestV1.Jib if err != nil { return nil, dependencyErr(JibMaven, workspace, err) } - logrus.Debugf("Found dependencies for jib maven artifact: %v", deps) + log.Entry(ctx).Debugf("Found dependencies for jib maven artifact: %v", deps) return deps, nil } diff --git a/pkg/skaffold/build/jib/sync.go b/pkg/skaffold/build/jib/sync.go index 1c0f9af029f..d3ff3cde823 100644 --- a/pkg/skaffold/build/jib/sync.go +++ b/pkg/skaffold/build/jib/sync.go @@ -27,9 +27,8 @@ import ( "regexp" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/filemon" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -72,7 +71,7 @@ func getSyncDiff(ctx context.Context, workspace string, a *latestV1.JibArtifact, // no deletions allowed if len(e.Deleted) != 0 { // change into logging - logrus.Debug("Deletions are not supported by jib auto sync at the moment") + log.Entry(ctx).Debug("Deletions are not supported by jib auto sync at the moment") return nil, nil, nil } diff --git a/pkg/skaffold/build/local/local.go b/pkg/skaffold/build/local/local.go index 9cab058515c..2dbbfc374ec 100644 --- a/pkg/skaffold/build/local/local.go +++ b/pkg/skaffold/build/local/local.go @@ -20,11 +20,10 @@ import ( "context" "io" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -80,7 +79,7 @@ func (b *Builder) buildArtifact(ctx context.Context, out io.Writer, a *latestV1. if a.DockerArtifact != nil { imageID, err := b.getImageIDForTag(ctx, tag) if err != nil { - logrus.Warnf("unable to inspect image: built images may not be cleaned up correctly by skaffold") + log.Entry(ctx).Warn("unable to inspect image: built images may not be cleaned up correctly by skaffold") } if imageID != "" { b.builtImages = append(b.builtImages, imageID) diff --git a/pkg/skaffold/build/local/prune.go b/pkg/skaffold/build/local/prune.go index fdff6c6e496..b0b1d9bd541 100644 --- a/pkg/skaffold/build/local/prune.go +++ b/pkg/skaffold/build/local/prune.go @@ -24,9 +24,9 @@ import ( "github.com/docker/docker/api/types" "github.com/dustin/go-humanize" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const ( @@ -76,13 +76,13 @@ func (p *pruner) cleanup(ctx context.Context, sync bool, artifacts []string) { if sync { err := p.runPrune(ctx, toPrune) if err != nil { - logrus.Debugf("Failed to prune: %v", err) + log.Entry(ctx).Debugf("Failed to prune: %v", err) } } else { go func() { err := p.runPrune(ctx, toPrune) if err != nil { - logrus.Debugf("Failed to prune: %v", err) + log.Entry(ctx).Debugf("Failed to prune: %v", err) } }() } @@ -104,12 +104,12 @@ func (p *pruner) isPruned(id string) bool { } func (p *pruner) runPrune(ctx context.Context, ids []string) error { - logrus.Debugf("Going to prune: %v", ids) + log.Entry(ctx).Debugf("Going to prune: %v", ids) // docker API does not support concurrent prune/utilization info request // so let's serialize the access to it t0 := time.Now() p.pruneMutex.Lock() - logrus.Tracef("Prune mutex wait time: %v", time.Since(t0)) + log.Entry(ctx).Tracef("Prune mutex wait time: %v", time.Since(t0)) defer p.pruneMutex.Unlock() beforeDu, err := p.diskUsage(ctx) @@ -117,7 +117,7 @@ func (p *pruner) runPrune(ctx context.Context, ids []string) error { if ctx.Err() != nil { return ctx.Err() } - logrus.Debugf("Failed to get docker usage info: %v", err) + log.Entry(ctx).Debugf("Failed to get docker usage info: %v", err) } pruned, err := p.localDocker.Prune(ctx, ids, p.pruneChildren) @@ -134,14 +134,14 @@ func (p *pruner) runPrune(ctx context.Context, ids []string) error { if ctx.Err() != nil { return ctx.Err() } - logrus.Debugf("Failed to get docker usage info: %v", err) + log.Entry(ctx).Debugf("Failed to get docker usage info: %v", err) return nil } if beforeDu >= afterDu { - logrus.Infof("%d image(s) pruned. Reclaimed disk space: %s", + log.Entry(ctx).Infof("%d image(s) pruned. Reclaimed disk space: %s", len(ids), humanize.Bytes(beforeDu-afterDu)) } else { - logrus.Infof("%d image(s) pruned", len(ids)) + log.Entry(ctx).Infof("%d image(s) pruned", len(ids)) } } return nil @@ -167,7 +167,7 @@ func (p *pruner) collectImagesToPrune(ctx context.Context, artifacts []string) [ case context.Canceled, context.DeadlineExceeded: return []string{} } - logrus.Warnf("failed to list images: %v", err) + log.Entry(ctx).Warnf("failed to list images: %v", err) continue } for i := imgNameCount[a]; i < len(imgs); i++ { @@ -187,7 +187,7 @@ func (p *pruner) diskUsage(ctx context.Context) (uint64, error) { return 0, ctx.Err() } // DiskUsage(..) may return "operation in progress" error. - logrus.Debugf("[%d of %d] failed to get disk usage: %v. Will retry in %v", + log.Entry(ctx).Debugf("[%d of %d] failed to get disk usage: %v. Will retry in %v", retry, usageRetries, err, usageRetryInterval) time.Sleep(usageRetryInterval) } @@ -196,6 +196,6 @@ func (p *pruner) diskUsage(ctx context.Context) (uint64, error) { if err == nil { return usage, nil } - logrus.Debugf("Failed to get usage after: %v. giving up", err) + log.Entry(ctx).Debugf("Failed to get usage after: %v. giving up", err) return 0, err } diff --git a/pkg/skaffold/build/local/types.go b/pkg/skaffold/build/local/types.go index 69198c63983..84b98a5f566 100644 --- a/pkg/skaffold/build/local/types.go +++ b/pkg/skaffold/build/local/types.go @@ -21,8 +21,6 @@ import ( "fmt" "io" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/bazel" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/buildpacks" @@ -33,6 +31,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -92,10 +91,10 @@ func NewBuilder(bCtx BuilderContext, buildCfg *latestV1.LocalBuild) (*Builder, e switch { case pushFlag.Value() != nil: pushImages = *pushFlag.Value() - logrus.Debugf("push value set via skaffold build --push flag, --push=%t", *pushFlag.Value()) + log.Entry(context.Background()).Debugf("push value set via skaffold build --push flag, --push=%t", *pushFlag.Value()) case buildCfg.Push == nil: pushImages = cluster.PushImages - logrus.Debugf("push value not present in NewBuilder, defaulting to %t because cluster.PushImages is %t", pushImages, cluster.PushImages) + log.Entry(context.Background()).Debugf("push value not present in NewBuilder, defaulting to %t because cluster.PushImages is %t", pushImages, cluster.PushImages) default: pushImages = *buildCfg.Push } diff --git a/pkg/skaffold/build/misc/graceful.go b/pkg/skaffold/build/misc/graceful.go index 9171ece663d..00fd5fd213c 100644 --- a/pkg/skaffold/build/misc/graceful.go +++ b/pkg/skaffold/build/misc/graceful.go @@ -24,7 +24,7 @@ import ( "sync" "time" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // For testing @@ -49,7 +49,7 @@ func HandleGracefulTermination(ctx context.Context, cmd *exec.Cmd) error { return } - logrus.Debugln("Sending SIGINT to process", cmd.Process.Pid) + log.Entry(ctx).Debug("Sending SIGINT to process", cmd.Process.Pid) if err := cmd.Process.Signal(os.Interrupt); err != nil { // kill process on error cmd.Process.Kill() @@ -59,7 +59,7 @@ func HandleGracefulTermination(ctx context.Context, cmd *exec.Cmd) error { // wait 2 seconds or wait for the process to complete select { case <-time.After(gracePeriod): - logrus.Debugln("Killing process", cmd.Process.Pid) + log.Entry(ctx).Debug("Killing process", cmd.Process.Pid) // forcefully kill process after grace period cmd.Process.Kill() case <-done: diff --git a/pkg/skaffold/build/result.go b/pkg/skaffold/build/result.go index cdde1596bba..d959b0c610b 100644 --- a/pkg/skaffold/build/result.go +++ b/pkg/skaffold/build/result.go @@ -23,10 +23,9 @@ import ( "io" "sync" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -158,7 +157,7 @@ func (ba *artifactStoreImpl) GetImageTag(imageName string) (string, bool) { } t, ok := v.(string) if !ok { - logrus.Fatalf("invalid build output recorded for image %s", imageName) + log.Entry(context.Background()).Fatalf("invalid build output recorded for image %s", imageName) } return t, true } diff --git a/pkg/skaffold/build/scheduler.go b/pkg/skaffold/build/scheduler.go index 8655d6561fd..cbb4e155816 100644 --- a/pkg/skaffold/build/scheduler.go +++ b/pkg/skaffold/build/scheduler.go @@ -110,7 +110,7 @@ func (s *scheduler) build(ctx context.Context, tags tag.ImageTags, i int) error } defer closeFn() - w = output.WithEventContext(w, constants.Build, a.ImageName) + w, ctx = output.WithEventContext(ctx, w, constants.Build, a.ImageName) finalTag, err := performBuild(ctx, w, tags, a, s.artifactBuilder) if err != nil { event.BuildFailed(a.ImageName, err) diff --git a/pkg/skaffold/cluster/minikube.go b/pkg/skaffold/cluster/minikube.go index 7579c19037d..7ac369c7f43 100644 --- a/pkg/skaffold/cluster/minikube.go +++ b/pkg/skaffold/cluster/minikube.go @@ -17,6 +17,7 @@ limitations under the License. package cluster import ( + "context" "encoding/json" "errors" "fmt" @@ -27,11 +28,11 @@ import ( "sync" "github.com/blang/semver" - "github.com/sirupsen/logrus" "k8s.io/client-go/util/homedir" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + kctx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/version" ) @@ -44,7 +45,7 @@ var ( // To override during tests var ( FindMinikubeBinary = minikubeBinary - getClusterInfo = context.GetClusterInfo + getClusterInfo = kctx.GetClusterInfo GetCurrentVersionFunc = getCurrentVersion findOnce sync.Once @@ -70,7 +71,7 @@ func getClient() Client { func (clientImpl) IsMinikube(kubeContext string) bool { if _, _, err := FindMinikubeBinary(); err != nil { - logrus.Tracef("Minikube cluster not detected: %v", err) + log.Entry(context.Background()).Tracef("Minikube cluster not detected: %v", err) return false } // short circuit if context is 'minikube' @@ -80,21 +81,21 @@ func (clientImpl) IsMinikube(kubeContext string) bool { cluster, err := getClusterInfo(kubeContext) if err != nil { - logrus.Tracef("failed to get cluster info: %v", err) + log.Entry(context.Background()).Tracef("failed to get cluster info: %v", err) return false } if matchClusterCertPath(cluster.CertificateAuthority) { - logrus.Debugf("Minikube cluster detected: cluster certificate for context %q found inside the minikube directory", kubeContext) + log.Entry(context.Background()).Debugf("Minikube cluster detected: cluster certificate for context %q found inside the minikube directory", kubeContext) return true } if ok, err := matchServerURL(cluster.Server); err != nil { - logrus.Tracef("failed to match server url: %v", err) + log.Entry(context.Background()).Tracef("failed to match server url: %v", err) } else if ok { - logrus.Debugf("Minikube cluster detected: server url for context %q matches minikube node ip", kubeContext) + log.Entry(context.Background()).Debugf("Minikube cluster detected: server url for context %q matches minikube node ip", kubeContext) return true } - logrus.Tracef("Minikube cluster not detected for context %q", kubeContext) + log.Entry(context.Background()).Tracef("Minikube cluster not detected for context %q", kubeContext) return false } @@ -183,7 +184,7 @@ func matchServerURL(server string) (bool, error) { serverURL, err := url.Parse(server) if err != nil { - logrus.Tracef("invalid server url: %v", err) + log.Entry(context.Background()).Tracef("invalid server url: %v", err) } for _, v := range data.Valid { diff --git a/pkg/skaffold/config/portforward.go b/pkg/skaffold/config/portforward.go index 6c90cd379fd..b8b27373bc0 100644 --- a/pkg/skaffold/config/portforward.go +++ b/pkg/skaffold/config/portforward.go @@ -17,12 +17,14 @@ limitations under the License. package config import ( + "context" "fmt" "strconv" "strings" - "github.com/sirupsen/logrus" "github.com/spf13/pflag" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // These are the list of accepted port-forward modes. @@ -128,7 +130,7 @@ func (p *PortForwardOptions) Replace(options []string) error { p.reset() for _, o := range options { if err := p.Append(o); err != nil { - logrus.Fatal(err) // should never happen since we validated the options + log.Entry(context.Background()).Fatal(err) // should never happen since we validated the options } } return nil diff --git a/pkg/skaffold/config/util.go b/pkg/skaffold/config/util.go index 071329dd35a..cd37cf5e29b 100644 --- a/pkg/skaffold/config/util.go +++ b/pkg/skaffold/config/util.go @@ -17,6 +17,7 @@ limitations under the License. package config import ( + "context" "fmt" "io/ioutil" "path/filepath" @@ -26,11 +27,11 @@ import ( "github.com/imdario/mergo" "github.com/mitchellh/go-homedir" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/cluster" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/timeutil" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" @@ -71,12 +72,12 @@ func readConfigFileCached(filename string) (*GlobalConfig, error) { filenameOrDefault, err := ResolveConfigFile(filename) if err != nil { configFileErr = err - logrus.Warnf("Could not load global Skaffold defaults. Error resolving config file %q", filenameOrDefault) + log.Entry(context.Background()).Warnf("Could not load global Skaffold defaults. Error resolving config file %q", filenameOrDefault) return } configFile, configFileErr = ReadConfigFileNoCache(filenameOrDefault) if configFileErr == nil { - logrus.Infof("Loaded Skaffold defaults from %q", filenameOrDefault) + log.Entry(context.Background()).Infof("Loaded Skaffold defaults from %q", filenameOrDefault) } }) return configFile, configFileErr @@ -99,12 +100,12 @@ func ResolveConfigFile(configFile string) (string, error) { func ReadConfigFileNoCache(configFile string) (*GlobalConfig, error) { contents, err := ioutil.ReadFile(configFile) if err != nil { - logrus.Warnf("Could not load global Skaffold defaults. Error encounter while reading file %q", configFile) + log.Entry(context.Background()).Warnf("Could not load global Skaffold defaults. Error encounter while reading file %q", configFile) return nil, fmt.Errorf("reading global config: %w", err) } config := GlobalConfig{} if err := yaml.Unmarshal(contents, &config); err != nil { - logrus.Warnf("Could not load global Skaffold defaults. Error encounter while unmarshalling the contents of file %q", configFile) + log.Entry(context.Background()).Warnf("Could not load global Skaffold defaults. Error encounter while unmarshalling the contents of file %q", configFile) return nil, fmt.Errorf("unmarshalling global skaffold config: %w", err) } return &config, nil @@ -142,7 +143,7 @@ func getConfigForKubeContextWithGlobalDefaults(cfg *GlobalConfig, kubeContext st var mergedConfig ContextConfig for _, contextCfg := range cfg.ContextConfigs { if util.RegexEqual(contextCfg.Kubecontext, kubeContext) { - logrus.Debugf("found config for context %q", kubeContext) + log.Entry(context.Background()).Debugf("found config for context %q", kubeContext) mergedConfig = *contextCfg } } @@ -169,7 +170,7 @@ func GetDefaultRepo(configFile string, cliValue *string) (string, error) { return "", err } if cfg.DefaultRepo != "" { - logrus.Infof("Using default-repo=%s from config", cfg.DefaultRepo) + log.Entry(context.Background()).Infof("Using default-repo=%s from config", cfg.DefaultRepo) } return cfg.DefaultRepo, nil } @@ -180,7 +181,7 @@ func GetInsecureRegistries(configFile string) ([]string, error) { return nil, err } if len(cfg.InsecureRegistries) > 0 { - logrus.Infof("Using insecure-registries=%v from config", cfg.InsecureRegistries) + log.Entry(context.Background()).Infof("Using insecure-registries=%v from config", cfg.InsecureRegistries) } return cfg.InsecureRegistries, nil } @@ -192,7 +193,7 @@ func GetDebugHelpersRegistry(configFile string) (string, error) { } if cfg.DebugHelpersRegistry != "" { - logrus.Infof("Using debug-helpers-registry=%s from config", cfg.DebugHelpersRegistry) + log.Entry(context.Background()).Infof("Using debug-helpers-registry=%s from config", cfg.DebugHelpersRegistry) return cfg.DebugHelpersRegistry, nil } return constants.DefaultDebugHelpersRegistry, nil @@ -213,7 +214,7 @@ func GetCluster(configFile string, minikubeProfile string, detectMinikube bool) local = true case cfg.LocalCluster != nil: - logrus.Infof("Using local-cluster=%t from config", *cfg.LocalCluster) + log.Entry(context.Background()).Infof("Using local-cluster=%t from config", *cfg.LocalCluster) local = *cfg.LocalCluster case kubeContext == constants.DefaultMinikubeContext || diff --git a/pkg/skaffold/constants/constants.go b/pkg/skaffold/constants/constants.go index dacd57ef183..32d4c34b855 100644 --- a/pkg/skaffold/constants/constants.go +++ b/pkg/skaffold/constants/constants.go @@ -76,6 +76,10 @@ const ( // HaTS is the HaTS Survey ID HaTS = "hats" + + // SubtaskIDNone is the value used for Event API messages when there is no + // corresponding subtask + SubtaskIDNone = "-1" ) type Phase string diff --git a/pkg/skaffold/debug/apply_transforms.go b/pkg/skaffold/debug/apply_transforms.go index 3c86f582c93..270802c3ec9 100644 --- a/pkg/skaffold/debug/apply_transforms.go +++ b/pkg/skaffold/debug/apply_transforms.go @@ -31,6 +31,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" ) @@ -67,14 +68,14 @@ func applyDebuggingTransforms(l manifest.ManifestList, retriever configurationRe for _, manifest := range l { obj, _, err := decodeFromYaml(manifest, nil, nil) if err != nil { - logrus.Debugf("Unable to interpret manifest for debugging: %v\n", err) + log.Entry(context.Background()).Debugf("Unable to interpret manifest for debugging: %v\n", err) } else if transformManifest(obj, retriever, debugHelpersRegistry) { manifest, err = encodeAsYaml(obj) if err != nil { return nil, fmt.Errorf("marshalling yaml: %w", err) } if logrus.IsLevelEnabled(logrus.DebugLevel) { - logrus.Debugln("Applied debugging transform:\n", string(manifest)) + log.Entry(context.Background()).Debugln("Applied debugging transform:\n", string(manifest)) } } updated = append(updated, manifest) @@ -87,12 +88,12 @@ func applyDebuggingTransforms(l manifest.ManifestList, retriever configurationRe // If `builds` is empty, then treat all `image` images as a build artifact. func findArtifact(image string, builds []graph.Artifact) *graph.Artifact { if len(builds) == 0 { - logrus.Debugf("No build artifacts specified: using image as-is %q", image) + log.Entry(context.Background()).Debugf("No build artifacts specified: using image as-is %q", image) return &graph.Artifact{ImageName: image, Tag: image} } for _, artifact := range builds { if image == artifact.ImageName || image == artifact.Tag { - logrus.Debugf("Found artifact for image %q", image) + log.Entry(context.Background()).Debugf("Found artifact for image %q", image) return &artifact } } @@ -113,12 +114,12 @@ func retrieveImageConfiguration(ctx context.Context, artifact *graph.Artifact, i // the apiClient will go to the remote registry if local docker daemon is not available manifest, err := apiClient.ConfigFile(ctx, artifact.Tag) if err != nil { - logrus.Debugf("Error retrieving image manifest for %v: %v", artifact.Tag, err) + log.Entry(ctx).Debugf("Error retrieving image manifest for %v: %v", artifact.Tag, err) return imageConfiguration{}, fmt.Errorf("retrieving image config for %q: %w", artifact.Tag, err) } config := manifest.Config - logrus.Debugf("Retrieved local image configuration for %v: %v", artifact.Tag, config) + log.Entry(ctx).Debugf("Retrieved local image configuration for %v: %v", artifact.Tag, config) // need to duplicate slices as apiClient caches requests return imageConfiguration{ artifact: artifact.ImageName, diff --git a/pkg/skaffold/debug/cnb.go b/pkg/skaffold/debug/cnb.go index 9abc3a37904..f2340a31b19 100644 --- a/pkg/skaffold/debug/cnb.go +++ b/pkg/skaffold/debug/cnb.go @@ -17,6 +17,7 @@ limitations under the License. package debug import ( + "context" "encoding/json" "fmt" "strings" @@ -24,10 +25,10 @@ import ( cnb "github.com/buildpacks/lifecycle" cnbl "github.com/buildpacks/lifecycle/launch" shell "github.com/kballard/go-shellquote" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const ( @@ -202,7 +203,7 @@ func adjustCommandLine(m cnb.BuildMetadata, ic imageConfiguration) (imageConfigu } if len(ic.arguments) == 0 { - logrus.Warnf("no CNB launch found for %s", ic.artifact) + log.Entry(context.Background()).Warnf("no CNB launch found for %s", ic.artifact) return ic, nil } diff --git a/pkg/skaffold/debug/transform.go b/pkg/skaffold/debug/transform.go index ab53e1a5be9..1796df8e1a1 100644 --- a/pkg/skaffold/debug/transform.go +++ b/pkg/skaffold/debug/transform.go @@ -52,13 +52,13 @@ and a set of debugging ports. package debug import ( + "context" "encoding/json" "fmt" "strings" "time" shell "github.com/kballard/go-shellquote" - "github.com/sirupsen/logrus" appsv1 "k8s.io/api/apps/v1" batchv1 "k8s.io/api/batch/v1" v1 "k8s.io/api/core/v1" @@ -67,6 +67,7 @@ import ( "k8s.io/apimachinery/pkg/runtime" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // portAllocator is a function that takes a desired port and returns an available port @@ -174,12 +175,12 @@ func transformManifest(obj runtime.Object, retrieveImageConfiguration configurat if group == "apps" || group == "batch" { if version != "v1" { // treat deprecated objects as errors - logrus.Errorf("deprecated versions not supported by debug: %s (%s)", description, version) + log.Entry(context.Background()).Errorf("deprecated versions not supported by debug: %s (%s)", description, version) } else { - logrus.Warnf("no debug transformation for: %s", description) + log.Entry(context.Background()).Warnf("no debug transformation for: %s", description) } } else { - logrus.Debugf("no debug transformation for: %s", description) + log.Entry(context.Background()).Debugf("no debug transformation for: %s", description) } return false } @@ -199,23 +200,23 @@ func rewriteProbes(metadata *metav1.ObjectMeta, podSpec *v1.PodSpec) bool { var minTimeout time.Duration = 10 * time.Minute // make it configurable? if annotation, found := metadata.Annotations[annotations.DebugProbeTimeouts]; found { if annotation == "skip" { - logrus.Debugf("skipping probe rewrite on %q by request", metadata.Name) + log.Entry(context.Background()).Debugf("skipping probe rewrite on %q by request", metadata.Name) return false } if d, err := time.ParseDuration(annotation); err != nil { - logrus.Warnf("invalid probe timeout value for %q: %q: %v", metadata.Name, annotation, err) + log.Entry(context.Background()).Warnf("invalid probe timeout value for %q: %q: %v", metadata.Name, annotation, err) } else { minTimeout = d } } annotation, found := metadata.Annotations[annotations.DebugConfig] if !found { - logrus.Debugf("skipping probe rewrite on %q: not configured for debugging", metadata.Name) + log.Entry(context.Background()).Debugf("skipping probe rewrite on %q: not configured for debugging", metadata.Name) return false } var config map[string]annotations.ContainerDebugConfiguration if err := json.Unmarshal([]byte(annotation), &config); err != nil { - logrus.Warnf("error unmarshalling debugging configuration for %q: %v", metadata.Name, err) + log.Entry(context.Background()).Warnf("error unmarshalling debugging configuration for %q: %v", metadata.Name, err) return false } @@ -228,7 +229,7 @@ func rewriteProbes(metadata *metav1.ObjectMeta, podSpec *v1.PodSpec) bool { rp := rewriteHTTPGetProbe(c.ReadinessProbe, minTimeout) sp := rewriteHTTPGetProbe(c.StartupProbe, minTimeout) if lp || rp || sp { - logrus.Infof("Updated probe timeouts for %s/%s", metadata.Name, c.Name) + log.Entry(context.Background()).Infof("Updated probe timeouts for %s/%s", metadata.Name, c.Name) } changed = changed || lp || rp || sp } @@ -277,18 +278,18 @@ func rewriteContainers(metadata *metav1.ObjectMeta, podSpec *v1.PodSpec, retriev configurations[container.Name] = configuration podSpec.Containers[i] = container // apply any configuration changes if len(requiredImage) > 0 { - logrus.Infof("%q requires debugging support image %q", container.Name, requiredImage) + log.Entry(context.Background()).Infof("%q requires debugging support image %q", container.Name, requiredImage) containersRequiringSupport = append(containersRequiringSupport, &podSpec.Containers[i]) requiredSupportImages[requiredImage] = true } } else { - logrus.Warnf("Image %q not configured for debugging: %v", container.Name, err) + log.Entry(context.Background()).Warnf("Image %q not configured for debugging: %v", container.Name, err) } } // check if we have any images requiring additional debugging support files if len(containersRequiringSupport) > 0 { - logrus.Infof("Configuring installation of debugging support files") + log.Entry(context.Background()).Info("Configuring installation of debugging support files") // we create the volume that will hold the debugging support files supportVolume := v1.Volume{Name: debuggingSupportFilesVolume, VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{}}} podSpec.Volumes = append(podSpec.Volumes, supportVolume) @@ -434,7 +435,7 @@ func isShDashC(cmd, arg string) bool { } func performContainerTransform(container *v1.Container, config imageConfiguration, portAlloc portAllocator) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Tracef("Examining container %q with config %v", container.Name, config) + log.Entry(context.Background()).Tracef("Examining container %q with config %v", container.Name, config) for _, transform := range containerTransforms { if transform.IsApplicable(config) { return transform.Apply(container, config, portAlloc, Protocols) @@ -479,14 +480,14 @@ func exposePort(entries []v1.ContainerPort, portName string, port int32) []v1.Co switch { case entries[i].Name == portName: // Ports and names must be unique so rewrite an existing entry if found - logrus.Warnf("skaffold debug needs to expose port %d with name %s. Replacing clashing port definition %d (%s)", port, portName, entries[i].ContainerPort, entries[i].Name) + log.Entry(context.Background()).Warnf("skaffold debug needs to expose port %d with name %s. Replacing clashing port definition %d (%s)", port, portName, entries[i].ContainerPort, entries[i].Name) entries[i].Name = portName entries[i].ContainerPort = port found = true i++ case entries[i].ContainerPort == port: // Cut any entries with a clashing port - logrus.Warnf("skaffold debug needs to expose port %d for %s. Removing clashing port definition %d (%s)", port, portName, entries[i].ContainerPort, entries[i].Name) + log.Entry(context.Background()).Warnf("skaffold debug needs to expose port %d for %s. Removing clashing port definition %d (%s)", port, portName, entries[i].ContainerPort, entries[i].Name) entries = append(entries[:i], entries[i+1:]...) default: i++ diff --git a/pkg/skaffold/debug/transform_go.go b/pkg/skaffold/debug/transform_go.go index ef75153d269..80cefd4e70e 100644 --- a/pkg/skaffold/debug/transform_go.go +++ b/pkg/skaffold/debug/transform_go.go @@ -17,14 +17,15 @@ limitations under the License. package debug import ( + "context" "fmt" "strconv" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -62,7 +63,7 @@ func isLaunchingDlv(args []string) bool { func (t dlvTransformer) IsApplicable(config imageConfiguration) bool { for _, name := range []string{"GODEBUG", "GOGC", "GOMAXPROCS", "GOTRACEBACK"} { if _, found := config.env[name]; found { - logrus.Infof("Artifact %q has Go runtime: has env %q", config.artifact, name) + log.Entry(context.Background()).Infof("Artifact %q has Go runtime: has env %q", config.artifact, name) return true } } @@ -78,7 +79,7 @@ func (t dlvTransformer) IsApplicable(config imageConfiguration) bool { cnbBuildMetadata := config.labels["io.buildpacks.build.metadata"] for _, id := range knownGoBuildpackIds { if strings.Contains(cnbBuildMetadata, id) { - logrus.Infof("Artifact %q has Go buildpacks %q", config.artifact, id) + log.Entry(context.Background()).Infof("Artifact %q has Go buildpacks %q", config.artifact, id) return true } } @@ -94,7 +95,7 @@ func (t dlvTransformer) IsApplicable(config imageConfiguration) bool { // Apply configures a container definition for Go with Delve. // Returns the debug configuration details, with the "go" support image func (t dlvTransformer) Apply(container *v1.Container, config imageConfiguration, portAlloc portAllocator, overrideProtocols []string) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Infof("Configuring %q for Go/Delve debugging", container.Name) + log.Entry(context.Background()).Infof("Configuring %q for Go/Delve debugging", container.Name) // try to find existing `dlv` command spec := retrieveDlvSpec(config) diff --git a/pkg/skaffold/debug/transform_jvm.go b/pkg/skaffold/debug/transform_jvm.go index fef8935ad2f..e51d8f2b3b3 100644 --- a/pkg/skaffold/debug/transform_jvm.go +++ b/pkg/skaffold/debug/transform_jvm.go @@ -17,14 +17,15 @@ limitations under the License. package debug import ( + "context" "fmt" "strconv" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type jdwpTransformer struct{} @@ -66,7 +67,7 @@ type jdwpSpec struct { // Apply configures a container definition for JVM debugging. // Returns a simple map describing the debug configuration details. func (t jdwpTransformer) Apply(container *v1.Container, config imageConfiguration, portAlloc portAllocator, overrideProtocols []string) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Infof("Configuring %q for JVM debugging", container.Name) + log.Entry(context.Background()).Infof("Configuring %q for JVM debugging", container.Name) // try to find existing JAVA_TOOL_OPTIONS or jdwp command argument spec := retrieveJdwpSpec(config) diff --git a/pkg/skaffold/debug/transform_netcore.go b/pkg/skaffold/debug/transform_netcore.go index f218170a608..d6acb023b51 100644 --- a/pkg/skaffold/debug/transform_netcore.go +++ b/pkg/skaffold/debug/transform_netcore.go @@ -17,12 +17,13 @@ limitations under the License. package debug import ( + "context" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type netcoreTransformer struct{} @@ -70,7 +71,7 @@ func (t netcoreTransformer) IsApplicable(config imageConfiguration) bool { // Apply configures a container definition for vsdbg. // Returns a simple map describing the debug configuration details. func (t netcoreTransformer) Apply(container *v1.Container, config imageConfiguration, portAlloc portAllocator, overrideProtocols []string) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Infof("Configuring %q for netcore debugging", container.Name) + log.Entry(context.Background()).Infof("Configuring %q for netcore debugging", container.Name) return annotations.ContainerDebugConfiguration{ Runtime: "netcore", diff --git a/pkg/skaffold/debug/transform_nodejs.go b/pkg/skaffold/debug/transform_nodejs.go index da8526db6b3..5d907ca4edd 100644 --- a/pkg/skaffold/debug/transform_nodejs.go +++ b/pkg/skaffold/debug/transform_nodejs.go @@ -17,13 +17,14 @@ limitations under the License. package debug import ( + "context" "strconv" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -77,7 +78,7 @@ func (t nodeTransformer) IsApplicable(config imageConfiguration) bool { // Apply configures a container definition for NodeJS Chrome V8 Inspector. // Returns a simple map describing the debug configuration details. func (t nodeTransformer) Apply(container *v1.Container, config imageConfiguration, portAlloc portAllocator, overrideProtocols []string) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Infof("Configuring %q for node.js debugging", container.Name) + log.Entry(context.Background()).Infof("Configuring %q for node.js debugging", container.Name) // try to find existing `--inspect` command spec := retrieveNodeInspectSpec(config) @@ -164,7 +165,7 @@ func extractInspectArg(arg string) *inspectSpec { if split := strings.SplitN(address, ":", 2); len(split) == 1 { port, err := strconv.ParseInt(split[0], 10, 32) if err != nil { - logrus.Errorf("Invalid NodeJS inspect port %q: %s\n", address, err) + log.Entry(context.Background()).Errorf("Invalid NodeJS inspect port %q: %s\n", address, err) return nil } spec.port = int32(port) @@ -172,7 +173,7 @@ func extractInspectArg(arg string) *inspectSpec { spec.host = split[0] port, err := strconv.ParseInt(split[1], 10, 32) if err != nil { - logrus.Errorf("Invalid NodeJS inspect port %q: %s\n", address, err) + log.Entry(context.Background()).Errorf("Invalid NodeJS inspect port %q: %s\n", address, err) return nil } spec.port = int32(port) diff --git a/pkg/skaffold/debug/transform_python.go b/pkg/skaffold/debug/transform_python.go index 6cb77875f04..b72daa05111 100644 --- a/pkg/skaffold/debug/transform_python.go +++ b/pkg/skaffold/debug/transform_python.go @@ -17,14 +17,15 @@ limitations under the License. package debug import ( + "context" "fmt" "strconv" "strings" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -108,7 +109,7 @@ func (t pythonTransformer) IsApplicable(config imageConfiguration) bool { // Apply configures a container definition for Python with ptvsd/debugpy/pydevd. // Returns a simple map describing the debug configuration details. func (t pythonTransformer) Apply(container *v1.Container, config imageConfiguration, portAlloc portAllocator, overrideProtocols []string) (annotations.ContainerDebugConfiguration, string, error) { - logrus.Infof("Configuring %q for python debugging", container.Name) + log.Entry(context.Background()).Infof("Configuring %q for python debugging", container.Name) // try to find existing `-mptvsd` or `-mdebugpy` command if spec := retrievePythonDebugSpec(config); spec != nil { @@ -197,7 +198,7 @@ func extractPtvsdSpec(args []string) *pythonSpec { port, err := strconv.ParseInt(args[i+1], 10, 32) // spec.port, err := strconv.Atoi(args[i+1]) if err != nil { - logrus.Errorf("Invalid python ptvsd port %q: %s\n", args[i+1], err) + log.Entry(context.Background()).Errorf("Invalid python ptvsd port %q: %s\n", args[i+1], err) return nil } spec.port = int32(port) @@ -226,7 +227,7 @@ func extractDebugpySpec(args []string) *pythonSpec { } port, err := strconv.ParseInt(s[len(s)-1], 10, 32) if err != nil { - logrus.Errorf("Invalid port %q: %s\n", args[i+1], err) + log.Entry(context.Background()).Errorf("Invalid port %q: %s\n", args[i+1], err) return nil } spec.port = int32(port) @@ -286,7 +287,7 @@ func (spec pythonSpec) launcherMode() string { case debugpy: return "debugpy" } - logrus.Fatalf("invalid debugger type: %q", spec.debugger) + log.Entry(context.Background()).Fatalf("invalid debugger type: %q", spec.debugger) return "" } @@ -297,7 +298,7 @@ func (spec pythonSpec) protocol() string { case debugpy, ptvsd: return dapProtocol default: - logrus.Fatalf("invalid debugger type: %q", spec.debugger) + log.Entry(context.Background()).Fatalf("invalid debugger type: %q", spec.debugger) return dapProtocol } } diff --git a/pkg/skaffold/deploy/deploy_mux.go b/pkg/skaffold/deploy/deploy_mux.go index eebfad364ae..94fc84f817c 100644 --- a/pkg/skaffold/deploy/deploy_mux.go +++ b/pkg/skaffold/deploy/deploy_mux.go @@ -107,7 +107,7 @@ func (m DeployerMux) RegisterLocalImages(images []graph.Artifact) { func (m DeployerMux) Deploy(ctx context.Context, w io.Writer, as []graph.Artifact) error { for i, deployer := range m.deployers { eventV2.DeployInProgress(i) - w = output.WithEventContext(w, constants.Deploy, strconv.Itoa(i)) + w, ctx = output.WithEventContext(ctx, w, constants.Deploy, strconv.Itoa(i)) ctx, endTrace := instrumentation.StartTrace(ctx, "Deploy") deployHooks, ok := deployer.(deployerWithHooks) if ok { diff --git a/pkg/skaffold/deploy/docker/deploy.go b/pkg/skaffold/deploy/docker/deploy.go index 867947ea5a9..bdd53d88972 100644 --- a/pkg/skaffold/deploy/docker/deploy.go +++ b/pkg/skaffold/deploy/docker/deploy.go @@ -24,7 +24,6 @@ import ( "github.com/google/uuid" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/access" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug" @@ -34,6 +33,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker/tracker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" v1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/status" pkgsync "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -118,11 +118,11 @@ func (d *Deployer) Deploy(ctx context.Context, out io.Writer, builds []graph.Art func (d *Deployer) deploy(ctx context.Context, out io.Writer, b graph.Artifact) error { if !util.StrSliceContains(d.cfg.Images, b.ImageName) { // TODO(nkubala)[07/20/21]: should we error out in this case? - logrus.Warnf("skipping deploy for image %s since it was not built by Skaffold", b.ImageName) + olog.Entry(ctx).Warnf("skipping deploy for image %s since it was not built by Skaffold", b.ImageName) return nil } if container, found := d.tracker.ContainerForImage(b.ImageName); found { - logrus.Debugf("removing old container %s for image %s", container.ID, b.ImageName) + olog.Entry(ctx).Debugf("removing old container %s for image %s", container.ID, b.ImageName) if err := d.client.Delete(ctx, out, container.ID); err != nil { return fmt.Errorf("failed to remove old container %s for image %s: %w", container.ID, b.ImageName, err) } @@ -167,7 +167,7 @@ func (d *Deployer) getContainerName(ctx context.Context, name string) string { } if currentName != name { - logrus.Debugf("container %s already present in local daemon: using %s instead", name, currentName) + olog.Entry(ctx).Debugf("container %s already present in local daemon: using %s instead", name, currentName) } return currentName } diff --git a/pkg/skaffold/deploy/docker/port.go b/pkg/skaffold/deploy/docker/port.go index ce17040552b..cb8f415ab8b 100644 --- a/pkg/skaffold/deploy/docker/port.go +++ b/pkg/skaffold/deploy/docker/port.go @@ -24,11 +24,11 @@ import ( "sync" "github.com/docker/go-connections/nat" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" v1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -81,7 +81,7 @@ func (pm *PortManager) getPorts(containerName string, pf []*v1.PortForwardResour var ports []int for _, p := range pf { if strings.ToLower(string(p.Type)) != "container" { - logrus.Debugf("skipping non-container port forward resource in Docker deploy: %s\n", p.Name) + log.Entry(context.Background()).Debugf("skipping non-container port forward resource in Docker deploy: %s\n", p.Name) continue } localPort := util.GetAvailablePort(p.Address, p.LocalPort, &pm.portSet) diff --git a/pkg/skaffold/deploy/helm/args.go b/pkg/skaffold/deploy/helm/args.go index d8959d59ff2..a9dcfdc320b 100644 --- a/pkg/skaffold/deploy/helm/args.go +++ b/pkg/skaffold/deploy/helm/args.go @@ -17,16 +17,17 @@ limitations under the License. package helm import ( + "context" "fmt" "runtime" "strconv" "github.com/blang/semver" "github.com/mitchellh/go-homedir" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -74,7 +75,7 @@ func constructOverrideArgs(r *latestV1.HelmRelease, builds []graph.Artifact, arg envMap[k+suffix] = v } } - logrus.Debugf("EnvVarMap: %+v\n", envMap) + log.Entry(context.Background()).Debugf("EnvVarMap: %+v\n", envMap) for _, k := range sortKeys(r.SetValueTemplates) { v, err := util.ExpandEnvTemplate(r.SetValueTemplates[k], envMap) diff --git a/pkg/skaffold/deploy/helm/deploy.go b/pkg/skaffold/deploy/helm/deploy.go index 9dad78dce13..e06f58c13a5 100644 --- a/pkg/skaffold/deploy/helm/deploy.go +++ b/pkg/skaffold/deploy/helm/deploy.go @@ -33,7 +33,6 @@ import ( "github.com/blang/semver" backoff "github.com/cenkalti/backoff/v4" shell "github.com/kballard/go-shellquote" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/access" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" @@ -56,6 +55,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/loader" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/status" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -149,7 +149,7 @@ func NewDeployer(cfg Config, labeller *label.DefaultLabeller, h *latestV1.HelmDe kubectl := pkgkubectl.NewCLI(cfg, cfg.GetKubeNamespace()) namespaces, err := deployutil.GetAllPodNamespaces(cfg.GetNamespace(), cfg.GetPipelines()) if err != nil { - logrus.Warnf("unable to parse namespaces - deploy might not work correctly!") + olog.Entry(context.Background()).Warn("unable to parse namespaces - deploy might not work correctly!") } logger := component.NewLogger(cfg, kubectl, podSelector, &namespaces) return &Deployer{ @@ -229,7 +229,7 @@ func (h *Deployer) Deploy(ctx context.Context, out io.Writer, builds []graph.Art } endTrace() - logrus.Infof("Deploying with helm v%s ...", h.bV) + olog.Entry(ctx).Infof("Deploying with helm v%s ...", h.bV) var dRes []types.Artifact nsMap := map[string]struct{}{} @@ -489,17 +489,17 @@ func (h *Deployer) deployRelease(ctx context.Context, out io.Writer, releaseName opts.flags = h.Flags.Install } else { if r.UpgradeOnChange != nil && !*r.UpgradeOnChange { - logrus.Infof("Release %s already installed...", releaseName) + olog.Entry(ctx).Infof("Release %s already installed...", releaseName) return []types.Artifact{}, nil } else if r.UpgradeOnChange == nil && r.RemoteChart != "" { - logrus.Infof("Release %s not upgraded as it is remote...", releaseName) + olog.Entry(ctx).Infof("Release %s not upgraded as it is remote...", releaseName) return []types.Artifact{}, nil } } // Only build local dependencies, but allow a user to skip them. if !r.SkipBuildDependencies && r.ChartPath != "" { - logrus.Infof("Building helm dependencies...") + olog.Entry(ctx).Info("Building helm dependencies...") if err := h.exec(ctx, out, false, nil, "dep", "build", r.ChartPath); err != nil { return nil, userErr("building helm dependencies", err) @@ -563,13 +563,13 @@ func (h *Deployer) getReleaseManifest(ctx context.Context, releaseName string, n args := getArgs(releaseName, namespace) args = append(args, "--template", "{{.Release.Manifest}}") if err := h.exec(ctx, &b, false, nil, args...); err != nil { - logrus.Debugf("unable to get release: %v (may retry):\n%s", err, b.String()) + olog.Entry(ctx).Debugf("unable to get release: %v (may retry):\n%s", err, b.String()) return err } return nil }, opts) - logrus.Debug(b.String()) + olog.Entry(ctx).Debug(b.String()) return b, err } diff --git a/pkg/skaffold/deploy/helm/parse.go b/pkg/skaffold/deploy/helm/parse.go index edd7b5145a0..844d359abf9 100644 --- a/pkg/skaffold/deploy/helm/parse.go +++ b/pkg/skaffold/deploy/helm/parse.go @@ -19,15 +19,16 @@ package helm import ( "bufio" "bytes" + "context" "fmt" "io" - "github.com/sirupsen/logrus" k8syaml "k8s.io/apimachinery/pkg/util/yaml" "k8s.io/client-go/kubernetes/scheme" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/types" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) func parseReleaseInfo(namespace string, b *bufio.Reader) []types.Artifact { @@ -40,22 +41,22 @@ func parseReleaseInfo(namespace string, b *bufio.Reader) []types.Artifact { break } if err != nil { - logrus.Infof("error parsing object from string: %s", err.Error()) + log.Entry(context.Background()).Infof("error parsing object from string: %s", err.Error()) continue } objNamespace, err := getObjectNamespaceIfDefined(doc, namespace) if err != nil { - logrus.Infof("error parsing object from string: %s", err.Error()) + log.Entry(context.Background()).Infof("error parsing object from string: %s", err.Error()) continue } obj, err := parseRuntimeObject(objNamespace, doc) if err != nil { if i > 0 { - logrus.Infof(err.Error()) + log.Entry(context.Background()).Info(err.Error()) } } else { results = append(results, *obj) - logrus.Debugf("found deployed object: %+v", obj.Obj) + log.Entry(context.Background()).Debugf("found deployed object: %+v", obj.Obj) } } diff --git a/pkg/skaffold/deploy/helm/util.go b/pkg/skaffold/deploy/helm/util.go index 918e2ef48ca..f86f90dd6c8 100644 --- a/pkg/skaffold/deploy/helm/util.go +++ b/pkg/skaffold/deploy/helm/util.go @@ -29,11 +29,11 @@ import ( "strings" "github.com/blang/semver" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -180,7 +180,7 @@ func envVarForImage(imageName string, digest string) map[string]string { customMap[constants.ImageRef.Tag] = ref.Tag customMap[constants.ImageRef.Digest] = ref.Digest } else { - logrus.Warnf("unable to extract values for %v, %v and %v from image %v due to error:\n%v", constants.ImageRef.Repo, constants.ImageRef.Tag, constants.ImageRef.Digest, digest, err) + log.Entry(context.Background()).Warnf("unable to extract values for %v, %v and %v from image %v due to error:\n%v", constants.ImageRef.Repo, constants.ImageRef.Tag, constants.ImageRef.Digest, digest, err) } if digest == "" { diff --git a/pkg/skaffold/deploy/kpt/kpt.go b/pkg/skaffold/deploy/kpt/kpt.go index 87431266eb7..b8bc4f2e8c8 100644 --- a/pkg/skaffold/deploy/kpt/kpt.go +++ b/pkg/skaffold/deploy/kpt/kpt.go @@ -28,7 +28,6 @@ import ( "regexp" "strings" - "github.com/sirupsen/logrus" "golang.org/x/mod/semver" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" k8syaml "sigs.k8s.io/yaml" @@ -53,6 +52,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/loader" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/status" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -114,7 +114,7 @@ func NewDeployer(cfg Config, labeller *label.DefaultLabeller, d *latestV1.KptDep kubectl := pkgkubectl.NewCLI(cfg, cfg.GetKubeNamespace()) namespaces, err := deployutil.GetAllPodNamespaces(cfg.GetNamespace(), cfg.GetPipelines()) if err != nil { - logrus.Warnf("unable to parse namespaces - deploy might not work correctly!") + olog.Entry(context.Background()).Warn("unable to parse namespaces - deploy might not work correctly!") } logger := component.NewLogger(cfg, kubectl, podSelector, &namespaces) return &Deployer{ diff --git a/pkg/skaffold/deploy/kubectl/cli.go b/pkg/skaffold/deploy/kubectl/cli.go index 52d4e431cac..832686feed2 100644 --- a/pkg/skaffold/deploy/kubectl/cli.go +++ b/pkg/skaffold/deploy/kubectl/cli.go @@ -24,8 +24,6 @@ import ( "strings" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" deployerr "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/error" deploy "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/types" @@ -35,6 +33,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/portforward" kstatus "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/status" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -91,7 +90,7 @@ func (c *CLI) Apply(ctx context.Context, out io.Writer, manifests manifest.Manif // Only redeploy modified or new manifests // TODO(dgageot): should we delete a manifest that was deployed and is not anymore? updated := c.previousApply.Diff(manifests) - logrus.Debugln(len(manifests), "manifests to deploy.", len(updated), "are updated or new") + log.Entry(ctx).Debug(len(manifests), "manifests to deploy.", len(updated), "are updated or new") c.previousApply = manifests if len(updated) == 0 { return nil @@ -173,7 +172,7 @@ func (c *CLI) WaitForDeletions(ctx context.Context, out io.Writer, manifests man } list := `"` + strings.Join(marked, `", "`) + `"` - logrus.Debugln("Resources are marked for deletion:", list) + log.Entry(ctx).Debug("Resources are marked for deletion:", list) if list != previousList { if len(marked) == 1 { fmt.Fprintf(out, "%s is marked for deletion, waiting for completion\n", list) diff --git a/pkg/skaffold/deploy/kubectl/kubectl.go b/pkg/skaffold/deploy/kubectl/kubectl.go index 0deebe3cc22..6270f84225a 100644 --- a/pkg/skaffold/deploy/kubectl/kubectl.go +++ b/pkg/skaffold/deploy/kubectl/kubectl.go @@ -26,7 +26,6 @@ import ( "strings" "github.com/segmentio/textio" - "github.com/sirupsen/logrus" "go.opentelemetry.io/otel/trace" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/access" @@ -46,6 +45,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/loader" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/status" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -95,7 +95,7 @@ func NewDeployer(cfg Config, labeller *label.DefaultLabeller, d *latestV1.Kubect kubectl := NewCLI(cfg, d.Flags, defaultNamespace) namespaces, err := deployutil.GetAllPodNamespaces(cfg.GetNamespace(), cfg.GetPipelines()) if err != nil { - logrus.Warnf("unable to parse namespaces - deploy might not work correctly!") + olog.Entry(context.Background()).Warn("unable to parse namespaces - deploy might not work correctly!") } logger := component.NewLogger(cfg, kubectl.CLI, podSelector, &namespaces) @@ -294,8 +294,8 @@ func (k *Deployer) manifestFiles(manifests []string) ([]string, error) { for _, f := range list { if !kubernetes.HasKubernetesFileExtension(f) { if !util.StrSliceContains(manifests, f) { - logrus.Infof("refusing to deploy/delete non {json, yaml} file %s", f) - logrus.Info("If you still wish to deploy this file, please specify it directly, outside a glob pattern.") + olog.Entry(context.Background()).Infof("refusing to deploy/delete non {json, yaml} file %s", f) + olog.Entry(context.Background()).Info("If you still wish to deploy this file, please specify it directly, outside a glob pattern.") continue } } diff --git a/pkg/skaffold/deploy/kustomize/kustomize.go b/pkg/skaffold/deploy/kustomize/kustomize.go index 4413619e363..bd3bf2ea5a9 100644 --- a/pkg/skaffold/deploy/kustomize/kustomize.go +++ b/pkg/skaffold/deploy/kustomize/kustomize.go @@ -25,7 +25,6 @@ import ( "path/filepath" "github.com/segmentio/textio" - "github.com/sirupsen/logrus" yamlv3 "gopkg.in/yaml.v3" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/access" @@ -44,6 +43,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/loader" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/status" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -142,7 +142,7 @@ func NewDeployer(cfg kubectl.Config, labeller *label.DefaultLabeller, d *latestV podSelector := kubernetes.NewImageList() namespaces, err := deployutil.GetAllPodNamespaces(cfg.GetNamespace(), cfg.GetPipelines()) if err != nil { - logrus.Warnf("unable to parse namespaces - deploy might not work correctly!") + olog.Entry(context.Background()).Warn("unable to parse namespaces - deploy might not work correctly!") } logger := component.NewLogger(cfg, kubectl.CLI, podSelector, &namespaces) return &Deployer{ diff --git a/pkg/skaffold/deploy/label/labels.go b/pkg/skaffold/deploy/label/labels.go index 28168a17ae4..2722e3021e1 100644 --- a/pkg/skaffold/deploy/label/labels.go +++ b/pkg/skaffold/deploy/label/labels.go @@ -22,7 +22,6 @@ import ( "fmt" "time" - "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -34,6 +33,7 @@ import ( deploy "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/types" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // retry 3 times to give the object time to propagate to the API server @@ -68,7 +68,7 @@ func Apply(ctx context.Context, labels map[string]string, results []deploy.Artif time.Sleep(sleeptime) } if err != nil { - logrus.Warnf("error adding label to runtime object: %s", err.Error()) + log.Entry(ctx).Warnf("error adding label to runtime object: %s", err.Error()) } } @@ -116,12 +116,12 @@ func updateRuntimeObject(ctx context.Context, client dynamic.Interface, disco di return fmt.Errorf("resolving namespace: %w", err) } - logrus.Debugln("Patching", name, "in namespace", ns) + log.Entry(ctx).Debug("Patching", name, "in namespace", ns) if _, err := client.Resource(gvr).Namespace(ns).Patch(ctx, name, types.StrategicMergePatchType, p, metav1.PatchOptions{}); err != nil { return fmt.Errorf("patching resource %s/%q: %w", ns, name, err) } } else { - logrus.Debugln("Patching", name) + log.Entry(ctx).Debug("Patching", name) if _, err := client.Resource(gvr).Patch(ctx, name, types.StrategicMergePatchType, p, metav1.PatchOptions{}); err != nil { return fmt.Errorf("patching resource %q: %w", name, err) } diff --git a/pkg/skaffold/docker/auth.go b/pkg/skaffold/docker/auth.go index 96f106948d5..3e9d4ea7eb3 100644 --- a/pkg/skaffold/docker/auth.go +++ b/pkg/skaffold/docker/auth.go @@ -30,9 +30,9 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/homedir" "github.com/docker/docker/registry" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/gcp" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const ( @@ -165,9 +165,9 @@ func (l *localDaemon) officialRegistry(ctx context.Context) string { info, err := l.apiClient.Info(ctx) switch { case err != nil: - logrus.Warnf("failed to get default registry endpoint from daemon (%v). Using system default: %s\n", err, serverAddress) + log.Entry(ctx).Warnf("failed to get default registry endpoint from daemon (%v). Using system default: %s\n", err, serverAddress) case info.IndexServerAddress == "": - logrus.Warnf("empty registry endpoint from daemon. Using system default: %s\n", serverAddress) + log.Entry(ctx).Warnf("empty registry endpoint from daemon. Using system default: %s\n", serverAddress) default: serverAddress = info.IndexServerAddress } diff --git a/pkg/skaffold/docker/build_args.go b/pkg/skaffold/docker/build_args.go index 6ee023c98de..f85d96354c6 100644 --- a/pkg/skaffold/docker/build_args.go +++ b/pkg/skaffold/docker/build_args.go @@ -17,12 +17,12 @@ limitations under the License. package docker import ( + "context" "fmt" "os" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -108,7 +108,7 @@ func ResolveDependencyImages(deps []*latestV1.ArtifactDependency, r ArtifactReso case found: m[d.Alias] = &t case missingIsFatal: - logrus.Fatalf("failed to resolve build result for required artifact %q", d.ImageName) + log.Entry(context.Background()).Fatalf("failed to resolve build result for required artifact %q", d.ImageName) default: m[d.Alias] = nil } diff --git a/pkg/skaffold/docker/client.go b/pkg/skaffold/docker/client.go index d704691498b..60bd7771fcc 100644 --- a/pkg/skaffold/docker/client.go +++ b/pkg/skaffold/docker/client.go @@ -28,10 +28,10 @@ import ( "github.com/docker/docker/client" "github.com/docker/go-connections/tlsconfig" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/cluster" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/version" ) @@ -113,7 +113,7 @@ func newMinikubeAPIClient(minikubeProfile string) ([]string, client.CommonAPICli var exitError ExitCoder if errors.As(err, &exitError) && (exitError.ExitCode() == minikubeDriverConfictExitCode || exitError.ExitCode() == oldMinikubeBadUsageExitCode) { // Let's ignore the error and fall back to local docker daemon. - logrus.Warnf("Could not get minikube docker env, falling back to local docker daemon: %s", err) + log.Entry(context.Background()).Warnf("Could not get minikube docker env, falling back to local docker daemon: %s", err) return newEnvAPIClient() } @@ -159,7 +159,7 @@ func newMinikubeAPIClient(minikubeProfile string) ([]string, client.CommonAPICli } if host != client.DefaultDockerHost { - logrus.Infof("Using minikube docker daemon at %s", host) + log.Entry(context.Background()).Infof("Using minikube docker daemon at %s", host) } // Keep the minikube environment variables @@ -174,7 +174,7 @@ func newMinikubeAPIClient(minikubeProfile string) ([]string, client.CommonAPICli func getUserAgentHeader() map[string]string { userAgent := fmt.Sprintf("skaffold-%s", version.Get().Version) - logrus.Debugf("setting Docker user agent to %s", userAgent) + log.Entry(context.Background()).Debugf("setting Docker user agent to %s", userAgent) return map[string]string{ "User-Agent": userAgent, } diff --git a/pkg/skaffold/docker/docker_init.go b/pkg/skaffold/docker/docker_init.go index 581db26d9fa..e76bc330b85 100644 --- a/pkg/skaffold/docker/docker_init.go +++ b/pkg/skaffold/docker/docker_init.go @@ -17,14 +17,15 @@ limitations under the License. package docker import ( + "context" "fmt" "os" "path/filepath" "github.com/moby/buildkit/frontend/dockerfile/command" "github.com/moby/buildkit/frontend/dockerfile/parser" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -84,7 +85,7 @@ func (c ArtifactConfig) Path() string { func validate(path string) bool { f, err := os.Open(path) if err != nil { - logrus.Warnf("opening file %s: %s", path, err.Error()) + log.Entry(context.Background()).Warnf("opening file %s: %s", path, err.Error()) return false } defer f.Close() diff --git a/pkg/skaffold/docker/image.go b/pkg/skaffold/docker/image.go index 4f310abf04c..0538bc13144 100644 --- a/pkg/skaffold/docker/image.go +++ b/pkg/skaffold/docker/image.go @@ -39,10 +39,10 @@ import ( "github.com/docker/docker/pkg/streamformatter" "github.com/docker/go-connections/nat" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -178,7 +178,7 @@ func (l *localDaemon) ContainerExists(ctx context.Context, name string) bool { // Delete stops, removes, and prunes a running container func (l *localDaemon) Delete(ctx context.Context, out io.Writer, id string) error { if err := l.apiClient.ContainerStop(ctx, id, nil); err != nil { - logrus.Warnf("unable to stop running container: %s", err.Error()) + log.Entry(ctx).Warnf("unable to stop running container: %s", err.Error()) } if err := l.apiClient.ContainerRemove(ctx, id, types.ContainerRemoveOptions{}); err != nil { return fmt.Errorf("removing stopped container: %w", err) @@ -231,7 +231,7 @@ func (l *localDaemon) NetworkCreate(ctx context.Context, name string) error { return err } if r.Warning != "" { - logrus.Warnln(r.Warning) + log.Entry(ctx).Warn(r.Warning) } return nil } @@ -283,7 +283,7 @@ func (l *localDaemon) CheckCompatible(a *latestV1.DockerArtifact) error { // Build performs a docker build and returns the imageID. func (l *localDaemon) Build(ctx context.Context, out io.Writer, workspace string, artifact string, a *latestV1.DockerArtifact, opts BuildOptions) (string, error) { - logrus.Debugf("Running docker build: context: %s, dockerfile: %s", workspace, a.DockerfilePath) + log.Entry(ctx).Debugf("Running docker build: context: %s, dockerfile: %s", workspace, a.DockerfilePath) if err := l.CheckCompatible(a); err != nil { return "", err @@ -336,7 +336,7 @@ func (l *localDaemon) Build(ctx context.Context, out io.Writer, workspace string var result BuildResult if err := json.Unmarshal(*msg.Aux, &result); err != nil { - logrus.Debugln("Unable to parse build output:", err) + log.Entry(ctx).Debug("Unable to parse build output:", err) return } imageID = result.ID @@ -392,7 +392,7 @@ func (l *localDaemon) Push(ctx context.Context, out io.Writer, ref string) (stri var result PushResult if err := json.Unmarshal(*msg.Aux, &result); err != nil { - logrus.Debugln("Unable to parse push output:", err) + log.Entry(ctx).Debug("Unable to parse push output:", err) return } digest = result.Digest @@ -649,10 +649,10 @@ func (l *localDaemon) Prune(ctx context.Context, images []string, pruneChildren for _, r := range resp { if r.Deleted != "" { - logrus.Debugf("deleted image %s\n", r.Deleted) + log.Entry(ctx).Debugf("deleted image %s\n", r.Deleted) } if r.Untagged != "" { - logrus.Debugf("untagged image %s\n", r.Untagged) + log.Entry(ctx).Debugf("untagged image %s\n", r.Untagged) } } } diff --git a/pkg/skaffold/docker/image_util.go b/pkg/skaffold/docker/image_util.go index 2ee5a8f3fbc..d4c188582e1 100644 --- a/pkg/skaffold/docker/image_util.go +++ b/pkg/skaffold/docker/image_util.go @@ -22,7 +22,8 @@ import ( "strings" v1 "github.com/google/go-containerregistry/pkg/v1" - "github.com/sirupsen/logrus" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) func RetrieveConfigFile(tagged string, cfg Config) (*v1.ConfigFile, error) { @@ -56,7 +57,7 @@ func RetrieveWorkingDir(tagged string, cfg Config) (string, error) { case cf == nil: return "/", nil case cf.Config.WorkingDir == "": - logrus.Debugf("Using default workdir '/' for %s", tagged) + log.Entry(context.Background()).Debugf("Using default workdir '/' for %s", tagged) return "/", nil default: return cf.Config.WorkingDir, nil diff --git a/pkg/skaffold/docker/logger/log.go b/pkg/skaffold/docker/logger/log.go index 53bdfe511ea..648eef56b49 100644 --- a/pkg/skaffold/docker/logger/log.go +++ b/pkg/skaffold/docker/logger/log.go @@ -22,13 +22,12 @@ import ( "sync/atomic" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker/tracker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" logstream "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log/stream" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type Logger struct { @@ -87,7 +86,7 @@ func (l *Logger) streamLogsFromContainer(ctx context.Context, id string) { // TODO(nkubala)[07/23/21]: if container is lost, emit API event and attempt to reattach // https://github.com/GoogleContainerTools/skaffold/issues/6281 if ctx.Err() != context.Canceled { - logrus.Warn(err) + log.Entry(ctx).Warn(err) } } _ = tw.Close() @@ -95,7 +94,7 @@ func (l *Logger) streamLogsFromContainer(ctx context.Context, id string) { formatter := NewDockerLogFormatter(l.colorPicker, l.tracker, l.IsMuted, id) if err := logstream.StreamRequest(ctx, l.out, formatter, tr); err != nil { - logrus.Errorf("streaming request: %s", err) + log.Entry(ctx).Errorf("streaming request: %s", err) } } diff --git a/pkg/skaffold/docker/parse.go b/pkg/skaffold/docker/parse.go index c883e29c487..bc0204cf1a2 100644 --- a/pkg/skaffold/docker/parse.go +++ b/pkg/skaffold/docker/parse.go @@ -34,10 +34,10 @@ import ( "github.com/moby/buildkit/frontend/dockerfile/instructions" "github.com/moby/buildkit/frontend/dockerfile/parser" "github.com/moby/buildkit/frontend/dockerfile/shell" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -199,7 +199,7 @@ func expandSrcGlobPatterns(workspace string, cpCmds []*copyCommand) ([]fromTo, e } } - logrus.Debugf("Found dependencies for dockerfile: %v", fts) + log.Entry(context.Background()).Debugf("Found dependencies for dockerfile: %v", fts) return fts, nil } @@ -295,7 +295,7 @@ func readCopyCommand(value *parser.Node, envs []string, workdir string) (*copyCo var srcs []string for _, src := range paths[0 : len(paths)-1] { if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") { - logrus.Debugln("Skipping watch on remote dependency", src) + log.Entry(context.Background()).Debugln("Skipping watch on remote dependency", src) continue } @@ -338,7 +338,7 @@ func expandOnbuildInstructions(nodes []*parser.Node, cfg Config) ([]*parser.Node } else if ons, err := parseOnbuild(from.image, cfg); err == nil { onbuildNodes = ons } else if warnMsg, ok, _ := isOldImageManifestProblem(cfg, err); ok && warnMsg != "" { - logrus.Warn(warnMsg) + log.Entry(context.Background()).Warn(warnMsg) } else if !ok { return nil, fmt.Errorf("parsing ONBUILD instructions: %w", err) } @@ -356,7 +356,7 @@ func expandOnbuildInstructions(nodes []*parser.Node, cfg Config) ([]*parser.Node } func parseOnbuild(image string, cfg Config) ([]*parser.Node, error) { - logrus.Tracef("Checking base image %s for ONBUILD triggers.", image) + log.Entry(context.Background()).Tracef("Checking base image %s for ONBUILD triggers.", image) // Image names are case SENSITIVE img, err := RetrieveImage(image, cfg) @@ -368,7 +368,7 @@ func parseOnbuild(image string, cfg Config) ([]*parser.Node, error) { return []*parser.Node{}, nil } - logrus.Tracef("Found ONBUILD triggers %v in image %s", img.Config.OnBuild, image) + log.Entry(context.Background()).Tracef("Found ONBUILD triggers %v in image %s", img.Config.OnBuild, image) obRes, err := parser.Parse(strings.NewReader(strings.Join(img.Config.OnBuild, "\n"))) if err != nil { diff --git a/pkg/skaffold/docker/remote.go b/pkg/skaffold/docker/remote.go index 53270af2687..c62fb560d1e 100644 --- a/pkg/skaffold/docker/remote.go +++ b/pkg/skaffold/docker/remote.go @@ -17,15 +17,16 @@ limitations under the License. package docker import ( + "context" "fmt" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/remote" "github.com/google/go-containerregistry/pkg/v1/tarball" - "github.com/sirupsen/logrus" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // for testing @@ -36,7 +37,7 @@ var ( ) func AddRemoteTag(src, target string, cfg Config) error { - logrus.Debugf("attempting to add tag %s to src %s", target, src) + log.Entry(context.Background()).Debugf("attempting to add tag %s to src %s", target, src) img, err := getRemoteImage(src, cfg) if err != nil { return fmt.Errorf("getting image: %w", err) @@ -125,7 +126,7 @@ func parseReference(s string, cfg Config, opts ...name.Option) (name.Reference, if IsInsecure(ref, cfg.GetInsecureRegistries()) { ref, err = name.ParseReference(s, name.Insecure) if err != nil { - logrus.Warnf("error getting insecure registry: %s\nremote references may not be retrieved", err.Error()) + log.Entry(context.Background()).Warnf("error getting insecure registry: %s\nremote references may not be retrieved", err.Error()) } } diff --git a/pkg/skaffold/event/v2/event.go b/pkg/skaffold/event/v2/event.go index 735099759c9..9a82da09062 100644 --- a/pkg/skaffold/event/v2/event.go +++ b/pkg/skaffold/event/v2/event.go @@ -43,8 +43,6 @@ const ( Succeeded = "Succeeded" Terminated = "Terminated" Canceled = "Canceled" - - SubtaskIDNone = "-1" ) var handler = newHandler() diff --git a/pkg/skaffold/filemon/changes.go b/pkg/skaffold/filemon/changes.go index b6285421c0e..206f6661b35 100644 --- a/pkg/skaffold/filemon/changes.go +++ b/pkg/skaffold/filemon/changes.go @@ -17,13 +17,14 @@ limitations under the License. package filemon import ( + "context" "fmt" "os" "sort" "strings" "time" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // FileMap is a map of filename to modification times. @@ -40,7 +41,7 @@ func Stat(deps func() ([]string, error)) (FileMap, error) { stat, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { - logrus.Debugf("could not stat dependency: %s", err) + log.Entry(context.Background()).Debugf("could not stat dependency: %s", err) continue // Ignore files that don't exist } return nil, fmt.Errorf("unable to stat file %q: %w", path, err) @@ -117,12 +118,12 @@ func sortEvents(e Events) { func logEvents(e Events) { if e.Added != nil && len(e.Added) > 0 { - logrus.Infof("files added: %v", e.Added) + log.Entry(context.Background()).Infof("files added: %v", e.Added) } if e.Modified != nil && len(e.Modified) > 0 { - logrus.Infof("files modified: %v", e.Modified) + log.Entry(context.Background()).Infof("files modified: %v", e.Modified) } if e.Deleted != nil && len(e.Deleted) > 0 { - logrus.Infof("files deleted: %v", e.Deleted) + log.Entry(context.Background()).Infof("files deleted: %v", e.Deleted) } } diff --git a/pkg/skaffold/gcp/auth.go b/pkg/skaffold/gcp/auth.go index bf63006f0d0..663c8e6d7f1 100644 --- a/pkg/skaffold/gcp/auth.go +++ b/pkg/skaffold/gcp/auth.go @@ -24,9 +24,9 @@ import ( "sync" "github.com/docker/cli/cli/config/configfile" - "github.com/sirupsen/logrus" "golang.org/x/oauth2/google" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -44,7 +44,7 @@ var gcrPrefixes = []string{"gcr.io", "us.gcr.io", "eu.gcr.io", "asia.gcr.io", "s // This doesn't modify the ~/.docker/config.json. It's only in-memory func AutoConfigureGCRCredentialHelper(cf *configfile.ConfigFile) { if path, _ := exec.LookPath("docker-credential-gcloud"); path == "" { - logrus.Debugln("Skipping credential configuration because docker-credential-gcloud is not on PATH.") + log.Entry(context.Background()).Debug("Skipping credential configuration because docker-credential-gcloud is not on PATH.") return } @@ -64,8 +64,8 @@ func activeUserCredentials() (*google.Credentials, error) { cmd := exec.Command("gcloud", "auth", "print-access-token", "--format=json") body, err := util.RunCmdOut(cmd) if err != nil { - logrus.Infof("unable to retrieve gcloud access token: %v", err) - logrus.Infof("falling back to application default credentials") + log.Entry(context.Background()).Infof("unable to retrieve gcloud access token: %v", err) + log.Entry(context.Background()).Info("falling back to application default credentials") credsErr = fmt.Errorf("retrieving gcloud access token: %w", err) return } @@ -76,14 +76,14 @@ func activeUserCredentials() (*google.Credentials, error) { c, err := google.CredentialsFromJSON(context.Background(), body) if err != nil { - logrus.Infof("unable to retrieve google creds: %v", err) - logrus.Infof("falling back to application default credentials") + log.Entry(context.Background()).Infof("unable to retrieve google creds: %v", err) + log.Entry(context.Background()).Info("falling back to application default credentials") return } _, err = c.TokenSource.Token() if err != nil { - logrus.Infof("unable to retrieve token: %v", err) - logrus.Infof("falling back to application default credentials") + log.Entry(context.Background()).Infof("unable to retrieve token: %v", err) + log.Entry(context.Background()).Info("falling back to application default credentials") return } creds = c diff --git a/pkg/skaffold/hooks/host.go b/pkg/skaffold/hooks/host.go index 0e52642e3d6..fd8eb95e7c3 100644 --- a/pkg/skaffold/hooks/host.go +++ b/pkg/skaffold/hooks/host.go @@ -24,9 +24,8 @@ import ( "runtime" "strings" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/misc" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" v1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -40,12 +39,12 @@ type hostHook struct { // run executes the lifecycle hook on the host machine func (h hostHook) run(ctx context.Context, out io.Writer) error { if len(h.cfg.OS) > 0 && !util.StrSliceContains(h.cfg.OS, runtime.GOOS) { - logrus.Infof("host hook execution skipped due to OS criteria %q not matched for commands:\n%q\n", strings.Join(h.cfg.OS, ","), strings.Join(h.cfg.Command, " ")) + log.Entry(ctx).Infof("host hook execution skipped due to OS criteria %q not matched for commands:\n%q\n", strings.Join(h.cfg.OS, ","), strings.Join(h.cfg.Command, " ")) return nil } cmd := h.retrieveCmd(ctx, out) - logrus.Debugf("Running command: %s", cmd.Args) + log.Entry(ctx).Debugf("Running command: %s", cmd.Args) if err := cmd.Start(); err != nil { return fmt.Errorf("starting cmd: %w", err) } diff --git a/pkg/skaffold/initializer/analyze/analyze.go b/pkg/skaffold/initializer/analyze/analyze.go index c649e76c118..da8a2ad1151 100644 --- a/pkg/skaffold/initializer/analyze/analyze.go +++ b/pkg/skaffold/initializer/analyze/analyze.go @@ -17,16 +17,17 @@ limitations under the License. package analyze import ( + "context" "os" "path/filepath" "sort" "strings" "github.com/karrick/godirwalk" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/config" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -147,7 +148,7 @@ func (a *ProjectAnalysis) Analyze(dir string) error { continue } if stat.Size() > a.maxFileSize { - logrus.Debugf("skipping %s as it is larger (%d) than max allowed size %d", filePath, stat.Size(), a.maxFileSize) + log.Entry(context.Background()).Debugf("skipping %s as it is larger (%d) than max allowed size %d", filePath, stat.Size(), a.maxFileSize) continue } } diff --git a/pkg/skaffold/initializer/config.go b/pkg/skaffold/initializer/config.go index 5679abe0d2e..409853fa025 100644 --- a/pkg/skaffold/initializer/config.go +++ b/pkg/skaffold/initializer/config.go @@ -17,15 +17,15 @@ limitations under the License. package initializer import ( + "context" "os" "path/filepath" "regexp" "strings" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/deploy" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/warnings" ) @@ -38,7 +38,7 @@ var ( func generateSkaffoldConfig(b build.Initializer, d deploy.Initializer) *latestV1.SkaffoldConfig { // if we're here, the user has no skaffold yaml so we need to generate one // if the user doesn't have any k8s yamls, generate one for each dockerfile - logrus.Info("generating skaffold config") + log.Entry(context.Background()).Info("generating skaffold config") name, err := suggestConfigName() if err != nil { diff --git a/pkg/skaffold/initializer/deploy/kustomize.go b/pkg/skaffold/initializer/deploy/kustomize.go index 00edb7c5b0c..5f77749a2cd 100644 --- a/pkg/skaffold/initializer/deploy/kustomize.go +++ b/pkg/skaffold/initializer/deploy/kustomize.go @@ -17,13 +17,13 @@ limitations under the License. package deploy import ( + "context" "path/filepath" - "github.com/sirupsen/logrus" - pkgkustomize "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/kustomize" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/initializer/errors" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -100,7 +100,7 @@ func (k *kustomize) DeployConfig() (latestV1.DeployConfig, []latestV1.Profile) { default: defaultKustomization = k.kustomizations[0] } - logrus.Warnf("multiple kustomizations found but no default provided - defaulting to %s", defaultKustomization) + log.Entry(context.Background()).Warnf("multiple kustomizations found but no default provided - defaulting to %s", defaultKustomization) } for _, kustomization := range k.kustomizations { diff --git a/pkg/skaffold/initializer/kompose.go b/pkg/skaffold/initializer/kompose.go index 7ba79231dcf..18268136f8b 100644 --- a/pkg/skaffold/initializer/kompose.go +++ b/pkg/skaffold/initializer/kompose.go @@ -21,8 +21,7 @@ import ( "os" "os/exec" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -32,7 +31,7 @@ func runKompose(ctx context.Context, composeFile string) error { return err } - logrus.Infof("running 'kompose convert' for file %s", composeFile) + log.Entry(ctx).Infof("running 'kompose convert' for file %s", composeFile) komposeCmd := exec.CommandContext(ctx, "kompose", "convert", "-f", composeFile) _, err := util.RunCmdOut(komposeCmd) return err diff --git a/pkg/skaffold/initializer/testdata/init/microservices/leeroy-web/web.go b/pkg/skaffold/initializer/testdata/init/microservices/leeroy-web/web.go index 69f92785651..7ac7850510e 100644 --- a/pkg/skaffold/initializer/testdata/init/microservices/leeroy-web/web.go +++ b/pkg/skaffold/initializer/testdata/init/microservices/leeroy-web/web.go @@ -2,9 +2,8 @@ package main import ( "io" - "net/http" - "log" + "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/skaffold/initializer/testdata/init/windows/apps/web/web.go b/pkg/skaffold/initializer/testdata/init/windows/apps/web/web.go index 69f92785651..7ac7850510e 100644 --- a/pkg/skaffold/initializer/testdata/init/windows/apps/web/web.go +++ b/pkg/skaffold/initializer/testdata/init/windows/apps/web/web.go @@ -2,9 +2,8 @@ package main import ( "io" - "net/http" - "log" + "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { diff --git a/pkg/skaffold/instrumentation/export.go b/pkg/skaffold/instrumentation/export.go index 90087b8ac4e..a7021237067 100644 --- a/pkg/skaffold/instrumentation/export.go +++ b/pkg/skaffold/instrumentation/export.go @@ -32,7 +32,6 @@ import ( texporter "github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/trace" "github.com/mitchellh/go-homedir" "github.com/rakyll/statik/fs" - "github.com/sirupsen/logrus" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/exporters/stdout" @@ -48,6 +47,7 @@ import ( "github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/cmd/statik" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/user" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -68,7 +68,7 @@ func ExportMetrics(exitCode int) error { } func exportMetrics(ctx context.Context, filename string, meter skaffoldMeter) error { - logrus.Debug("exporting metrics") + log.Entry(ctx).Debug("exporting metrics") p, err := initExporter() if p == nil { return err @@ -96,12 +96,12 @@ func exportMetrics(ctx context.Context, filename string, meter skaffoldMeter) er createMetrics(ctx, m) } if err := p.Stop(ctx); err != nil { - logrus.Debugf("error uploading metrics: %s", err) - logrus.Debugf("writing to file %s instead", filename) + log.Entry(ctx).Debugf("error uploading metrics: %s", err) + log.Entry(ctx).Debugf("writing to file %s instead", filename) b, _ = json.Marshal(meters) return ioutil.WriteFile(filename, b, 0666) } - logrus.Debugf("metrics uploading complete in %s", time.Since(start).String()) + log.Entry(ctx).Debugf("metrics uploading complete in %s", time.Since(start).String()) if fileExists { return os.Remove(filename) @@ -140,7 +140,7 @@ func initCloudMonitoringExporterMetrics() (*basic.Controller, error) { mexporter.WithMetricDescriptorTypeFormatter(formatter), mexporter.WithMonitoringClientOptions(option.WithCredentialsJSON(b)), mexporter.WithOnError(func(err error) { - logrus.Debugf("Error with metrics: %v", err) + log.Entry(context.Background()).Debugf("Error with metrics: %v", err) }), }, ) @@ -321,20 +321,20 @@ func initTraceExporter(opts ...TraceExporterOption) (trace.TracerProvider, func( switch os.Getenv("SKAFFOLD_TRACE") { case "stdout": - logrus.Debugf("using stdout trace exporter") + log.Entry(context.Background()).Debug("using stdout trace exporter") return initIOWriterTracer(teconf.writer) case "gcp-adc": - logrus.Debugf("using cloud trace exporter w/ application default creds") + log.Entry(context.Background()).Debug("using cloud trace exporter w/ application default creds") tp, shutdown, err := initCloudTraceExporterApplicationDefaultCreds() return tp, func(context.Context) error { shutdown(); return nil }, err case "jaeger": - logrus.Debugf("using jaeger trace exporter") + log.Entry(context.Background()).Debug("using jaeger trace exporter") tp, shutdown, err := initJaegerTraceExporter() return tp, func(context.Context) error { shutdown(); return nil }, err } if otelTraceExporterVal, ok := os.LookupEnv("OTEL_TRACES_EXPORTER"); ok { - logrus.Debugf("using otel default exporter - OTEL_TRACES_EXPORTER=%s", otelTraceExporterVal) + log.Entry(context.Background()).Debugf("using otel default exporter - OTEL_TRACES_EXPORTER=%s", otelTraceExporterVal) return nil, func(context.Context) error { return nil }, nil } @@ -364,7 +364,7 @@ func initCloudTraceExporterApplicationDefaultCreds() (trace.TracerProvider, func []texporter.Option{ texporter.WithProjectID(os.Getenv("GOOGLE_CLOUD_PROJECT")), texporter.WithOnError(func(err error) { - logrus.Debugf("Error with metrics: %v", err) + log.Entry(context.Background()).Debugf("Error with metrics: %v", err) }), }, sdktrace.WithSampler(sdktrace.AlwaysSample()), diff --git a/pkg/skaffold/instrumentation/new.go b/pkg/skaffold/instrumentation/new.go index fe96502b48b..a20cdffd7db 100644 --- a/pkg/skaffold/instrumentation/new.go +++ b/pkg/skaffold/instrumentation/new.go @@ -19,8 +19,7 @@ package instrumentation import ( "context" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -32,9 +31,9 @@ func Init(configs []*latestV1.SkaffoldConfig, user string, opts ...TraceExporter func ShutdownAndFlush(ctx context.Context, exitCode int) { if err := ExportMetrics(exitCode); err != nil { - logrus.Debugf("error exporting metrics %v", err) + log.Entry(ctx).Debugf("error exporting metrics %v", err) } if err := TracerShutdown(ctx); err != nil { - logrus.Debugf("error shutting down tracer %v", err) + log.Entry(ctx).Debugf("error shutting down tracer %v", err) } } diff --git a/pkg/skaffold/instrumentation/trace.go b/pkg/skaffold/instrumentation/trace.go index 0144030a789..52c60ff11f9 100644 --- a/pkg/skaffold/instrumentation/trace.go +++ b/pkg/skaffold/instrumentation/trace.go @@ -23,10 +23,11 @@ import ( "runtime" "sync" - "github.com/sirupsen/logrus" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) var traceEnabled bool @@ -59,7 +60,7 @@ func InitTraceFromEnvVar(opts ...TraceExporterOption) (trace.TracerProvider, fun } }) if tracerInitErr != nil { - logrus.Debugf("error initializing tracing: %v", tracerInitErr) + log.Entry(context.Background()).Debugf("error initializing tracing: %v", tracerInitErr) } return tracerProvider, tracerShutdown, tracerInitErr } diff --git a/pkg/skaffold/instrumentation/types.go b/pkg/skaffold/instrumentation/types.go index 67e329adda8..d881e4018a3 100644 --- a/pkg/skaffold/instrumentation/types.go +++ b/pkg/skaffold/instrumentation/types.go @@ -17,10 +17,10 @@ limitations under the License. package instrumentation import ( + "context" "time" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -107,5 +107,5 @@ type creds struct { type errHandler struct{} func (h errHandler) Handle(err error) { - logrus.Debugf("Error with metrics: %v", err) + log.Entry(context.Background()).Debugf("Error with metrics: %v", err) } diff --git a/pkg/skaffold/kubernetes/context/context.go b/pkg/skaffold/kubernetes/context/context.go index 76f6b632ec8..95f831a2fac 100644 --- a/pkg/skaffold/kubernetes/context/context.go +++ b/pkg/skaffold/kubernetes/context/context.go @@ -17,13 +17,15 @@ limitations under the License. package context import ( + "context" "fmt" "sync" - "github.com/sirupsen/logrus" restclient "k8s.io/client-go/rest" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // For testing @@ -49,7 +51,7 @@ func ConfigureKubeConfig(cliKubeConfig, cliKubeContext string) { kubeContext = cliKubeContext kubeConfigFile = cliKubeConfig if kubeContext != "" { - logrus.Infof("Activated kube-context %q", kubeContext) + log.Entry(context.Background()).Infof("Activated kube-context %q", kubeContext) } }) } @@ -82,7 +84,7 @@ func GetClusterInfo(kctx string) (*clientcmdapi.Cluster, error) { } func getRestClientConfig(kctx string, kcfg string) (*restclient.Config, error) { - logrus.Debugf("getting client config for kubeContext: `%s`", kctx) + log.Entry(context.Background()).Debugf("getting client config for kubeContext: `%s`", kctx) rawConfig, err := getCurrentConfig() if err != nil { @@ -92,7 +94,7 @@ func getRestClientConfig(kctx string, kcfg string) (*restclient.Config, error) { clientConfig := clientcmd.NewNonInteractiveClientConfig(rawConfig, kctx, &clientcmd.ConfigOverrides{CurrentContext: kctx}, clientcmd.NewDefaultClientConfigLoadingRules()) restConfig, err := clientConfig.ClientConfig() if kctx == "" && kcfg == "" && clientcmd.IsEmptyConfig(err) { - logrus.Debug("no kube-context set and no kubeConfig found, attempting in-cluster config") + log.Entry(context.Background()).Debug("no kube-context set and no kubeConfig found, attempting in-cluster config") restConfig, err := restclient.InClusterConfig() if err != nil { return restConfig, fmt.Errorf("error creating REST client config in-cluster: %w", err) diff --git a/pkg/skaffold/kubernetes/debugging/container_manager.go b/pkg/skaffold/kubernetes/debugging/container_manager.go index 4cb022a3f0e..3e5efe67bef 100644 --- a/pkg/skaffold/kubernetes/debugging/container_manager.go +++ b/pkg/skaffold/kubernetes/debugging/container_manager.go @@ -20,13 +20,13 @@ import ( "context" "encoding/json" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/debug/annotations" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) var ( @@ -111,7 +111,7 @@ func (d *ContainerManager) checkPod(pod *v1.Pod) { } var configurations map[string]annotations.ContainerDebugConfiguration if err := json.Unmarshal([]byte(debugConfigString), &configurations); err != nil { - logrus.Warnf("Unable to parse debug-config for pod %s/%s: '%s'", pod.Namespace, pod.Name, debugConfigString) + log.Entry(context.Background()).Warnf("Unable to parse debug-config for pod %s/%s: '%s'", pod.Namespace, pod.Name, debugConfigString) return } for _, c := range pod.Status.ContainerStatuses { diff --git a/pkg/skaffold/kubernetes/logger/log.go b/pkg/skaffold/kubernetes/logger/log.go index 2e2030f8c3b..3aabbcb7215 100644 --- a/pkg/skaffold/kubernetes/logger/log.go +++ b/pkg/skaffold/kubernetes/logger/log.go @@ -24,7 +24,6 @@ import ( "sync/atomic" "time" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/watch" @@ -34,6 +33,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log/stream" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -184,7 +184,7 @@ func sinceSeconds(d time.Duration) int64 { } func (a *LogAggregator) streamContainerLogs(ctx context.Context, pod *v1.Pod, container v1.ContainerStatus) { - logrus.Infof("Streaming logs from pod: %s container: %s", pod.Name, container.Name) + olog.Entry(ctx).Infof("Streaming logs from pod: %s container: %s", pod.Name, container.Name) // In theory, it's more precise to use --since-time='' but there can be a time // difference between the user's machine and the server. @@ -197,14 +197,14 @@ func (a *LogAggregator) streamContainerLogs(ctx context.Context, pod *v1.Pod, co // Don't print errors if the user interrupted the logs // or if the logs were interrupted because of a configuration change if ctx.Err() != context.Canceled { - logrus.Warn(err) + olog.Entry(ctx).Warn(err) } } _ = tw.Close() }() if err := stream.StreamRequest(ctx, a.output, a.formatter(*pod, container, a.IsMuted), tr); err != nil { - logrus.Errorf("streaming request %s", err) + olog.Entry(ctx).Errorf("streaming request %s", err) } } diff --git a/pkg/skaffold/kubernetes/manifest/images.go b/pkg/skaffold/kubernetes/manifest/images.go index b1d139b4cb7..9c3758ae772 100644 --- a/pkg/skaffold/kubernetes/manifest/images.go +++ b/pkg/skaffold/kubernetes/manifest/images.go @@ -20,11 +20,10 @@ import ( "context" "strconv" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // GetImages gathers a map of base image names to the image with its tag @@ -49,7 +48,7 @@ func (is *imageSaver) Visit(o map[string]interface{}, k string, v interface{}) b } parsed, err := docker.ParseReference(image) if err != nil { - logrus.Debugf("Couldn't parse image [%s]: %s", image, err.Error()) + log.Entry(context.Background()).Debugf("Couldn't parse image [%s]: %s", image, err.Error()) return false } @@ -88,7 +87,7 @@ func (l *ManifestList) replaceImages(ctx context.Context, builds []graph.Artifac } replacer.Check() - logrus.Debugln("manifests with tagged images:", updated.String()) + log.Entry(ctx).Debug("manifests with tagged images:", updated.String()) return updated, nil } @@ -124,7 +123,7 @@ func (r *imageReplacer) Visit(o map[string]interface{}, k string, v interface{}) } parsed, err := docker.ParseReference(image) if err != nil { - logrus.Debugf("Couldn't parse image [%s]: %s", image, err.Error()) + log.Entry(context.Background()).Debugf("Couldn't parse image [%s]: %s", image, err.Error()) return false } if imageName, tag, selected := r.selector(r.tagsByImageName, parsed); selected { @@ -137,7 +136,7 @@ func (r *imageReplacer) Visit(o map[string]interface{}, k string, v interface{}) func (r *imageReplacer) Check() { for imageName := range r.tagsByImageName { if !r.found[imageName] { - logrus.Debugf("image [%s] is not used by the current deployment", imageName) + log.Entry(context.Background()).Debugf("image [%s] is not used by the current deployment", imageName) } } } diff --git a/pkg/skaffold/kubernetes/manifest/labels.go b/pkg/skaffold/kubernetes/manifest/labels.go index b556b2ce3a5..2f545cc65a6 100644 --- a/pkg/skaffold/kubernetes/manifest/labels.go +++ b/pkg/skaffold/kubernetes/manifest/labels.go @@ -17,7 +17,9 @@ limitations under the License. package manifest import ( - "github.com/sirupsen/logrus" + "context" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // SetLabels add labels to a list of Kubernetes manifests. @@ -32,7 +34,7 @@ func (l *ManifestList) SetLabels(labels map[string]string) (ManifestList, error) return nil, labelSettingErr(err) } - logrus.Debugln("manifests with labels", updated.String()) + log.Entry(context.Background()).Debugln("manifests with labels", updated.String()) return updated, nil } diff --git a/pkg/skaffold/kubernetes/owner.go b/pkg/skaffold/kubernetes/owner.go index c5b845278e8..2f114adf18d 100644 --- a/pkg/skaffold/kubernetes/owner.go +++ b/pkg/skaffold/kubernetes/owner.go @@ -20,10 +20,10 @@ import ( "context" "fmt" - "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // TopLevelOwnerKey returns a key associated with the top level @@ -38,7 +38,7 @@ func TopLevelOwnerKey(ctx context.Context, obj metav1.Object, kubeContext string kind = or[0].Kind obj, err = ownerMetaObject(ctx, obj.GetNamespace(), kubeContext, or[0]) if err != nil { - logrus.Warnf("unable to get owner from reference: %v", or[0]) + log.Entry(ctx).Warnf("unable to get owner from reference: %v", or[0]) return "" } } diff --git a/pkg/skaffold/kubernetes/portforward/entry_manager.go b/pkg/skaffold/kubernetes/portforward/entry_manager.go index f3dbd3ac5a9..1fc89549d2f 100644 --- a/pkg/skaffold/kubernetes/portforward/entry_manager.go +++ b/pkg/skaffold/kubernetes/portforward/entry_manager.go @@ -77,7 +77,7 @@ func NewEntryManager(entryForwarder EntryForwarder) *EntryManager { } func (b *EntryManager) forwardPortForwardEntry(ctx context.Context, out io.Writer, entry *portForwardEntry) { - out = output.WithEventContext(out, constants.PortForward, fmt.Sprintf("%s/%s", entry.resource.Type, entry.resource.Name)) + out, ctx = output.WithEventContext(ctx, out, constants.PortForward, fmt.Sprintf("%s/%s", entry.resource.Type, entry.resource.Name)) // Check if this resource has already been forwarded if _, found := b.forwardedResources.LoadOrStore(entry.key(), entry); found { diff --git a/pkg/skaffold/kubernetes/portforward/forwarder_manager.go b/pkg/skaffold/kubernetes/portforward/forwarder_manager.go index 8a2235675e0..b61709f069c 100644 --- a/pkg/skaffold/kubernetes/portforward/forwarder_manager.go +++ b/pkg/skaffold/kubernetes/portforward/forwarder_manager.go @@ -21,7 +21,6 @@ import ( "encoding/json" "io" - "github.com/sirupsen/logrus" "golang.org/x/sync/singleflight" v1 "k8s.io/api/core/v1" @@ -32,6 +31,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -105,18 +105,18 @@ func debugPorts(pod *v1.Pod, c v1.Container) []v1.ContainerPort { } var configurations map[string]annotations.ContainerDebugConfiguration if err := json.Unmarshal([]byte(annot), &configurations); err != nil { - logrus.Warnf("could not decode debug annotation on pod/%s (%q): %v", pod.Name, annot, err) + log.Entry(context.Background()).Warnf("could not decode debug annotation on pod/%s (%q): %v", pod.Name, annot, err) return nil } dc, found := configurations[c.Name] if !found { - logrus.Debugf("no debug configuration found on pod/%s/%s", pod.Name, c.Name) + log.Entry(context.Background()).Debugf("no debug configuration found on pod/%s/%s", pod.Name, c.Name) return nil } for _, port := range c.Ports { for _, exposed := range dc.Ports { if uint32(port.ContainerPort) == exposed { - logrus.Debugf("selecting debug port for pod/%s/%s: %v", pod.Name, c.Name, port) + log.Entry(context.Background()).Debugf("selecting debug port for pod/%s/%s: %v", pod.Name, c.Name, port) ports = append(ports, port) } } diff --git a/pkg/skaffold/kubernetes/portforward/kubectl_forwarder.go b/pkg/skaffold/kubernetes/portforward/kubectl_forwarder.go index e123e0d0e7a..3abfd83b035 100644 --- a/pkg/skaffold/kubernetes/portforward/kubectl_forwarder.go +++ b/pkg/skaffold/kubernetes/portforward/kubectl_forwarder.go @@ -37,6 +37,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -84,7 +85,7 @@ func (k *KubectlForwarder) Forward(parentCtx context.Context, pfe *portForwardEn return <-errChan } -func (k *KubectlForwarder) forward(parentCtx context.Context, pfe *portForwardEntry, errChan chan error) { +func (k *KubectlForwarder) forward(ctx context.Context, pfe *portForwardEntry, errChan chan error) { if atomic.LoadInt32(&k.started) == 0 { errChan <- fmt.Errorf("Forward() called before kubectl forwarder was started") return @@ -95,7 +96,7 @@ func (k *KubectlForwarder) forward(parentCtx context.Context, pfe *portForwardEn for { pfe.terminationLock.Lock() if pfe.terminated { - logrus.Debugf("port forwarding %v was cancelled...", pfe) + log.Entry(ctx).Debugf("port forwarding %v was cancelled...", pfe) pfe.terminationLock.Unlock() errChan <- nil return @@ -116,7 +117,7 @@ func (k *KubectlForwarder) forward(parentCtx context.Context, pfe *portForwardEn notifiedUser = false } - ctx, cancel := context.WithCancel(parentCtx) + ctx, cancel := context.WithCancel(ctx) pfe.cancel = cancel args := portForwardArgs(ctx, k.kubectl.KubeContext, pfe) @@ -125,14 +126,14 @@ func (k *KubectlForwarder) forward(parentCtx context.Context, pfe *portForwardEn cmd.Stdout = &buf cmd.Stderr = &buf - logrus.Debugf("Running command: %s", cmd.Args) + log.Entry(ctx).Debugf("Running command: %s", cmd.Args) if err := cmd.Start(); err != nil { if ctx.Err() == context.Canceled { - logrus.Debugf("couldn't start %v due to context cancellation", pfe) + log.Entry(ctx).Debugf("couldn't start %v due to context cancellation", pfe) return } // Retry on exit at Start() - logrus.Debugf("error starting port forwarding %v: %s, output: %s", pfe, err, buf.String()) + log.Entry(ctx).Debugf("error starting port forwarding %v: %s, output: %s", pfe, err, buf.String()) time.Sleep(500 * time.Millisecond) continue } @@ -141,14 +142,14 @@ func (k *KubectlForwarder) forward(parentCtx context.Context, pfe *portForwardEn go k.monitorLogs(ctx, &buf, cmd, pfe, errChan) if err := cmd.Wait(); err != nil { if ctx.Err() == context.Canceled { - logrus.Debugf("terminated %v due to context cancellation", pfe) + log.Entry(ctx).Debugf("terminated %v due to context cancellation", pfe) return } // To make sure that the log monitor gets cleared up cancel() s := buf.String() - logrus.Debugf("port forwarding %v got terminated: %s, output: %s", pfe, err, s) + log.Entry(ctx).Debugf("port forwarding %v got terminated: %s, output: %s", pfe, err, s) if !strings.Contains(s, "address already in use") { select { case errChan <- fmt.Errorf("port forwarding %v got terminated: output: %s", pfe, s): @@ -172,7 +173,7 @@ func portForwardArgs(ctx context.Context, kubeContext string, pfe *portForwardEn args = append(args, fmt.Sprintf("pod/%s", podName), fmt.Sprintf("%d:%d", pfe.localPort, remotePort)) break } - logrus.Warnf("could not map pods to service %s/%s/%s: %v", pfe.resource.Namespace, pfe.resource.Name, pfe.resource.Port.String(), err) + log.Entry(ctx).Warnf("could not map pods to service %s/%s/%s: %v", pfe.resource.Namespace, pfe.resource.Name, pfe.resource.Port.String(), err) fallthrough // and let kubectl try to handle it default: @@ -187,7 +188,7 @@ func portForwardArgs(ctx context.Context, kubeContext string, pfe *portForwardEn // Terminate terminates an existing kubectl port-forward command using SIGTERM func (*KubectlForwarder) Terminate(p *portForwardEntry) { - logrus.Debugf("Terminating port-forward %v", p) + log.Entry(context.Background()).Debugf("Terminating port-forward %v", p) p.terminationLock.Lock() defer p.terminationLock.Unlock() @@ -216,15 +217,15 @@ func (*KubectlForwarder) monitorLogs(ctx context.Context, logs io.Reader, cmd *k continue } - logrus.Tracef("[port-forward] %s", s) + log.Entry(ctx).Tracef("[port-forward] %s", s) if strings.Contains(s, "error forwarding port") || strings.Contains(s, "unable to forward") || strings.Contains(s, "error upgrading connection") { // kubectl is having an error. retry the command - logrus.Tracef("killing port forwarding %v", p) + log.Entry(ctx).Tracef("killing port forwarding %v", p) if err := cmd.Terminate(); err != nil { - logrus.Tracef("failed to kill port forwarding %v, err: %s", p, err) + log.Entry(ctx).Tracef("failed to kill port forwarding %v, err: %s", p, err) } select { case err <- fmt.Errorf("port forwarding %v got terminated: output: %s", p, s): @@ -282,12 +283,12 @@ func findNewestPodForService(ctx context.Context, kubeContext, ns, serviceName s for _, p := range pods { names = append(names, fmt.Sprintf("(pod:%q phase:%v created:%v)", p.Name, p.Status.Phase, p.CreationTimestamp)) } - logrus.Tracef("service %s/%s maps to %d pods: %v", serviceName, servicePort.String(), len(pods), names) + log.Entry(ctx).Tracef("service %s/%s maps to %d pods: %v", serviceName, servicePort.String(), len(pods), names) } for _, p := range pods { if targetPort := findTargetPort(svcPort, p); targetPort > 0 { - logrus.Debugf("Forwarding service %s/%s to pod %s/%d", serviceName, servicePort.String(), p.Name, targetPort) + log.Entry(ctx).Debugf("Forwarding service %s/%s to pod %s/%d", serviceName, servicePort.String(), p.Name, targetPort) return p.Name, targetPort, nil } } diff --git a/pkg/skaffold/kubernetes/portforward/pod_forwarder.go b/pkg/skaffold/kubernetes/portforward/pod_forwarder.go index c21319a5d51..b02b591d9dd 100644 --- a/pkg/skaffold/kubernetes/portforward/pod_forwarder.go +++ b/pkg/skaffold/kubernetes/portforward/pod_forwarder.go @@ -22,13 +22,13 @@ import ( "io" "strconv" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/watch" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" ) @@ -91,7 +91,7 @@ func (p *WatchingPodForwarder) Start(ctx context.Context, out io.Writer, namespa pod := evt.Pod if evt.Type != watch.Deleted && pod.Status.Phase == v1.PodRunning && pod.DeletionTimestamp == nil { if err := p.portForwardPod(ctx, pod); err != nil { - logrus.Warnf("port forwarding pod failed: %s", err) + log.Entry(ctx).Warnf("port forwarding pod failed: %s", err) } } } diff --git a/pkg/skaffold/kubernetes/portforward/port_forward_integration.go b/pkg/skaffold/kubernetes/portforward/port_forward_integration.go index 53a405ac6c8..8e10d797389 100644 --- a/pkg/skaffold/kubernetes/portforward/port_forward_integration.go +++ b/pkg/skaffold/kubernetes/portforward/port_forward_integration.go @@ -22,10 +22,10 @@ import ( "testing" "time" - "github.com/sirupsen/logrus" "k8s.io/apimachinery/pkg/util/wait" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -49,11 +49,11 @@ func SimulateDevCycle(t *testing.T, kubectlCLI *kubectl.CLI, namespace string) { em.forwardPortForwardEntry(ctx, os.Stdout, pfe) em.Stop() - logrus.Info("waiting for the same port to become available...") + log.Entry(ctx).Info("waiting for the same port to become available...") if err := wait.Poll(100*time.Millisecond, 5*time.Second, func() (done bool, err error) { nextPort := retrieveAvailablePort(util.Loopback, localPort, &em.forwardedPorts) - logrus.Infof("next port %d", nextPort) + log.Entry(ctx).Infof("next port %d", nextPort) // theoretically we should be able to bind to the very same port // this might get flaky when multiple tests are ran. However diff --git a/pkg/skaffold/kubernetes/portforward/resource_forwarder.go b/pkg/skaffold/kubernetes/portforward/resource_forwarder.go index 01058561d78..d1f6057f031 100644 --- a/pkg/skaffold/kubernetes/portforward/resource_forwarder.go +++ b/pkg/skaffold/kubernetes/portforward/resource_forwarder.go @@ -22,11 +22,11 @@ import ( "io" "sync" - "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -90,7 +90,7 @@ func (p *ResourceForwarder) Start(ctx context.Context, out io.Writer, namespaces } validResources = append(validResources, pf) } else { - logrus.Warnf("Skipping the port forwarding resource %s/%s because namespace is not specified", pf.Type, pf.Name) + log.Entry(ctx).Warnf("Skipping the port forwarding resource %s/%s because namespace is not specified", pf.Type, pf.Name) } } p.userDefinedResources = validResources diff --git a/pkg/skaffold/kubernetes/status/resource/deployment.go b/pkg/skaffold/kubernetes/status/resource/deployment.go index 200a4b16dae..0fc5e953020 100644 --- a/pkg/skaffold/kubernetes/status/resource/deployment.go +++ b/pkg/skaffold/kubernetes/status/resource/deployment.go @@ -22,14 +22,13 @@ import ( "strings" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/diag" "github.com/GoogleContainerTools/skaffold/pkg/diag/validator" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubectl" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -140,7 +139,7 @@ func (d *Deployment) CheckStatus(ctx context.Context, cfg kubectl.Config) { d.UpdateStatus(ae) if err := d.fetchPods(ctx); err != nil { - logrus.Debugf("pod statuses could not be fetched this time due to %s", err) + log.Entry(ctx).Debugf("pod statuses could not be fetched this time due to %s", err) } } @@ -202,7 +201,7 @@ func (d *Deployment) ReportSinceLastUpdated(isMuted bool) string { // result. out, writeTrimLines, err := withLogFile(p.Name(), &result, p.Logs(), isMuted) if err != nil { - logrus.Debugf("could not create log file %v", err) + log.Entry(context.Background()).Debugf("could not create log file %v", err) } trimLines := []string{} for i, l := range p.Logs() { diff --git a/pkg/skaffold/kubernetes/status/status_check.go b/pkg/skaffold/kubernetes/status/status_check.go index 41cfa46c538..91395b69c30 100644 --- a/pkg/skaffold/kubernetes/status/status_check.go +++ b/pkg/skaffold/kubernetes/status/status_check.go @@ -25,7 +25,6 @@ import ( "sync/atomic" "time" - "github.com/sirupsen/logrus" "golang.org/x/sync/singleflight" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" @@ -43,6 +42,7 @@ import ( kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/status/resource" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/proto/v1" ) @@ -224,7 +224,7 @@ func pollDeploymentStatus(ctx context.Context, cfg kubectl.Config, r *resource.D defer ticker.Stop() // Add poll duration to account for one last attempt after progressDeadlineSeconds. timeoutContext, cancel := context.WithTimeout(ctx, r.Deadline()+pollDuration) - logrus.Debugf("checking status %s", r) + log.Entry(ctx).Debugf("checking status %s", r) defer cancel() for { select { @@ -290,7 +290,7 @@ func (s *Monitor) printStatusCheckSummary(out io.Writer, r *resource.Deployment, } event.ResourceStatusCheckEventCompleted(r.String(), ae) eventV2.ResourceStatusCheckEventCompleted(r.String(), sErrors.V2fromV1(ae)) - out = output.WithEventContext(out, constants.Deploy, r.String()) + out, _ = output.WithEventContext(context.Background(), out, constants.Deploy, r.String()) status := fmt.Sprintf("%s %s", tabHeader, r) if ae.ErrCode != proto.StatusCode_STATUSCHECK_SUCCESS { if str := r.ReportSinceLastUpdated(s.muteLogs); str != "" { @@ -336,7 +336,7 @@ func (s *Monitor) printStatus(deployments []*resource.Deployment, out io.Writer) ae := r.Status().ActionableError() event.ResourceStatusCheckEventUpdated(r.String(), ae) eventV2.ResourceStatusCheckEventUpdated(r.String(), sErrors.V2fromV1(ae)) - out := output.WithEventContext(out, constants.Deploy, r.String()) + out, _ := output.WithEventContext(context.Background(), out, constants.Deploy, r.String()) fmt.Fprintln(out, trimNewLine(str)) } } diff --git a/pkg/skaffold/kubernetes/util.go b/pkg/skaffold/kubernetes/util.go index f401e8c38e6..eb11e9296ec 100644 --- a/pkg/skaffold/kubernetes/util.go +++ b/pkg/skaffold/kubernetes/util.go @@ -18,16 +18,17 @@ package kubernetes import ( "bufio" + "context" "errors" "fmt" "io" "os" "strings" - "github.com/sirupsen/logrus" k8syaml "k8s.io/apimachinery/pkg/util/yaml" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" ) @@ -121,7 +122,7 @@ func parseKubernetesObjects(filepath string) ([]yamlObject, error) { func hasRequiredK8sManifestFields(doc map[string]interface{}) bool { for _, field := range requiredFields { if _, ok := doc[field]; !ok { - logrus.Debugf("%s not present in yaml, continuing", field) + log.Entry(context.Background()).Debugf("%s not present in yaml, continuing", field) return false } } diff --git a/pkg/skaffold/kubernetes/wait.go b/pkg/skaffold/kubernetes/wait.go index a810b898c62..40b40106122 100644 --- a/pkg/skaffold/kubernetes/wait.go +++ b/pkg/skaffold/kubernetes/wait.go @@ -23,7 +23,6 @@ import ( "time" "github.com/golang/glog" - "github.com/sirupsen/logrus" appsv1 "k8s.io/api/apps/v1" v1 "k8s.io/api/core/v1" apierrs "k8s.io/apimachinery/pkg/api/errors" @@ -33,6 +32,8 @@ import ( "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/kubernetes" corev1 "k8s.io/client-go/kubernetes/typed/core/v1" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // WatchUntil reads items from the watch until the provided condition succeeds or the context is cancelled. @@ -58,7 +59,7 @@ func watchUntilTimeout(ctx context.Context, timeout time.Duration, w watch.Inter // WaitForPodSucceeded waits until the Pod status is Succeeded. func WaitForPodSucceeded(ctx context.Context, pods corev1.PodInterface, podName string, timeout time.Duration) error { - logrus.Infof("Waiting for %s to be complete", podName) + log.Entry(ctx).Infof("Waiting for %s to be complete", podName) w, err := pods.Watch(ctx, metav1.ListOptions{}) if err != nil { @@ -95,7 +96,7 @@ func isPodSucceeded(podName string) func(event *watch.Event) (bool, error) { // WaitForPodInitialized waits until init containers have started running func WaitForPodInitialized(ctx context.Context, pods corev1.PodInterface, podName string) error { - logrus.Infof("Waiting for %s to be initialized", podName) + log.Entry(ctx).Infof("Waiting for %s to be initialized", podName) w, err := pods.Watch(ctx, metav1.ListOptions{}) if err != nil { @@ -120,7 +121,7 @@ func WaitForPodInitialized(ctx context.Context, pods corev1.PodInterface, podNam // WaitForDeploymentToStabilize waits until the Deployment has a matching generation/replica count between spec and status. func WaitForDeploymentToStabilize(ctx context.Context, c kubernetes.Interface, ns, name string, timeout time.Duration) error { - logrus.Infof("Waiting for %s to stabilize", name) + log.Entry(ctx).Infof("Waiting for %s to stabilize", name) fields := fields.Set{ "metadata.name": name, diff --git a/pkg/skaffold/kubernetes/watcher.go b/pkg/skaffold/kubernetes/watcher.go index 698fa50a506..7c5efd8a21b 100644 --- a/pkg/skaffold/kubernetes/watcher.go +++ b/pkg/skaffold/kubernetes/watcher.go @@ -22,12 +22,12 @@ import ( "fmt" "sync" - "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/watch" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type PodWatcher interface { @@ -100,7 +100,7 @@ func (w *podWatcher) Start(kubeContext string, namespaces []string) (func(), err for evt := range watcher.ResultChan() { // If the event's type is "ERROR", warn and continue. if evt.Type == watch.Error { - logrus.Warnf("got unexpected event of type %s", evt.Type) + log.Entry(context.Background()).Warnf("got unexpected event of type %s", evt.Type) continue } diff --git a/pkg/skaffold/log/stream/stream.go b/pkg/skaffold/log/stream/stream.go index 405a854bd12..cebd9d1190a 100644 --- a/pkg/skaffold/log/stream/stream.go +++ b/pkg/skaffold/log/stream/stream.go @@ -23,9 +23,8 @@ import ( "io" "strings" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/log" + olog "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) //nolint:golint @@ -34,7 +33,7 @@ func StreamRequest(ctx context.Context, out io.Writer, formatter log.Formatter, for { select { case <-ctx.Done(): - logrus.Infof("%s interrupted", formatter.Name()) + olog.Entry(ctx).Infof("%s interrupted", formatter.Name()) return nil default: // Read up to newline diff --git a/pkg/skaffold/output/color.go b/pkg/skaffold/output/color.go index b73c410792b..cb4628a02fe 100644 --- a/pkg/skaffold/output/color.go +++ b/pkg/skaffold/output/color.go @@ -17,14 +17,15 @@ limitations under the License. package output import ( + "context" "fmt" "io" "strings" colors "github.com/heroku/color" "github.com/mattn/go-colorable" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -55,7 +56,7 @@ func SetupColors(out io.Writer, defaultColor int, forceColors bool) io.Writer { _, isTerm := util.IsTerminal(out) supportsColor, err := util.SupportsColor() if err != nil { - logrus.Debugf("error checking for color support: %v", err) + log.Entry(context.Background()).Debugf("error checking for color support: %v", err) } useColors := (isTerm && supportsColor) || forceColors diff --git a/pkg/skaffold/output/log/log.go b/pkg/skaffold/output/log/log.go new file mode 100644 index 00000000000..cfb36aa2455 --- /dev/null +++ b/pkg/skaffold/output/log/log.go @@ -0,0 +1,53 @@ +/* +Copyright 2021 The Skaffold Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package log + +import ( + "context" + + "github.com/sirupsen/logrus" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" +) + +type contextKey struct{} + +var ContextKey = contextKey{} + +type EventContext struct { + Task constants.Phase + Subtask string +} + +// Entry takes an context.Context and constructs a logrus.Entry from it, adding +// fields for task and subtask information +func Entry(ctx context.Context) *logrus.Entry { + val := ctx.Value(ContextKey) + if eventContext, ok := val.(EventContext); ok { + return logrus.WithFields(logrus.Fields{ + "task": eventContext.Task, + "subtask": eventContext.Subtask, + }) + } + + // Use constants.DevLoop as the default task, as it's the highest level task we + // can default to if one isn't specified. + return logrus.WithFields(logrus.Fields{ + "task": constants.DevLoop, + "subtask": constants.SubtaskIDNone, + }) +} diff --git a/pkg/skaffold/output/log/log_test.go b/pkg/skaffold/output/log/log_test.go new file mode 100644 index 00000000000..1a90b2abc3c --- /dev/null +++ b/pkg/skaffold/output/log/log_test.go @@ -0,0 +1,66 @@ +/* +Copyright 2021 The Skaffold Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package log + +import ( + "context" + "testing" + + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" + "github.com/GoogleContainerTools/skaffold/testutil" +) + +func TestEntry(t *testing.T) { + tests := []struct { + name string + task constants.Phase + expectedTask constants.Phase + subtask string + expectedSubtask string + emptyContext bool + }{ + { + name: "arbitrary task and subtask values", + task: constants.Build, + subtask: "test", + expectedTask: constants.Build, + expectedSubtask: "test", + }, + { + name: "context missing values", + emptyContext: true, + expectedTask: constants.DevLoop, + expectedSubtask: constants.SubtaskIDNone, + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + ctx := context.Background() + if !test.emptyContext { + ctx = context.WithValue(ctx, ContextKey, EventContext{ + Task: test.task, + Subtask: test.subtask, + }) + } + + got := Entry(ctx) + testutil.CheckDeepEqual(t, test.expectedTask, got.Data["task"]) + testutil.CheckDeepEqual(t, test.expectedSubtask, got.Data["subtask"]) + }) + } +} diff --git a/pkg/skaffold/output/output.go b/pkg/skaffold/output/output.go index 2c4998fc1ab..1a3f251aa82 100644 --- a/pkg/skaffold/output/output.go +++ b/pkg/skaffold/output/output.go @@ -17,14 +17,14 @@ limitations under the License. package output import ( + "context" "io" "os" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const timestampFormat = "2006-01-02 15:04:05" @@ -103,7 +103,12 @@ func GetUnderlyingWriter(out io.Writer) io.Writer { // WithEventContext will return a new skaffoldWriter with the given parameters to be used for the event writer. // If the passed io.Writer is not a skaffoldWriter, then it is simply returned. -func WithEventContext(out io.Writer, phase constants.Phase, subtaskID string) io.Writer { +func WithEventContext(ctx context.Context, out io.Writer, phase constants.Phase, subtaskID string) (io.Writer, context.Context) { + ctx = context.WithValue(ctx, log.ContextKey, log.EventContext{ + Task: phase, + Subtask: subtaskID, + }) + if sw, isSW := out.(skaffoldWriter); isSW { return skaffoldWriter{ MainWriter: sw.MainWriter, @@ -111,27 +116,8 @@ func WithEventContext(out io.Writer, phase constants.Phase, subtaskID string) io task: phase, subtask: subtaskID, timestamps: sw.timestamps, - } - } - - return out -} - -// Log takes an io.Writer (ideally of type output.skaffoldWriter) and constructs -// a logrus.Entry from it, adding fields for task and subtask information -func Log(out io.Writer) *logrus.Entry { - sw, isSW := out.(skaffoldWriter) - if isSW { - return logrus.WithFields(logrus.Fields{ - "task": sw.task, - "subtask": sw.subtask, - }) + }, ctx } - // Use constants.DevLoop as the default task, as it's the highest level task we - // can default to if one isn't specified. - return logrus.WithFields(logrus.Fields{ - "task": constants.DevLoop, - "subtask": eventV2.SubtaskIDNone, - }) + return out, ctx } diff --git a/pkg/skaffold/output/output_test.go b/pkg/skaffold/output/output_test.go index 833b6f10759..7ca8ac609b1 100644 --- a/pkg/skaffold/output/output_test.go +++ b/pkg/skaffold/output/output_test.go @@ -18,6 +18,7 @@ package output import ( "bytes" + "context" "io" "io/ioutil" "os" @@ -152,7 +153,7 @@ func TestWithEventContext(t *testing.T) { for _, test := range tests { testutil.Run(t, test.name, func(t *testutil.T) { - got := WithEventContext(test.writer, test.phase, test.subtaskID) + got, _ := WithEventContext(context.Background(), test.writer, test.phase, test.subtaskID) t.CheckDeepEqual(test.expected, got, cmpopts.IgnoreTypes(false, "", constants.DevLoop)) }) } @@ -217,36 +218,3 @@ func TestWriteWithTimeStamps(t *testing.T) { }) } } - -func TestLog(t *testing.T) { - tests := []struct { - name string - writer io.Writer - expectedTask constants.Phase - expectedSubtask string - }{ - { - name: "arbitrary task and subtask from writer", - writer: skaffoldWriter{ - task: constants.Build, - subtask: "test", - }, - expectedTask: constants.Build, - expectedSubtask: "test", - }, - { - name: "non skaffoldWriter", - writer: ioutil.Discard, - expectedTask: constants.DevLoop, - expectedSubtask: eventV2.SubtaskIDNone, - }, - } - - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - got := Log(test.writer) - testutil.CheckDeepEqual(t, test.expectedTask, got.Data["task"]) - testutil.CheckDeepEqual(t, test.expectedSubtask, got.Data["subtask"]) - }) - } -} diff --git a/pkg/skaffold/parser/config.go b/pkg/skaffold/parser/config.go index 08bd65b6611..4b5fed461da 100644 --- a/pkg/skaffold/parser/config.go +++ b/pkg/skaffold/parser/config.go @@ -17,6 +17,7 @@ limitations under the License. package parser import ( + "context" "errors" "fmt" "os" @@ -24,10 +25,9 @@ import ( "sort" "strings" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/git" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/defaults" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/errors" @@ -115,7 +115,7 @@ func getConfigs(cfgOpts configOpts, opts config.SkaffoldOptions, r *record) (Ska if len(parsed) == 0 { return nil, sErrors.ZeroConfigsParsedErr(cfgOpts.file) } - logrus.Debugf("parsed %d configs from configuration file %s", len(parsed), cfgOpts.file) + log.Entry(context.Background()).Debugf("parsed %d configs from configuration file %s", len(parsed), cfgOpts.file) // validate that config names are unique if specified seen := make(map[string]bool) @@ -295,7 +295,7 @@ func cacheRepo(g latestV1.GitInfo, opts config.SkaffoldOptions, r *record) (stri case error: return "", v default: - logrus.Fatalf("unable to check download status of repo %s at ref %s", g.Repo, g.Ref) + log.Entry(context.Background()).Fatalf("unable to check download status of repo %s at ref %s", g.Repo, g.Ref) return "", nil } } else { @@ -362,10 +362,10 @@ func isMakePathsAbsoluteSet(opts config.SkaffoldOptions) bool { func getBase(cfgOpts configOpts) (string, error) { if cfgOpts.isDependency { - logrus.Tracef("found %s base dir for absolute path substitution within skaffold config %s", filepath.Dir(cfgOpts.file), cfgOpts.file) + log.Entry(context.Background()).Tracef("found %s base dir for absolute path substitution within skaffold config %s", filepath.Dir(cfgOpts.file), cfgOpts.file) return filepath.Dir(cfgOpts.file), nil } - logrus.Tracef("found cwd as base for absolute path substitution within skaffold config %s", cfgOpts.file) + log.Entry(context.Background()).Tracef("found cwd as base for absolute path substitution within skaffold config %s", cfgOpts.file) return util.RealWorkDir() } diff --git a/pkg/skaffold/render/generate/generate.go b/pkg/skaffold/render/generate/generate.go index 511e5da498e..03a36d5dec6 100644 --- a/pkg/skaffold/render/generate/generate.go +++ b/pkg/skaffold/render/generate/generate.go @@ -23,11 +23,10 @@ import ( "path/filepath" "strings" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/kustomize" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -108,8 +107,8 @@ func (g *Generator) Generate(ctx context.Context) (manifest.ManifestList, error) for _, nkPath := range nonKustomizePaths { if !kubernetes.HasKubernetesFileExtension(nkPath) { if !util.StrSliceContains(g.config.RawK8s, nkPath) { - logrus.Infof("refusing to deploy/delete non {json, yaml} file %s", nkPath) - logrus.Info("If you still wish to deploy this file, please specify it directly, outside a glob pattern.") + log.Entry(ctx).Infof("refusing to deploy/delete non {json, yaml} file %s", nkPath) + log.Entry(ctx).Info("If you still wish to deploy this file, please specify it directly, outside a glob pattern.") continue } } diff --git a/pkg/skaffold/render/renderer/renderer.go b/pkg/skaffold/render/renderer/renderer.go index 46e9f41bc2b..0c74e99e065 100644 --- a/pkg/skaffold/render/renderer/renderer.go +++ b/pkg/skaffold/render/renderer/renderer.go @@ -24,12 +24,12 @@ import ( "os/exec" "path/filepath" - "github.com/sirupsen/logrus" "gopkg.in/yaml.v2" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/manifest" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/generate" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/kptfile" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/render/transform" @@ -105,7 +105,7 @@ type SkaffoldRenderer struct { // hydrated in place. func (r *SkaffoldRenderer) prepareHydrationDir(ctx context.Context) error { if _, err := os.Stat(r.hydrationDir); os.IsNotExist(err) { - logrus.Debugf("creating render directory: %v", r.hydrationDir) + log.Entry(ctx).Debugf("creating render directory: %v", r.hydrationDir) if err := os.MkdirAll(r.hydrationDir, os.ModePerm); err != nil { return fmt.Errorf("creating render directory for hydration: %w", err) } diff --git a/pkg/skaffold/runner/build.go b/pkg/skaffold/runner/build.go index 8ab044a97ab..97959680cd7 100644 --- a/pkg/skaffold/runner/build.go +++ b/pkg/skaffold/runner/build.go @@ -23,8 +23,6 @@ import ( "os" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/cache" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" @@ -32,6 +30,7 @@ import ( eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" @@ -65,7 +64,7 @@ func (r *Builder) GetBuilds() []graph.Artifact { // Build builds a list of artifacts. func (r *Builder) Build(ctx context.Context, out io.Writer, artifacts []*latestV1.Artifact) ([]graph.Artifact, error) { eventV2.TaskInProgress(constants.Build, "Build containers") - out = output.WithEventContext(out, constants.Build, eventV2.SubtaskIDNone) + out, ctx = output.WithEventContext(ctx, out, constants.Build, constants.SubtaskIDNone) // Use tags directly from the Kubernetes manifests. if r.runCtx.DigestSource() == NoneDigestSource { @@ -172,7 +171,7 @@ func (r *Builder) imageTags(ctx context.Context, out io.Writer, artifacts []*lat for i, artifact := range artifacts { imageName := artifact.ImageName - out := output.WithEventContext(out, constants.Build, imageName) + out, ctx := output.WithEventContext(ctx, out, constants.Build, imageName) output.Default.Fprintf(out, " - %s -> ", imageName) select { @@ -181,8 +180,8 @@ func (r *Builder) imageTags(ctx context.Context, out io.Writer, artifacts []*lat case t := <-tagErrs[i]: if t.err != nil { - logrus.Debugln(t.err) - logrus.Debugln("Using a fall-back tagger") + log.Entry(ctx).Debug(t.err) + log.Entry(ctx).Debug("Using a fall-back tagger") fallbackTag, err := tag.GenerateFullyQualifiedImageName(&tag.ChecksumTagger{}, *artifact) if err != nil { @@ -207,7 +206,7 @@ func (r *Builder) imageTags(ctx context.Context, out io.Writer, artifacts []*lat output.Yellow.Fprintln(out, "Some taggers failed. Rerun with -vdebug for errors.") } - logrus.Infoln("Tags generated in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Info("Tags generated in", util.ShowHumanizeTime(time.Since(start))) return imageTags, nil } diff --git a/pkg/skaffold/runner/builder.go b/pkg/skaffold/runner/builder.go index eab3e4612f2..b89d62ce6ac 100644 --- a/pkg/skaffold/runner/builder.go +++ b/pkg/skaffold/runner/builder.go @@ -17,15 +17,15 @@ limitations under the License. package runner import ( + "context" "fmt" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/cluster" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/gcb" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/local" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -50,7 +50,7 @@ func GetBuilder(r *runcontext.RunContext, s build.ArtifactStore, d graph.SourceD bCtx := &builderCtx{artifactStore: s, sourceDependenciesCache: d, RunContext: r} switch { case p.Build.LocalBuild != nil: - logrus.Debugln("Using builder: local") + log.Entry(context.Background()).Debug("Using builder: local") builder, err := local.NewBuilder(bCtx, p.Build.LocalBuild) if err != nil { return nil, err @@ -58,12 +58,12 @@ func GetBuilder(r *runcontext.RunContext, s build.ArtifactStore, d graph.SourceD return builder, nil case p.Build.GoogleCloudBuild != nil: - logrus.Debugln("Using builder: google cloud") + log.Entry(context.Background()).Debug("Using builder: google cloud") builder := gcb.NewBuilder(bCtx, p.Build.GoogleCloudBuild) return builder, nil case p.Build.Cluster != nil: - logrus.Debugln("Using builder: cluster") + log.Entry(context.Background()).Debug("Using builder: cluster") builder, err := cluster.NewBuilder(bCtx, p.Build.Cluster) if err != nil { return nil, err diff --git a/pkg/skaffold/runner/listen.go b/pkg/skaffold/runner/listen.go index 4d57758c8c9..caea9f054bf 100644 --- a/pkg/skaffold/runner/listen.go +++ b/pkg/skaffold/runner/listen.go @@ -22,10 +22,9 @@ import ( "fmt" "io" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/filemon" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/trigger" ) @@ -92,7 +91,7 @@ func (l *SkaffoldListener) do(devLoop func() error) error { // reset the dependencies resolver cache at the start of every dev loop. l.sourceDependenciesCache.Reset() if err := l.Monitor.Run(l.Trigger.Debounce()); err != nil { - logrus.Warnf("Ignoring changes: %s", err.Error()) + log.Entry(context.Background()).Warnf("Ignoring changes: %s", err.Error()) return nil } @@ -102,7 +101,7 @@ func (l *SkaffoldListener) do(devLoop func() error) error { if errors.Is(err, ErrorConfigurationChanged) { return err } - logrus.Errorf("error running dev loop: %s", err.Error()) + log.Entry(context.Background()).Errorf("error running dev loop: %s", err.Error()) } return nil diff --git a/pkg/skaffold/runner/runcontext/context.go b/pkg/skaffold/runner/runcontext/context.go index e77c0c73758..9957122f0e0 100644 --- a/pkg/skaffold/runner/runcontext/context.go +++ b/pkg/skaffold/runner/runcontext/context.go @@ -17,14 +17,15 @@ limitations under the License. package runcontext import ( + "context" "fmt" "os" "github.com/google/uuid" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemaUtil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" ) @@ -209,7 +210,7 @@ func GetRunContext(opts config.SkaffoldOptions, configs []schemaUtil.VersionedCo return nil, fmt.Errorf("getting current cluster context: %w", err) } kubeContext := kubeConfig.CurrentContext - logrus.Infof("Using kubectl context: %s", kubeContext) + log.Entry(context.Background()).Infof("Using kubectl context: %s", kubeContext) // TODO(dgageot): this should be the folder containing skaffold.yaml. Should also be moved elsewhere. cwd, err := os.Getwd() @@ -220,7 +221,7 @@ func GetRunContext(opts config.SkaffoldOptions, configs []schemaUtil.VersionedCo // combine all provided lists of insecure registries into a map cfgRegistries, err := config.GetInsecureRegistries(opts.GlobalConfig) if err != nil { - logrus.Warnf("error retrieving insecure registries from global config: push/pull issues may exist...") + log.Entry(context.Background()).Warn("error retrieving insecure registries from global config: push/pull issues may exist...") } var regList []string regList = append(regList, opts.InsecureRegistries...) diff --git a/pkg/skaffold/runner/timings.go b/pkg/skaffold/runner/timings.go index 43c5f45fb7e..a2847788201 100644 --- a/pkg/skaffold/runner/timings.go +++ b/pkg/skaffold/runner/timings.go @@ -21,12 +21,11 @@ import ( "io" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/tag" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/test" @@ -63,7 +62,7 @@ func (w withTimings) Build(ctx context.Context, out io.Writer, tags tag.ImageTag if err != nil { return nil, err } - logrus.Infoln("Build completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Infoln("Build completed in", util.ShowHumanizeTime(time.Since(start))) return bRes, nil } @@ -75,7 +74,7 @@ func (w withTimings) Test(ctx context.Context, out io.Writer, builds []graph.Art if err != nil { return err } - logrus.Infoln("Test completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Infoln("Test completed in", util.ShowHumanizeTime(time.Since(start))) return nil } @@ -87,7 +86,7 @@ func (w withTimings) Deploy(ctx context.Context, out io.Writer, builds []graph.A if err != nil { return err } - logrus.Infoln("Deploy completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Infoln("Deploy completed in", util.ShowHumanizeTime(time.Since(start))) return err } @@ -99,7 +98,7 @@ func (w withTimings) Cleanup(ctx context.Context, out io.Writer) error { if err != nil { return err } - logrus.Infoln("Cleanup completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Infoln("Cleanup completed in", util.ShowHumanizeTime(time.Since(start))) return nil } @@ -111,6 +110,6 @@ func (w withTimings) Prune(ctx context.Context, out io.Writer) error { if err != nil { return err } - logrus.Infoln("Image prune completed in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Infoln("Image prune completed in", util.ShowHumanizeTime(time.Since(start))) return nil } diff --git a/pkg/skaffold/runner/v1/deploy.go b/pkg/skaffold/runner/v1/deploy.go index 088f5db6426..c0b6ee79369 100644 --- a/pkg/skaffold/runner/v1/deploy.go +++ b/pkg/skaffold/runner/v1/deploy.go @@ -22,8 +22,6 @@ import ( "io" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" deployutil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" @@ -31,6 +29,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // DeployAndLog deploys a list of already built artifacts and optionally show the logs. @@ -47,7 +46,7 @@ func (r *SkaffoldRunner) DeployAndLog(ctx context.Context, out io.Writer, artifa defer r.deployer.GetAccessor().Stop() if err := r.deployer.GetAccessor().Start(ctx, out); err != nil { - logrus.Warnln("Error starting port forwarding:", err) + log.Entry(ctx).Warn("Error starting port forwarding:", err) } // Start printing the logs after deploy is finished @@ -69,7 +68,7 @@ func (r *SkaffoldRunner) Deploy(ctx context.Context, out io.Writer, artifacts [] } defer r.deployer.GetStatusMonitor().Reset() - out = output.WithEventContext(out, constants.Deploy, eventV2.SubtaskIDNone) + out, _ = output.WithEventContext(ctx, out, constants.Deploy, constants.SubtaskIDNone) output.Default.Fprintln(out, "Tags used in deployment:") @@ -88,7 +87,7 @@ func (r *SkaffoldRunner) Deploy(ctx context.Context, out io.Writer, artifacts [] } if len(localImages) > 0 { - logrus.Debugln(`Local images can't be referenced by digest. + log.Entry(ctx).Debug(`Local images can't be referenced by digest. They are tagged and referenced by a unique, local only, tag instead. See https://skaffold.dev/docs/pipeline-stages/taggers/#how-tagging-works`) } diff --git a/pkg/skaffold/runner/v1/dev.go b/pkg/skaffold/runner/v1/dev.go index 997a3cd170d..b2ed25108a7 100644 --- a/pkg/skaffold/runner/v1/dev.go +++ b/pkg/skaffold/runner/v1/dev.go @@ -23,8 +23,6 @@ import ( "strconv" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" eventV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event/v2" @@ -32,6 +30,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/sync" @@ -55,7 +54,7 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { } buildIntent, syncIntent, deployIntent := r.intents.GetIntents() - logrus.Tracef("dev intents: build %t, sync %t, deploy %t\n", buildIntent, syncIntent, deployIntent) + log.Entry(ctx).Tracef("dev intents: build %t, sync %t, deploy %t\n", buildIntent, syncIntent, deployIntent) needsSync := syncIntent && len(r.changeSet.NeedsResync()) > 0 needsBuild := buildIntent && len(r.changeSet.NeedsRebuild()) > 0 needsTest := len(r.changeSet.NeedsRetest()) > 0 @@ -93,7 +92,7 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { fileSyncInProgress(fileCount, s.Image) if err := r.deployer.GetSyncer().Sync(childCtx, out, s); err != nil { - logrus.Warnln("Skipping deploy due to sync error:", err) + log.Entry(ctx).Warn("Skipping deploy due to sync error:", err) fileSyncFailed(fileCount, s.Image, err) event.DevLoopFailedInPhase(r.devIteration, constants.Sync, err) eventV2.TaskFailed(constants.DevLoop, err) @@ -123,7 +122,7 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { var err error bRes, err = r.Build(childCtx, out, r.changeSet.NeedsRebuild()) if err != nil { - logrus.Warnln("Skipping test and deploy due to build error:", err) + log.Entry(ctx).Warn("Skipping test and deploy due to build error:", err) event.DevLoopFailedInPhase(r.devIteration, constants.Build, err) eventV2.TaskFailed(constants.DevLoop, err) endTrace(instrumentation.TraceEndError(err)) @@ -151,7 +150,7 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { } if err := r.Test(childCtx, out, bRes); err != nil { if needsDeploy { - logrus.Warnln("Skipping deploy due to test error:", err) + log.Entry(ctx).Warn("Skipping deploy due to test error:", err) } event.DevLoopFailedInPhase(r.devIteration, constants.Test, err) eventV2.TaskFailed(constants.DevLoop, err) @@ -169,17 +168,17 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { r.intents.ResetDeploy() }() - logrus.Debugln("stopping accessor") + log.Entry(ctx).Debug("stopping accessor") r.deployer.GetAccessor().Stop() - logrus.Debugln("stopping debugger") + log.Entry(ctx).Debug("stopping debugger") r.deployer.GetDebugger().Stop() if !meterUpdated { instrumentation.AddDevIteration("deploy") } if err := r.Deploy(childCtx, out, r.Builds); err != nil { - logrus.Warnln("Skipping deploy due to error:", err) + log.Entry(ctx).Warn("Skipping deploy due to error:", err) event.DevLoopFailedInPhase(r.devIteration, constants.Deploy, err) eventV2.TaskFailed(constants.DevLoop, err) endTrace(instrumentation.TraceEndError(err)) @@ -187,11 +186,11 @@ func (r *SkaffoldRunner) doDev(ctx context.Context, out io.Writer) error { } if err := r.deployer.GetAccessor().Start(childCtx, out); err != nil { - logrus.Warnf("failed to start accessor: %v", err) + log.Entry(ctx).Warnf("failed to start accessor: %v", err) } if err := r.deployer.GetDebugger().Start(childCtx); err != nil { - logrus.Warnf("failed to start debugger: %v", err) + log.Entry(ctx).Warnf("failed to start debugger: %v", err) } endTrace() @@ -240,7 +239,7 @@ func (r *SkaffoldRunner) Dev(ctx context.Context, out io.Writer, artifacts []*la s, err := sync.NewItem(ctx, artifact, e, r.Builds, r.runCtx, len(g[artifact.ImageName])) switch { case err != nil: - logrus.Warnf("error adding dirty artifact to changeset: %s", err.Error()) + log.Entry(ctx).Warnf("error adding dirty artifact to changeset: %s", err.Error()) case s != nil: r.changeSet.AddResync(s) default: @@ -292,7 +291,7 @@ func (r *SkaffoldRunner) Dev(ctx context.Context, out io.Writer, artifacts []*la return fmt.Errorf("watching skaffold configuration %q: %w", r.runCtx.ConfigurationFile(), err) } - logrus.Infoln("List generated in", util.ShowHumanizeTime(time.Since(start))) + log.Entry(ctx).Info("List generated in", util.ShowHumanizeTime(time.Since(start))) // Init Sync State if err := sync.Init(ctx, artifacts); err != nil { @@ -337,10 +336,10 @@ func (r *SkaffoldRunner) Dev(ctx context.Context, out io.Writer, artifacts []*la defer r.deployer.GetAccessor().Stop() if err := r.deployer.GetAccessor().Start(ctx, out); err != nil { - logrus.Warnln("Error starting resource accessor:", err) + log.Entry(ctx).Warn("Error starting resource accessor:", err) } if err := r.deployer.GetDebugger().Start(ctx); err != nil { - logrus.Warnln("Error starting debug container notification:", err) + log.Entry(ctx).Warn("Error starting debug container notification:", err) } // Start printing the logs after deploy is finished if err := r.deployer.GetLogger().Start(ctx, out); err != nil { diff --git a/pkg/skaffold/runner/v1/new.go b/pkg/skaffold/runner/v1/new.go index 4a189f5d0a2..825262031c3 100644 --- a/pkg/skaffold/runner/v1/new.go +++ b/pkg/skaffold/runner/v1/new.go @@ -20,8 +20,6 @@ import ( "context" "fmt" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/cache" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/deploy" @@ -31,6 +29,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/filemon" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/instrumentation" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" @@ -155,7 +154,7 @@ func setupTrigger(triggerName string, setIntent func(bool), setAutoTrigger func( // give the server a callback to set the intent value when a user request is received singleTriggerCallback(func() { if !getAutoTrigger() { // if auto trigger is disabled, we're in manual mode - logrus.Debugf("%s intent received, calling back to runner", triggerName) + log.Entry(context.Background()).Debugf("%s intent received, calling back to runner", triggerName) c <- true setIntent(true) } @@ -163,7 +162,7 @@ func setupTrigger(triggerName string, setIntent func(bool), setAutoTrigger func( // give the server a callback to update auto trigger value when a user request is received autoTriggerCallback(func(val bool) { - logrus.Debugf("%s auto trigger update to %t received, calling back to runner", triggerName, val) + log.Entry(context.Background()).Debugf("%s auto trigger update to %t received, calling back to runner", triggerName, val) // signal chan only when auto trigger is set to true if val { c <- true @@ -187,11 +186,11 @@ func isImageLocal(runCtx *runcontext.RunContext, imageName string) (bool, error) switch { case runCtx.Opts.PushImages.Value() != nil: - logrus.Debugf("push value set via skaffold build --push flag, --push=%t", *runCtx.Opts.PushImages.Value()) + log.Entry(context.Background()).Debugf("push value set via skaffold build --push flag, --push=%t", *runCtx.Opts.PushImages.Value()) pushImages = *runCtx.Opts.PushImages.Value() case pipeline.Build.LocalBuild.Push == nil: pushImages = cl.PushImages - logrus.Debugf("push value not present in isImageLocal(), defaulting to %t because cluster.PushImages is %t", pushImages, cl.PushImages) + log.Entry(context.Background()).Debugf("push value not present in isImageLocal(), defaulting to %t because cluster.PushImages is %t", pushImages, cl.PushImages) default: pushImages = *pipeline.Build.LocalBuild.Push } diff --git a/pkg/skaffold/schema/defaults/defaults.go b/pkg/skaffold/schema/defaults/defaults.go index 2b38ed8f51b..908599677d6 100644 --- a/pkg/skaffold/schema/defaults/defaults.go +++ b/pkg/skaffold/schema/defaults/defaults.go @@ -17,15 +17,16 @@ limitations under the License. package defaults import ( + "context" "fmt" "github.com/google/uuid" "github.com/mitchellh/go-homedir" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/kaniko" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" schemautil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -122,7 +123,7 @@ func defaultToLocalBuild(c *latestV1.SkaffoldConfig) { return } - logrus.Debugf("Defaulting build type to local build") + log.Entry(context.Background()).Debug("Defaulting build type to local build") c.Build.BuildType.LocalBuild = &latestV1.LocalBuild{} } @@ -131,7 +132,7 @@ func defaultToKubectlDeploy(c *latestV1.SkaffoldConfig) { return } - logrus.Debugf("Defaulting deploy type to kubectl") + log.Entry(context.Background()).Debug("Defaulting deploy type to kubectl") c.Deploy.DeployType.KubectlDeploy = &latestV1.KubectlDeploy{} } diff --git a/pkg/skaffold/schema/profiles.go b/pkg/skaffold/schema/profiles.go index be2f569245e..f8128358658 100644 --- a/pkg/skaffold/schema/profiles.go +++ b/pkg/skaffold/schema/profiles.go @@ -17,16 +17,17 @@ limitations under the License. package schema import ( + "context" "fmt" "os" "reflect" "strings" yamlpatch "github.com/krishicks/yaml-patch" - "github.com/sirupsen/logrus" cfg "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" kubectx "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" skutil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -195,7 +196,7 @@ func isKubeContext(kubeContext string, opts cfg.SkaffoldOptions) (bool, error) { } func applyProfile(config *latestV1.SkaffoldConfig, profile latestV1.Profile) error { - logrus.Infof("applying profile: %s", profile.Name) + log.Entry(context.Background()).Infof("applying profile: %s", profile.Name) // Apply profile, field by field mergedV := reflect.Indirect(reflect.ValueOf(&config.Pipeline)) @@ -293,7 +294,7 @@ func overlayOneOfField(config interface{}, profile interface{}) interface{} { } } // if we're here, we didn't find any values set in the profile config. just return the original. - logrus.Infof("no values found in profile for field %s, using original config values", t.Name()) + log.Entry(context.Background()).Infof("no values found in profile for field %s, using original config values", t.Name()) return config } @@ -316,7 +317,7 @@ func overlayStructField(config interface{}, profile interface{}) interface{} { func overlayProfileField(fieldName string, config interface{}, profile interface{}) interface{} { v := reflect.ValueOf(profile) // the profile itself t := reflect.TypeOf(profile) // the type of the profile, used for getting struct field types - logrus.Debugf("overlaying profile on config for field %s", fieldName) + log.Entry(context.Background()).Debugf("overlaying profile on config for field %s", fieldName) switch v.Kind() { case reflect.Struct: // check the first field of the struct for a oneOf yamltag. @@ -347,7 +348,7 @@ func overlayProfileField(fieldName string, config interface{}, profile interface } return v.Interface() default: - logrus.Fatalf("Type mismatch in profile overlay for field '%s' with type %s; falling back to original config values", fieldName, v.Kind()) + log.Entry(context.Background()).Fatalf("Type mismatch in profile overlay for field '%s' with type %s; falling back to original config values", fieldName, v.Kind()) return config } } diff --git a/pkg/skaffold/schema/v1alpha1/upgrade.go b/pkg/skaffold/schema/v1alpha1/upgrade.go index 1d235f7b708..4b3c60fab55 100644 --- a/pkg/skaffold/schema/v1alpha1/upgrade.go +++ b/pkg/skaffold/schema/v1alpha1/upgrade.go @@ -17,8 +17,9 @@ limitations under the License. package v1alpha1 import ( - "github.com/sirupsen/logrus" + "context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" next "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v1alpha2" ) @@ -71,7 +72,7 @@ func (config *SkaffoldConfig) Upgrade() (util.VersionedConfig, error) { var newKubectlDeploy *next.KubectlDeploy if config.Deploy.DeployType.KubectlDeploy != nil { var newManifests []string - logrus.Warn("Ignoring manifest parameters when transforming v1alpha1 config; check Kubernetes yaml before running skaffold") + log.Entry(context.Background()).Warn("Ignoring manifest parameters when transforming v1alpha1 config; check Kubernetes yaml before running skaffold") for _, manifest := range config.Deploy.DeployType.KubectlDeploy.Manifests { newManifests = append(newManifests, manifest.Paths...) } diff --git a/pkg/skaffold/schema/v1beta9/upgrade.go b/pkg/skaffold/schema/v1beta9/upgrade.go index 5d1cbd5c326..1724762bdd4 100644 --- a/pkg/skaffold/schema/v1beta9/upgrade.go +++ b/pkg/skaffold/schema/v1beta9/upgrade.go @@ -17,11 +17,11 @@ limitations under the License. package v1beta9 import ( + "context" "regexp" "strings" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" next "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v1beta10" pkgutil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -110,7 +110,7 @@ func convertSyncRules(artifacts []*Artifact) [][]*next.SyncRule { a.Sync = nil } if len(incompatiblePatterns) > 0 { - logrus.Warnf(incompatibleSyncWarning, incompatiblePatterns) + log.Entry(context.Background()).Warnf(incompatibleSyncWarning, incompatiblePatterns) } return newSync } diff --git a/pkg/skaffold/schema/v2beta16/upgrade.go b/pkg/skaffold/schema/v2beta16/upgrade.go index b9c6b41ea1c..bf12c46c5db 100644 --- a/pkg/skaffold/schema/v2beta16/upgrade.go +++ b/pkg/skaffold/schema/v2beta16/upgrade.go @@ -17,8 +17,9 @@ limitations under the License. package v2beta16 import ( - "github.com/sirupsen/logrus" + "context" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/util" next "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v2beta17" pkgutil "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" @@ -38,7 +39,7 @@ func (c *SkaffoldConfig) Upgrade() (util.VersionedConfig, error) { func upgradeOnePipeline(oldPipeline, newPipeline interface{}) error { for _, a := range oldPipeline.(*Pipeline).Build.Artifacts { if a.DockerArtifact != nil && a.DockerArtifact.Secret != nil && a.DockerArtifact.Secret.Destination != "" { - logrus.Warnf("Artifact %q: Docker secret destination is no longer supported: %q", a.ImageName, a.DockerArtifact.Secret.Destination) + log.Entry(context.Background()).Warnf("Artifact %q: Docker secret destination is no longer supported: %q", a.ImageName, a.DockerArtifact.Secret.Destination) } } return nil diff --git a/pkg/skaffold/schema/validation/validation.go b/pkg/skaffold/schema/validation/validation.go index 5d4693d06d8..9a96e314423 100644 --- a/pkg/skaffold/schema/validation/validation.go +++ b/pkg/skaffold/schema/validation/validation.go @@ -27,13 +27,13 @@ import ( "github.com/docker/docker/api/types" "github.com/pkg/errors" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/build/misc" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/errors" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/parser" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner/runcontext" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" @@ -602,7 +602,7 @@ func validateKubectlManifests(configs parser.SkaffoldConfigSet) (errs []error) { continue } if len(c.Deploy.KubectlDeploy.Manifests) == 1 && c.Deploy.KubectlDeploy.Manifests[0] == constants.DefaultKubectlManifests[0] { - logrus.Debugln("skipping validating `kubectl` deployer manifests since only the default manifest list is defined") + log.Entry(context.Background()).Debug("skipping validating `kubectl` deployer manifests since only the default manifest list is defined") continue } diff --git a/pkg/skaffold/schema/versions.go b/pkg/skaffold/schema/versions.go index 86cbf7c2c1e..dca9d14ca0f 100644 --- a/pkg/skaffold/schema/versions.go +++ b/pkg/skaffold/schema/versions.go @@ -18,17 +18,18 @@ package schema import ( "bytes" + "context" "errors" "fmt" "io" "regexp" "strings" - "github.com/sirupsen/logrus" "gopkg.in/yaml.v3" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/apiversion" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" sErrors "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/errors" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" latestV2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v2" @@ -372,7 +373,7 @@ func UpgradeTo(configs []util.VersionedConfig, toVersion string) ([]util.Version if !upgradeNeeded { return configs, nil } - logrus.Debugf("config version out of date: upgrading to latest %q", toVersion) + log.Entry(context.Background()).Debugf("config version out of date: upgrading to latest %q", toVersion) var err error var upgraded []util.VersionedConfig for _, cfg := range configs { diff --git a/pkg/skaffold/server/server.go b/pkg/skaffold/server/server.go index 920155d5a19..35bed46c4b3 100644 --- a/pkg/skaffold/server/server.go +++ b/pkg/skaffold/server/server.go @@ -26,12 +26,12 @@ import ( "time" "github.com/grpc-ecosystem/grpc-gateway/runtime" - "github.com/sirupsen/logrus" "google.golang.org/grpc" "google.golang.org/grpc/status" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" v2 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/server/v2" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/proto/v1" @@ -140,9 +140,9 @@ func newGRPCServer(preferredPort int, usedPorts *util.PortSet) (func() error, in } if port != preferredPort { - logrus.Warnf("starting gRPC server on port %d. (%d is already in use)", port, preferredPort) + log.Entry(context.Background()).Warnf("starting gRPC server on port %d. (%d is already in use)", port, preferredPort) } else { - logrus.Infof("starting gRPC server on port %d", port) + log.Entry(context.Background()).Infof("starting gRPC server on port %d", port) } s := grpc.NewServer() @@ -167,7 +167,7 @@ func newGRPCServer(preferredPort int, usedPorts *util.PortSet) (func() error, in go func() { if err := s.Serve(l); err != nil { - logrus.Errorf("failed to start grpc server: %s", err) + log.Entry(context.Background()).Errorf("failed to start grpc server: %s", err) } }() return func() error { @@ -207,9 +207,9 @@ func newHTTPServer(preferredPort, proxyPort int, usedPorts *util.PortSet) (func( } if port != preferredPort { - logrus.Warnf("starting gRPC HTTP server on port %d. (%d is already in use)", port, preferredPort) + log.Entry(context.Background()).Warnf("starting gRPC HTTP server on port %d. (%d is already in use)", port, preferredPort) } else { - logrus.Infof("starting gRPC HTTP server on port %d", port) + log.Entry(context.Background()).Infof("starting gRPC HTTP server on port %d", port) } server := &http.Server{ diff --git a/pkg/skaffold/survey/survey.go b/pkg/skaffold/survey/survey.go index 2a513e5bba1..72cea850d84 100644 --- a/pkg/skaffold/survey/survey.go +++ b/pkg/skaffold/survey/survey.go @@ -23,10 +23,10 @@ import ( "time" "github.com/pkg/browser" - "github.com/sirupsen/logrus" sConfig "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/timeutil" ) @@ -129,7 +129,7 @@ func (s *Runner) OpenSurveyForm(_ context.Context, out io.Writer, id string) err return err } if err := open(sc.URL); err != nil { - logrus.Debugf("could not open url %s", sc.URL) + log.Entry(context.Background()).Debugf("could not open url %s", sc.URL) return err } @@ -168,7 +168,7 @@ func (s *Runner) selectSurvey(takenSurveys map[string]struct{}) string { sortSurveys(candidates) cfgs, err := parseConfig(s.skaffoldConfig) if err != nil { - logrus.Debugf("error parsing skaffold.yaml %s", err) + log.Entry(context.Background()).Debugf("error parsing skaffold.yaml %s", err) return "" } for _, sc := range candidates { diff --git a/pkg/skaffold/sync/docker.go b/pkg/skaffold/sync/docker.go index d8c94103ffe..71cda296d6f 100644 --- a/pkg/skaffold/sync/docker.go +++ b/pkg/skaffold/sync/docker.go @@ -22,8 +22,7 @@ import ( "io" "os/exec" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -35,14 +34,14 @@ func NewContainerSyncer() *ContainerSyncer { func (s *ContainerSyncer) Sync(ctx context.Context, _ io.Writer, item *Item) error { if len(item.Copy) > 0 { - logrus.Infoln("Copying files:", item.Copy, "to", item.Image) + log.Entry(ctx).Info("Copying files:", item.Copy, "to", item.Image) if _, err := util.RunCmdOut(s.copyFileFn(ctx, item.Artifact.ImageName, item.Copy)); err != nil { return fmt.Errorf("copying files: %w", err) } } if len(item.Delete) > 0 { - logrus.Infoln("Deleting files:", item.Delete, "from", item.Image) + log.Entry(ctx).Info("Deleting files:", item.Delete, "from", item.Image) if _, err := util.RunCmdOut(s.deleteFileFn(ctx, item.Artifact.ImageName, item.Delete)); err != nil { return fmt.Errorf("deleting files: %w", err) } diff --git a/pkg/skaffold/sync/sync.go b/pkg/skaffold/sync/sync.go index 3110d3d9595..3a77f455020 100644 --- a/pkg/skaffold/sync/sync.go +++ b/pkg/skaffold/sync/sync.go @@ -27,7 +27,6 @@ import ( "strings" "github.com/bmatcuk/doublestar" - "github.com/sirupsen/logrus" "golang.org/x/sync/errgroup" v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -40,6 +39,7 @@ import ( "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/hooks" kubernetesclient "github.com/GoogleContainerTools/skaffold/pkg/skaffold/kubernetes/client" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -57,7 +57,7 @@ func NewItem(ctx context.Context, a *latestV1.Artifact, e filemon.Events, builds } if dependentArtifactsCount > 0 { - logrus.Warnf("Ignoring sync rules for image %q as it is being used as a required artifact for other images.", a.ImageName) + log.Entry(ctx).Warnf("Ignoring sync rules for image %q as it is being used as a required artifact for other images.", a.ImageName) return nil, nil } @@ -134,14 +134,14 @@ func inferredSyncItem(a *latestV1.Artifact, tag string, e filemon.Events, cfg do } } if !matches { - logrus.Infof("Changed file %s does not match any sync pattern. Skipping sync", relPath) + log.Entry(context.Background()).Infof("Changed file %s does not match any sync pattern. Skipping sync", relPath) return nil, nil } if dsts, ok := syncMap[relPath]; ok { toCopy[f] = dsts } else { - logrus.Infof("Changed file %s is not syncable. Skipping sync", relPath) + log.Entry(context.Background()).Infof("Changed file %s is not syncable. Skipping sync", relPath) return nil, nil } } @@ -220,7 +220,7 @@ func intersect(contextWd, containerWd string, syncRules []*latestV1.SyncRule, fi } if len(dsts) == 0 { - logrus.Infof("Changed file %s does not match any sync pattern. Skipping sync", relPath) + log.Entry(context.Background()).Infof("Changed file %s does not match any sync pattern. Skipping sync", relPath) return nil, nil } @@ -286,7 +286,7 @@ func (s *PodSyncer) Sync(ctx context.Context, out io.Writer, item *Item) error { func (s *PodSyncer) sync(ctx context.Context, item *Item) error { if len(item.Copy) > 0 { - logrus.Infoln("Copying files:", item.Copy, "to", item.Image) + log.Entry(ctx).Info("Copying files:", item.Copy, "to", item.Image) if err := Perform(ctx, item.Image, item.Copy, s.copyFileFn, *s.namespaces, s.kubectl.KubeContext); err != nil { return fmt.Errorf("copying files: %w", err) @@ -294,7 +294,7 @@ func (s *PodSyncer) sync(ctx context.Context, item *Item) error { } if len(item.Delete) > 0 { - logrus.Infoln("Deleting files:", item.Delete, "from", item.Image) + log.Entry(ctx).Info("Deleting files:", item.Delete, "from", item.Image) if err := Perform(ctx, item.Image, item.Delete, s.deleteFileFn, *s.namespaces, s.kubectl.KubeContext); err != nil { return fmt.Errorf("deleting files: %w", err) diff --git a/pkg/skaffold/tag/custom_template.go b/pkg/skaffold/tag/custom_template.go index 4d045075ba1..03bd7b15773 100644 --- a/pkg/skaffold/tag/custom_template.go +++ b/pkg/skaffold/tag/custom_template.go @@ -18,11 +18,11 @@ package tag import ( "bytes" + "context" "fmt" "text/template" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -94,7 +94,7 @@ func ParseCustomTemplate(t string) (*template.Template, error) { // ExecuteCustomTemplate executes a customTemplate against a custom map. func ExecuteCustomTemplate(customTemplate *template.Template, customMap map[string]string) (string, error) { var buf bytes.Buffer - logrus.Debugf("Executing custom template %v with custom map %v", customTemplate, customMap) + log.Entry(context.Background()).Debugf("Executing custom template %v with custom map %v", customTemplate, customMap) if err := customTemplate.Execute(&buf, customMap); err != nil { return "", fmt.Errorf("executing template: %w", err) } diff --git a/pkg/skaffold/tag/git_commit.go b/pkg/skaffold/tag/git_commit.go index 55cefb17da2..3754e7ed6ad 100644 --- a/pkg/skaffold/tag/git_commit.go +++ b/pkg/skaffold/tag/git_commit.go @@ -18,14 +18,14 @@ package tag import ( "bytes" + "context" "fmt" "os/exec" "path/filepath" "regexp" "strings" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -99,7 +99,7 @@ func sanitizeTag(tag string) string { } if tag != sanitized { - logrus.Warnf("Using %q instead of %q as an image tag", sanitized, tag) + log.Entry(context.Background()).Warnf("Using %q instead of %q as an image tag", sanitized, tag) } return sanitized diff --git a/pkg/skaffold/tag/input_digest.go b/pkg/skaffold/tag/input_digest.go index 8a253decd20..33840c2977b 100644 --- a/pkg/skaffold/tag/input_digest.go +++ b/pkg/skaffold/tag/input_digest.go @@ -28,10 +28,9 @@ import ( "path/filepath" "sort" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" ) @@ -62,7 +61,7 @@ func (t *inputDigestTagger) GenerateTag(image latestV1.Artifact) (string, error) h, err := fileHasher(d) if err != nil { if os.IsNotExist(err) { - logrus.Tracef("skipping dependency %q for artifact cache calculation: %v", d, err) + log.Entry(ctx).Tracef("skipping dependency %q for artifact cache calculation: %v", d, err) continue // Ignore files that don't exist } diff --git a/pkg/skaffold/tags/paths.go b/pkg/skaffold/tags/paths.go index 11436eb275f..ec52e6c81e5 100644 --- a/pkg/skaffold/tags/paths.go +++ b/pkg/skaffold/tags/paths.go @@ -17,12 +17,13 @@ limitations under the License. package tags import ( + "context" "fmt" "path/filepath" "reflect" "strings" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // MakeFilePathsAbsolute recursively sets all fields marked with the tag `filepath` to absolute paths @@ -62,7 +63,7 @@ func makeFilePathsAbsolute(config interface{}, base string) []error { continue } v.SetString(filepath.Join(base, path)) - logrus.Tracef("setting absolute path %q for config field %q", filepath.Join(base, path), f.Name) + log.Entry(context.Background()).Tracef("setting absolute path %q for config field %q", filepath.Join(base, path), f.Name) case []string: for j := 0; j < v.Len(); j++ { elem := v.Index(j) @@ -71,7 +72,7 @@ func makeFilePathsAbsolute(config interface{}, base string) []error { continue } elem.SetString(filepath.Join(base, path)) - logrus.Tracef("setting absolute paths for config field %q index %d", f.Name, j) + log.Entry(context.Background()).Tracef("setting absolute paths for config field %q index %d", f.Name, j) } case map[string]string: for _, key := range v.MapKeys() { @@ -80,7 +81,7 @@ func makeFilePathsAbsolute(config interface{}, base string) []error { continue } v.SetMapIndex(key, reflect.ValueOf(filepath.Join(base, path))) - logrus.Tracef("setting absolute paths for config field %q key %q", f.Name, key.String()) + log.Entry(context.Background()).Tracef("setting absolute paths for config field %q key %q", f.Name, key.String()) } default: return []error{fmt.Errorf("yaml tag `filepath` needs struct field %q to be string or string slice", f.Name)} diff --git a/pkg/skaffold/test/structure/structure.go b/pkg/skaffold/test/structure/structure.go index cf879226ca0..224c1ac5852 100644 --- a/pkg/skaffold/test/structure/structure.go +++ b/pkg/skaffold/test/structure/structure.go @@ -23,10 +23,9 @@ import ( "os" "os/exec" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/docker" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/event" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -82,7 +81,7 @@ func (cst *Runner) runStructureTests(ctx context.Context, out io.Writer, imageTa return err } - logrus.Infof("Running structure tests for files %v", files) + log.Entry(ctx).Infof("Running structure tests for files %v", files) args := []string{"test", "-v", "warn", "--image", imageTag} for _, f := range files { diff --git a/pkg/skaffold/timeutil/util.go b/pkg/skaffold/timeutil/util.go index 8cad2669f5c..b9c70bb4add 100644 --- a/pkg/skaffold/timeutil/util.go +++ b/pkg/skaffold/timeutil/util.go @@ -17,15 +17,16 @@ limitations under the License. package timeutil import ( + "context" "time" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) func LessThan(date string, duration time.Duration) bool { t, err := time.Parse(time.RFC3339, date) if err != nil { - logrus.Debugf("could not parse date %q", date) + log.Entry(context.Background()).Debugf("could not parse date %q", date) return false } return time.Since(t) < duration diff --git a/pkg/skaffold/trigger/fsnotify/trigger.go b/pkg/skaffold/trigger/fsnotify/trigger.go index 36500d5fa1d..9ad2ce1bc9e 100644 --- a/pkg/skaffold/trigger/fsnotify/trigger.go +++ b/pkg/skaffold/trigger/fsnotify/trigger.go @@ -23,9 +23,9 @@ import ( "time" "github.com/rjeczalik/notify" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" ) @@ -121,7 +121,7 @@ func (t *Trigger) Start(ctx context.Context) (<-chan bool, error) { if !t.isActive() && t.Ignore(e) { continue } - logrus.Debugln("Change detected", e) + log.Entry(ctx).Debug("Change detected", e) // Wait t.Ienterval before triggering. // This way, rapid stream of events will be grouped. diff --git a/pkg/skaffold/trigger/triggers.go b/pkg/skaffold/trigger/triggers.go index 4ad0d94c3e5..57226f8891b 100644 --- a/pkg/skaffold/trigger/triggers.go +++ b/pkg/skaffold/trigger/triggers.go @@ -26,9 +26,8 @@ import ( "sync/atomic" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" latestV1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1" fsNotify "github.com/GoogleContainerTools/skaffold/pkg/skaffold/trigger/fsnotify" ) @@ -150,7 +149,7 @@ func (t *manualTrigger) Start(ctx context.Context) (<-chan bool, error) { for { _, _, err := reader.ReadRune() if err != nil { - logrus.Debugf("manual trigger error: %s", err) + log.Entry(ctx).Debugf("manual trigger error: %s", err) } // Wait until the context is cancelled. @@ -177,7 +176,7 @@ func StartTrigger(ctx context.Context, t Trigger) (<-chan bool, error) { return ret, err } if fsnotify, ok := t.(*fsNotify.Trigger); ok { - logrus.Debugln("Couldn't start notify trigger. Falling back to a polling trigger") + log.Entry(ctx).Debug("Couldn't start notify trigger. Falling back to a polling trigger") t = &pollTrigger{ Interval: fsnotify.Interval, diff --git a/pkg/skaffold/update/update.go b/pkg/skaffold/update/update.go index 066b31514bc..8e983d73279 100644 --- a/pkg/skaffold/update/update.go +++ b/pkg/skaffold/update/update.go @@ -17,13 +17,14 @@ limitations under the License. package update import ( + "context" "fmt" "strings" "github.com/blang/semver" - "github.com/sirupsen/logrus" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/config" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/version" ) @@ -51,7 +52,7 @@ func CheckVersionOnError(config string) (string, error) { func checkVersion(configfile string, onError bool) (string, error) { if !isUpdateCheckEnabled(configfile) { - logrus.Debugf("Update check not enabled, skipping.") + log.Entry(context.Background()).Debug("Update check not enabled, skipping.") return "", nil } latest, current, err := GetLatestAndCurrentVersion() @@ -81,7 +82,7 @@ func getLatestAndCurrentVersion() (semver.Version, semver.Version, error) { if err != nil { return none, none, err } - logrus.Tracef("latest skaffold version: %s", versionString) + log.Entry(context.Background()).Tracef("latest skaffold version: %s", versionString) latest, err := version.ParseVersion(versionString) if err != nil { return none, none, fmt.Errorf("parsing latest version from GCS: %w", err) diff --git a/pkg/skaffold/util/cmd.go b/pkg/skaffold/util/cmd.go index e633ded0c00..3004a98710b 100644 --- a/pkg/skaffold/util/cmd.go +++ b/pkg/skaffold/util/cmd.go @@ -18,10 +18,11 @@ package util import ( "bytes" + "context" "fmt" "os/exec" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type cmdError struct { @@ -69,7 +70,7 @@ type Commander struct{} // RunCmdOut runs an exec.Command and returns the stdout and error. func (*Commander) RunCmdOut(cmd *exec.Cmd) ([]byte, error) { - logrus.Debugf("Running command: %s", cmd.Args) + log.Entry(context.Background()).Debugf("Running command: %s", cmd.Args) stdout := bytes.Buffer{} cmd.Stdout = &stdout @@ -90,9 +91,9 @@ func (*Commander) RunCmdOut(cmd *exec.Cmd) ([]byte, error) { } if stderr.Len() > 0 { - logrus.Debugf("Command output: [%s], stderr: %s", stdout.String(), stderr.String()) + log.Entry(context.Background()).Debugf("Command output: [%s], stderr: %s", stdout.String(), stderr.String()) } else { - logrus.Debugf("Command output: [%s]", stdout.String()) + log.Entry(context.Background()).Debugf("Command output: [%s]", stdout.String()) } return stdout.Bytes(), nil @@ -100,6 +101,6 @@ func (*Commander) RunCmdOut(cmd *exec.Cmd) ([]byte, error) { // RunCmd runs an exec.Command. func (*Commander) RunCmd(cmd *exec.Cmd) error { - logrus.Debugf("Running command: %s", cmd.Args) + log.Entry(context.Background()).Debugf("Running command: %s", cmd.Args) return cmd.Run() } diff --git a/pkg/skaffold/util/config.go b/pkg/skaffold/util/config.go index 72267cee5c3..be286804d85 100644 --- a/pkg/skaffold/util/config.go +++ b/pkg/skaffold/util/config.go @@ -17,11 +17,12 @@ limitations under the License. package util import ( + "context" "errors" "io/ioutil" "os" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // ReadConfiguration reads a `skaffold.yaml` configuration and @@ -40,8 +41,8 @@ func ReadConfiguration(filename string) ([]byte, error) { // If the config file is the default `skaffold.yaml`, // then we also try to read `skaffold.yml`. if filename == "skaffold.yaml" { - logrus.Infof("Could not open skaffold.yaml: \"%s\"", err) - logrus.Infof("Trying to read from skaffold.yml instead") + log.Entry(context.Background()).Infof("Could not open skaffold.yaml: \"%s\"", err) + log.Entry(context.Background()).Info("Trying to read from skaffold.yml instead") contents, errIgnored := ioutil.ReadFile("skaffold.yml") if errIgnored != nil { // Return original error because it's the one that matters diff --git a/pkg/skaffold/util/env_template.go b/pkg/skaffold/util/env_template.go index 1f123b845a0..92db8ee999d 100644 --- a/pkg/skaffold/util/env_template.go +++ b/pkg/skaffold/util/env_template.go @@ -18,6 +18,7 @@ package util import ( "bytes" + "context" "fmt" "os" "reflect" @@ -25,7 +26,7 @@ import ( "strings" "text/template" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // For testing @@ -73,7 +74,7 @@ func ExecuteEnvTemplate(envTemplate *template.Template, customMap map[string]str } var buf bytes.Buffer - logrus.Debugf("Executing template %v with environment %v", envTemplate, envMap) + log.Entry(context.Background()).Debugf("Executing template %v with environment %v", envTemplate, envMap) if err := envTemplate.Execute(&buf, envMap); err != nil { return "", err } diff --git a/pkg/skaffold/util/gsutil.go b/pkg/skaffold/util/gsutil.go index 71cdc232b49..b6e5f6a9131 100644 --- a/pkg/skaffold/util/gsutil.go +++ b/pkg/skaffold/util/gsutil.go @@ -21,7 +21,7 @@ import ( "fmt" "os/exec" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) const GsutilExec = "gsutil" @@ -40,6 +40,6 @@ func (g *Gsutil) Copy(ctx context.Context, src, dst string, recursive bool) erro if err != nil { return fmt.Errorf("copy file(s) with %s failed: %w", GsutilExec, err) } - logrus.Info(out) + log.Entry(ctx).Info(out) return nil } diff --git a/pkg/skaffold/util/port.go b/pkg/skaffold/util/port.go index fa9fde60f45..5ec8ec5916d 100644 --- a/pkg/skaffold/util/port.go +++ b/pkg/skaffold/util/port.go @@ -17,12 +17,13 @@ limitations under the License. package util import ( + "context" "fmt" "net" "sort" "sync" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // Loopback network address. Skaffold should not bind to 0.0.0.0 @@ -99,10 +100,10 @@ func (f *PortSet) List() []int { // // See https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt func GetAvailablePort(address string, port int, usedPorts *PortSet) int { - logrus.Tracef("looking for port: %s:%d", address, port) + log.Entry(context.Background()).Tracef("looking for port: %s:%d", address, port) if port > 0 { if getPortIfAvailable(address, port, usedPorts) { - logrus.Debugf("found open port: %d", port) + log.Entry(context.Background()).Debugf("found open port: %d", port) return port } @@ -110,7 +111,7 @@ func GetAvailablePort(address string, port int, usedPorts *PortSet) int { for i := 0; i < 10; i++ { port++ if getPortIfAvailable(address, port, usedPorts) { - logrus.Debugf("found open port: %d", port) + log.Entry(context.Background()).Debugf("found open port: %d", port) return port } } @@ -118,7 +119,7 @@ func GetAvailablePort(address string, port int, usedPorts *PortSet) int { for port = 4503; port <= 4533; port++ { if getPortIfAvailable(address, port, usedPorts) { - logrus.Debugf("found open port: %d", port) + log.Entry(context.Background()).Debugf("found open port: %d", port) return port } } @@ -137,7 +138,7 @@ func GetAvailablePort(address string, port int, usedPorts *PortSet) int { func getPortIfAvailable(address string, p int, usedPorts *PortSet) bool { if alreadySet := usedPorts.LoadOrSet(p); alreadySet { - logrus.Tracef("port %d already allocated", p) + log.Entry(context.Background()).Tracef("port %d already allocated", p) return false } @@ -148,27 +149,27 @@ func IsPortFree(address string, p int) bool { // Ensure the port is available across all interfaces l, err := net.Listen("tcp", fmt.Sprintf(":%d", p)) if err != nil { - logrus.Tracef("port INADDR_ANY:%d already bound: %v", p, err) + log.Entry(context.Background()).Tracef("port INADDR_ANY:%d already bound: %v", p, err) return false } else if l == nil { - logrus.Tracef("port INADDR_ANY:%d nil listener", p) + log.Entry(context.Background()).Tracef("port INADDR_ANY:%d nil listener", p) return false } l.Close() - logrus.Tracef("was able to obtain INADDR_ANY:%d", p) + log.Entry(context.Background()).Tracef("was able to obtain INADDR_ANY:%d", p) if address != Any { // Ensure the port is available on the specific interface too l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", address, p)) if err != nil { - logrus.Tracef("port %s:%d already bound: %v", address, p, err) + log.Entry(context.Background()).Tracef("port %s:%d already bound: %v", address, p, err) return false } else if l == nil { - logrus.Tracef("port %s:%d nil listener", address, p) + log.Entry(context.Background()).Tracef("port %s:%d nil listener", address, p) return false } l.Close() - logrus.Tracef("was able to obtain %s:%d", address, p) + log.Entry(context.Background()).Tracef("was able to obtain %s:%d", address, p) } return true } diff --git a/pkg/skaffold/util/regex.go b/pkg/skaffold/util/regex.go index 41b5b8e68cd..f3891b7f8a3 100644 --- a/pkg/skaffold/util/regex.go +++ b/pkg/skaffold/util/regex.go @@ -17,10 +17,11 @@ limitations under the License. package util import ( + "context" re "regexp" "strings" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // RegexEqual matches the string 'actual' against a regex compiled from 'expected' @@ -42,7 +43,7 @@ func regexMatch(expected, actual string) bool { matcher, err := re.Compile(expected) if err != nil { - logrus.Infof("context activation criteria '%s' is not a valid regexp, falling back to string", expected) + log.Entry(context.Background()).Infof("context activation criteria '%s' is not a valid regexp, falling back to string", expected) return false } diff --git a/pkg/skaffold/util/tar.go b/pkg/skaffold/util/tar.go index 0fb8361fd7b..aeec96e32f0 100644 --- a/pkg/skaffold/util/tar.go +++ b/pkg/skaffold/util/tar.go @@ -19,6 +19,7 @@ package util import ( "archive/tar" "compress/gzip" + "context" "fmt" "io" "os" @@ -26,9 +27,8 @@ import ( "runtime" "time" - "github.com/sirupsen/logrus" - "github.com/GoogleContainerTools/skaffold/pkg/skaffold/constants" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) type headerModifier func(*tar.Header) @@ -120,7 +120,7 @@ func addFileToTar(root string, src string, dst string, tw *tar.Writer, hm header } if filepath.IsAbs(target) { - logrus.Warnf("Skipping %s. Only relative symlinks are supported.", src) + log.Entry(context.Background()).Warnf("Skipping %s. Only relative symlinks are supported.", src) return nil } diff --git a/pkg/skaffold/util/util.go b/pkg/skaffold/util/util.go index 791dab73977..d473da337fd 100644 --- a/pkg/skaffold/util/util.go +++ b/pkg/skaffold/util/util.go @@ -19,6 +19,7 @@ package util import ( "bufio" "bytes" + "context" "crypto/rand" "encoding/json" "fmt" @@ -29,8 +30,7 @@ import ( "strings" "time" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/walk" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" ) @@ -114,7 +114,7 @@ func ExpandPathsGlob(workingDir string, paths []string) ([]string, error) { return nil, fmt.Errorf("glob: %w", err) } if len(files) == 0 { - logrus.Warnf("%s did not match any file", p) + log.Entry(context.Background()).Warnf("%s did not match any file", p) } for _, f := range files { diff --git a/pkg/skaffold/util/wrapper_unix.go b/pkg/skaffold/util/wrapper_unix.go index 2a16a0caf7c..3ef91866538 100644 --- a/pkg/skaffold/util/wrapper_unix.go +++ b/pkg/skaffold/util/wrapper_unix.go @@ -22,7 +22,7 @@ import ( "context" "os/exec" - "github.com/sirupsen/logrus" + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" ) // CreateCommand creates an `exec.Cmd` that is configured to call the @@ -33,7 +33,7 @@ func (cw CommandWrapper) CreateCommand(ctx context.Context, workingDir string, a if cw.Wrapper != "" && !SkipWrapperCheck { if wrapperExecutable, err := AbsFile(workingDir, cw.Wrapper); err == nil { - logrus.Debugf("Using wrapper for %s: %s", cw.Wrapper, cw.Executable) + log.Entry(ctx).Debugf("Using wrapper for %s: %s", cw.Wrapper, cw.Executable) executable = wrapperExecutable } } diff --git a/pkg/skaffold/yamltags/tags.go b/pkg/skaffold/yamltags/tags.go index 4283d947bd1..9d7a6c52945 100644 --- a/pkg/skaffold/yamltags/tags.go +++ b/pkg/skaffold/yamltags/tags.go @@ -17,13 +17,13 @@ limitations under the License. package yamltags import ( + "context" "fmt" "reflect" "strings" "unicode" - "github.com/sirupsen/logrus" - + "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" ) @@ -33,7 +33,7 @@ type fieldSet map[string]struct{} func ValidateStruct(s interface{}) error { parentStruct := reflect.Indirect(reflect.ValueOf(s)) t := parentStruct.Type() - logrus.Tracef("validating yamltags of struct %s", t.Name()) + log.Entry(context.Background()).Tracef("validating yamltags of struct %s", t.Name()) // Loop through the fields on the struct, looking for tags. for i := 0; i < t.NumField(); i++ { @@ -64,7 +64,7 @@ func YamlName(field reflect.StructField) string { func GetYamlTag(value interface{}) string { buf, err := yaml.Marshal(value) if err != nil { - logrus.Warnf("error marshaling %-v", value) + log.Entry(context.Background()).Warnf("error marshaling %-v", value) return "" } rawStr := string(buf) @@ -145,7 +145,7 @@ func processTags(yamltags string, val reflect.Value, parentStruct reflect.Value, Field: field, } default: - logrus.Panicf("unknown yaml tag in %s", yamltags) + log.Entry(context.Background()).Panicf("unknown yaml tag in %s", yamltags) } if err := yt.Load(tagParts); err != nil { return err