diff --git a/Makefile b/Makefile index 2999002d0e..6428e763b4 100644 --- a/Makefile +++ b/Makefile @@ -668,6 +668,7 @@ kind-deploy-kyverno: kind-load-all ## Build images, load them in kind cluster an --set image.tag=$(IMAGE_TAG_DEV) \ --set initImage.repository=$(LOCAL_KYVERNOPRE_IMAGE) \ --set initImage.tag=$(IMAGE_TAG_DEV) \ + --set initContainer.extraArgs={--loggingFormat=text} --set "extraArgs={--autogenInternals=true,--loggingFormat=text}" @echo Restart kyverno pods... >&2 @kubectl rollout restart deployment -n kyverno kyverno diff --git a/api/kyverno/v1/utils.go b/api/kyverno/v1/utils.go index 463b7c6fed..e6623f1054 100755 --- a/api/kyverno/v1/utils.go +++ b/api/kyverno/v1/utils.go @@ -1,16 +1,16 @@ package v1 import ( + log "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/util/validation/field" - log "sigs.k8s.io/controller-runtime/pkg/log" ) func FromJSON(in *apiextv1.JSON) apiextensions.JSON { var out apiextensions.JSON if err := apiextv1.Convert_v1_JSON_To_apiextensions_JSON(in, &out, nil); err != nil { - log.Log.Error(err, "failed to convert JSON to interface") + log.Error(err, "failed to convert JSON to interface") } return out } @@ -21,7 +21,7 @@ func ToJSON(in apiextensions.JSON) *apiextv1.JSON { } var out apiextv1.JSON if err := apiextv1.Convert_apiextensions_JSON_To_v1_JSON(&in, &out, nil); err != nil { - log.Log.Error(err, "failed to convert interface to JSON") + log.Error(err, "failed to convert interface to JSON") } return &out } diff --git a/charts/kyverno/Chart.yaml b/charts/kyverno/Chart.yaml index 05670366c5..9355de3e30 100644 --- a/charts/kyverno/Chart.yaml +++ b/charts/kyverno/Chart.yaml @@ -27,9 +27,9 @@ annotations: # valid kinds are: added, changed, deprecated, removed, fixed and security artifacthub.io/changes: | - kind: added - description: Added possibility to define additional init and sidecar container + description: Added possibility to define additional init and sidecar container. - kind: added - description: Added ability to remove namespaces from default resourceFilters list + description: Added ability to remove namespaces from default resourceFilters list. - kind: added description: Prevent installing Kyverno in namespace kube-system. - kind: fixed @@ -38,3 +38,5 @@ annotations: description: Enable autogen internals by default. - kind: fixed description: Self signed certificates not using SANs. + - kind: added + description: Extra args support for init container. diff --git a/charts/kyverno/README.md b/charts/kyverno/README.md index 820bdbce0b..45aedf3963 100644 --- a/charts/kyverno/README.md +++ b/charts/kyverno/README.md @@ -75,6 +75,7 @@ The command removes all the Kubernetes components associated with the chart and | initImage.repository | string | `"ghcr.io/kyverno/kyvernopre"` | Image repository | | initImage.tag | string | `nil` | Image tag If initImage.tag is missing, defaults to image.tag | | initImage.pullPolicy | string | `nil` | Image pull policy If initImage.pullPolicy is missing, defaults to image.pullPolicy | +| initContainer.extraArgs | list | `["--loggingFormat=text"]` | Extra arguments to give to the kyvernopre binary. | | testImage.repository | string | `nil` | Image repository Defaults to `busybox` if omitted | | testImage.tag | string | `nil` | Image tag Defaults to `latest` if omitted | | testImage.pullPolicy | string | `nil` | Image pull policy Defaults to image.pullPolicy if omitted | @@ -96,7 +97,7 @@ The command removes all the Kubernetes components associated with the chart and | dnsPolicy | string | `"ClusterFirst"` | `dnsPolicy` determines the manner in which DNS resolution happens in the cluster. In case of `hostNetwork: true`, usually, the `dnsPolicy` is suitable to be `ClusterFirstWithHostNet`. For further reference: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/#pod-s-dns-policy. | | envVarsInit | object | `{}` | Env variables for initContainers. | | envVars | object | `{}` | Env variables for containers. | -| extraArgs | list | `["--autogenInternals=true"]` | Extra arguments to give to the binary. | +| extraArgs | list | `["--autogenInternals=true","--loggingFormat=text"]` | Extra arguments to give to the binary. | | extraInitContainers | list | `[]` | Array of extra init containers | | extraContainers | list | `[]` | Array of extra containers to run alongside kyverno | | imagePullSecrets | object | `{}` | Image pull secrets for image verify and imageData policies. This will define the `--imagePullSecrets` Kyverno argument. | diff --git a/charts/kyverno/templates/deployment.yaml b/charts/kyverno/templates/deployment.yaml index 854d7c2215..deb50e42f1 100644 --- a/charts/kyverno/templates/deployment.yaml +++ b/charts/kyverno/templates/deployment.yaml @@ -71,6 +71,10 @@ spec: - name: kyverno-pre image: {{ .Values.initImage.repository }}:{{ default .Chart.AppVersion (default .Values.image.tag .Values.initImage.tag) }} imagePullPolicy: {{ default .Values.image.pullPolicy .Values.initImage.pullPolicy }} + {{- if .Values.initContainer.extraArgs }} + args: + {{ tpl (toYaml .Values.initContainer.extraArgs) . }} + {{- end }} {{- with .Values.initResources }} resources: {{ tpl (toYaml .) $ | nindent 12 }} {{- end }} diff --git a/charts/kyverno/values.yaml b/charts/kyverno/values.yaml index 06864cae8c..59515fe7e8 100644 --- a/charts/kyverno/values.yaml +++ b/charts/kyverno/values.yaml @@ -44,6 +44,12 @@ initImage: # If initImage.pullPolicy is missing, defaults to image.pullPolicy pullPolicy: +initContainer: + # -- Extra arguments to give to the kyvernopre binary. + extraArgs: + - --loggingFormat=text + + testImage: # -- Image repository # Defaults to `busybox` if omitted @@ -142,6 +148,7 @@ envVars: {} # -- Extra arguments to give to the binary. extraArgs: - --autogenInternals=true + - --loggingFormat=text # -- Array of extra init containers extraInitContainers: [] diff --git a/cmd/initContainer/main.go b/cmd/initContainer/main.go index 7ca2cded8f..bed1c42982 100644 --- a/cmd/initContainer/main.go +++ b/cmd/initContainer/main.go @@ -7,6 +7,7 @@ import ( "context" "encoding/json" "flag" + "fmt" "os" "os/signal" "sync" @@ -18,6 +19,7 @@ import ( "github.com/kyverno/kyverno/pkg/clients/dclient" "github.com/kyverno/kyverno/pkg/config" "github.com/kyverno/kyverno/pkg/leaderelection" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/tls" "github.com/kyverno/kyverno/pkg/utils" "go.uber.org/multierr" @@ -26,16 +28,14 @@ import ( "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/client-go/kubernetes" - "k8s.io/klog/v2" - "k8s.io/klog/v2/klogr" - "sigs.k8s.io/controller-runtime/pkg/log" ) var ( kubeconfig string - setupLog = log.Log.WithName("setup") + setupLog = logging.WithName("setup") clientRateLimitQPS float64 clientRateLimitBurst int + logFormat string ) const ( @@ -44,23 +44,31 @@ const ( convertGenerateRequest string = "ConvertGenerateRequest" ) -func main() { - // clear flags initialized in static dependencies - if flag.CommandLine.Lookup("log_dir") != nil { - flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) - } - - klog.InitFlags(nil) // add the block above before invoking klog.InitFlags() - log.SetLogger(klogr.New()) +func parseFlags() error { + logging.Init(nil) + flag.StringVar(&logFormat, "loggingFormat", logging.TextFormat, "This determines the output format of the logger.") flag.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") flag.Float64Var(&clientRateLimitQPS, "clientRateLimitQPS", 0, "Configure the maximum QPS to the Kubernetes API server from Kyverno. Uses the client default if zero.") flag.IntVar(&clientRateLimitBurst, "clientRateLimitBurst", 0, "Configure the maximum burst for throttle. Uses the client default if zero.") if err := flag.Set("v", "2"); err != nil { - klog.Fatalf("failed to set log level: %v", err) + return err } flag.Parse() + return nil +} +func main() { + // parse flags + if err := parseFlags(); err != nil { + fmt.Println("failed to parse flags", err) + os.Exit(1) + } + // setup logger + if err := logging.Setup(logFormat); err != nil { + fmt.Println("could not setup logger", err) + os.Exit(1) + } // os signal handler signalCtx, signalCancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer signalCancel() @@ -95,7 +103,7 @@ func main() { } // Exit for unsupported version of kubernetes cluster - if !utils.HigherThanKubernetesVersion(kubeClient.Discovery(), log.Log, 1, 16, 0) { + if !utils.HigherThanKubernetesVersion(kubeClient.Discovery(), logging.GlobalLogger(), 1, 16, 0) { os.Exit(1) } @@ -118,7 +126,7 @@ func main() { name := tls.GenerateRootCASecretName() _, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { - log.Log.V(2).Info("failed to fetch root CA secret", "name", name, "error", err.Error()) + logging.V(2).Info("failed to fetch root CA secret", "name", name, "error", err.Error()) if !errors.IsNotFound(err) { os.Exit(1) } @@ -127,14 +135,14 @@ func main() { name = tls.GenerateTLSPairSecretName() _, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{}) if err != nil { - log.Log.V(2).Info("failed to fetch TLS Pair secret", "name", name, "error", err.Error()) + logging.V(2).Info("failed to fetch TLS Pair secret", "name", name, "error", err.Error()) if !errors.IsNotFound(err) { os.Exit(1) } } if err = acquireLeader(signalCtx, kubeClient); err != nil { - log.Log.V(2).Info("Failed to create lease 'kyvernopre-lock'") + logging.V(2).Info("Failed to create lease 'kyvernopre-lock'") os.Exit(1) } @@ -148,19 +156,19 @@ func main() { for err := range merge(done, stopCh, p1, p2) { if err != nil { failure = true - log.Log.Error(err, "failed to cleanup resource") + logging.Error(err, "failed to cleanup resource") } } // if there is any failure then we fail process if failure { - log.Log.V(2).Info("failed to cleanup prior configurations") + logging.V(2).Info("failed to cleanup prior configurations") os.Exit(1) } os.Exit(0) } - le, err := leaderelection.New("kyvernopre", config.KyvernoNamespace(), kubeClient, config.KyvernoPodName(), run, nil, log.Log.WithName("kyvernopre/LeaderElection")) + le, err := leaderelection.New("kyvernopre", config.KyvernoNamespace(), kubeClient, config.KyvernoPodName(), run, nil, logging.WithName("kyvernopre/LeaderElection")) if err != nil { setupLog.Error(err, "failed to elect a leader") os.Exit(1) @@ -172,9 +180,9 @@ func main() { func acquireLeader(ctx context.Context, kubeClient kubernetes.Interface) error { _, err := kubeClient.CoordinationV1().Leases(config.KyvernoNamespace()).Get(ctx, "kyvernopre-lock", metav1.GetOptions{}) if err != nil { - log.Log.V(2).Info("Lease 'kyvernopre-lock' not found. Starting clean-up...") + logging.V(2).Info("Lease 'kyvernopre-lock' not found. Starting clean-up...") } else { - log.Log.V(2).Info("Leader was elected, quitting") + logging.V(2).Info("Leader was elected, quitting") os.Exit(0) } @@ -231,7 +239,7 @@ func gen(done <-chan struct{}, stopCh <-chan struct{}, requests ...request) <-ch // processes the requests func process(client dclient.Interface, kyvernoclient kyvernoclient.Interface, done <-chan struct{}, stopCh <-chan struct{}, requests <-chan request) <-chan error { - logger := log.Log.WithName("process") + logger := logging.WithName("process") out := make(chan error) go func() { defer close(out) @@ -252,7 +260,7 @@ func process(client dclient.Interface, kyvernoclient kyvernoclient.Interface, do // waits for all processes to be complete and merges result func merge(done <-chan struct{}, stopCh <-chan struct{}, processes ...<-chan error) <-chan error { - logger := log.Log.WithName("merge") + logger := logging.WithName("merge") var wg sync.WaitGroup out := make(chan error) // gets the output from each process @@ -285,7 +293,7 @@ func merge(done <-chan struct{}, stopCh <-chan struct{}, processes ...<-chan err } func convertGR(pclient kyvernoclient.Interface) error { - logger := log.Log.WithName("convertGenerateRequest") + logger := logging.WithName("convertGenerateRequest") var errors []error grs, err := pclient.KyvernoV1().GenerateRequests(config.KyvernoNamespace()).List(context.TODO(), metav1.ListOptions{}) diff --git a/cmd/kyverno/main.go b/cmd/kyverno/main.go index d4acd8611c..487f3655c1 100644 --- a/cmd/kyverno/main.go +++ b/cmd/kyverno/main.go @@ -94,7 +94,7 @@ var ( func parseFlags() error { logging.Init(nil) - flag.StringVar(&logFormat, "loggingFormat", logging.JSONFormat, "This determines the output format of the logger.") + flag.StringVar(&logFormat, "loggingFormat", logging.TextFormat, "This determines the output format of the logger.") flag.IntVar(&webhookTimeout, "webhookTimeout", int(webhookconfig.DefaultWebhookTimeout), "Timeout for webhook configurations.") flag.IntVar(&genWorkers, "genWorkers", 10, "Workers for generate controller.") flag.IntVar(&maxQueuedEvents, "maxQueuedEvents", 1000, "Maximum events to be queued.") diff --git a/pkg/auth/log.go b/pkg/auth/log.go index 41554d4bde..c1c15167f7 100644 --- a/pkg/auth/log.go +++ b/pkg/auth/log.go @@ -1,5 +1,5 @@ package auth -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("auth") +var logger = logging.WithName("auth") diff --git a/pkg/autogen/log.go b/pkg/autogen/log.go index a54b9f9894..cd8547e8e7 100644 --- a/pkg/autogen/log.go +++ b/pkg/autogen/log.go @@ -1,5 +1,5 @@ package autogen -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("autogen") +var logger = logging.WithName("autogen") diff --git a/pkg/background/common/labels.go b/pkg/background/common/labels.go index 577985f2e5..7178689e3a 100644 --- a/pkg/background/common/labels.go +++ b/pkg/background/common/labels.go @@ -7,10 +7,10 @@ import ( kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" pkglabels "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" - "sigs.k8s.io/controller-runtime/pkg/log" ) type Object interface { @@ -76,7 +76,7 @@ func managedBy(labels map[string]string) { val, ok := labels[key] if ok { if val != value { - log.Log.V(2).Info(fmt.Sprintf("resource managed by %s, kyverno wont over-ride the label", val)) + logging.V(2).Info(fmt.Sprintf("resource managed by %s, kyverno wont over-ride the label", val)) return } } @@ -104,7 +104,7 @@ func checkGeneratedBy(labels map[string]string, key, value string) { val, ok := labels[key] if ok { if val != value { - log.Log.V(2).Info(fmt.Sprintf("kyverno wont over-ride the label %s", key)) + logging.V(2).Info(fmt.Sprintf("kyverno wont over-ride the label %s", key)) return } } diff --git a/pkg/background/common/util.go b/pkg/background/common/util.go index 934ae299ba..a186e18c90 100644 --- a/pkg/background/common/util.go +++ b/pkg/background/common/util.go @@ -9,10 +9,10 @@ import ( "github.com/kyverno/kyverno/pkg/client/clientset/versioned" kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1" "github.com/kyverno/kyverno/pkg/config" + "github.com/kyverno/kyverno/pkg/logging" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/util/retry" - "sigs.k8s.io/controller-runtime/pkg/log" ) var DefaultRetry = wait.Backoff{ @@ -27,21 +27,21 @@ func Update(client versioned.Interface, urLister kyvernov1beta1listers.UpdateReq err := retry.RetryOnConflict(DefaultRetry, func() error { ur, err := urLister.Get(name) if err != nil { - log.Log.Error(err, "[ATTEMPT] failed to fetch update request", "name", name) + logging.Error(err, "[ATTEMPT] failed to fetch update request", "name", name) return err } ur = ur.DeepCopy() mutator(ur) _, err = client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Update(context.TODO(), ur, metav1.UpdateOptions{}) if err != nil { - log.Log.Error(err, "[ATTEMPT] failed to update update request", "name", name) + logging.Error(err, "[ATTEMPT] failed to update update request", "name", name) } return err }) if err != nil { - log.Log.Error(err, "failed to update update request", "name", name) + logging.Error(err, "failed to update update request", "name", name) } else { - log.Log.V(3).Info("updated update request", "name", name, "status") + logging.V(3).Info("updated update request", "name", name, "status") } return ur, err } @@ -51,7 +51,7 @@ func UpdateStatus(client versioned.Interface, urLister kyvernov1beta1listers.Upd err := retry.RetryOnConflict(DefaultRetry, func() error { ur, err := urLister.Get(name) if err != nil { - log.Log.Error(err, "[ATTEMPT] failed to fetch update request", "name", name) + logging.Error(err, "[ATTEMPT] failed to fetch update request", "name", name) return err } ur = ur.DeepCopy() @@ -62,15 +62,15 @@ func UpdateStatus(client versioned.Interface, urLister kyvernov1beta1listers.Upd } _, err = client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), ur, metav1.UpdateOptions{}) if err != nil { - log.Log.Error(err, "[ATTEMPT] failed to update update request status", "name", name) + logging.Error(err, "[ATTEMPT] failed to update update request status", "name", name) return err } return err }) if err != nil { - log.Log.Error(err, "failed to update update request status", "name", name) + logging.Error(err, "failed to update update request status", "name", name) } else { - log.Log.V(3).Info("updated update request status", "name", name, "status", string(state)) + logging.V(3).Info("updated update request status", "name", name, "status", string(state)) } return ur, err } diff --git a/pkg/background/generate/validate.go b/pkg/background/generate/validate.go index 8c17a8551f..ace7842375 100644 --- a/pkg/background/generate/validate.go +++ b/pkg/background/generate/validate.go @@ -8,7 +8,7 @@ import ( "github.com/go-logr/logr" "github.com/kyverno/kyverno/pkg/engine/common" "github.com/kyverno/kyverno/pkg/engine/wildcards" - "sigs.k8s.io/controller-runtime/pkg/log" + "github.com/kyverno/kyverno/pkg/logging" ) type Handler struct { @@ -147,7 +147,7 @@ func (dh Handler) Handle(handler resourceElementHandler, resourceMap map[string] } else if dh.pattern == "*" && resourceMap[dh.element] == nil { return dh.path, fmt.Errorf("failed at path %s, field %s is not present", dh.path, dh.element) } else { - path, err := handler(log.Log, resourceMap[dh.element], dh.pattern, originPattern, currentPath) + path, err := handler(logging.GlobalLogger(), resourceMap[dh.element], dh.pattern, originPattern, currentPath) if err != nil { return path, err } diff --git a/pkg/background/log.go b/pkg/background/log.go index c8d0aa7c8e..8f6123be29 100644 --- a/pkg/background/log.go +++ b/pkg/background/log.go @@ -1,5 +1,5 @@ package background -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("background") +var logger = logging.WithName("background") diff --git a/pkg/clients/dclient/log.go b/pkg/clients/dclient/log.go index fe393ee0a2..c896edb2f1 100644 --- a/pkg/clients/dclient/log.go +++ b/pkg/clients/dclient/log.go @@ -1,5 +1,5 @@ package dclient -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("dynamic-client") +var logger = logging.WithName("dynamic-client") diff --git a/pkg/common/common.go b/pkg/common/common.go index de9b78c0f0..7cbbcc9ca7 100644 --- a/pkg/common/common.go +++ b/pkg/common/common.go @@ -11,11 +11,11 @@ import ( kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1" "github.com/kyverno/kyverno/pkg/clients/dclient" enginutils "github.com/kyverno/kyverno/pkg/engine/utils" + "github.com/kyverno/kyverno/pkg/logging" "github.com/pkg/errors" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" corev1listers "k8s.io/client-go/listers/core/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) // Policy Reporting Types @@ -30,7 +30,7 @@ func GetNamespaceSelectorsFromNamespaceLister(kind, namespaceOfResource string, if kind != "Namespace" && namespaceOfResource != "" { namespaceObj, err := nsLister.Get(namespaceOfResource) if err != nil { - log.Log.Error(err, "failed to get the namespace", "name", namespaceOfResource) + logging.Error(err, "failed to get the namespace", "name", namespaceOfResource) return namespaceLabels } return GetNamespaceLabels(namespaceObj, logger) diff --git a/pkg/config/log.go b/pkg/config/log.go index 49b5ef4023..80263512f8 100644 --- a/pkg/config/log.go +++ b/pkg/config/log.go @@ -1,5 +1,5 @@ package config -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("config") +var logger = logging.WithName("config") diff --git a/pkg/controllers/certmanager/log.go b/pkg/controllers/certmanager/log.go index 1da0b3c01b..4be16f33b5 100644 --- a/pkg/controllers/certmanager/log.go +++ b/pkg/controllers/certmanager/log.go @@ -1,7 +1,7 @@ package certmanager -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "certmanager-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/config/log.go b/pkg/controllers/config/log.go index 55704b0dbf..78f93ce253 100644 --- a/pkg/controllers/config/log.go +++ b/pkg/controllers/config/log.go @@ -1,7 +1,7 @@ package config -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "config-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/policycache/log.go b/pkg/controllers/policycache/log.go index 99aea21b9e..6d24c6af96 100644 --- a/pkg/controllers/policycache/log.go +++ b/pkg/controllers/policycache/log.go @@ -1,7 +1,7 @@ package policycache -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "policycache-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/report/admission/log.go b/pkg/controllers/report/admission/log.go index ffd74d7f3b..9fb48c80f6 100644 --- a/pkg/controllers/report/admission/log.go +++ b/pkg/controllers/report/admission/log.go @@ -1,7 +1,7 @@ package admission -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "admission-report-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/report/aggregate/log.go b/pkg/controllers/report/aggregate/log.go index 4ad9579563..83df571f92 100644 --- a/pkg/controllers/report/aggregate/log.go +++ b/pkg/controllers/report/aggregate/log.go @@ -1,7 +1,7 @@ package aggregate -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "aggregate-report-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/report/background/log.go b/pkg/controllers/report/background/log.go index 69958b523a..02cbd726a6 100644 --- a/pkg/controllers/report/background/log.go +++ b/pkg/controllers/report/background/log.go @@ -1,7 +1,7 @@ package background -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "background-scan-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/controllers/report/resource/log.go b/pkg/controllers/report/resource/log.go index 818ff65701..b1009b3edc 100644 --- a/pkg/controllers/report/resource/log.go +++ b/pkg/controllers/report/resource/log.go @@ -1,7 +1,7 @@ package resource -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" const controllerName = "resource-report-controller" -var logger = log.Log.WithName(controllerName) +var logger = logging.WithName(controllerName) diff --git a/pkg/cosign/log.go b/pkg/cosign/log.go index 5fd5a6ac4a..688e4eefe9 100644 --- a/pkg/cosign/log.go +++ b/pkg/cosign/log.go @@ -1,5 +1,5 @@ package cosign -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("cosign") +var logger = logging.WithName("cosign") diff --git a/pkg/engine/anchor/anchor.go b/pkg/engine/anchor/anchor.go index fe53715004..95d1f9d15a 100644 --- a/pkg/engine/anchor/anchor.go +++ b/pkg/engine/anchor/anchor.go @@ -5,7 +5,7 @@ import ( "strconv" "github.com/go-logr/logr" - "sigs.k8s.io/controller-runtime/pkg/log" + "github.com/kyverno/kyverno/pkg/logging" ) // ValidationHandler for element processes @@ -86,7 +86,7 @@ func (eh EqualityHandler) Handle(handler resourceElementHandler, resourceMap map // check if anchor is present in resource if value, ok := resourceMap[anchorKey]; ok { // validate the values of the pattern - returnPath, err := handler(log.Log, value, eh.pattern, originPattern, currentPath, ac) + returnPath, err := handler(logging.GlobalLogger(), value, eh.pattern, originPattern, currentPath, ac) if err != nil { return returnPath, err } @@ -119,7 +119,7 @@ func (dh DefaultHandler) Handle(handler resourceElementHandler, resourceMap map[ } else if dh.pattern == "*" && resourceMap[dh.element] == nil { return dh.path, fmt.Errorf("%s/%s not found", dh.path, dh.element) } else { - path, err := handler(log.Log, resourceMap[dh.element], dh.pattern, originPattern, currentPath, ac) + path, err := handler(logging.GlobalLogger(), resourceMap[dh.element], dh.pattern, originPattern, currentPath, ac) if err != nil { return path, err } @@ -150,7 +150,7 @@ func (ch ConditionAnchorHandler) Handle(handler resourceElementHandler, resource // check if anchor is present in resource if value, ok := resourceMap[anchorKey]; ok { // validate the values of the pattern - returnPath, err := handler(log.Log, value, ch.pattern, originPattern, currentPath, ac) + returnPath, err := handler(logging.GlobalLogger(), value, ch.pattern, originPattern, currentPath, ac) if err != nil { ac.AnchorError = NewConditionalAnchorError(err.Error()) return returnPath, ac.AnchorError.Error() @@ -185,7 +185,7 @@ func (gh GlobalAnchorHandler) Handle(handler resourceElementHandler, resourceMap // check if anchor is present in resource if value, ok := resourceMap[anchorKey]; ok { // validate the values of the pattern - returnPath, err := handler(log.Log, value, gh.pattern, originPattern, currentPath, ac) + returnPath, err := handler(logging.GlobalLogger(), value, gh.pattern, originPattern, currentPath, ac) if err != nil { ac.AnchorError = NewGlobalAnchorError(err.Error()) return returnPath, ac.AnchorError.Error() @@ -251,7 +251,7 @@ func validateExistenceListResource(handler resourceElementHandler, resourceList // if non satisfy then throw an error for i, resourceElement := range resourceList { currentPath := path + strconv.Itoa(i) + "/" - _, err := handler(log.Log, resourceElement, patternMap, originPattern, currentPath, ac) + _, err := handler(logging.GlobalLogger(), resourceElement, patternMap, originPattern, currentPath, ac) if err == nil { // condition is satisfied, dont check further return "", nil diff --git a/pkg/engine/attestation_test.go b/pkg/engine/attestation_test.go index 558d5efb38..0da75b2a5e 100644 --- a/pkg/engine/attestation_test.go +++ b/pkg/engine/attestation_test.go @@ -6,11 +6,11 @@ import ( v1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/engine/context" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/utils/api" "github.com/kyverno/kyverno/pkg/utils/image" "gotest.tools/assert" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) var scanPredicate = ` @@ -258,7 +258,7 @@ func Test_Conditions(t *testing.T) { err := json.Unmarshal([]byte(scanPredicate), &dataMap) assert.NilError(t, err) - pass, err := evaluateConditions(conditions, ctx, dataMap, log.Log) + pass, err := evaluateConditions(conditions, ctx, dataMap, logging.GlobalLogger()) assert.NilError(t, err) assert.Equal(t, pass, true) } diff --git a/pkg/engine/background.go b/pkg/engine/background.go index 152d2bf493..d1bde7fd96 100644 --- a/pkg/engine/background.go +++ b/pkg/engine/background.go @@ -8,7 +8,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/common" "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/variables" - "sigs.k8s.io/controller-runtime/pkg/log" + "github.com/kyverno/kyverno/pkg/logging" ) // ApplyBackgroundChecks checks for validity of generate and mutateExisting rules on the resource @@ -45,7 +45,7 @@ func filterRules(policyContext *PolicyContext, startTime time.Time) *response.En } if policyContext.ExcludeResourceFunc(kind, namespace, name) { - log.Log.WithName("ApplyBackgroundChecks").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name) + logging.WithName("ApplyBackgroundChecks").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name) return resp } @@ -83,7 +83,7 @@ func filterRule(rule kyvernov1.Rule, policyContext *PolicyContext) *response.Rul excludeGroupRole := policyContext.ExcludeGroupRole namespaceLabels := policyContext.NamespaceLabels - logger := log.Log.WithName(string(ruleType)).WithValues("policy", policy.GetName(), + logger := logging.WithName(string(ruleType)).WithValues("policy", policy.GetName(), "kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName()) if err = MatchesResourceDescription(newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err != nil { diff --git a/pkg/engine/common/pattern_test.go b/pkg/engine/common/pattern_test.go index 9fcead14c7..a85986b835 100644 --- a/pkg/engine/common/pattern_test.go +++ b/pkg/engine/common/pattern_test.go @@ -5,15 +5,15 @@ import ( "testing" "github.com/kyverno/kyverno/pkg/engine/operator" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func TestValidateValueWithPattern_Bool(t *testing.T) { - assert.Assert(t, ValidateValueWithPattern(log.Log, true, true)) - assert.Assert(t, !ValidateValueWithPattern(log.Log, true, false)) - assert.Assert(t, !ValidateValueWithPattern(log.Log, false, true)) - assert.Assert(t, ValidateValueWithPattern(log.Log, false, false)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), true, true)) + assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), true, false)) + assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), false, true)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), false, false)) } func TestValidateString_AsteriskTest(t *testing.T) { @@ -21,8 +21,8 @@ func TestValidateString_AsteriskTest(t *testing.T) { value := "anything" empty := "" - assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) - assert.Assert(t, validateString(log.Log, empty, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), empty, pattern, operator.Equal)) } func TestValidateString_LeftAsteriskTest(t *testing.T) { @@ -30,32 +30,32 @@ func TestValidateString_LeftAsteriskTest(t *testing.T) { value := "leftright" right := "right" - assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) - assert.Assert(t, validateString(log.Log, right, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), right, pattern, operator.Equal)) value = "leftmiddle" middle := "middle" - assert.Assert(t, !validateString(log.Log, value, pattern, operator.Equal)) - assert.Assert(t, !validateString(log.Log, middle, pattern, operator.Equal)) + assert.Assert(t, !validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) + assert.Assert(t, !validateString(logging.GlobalLogger(), middle, pattern, operator.Equal)) } func TestValidateString_MiddleAsteriskTest(t *testing.T) { pattern := "ab*ba" value := "abbeba" - assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) value = "abbca" - assert.Assert(t, !validateString(log.Log, value, pattern, operator.Equal)) + assert.Assert(t, !validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) } func TestValidateString_QuestionMark(t *testing.T) { pattern := "ab?ba" value := "abbba" - assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) + assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) value = "abbbba" - assert.Assert(t, !validateString(log.Log, value, pattern, operator.Equal)) + assert.Assert(t, !validateString(logging.GlobalLogger(), value, pattern, operator.Equal)) } func TestValidateValueWithPattern_BoolInJson(t *testing.T) { @@ -77,7 +77,7 @@ func TestValidateValueWithPattern_BoolInJson(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_NullPatternStringValue(t *testing.T) { @@ -99,7 +99,7 @@ func TestValidateValueWithPattern_NullPatternStringValue(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, !ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_NullPatternDefaultString(t *testing.T) { @@ -121,7 +121,7 @@ func TestValidateValueWithPattern_NullPatternDefaultString(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_NullPatternDefaultFloat(t *testing.T) { @@ -143,7 +143,7 @@ func TestValidateValueWithPattern_NullPatternDefaultFloat(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_NullPatternDefaultInt(t *testing.T) { @@ -165,7 +165,7 @@ func TestValidateValueWithPattern_NullPatternDefaultInt(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_NullPatternDefaultBool(t *testing.T) { @@ -187,93 +187,93 @@ func TestValidateValueWithPattern_NullPatternDefaultBool(t *testing.T) { err = json.Unmarshal(rawValue, &value) assert.Assert(t, err) - assert.Assert(t, ValidateValueWithPattern(log.Log, value["key"], pattern["key"])) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value["key"], pattern["key"])) } func TestValidateValueWithPattern_StringsLogicalOr(t *testing.T) { pattern := "192.168.88.1 | 10.100.11.*" value := "10.100.11.54" - assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern)) } func TestValidateValueWithPattern_StringsLogicalAnd(t *testing.T) { pattern := ">1 & <20" value := "10" - assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern)) } func TestValidateValueWithPattern_StringsAllLogicalOperators(t *testing.T) { pattern := ">1 & <20 | >31 & <33" value := "10" - assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern)) value = "32" - assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern)) value = "21" - assert.Assert(t, !ValidateValueWithPattern(log.Log, value, pattern)) + assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), value, pattern)) } func TestValidateValueWithPattern_EqualTwoFloats(t *testing.T) { - assert.Assert(t, ValidateValueWithPattern(log.Log, 7.0, 7.000)) + assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), 7.0, 7.000)) } func TestValidateValueWithNilPattern_NullPatternStringValue(t *testing.T) { - assert.Assert(t, !validateValueWithNilPattern(log.Log, "value")) + assert.Assert(t, !validateValueWithNilPattern(logging.GlobalLogger(), "value")) } func TestValidateValueWithNilPattern_NullPatternDefaultString(t *testing.T) { - assert.Assert(t, validateValueWithNilPattern(log.Log, "")) + assert.Assert(t, validateValueWithNilPattern(logging.GlobalLogger(), "")) } func TestValidateValueWithNilPattern_NullPatternDefaultFloat(t *testing.T) { - assert.Assert(t, validateValueWithNilPattern(log.Log, 0.0)) + assert.Assert(t, validateValueWithNilPattern(logging.GlobalLogger(), 0.0)) } func TestValidateValueWithNilPattern_NullPatternFloat(t *testing.T) { - assert.Assert(t, !validateValueWithNilPattern(log.Log, 0.1)) + assert.Assert(t, !validateValueWithNilPattern(logging.GlobalLogger(), 0.1)) } func TestValidateValueWithNilPattern_NullPatternDefaultInt(t *testing.T) { - assert.Assert(t, validateValueWithNilPattern(log.Log, 0)) + assert.Assert(t, validateValueWithNilPattern(logging.GlobalLogger(), 0)) } func TestValidateValueWithNilPattern_NullPatternInt(t *testing.T) { - assert.Assert(t, !validateValueWithNilPattern(log.Log, 1)) + assert.Assert(t, !validateValueWithNilPattern(logging.GlobalLogger(), 1)) } func TestValidateValueWithNilPattern_NullPatternDefaultBool(t *testing.T) { - assert.Assert(t, validateValueWithNilPattern(log.Log, false)) + assert.Assert(t, validateValueWithNilPattern(logging.GlobalLogger(), false)) } func TestValidateValueWithNilPattern_NullPatternTrueBool(t *testing.T) { - assert.Assert(t, !validateValueWithNilPattern(log.Log, true)) + assert.Assert(t, !validateValueWithNilPattern(logging.GlobalLogger(), true)) } func TestValidateValueWithFloatPattern_FloatValue(t *testing.T) { - assert.Assert(t, validateValueWithFloatPattern(log.Log, 7.9914, 7.9914)) + assert.Assert(t, validateValueWithFloatPattern(logging.GlobalLogger(), 7.9914, 7.9914)) } func TestValidateValueWithFloatPattern_FloatValueNotPass(t *testing.T) { - assert.Assert(t, !validateValueWithFloatPattern(log.Log, 7.9914, 7.99141)) + assert.Assert(t, !validateValueWithFloatPattern(logging.GlobalLogger(), 7.9914, 7.99141)) } func TestValidateValueWithFloatPattern_FloatPatternWithoutFractionIntValue(t *testing.T) { - assert.Assert(t, validateValueWithFloatPattern(log.Log, 7, 7.000000)) + assert.Assert(t, validateValueWithFloatPattern(logging.GlobalLogger(), 7, 7.000000)) } func TestValidateValueWithFloatPattern_FloatPatternWithoutFraction(t *testing.T) { - assert.Assert(t, validateValueWithFloatPattern(log.Log, 7.000000, 7.000000)) + assert.Assert(t, validateValueWithFloatPattern(logging.GlobalLogger(), 7.000000, 7.000000)) } func TestValidateValueWithIntPattern_FloatValueWithoutFraction(t *testing.T) { - assert.Assert(t, validateValueWithFloatPattern(log.Log, 7.000000, 7)) + assert.Assert(t, validateValueWithFloatPattern(logging.GlobalLogger(), 7.000000, 7)) } func TestValidateValueWithIntPattern_FloatValueWitFraction(t *testing.T) { - assert.Assert(t, !validateValueWithFloatPattern(log.Log, 7.000001, 7)) + assert.Assert(t, !validateValueWithFloatPattern(logging.GlobalLogger(), 7.000001, 7)) } func TestValidateValueWithIntPattern_NotPass(t *testing.T) { - assert.Assert(t, !validateValueWithFloatPattern(log.Log, 8, 7)) + assert.Assert(t, !validateValueWithFloatPattern(logging.GlobalLogger(), 8, 7)) } func TestGetNumberAndStringPartsFromPattern_NumberAndString(t *testing.T) { @@ -307,75 +307,75 @@ func TestGetNumberAndStringPartsFromPattern_Empty(t *testing.T) { } func TestValidateValueWithStringPattern_WithSpace(t *testing.T) { - assert.Assert(t, validateValueWithStringPattern(log.Log, 4, ">= 3")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 4, ">= 3")) } func TestValidateValueWithStringPattern_Ranges(t *testing.T) { - assert.Assert(t, validateValueWithStringPattern(log.Log, 0, "0-2")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 1, "0-2")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2, "0-2")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 3, "0-2")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 0, "0-2")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 1, "0-2")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2, "0-2")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 3, "0-2")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 0, "10!-20")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 15, "10!-20")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 25, "10!-20")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 0, "10!-20")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 15, "10!-20")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 25, "10!-20")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 0, "0.00001-2.00001")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 1, "0.00001-2.00001")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2, "0.00001-2.00001")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 2.0001, "0.00001-2.00001")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 0, "0.00001-2.00001")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 1, "0.00001-2.00001")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2, "0.00001-2.00001")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 2.0001, "0.00001-2.00001")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 0, "0.00001!-2.00001")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 1, "0.00001!-2.00001")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 2, "0.00001!-2.00001")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2.0001, "0.00001!-2.00001")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 0, "0.00001!-2.00001")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 1, "0.00001!-2.00001")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 2, "0.00001!-2.00001")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2.0001, "0.00001!-2.00001")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2, "2-2")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, 2, "2!-2")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2, "2-2")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 2, "2!-2")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2.99999, "2.99998-3")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 2.99997, "2.99998!-3")) - assert.Assert(t, validateValueWithStringPattern(log.Log, 3.00001, "2.99998!-3")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2.99999, "2.99998-3")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2.99997, "2.99998!-3")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 3.00001, "2.99998!-3")) - assert.Assert(t, validateValueWithStringPattern(log.Log, "256Mi", "128Mi-512Mi")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, "1024Mi", "128Mi-512Mi")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, "64Mi", "128Mi-512Mi")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "256Mi", "128Mi-512Mi")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "1024Mi", "128Mi-512Mi")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "64Mi", "128Mi-512Mi")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, "256Mi", "128Mi!-512Mi")) - assert.Assert(t, validateValueWithStringPattern(log.Log, "1024Mi", "128Mi!-512Mi")) - assert.Assert(t, validateValueWithStringPattern(log.Log, "64Mi", "128Mi!-512Mi")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "256Mi", "128Mi!-512Mi")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "1024Mi", "128Mi!-512Mi")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "64Mi", "128Mi!-512Mi")) } func TestValidateNumberWithStr_LessFloatAndInt(t *testing.T) { - assert.Assert(t, validateNumberWithStr(log.Log, 7.00001, "7.000001", operator.More)) - assert.Assert(t, validateNumberWithStr(log.Log, 7.00001, "7", operator.NotEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 7.00001, "7.000001", operator.More)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 7.00001, "7", operator.NotEqual)) - assert.Assert(t, validateNumberWithStr(log.Log, 7.0000, "7", operator.Equal)) - assert.Assert(t, !validateNumberWithStr(log.Log, 6.000000001, "6", operator.Less)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 7.0000, "7", operator.Equal)) + assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), 6.000000001, "6", operator.Less)) } func TestValidateQuantity_InvalidQuantity(t *testing.T) { - assert.Assert(t, !validateNumberWithStr(log.Log, "1024Gi", "", operator.Equal)) - assert.Assert(t, !validateNumberWithStr(log.Log, "gii", "1024Gi", operator.Equal)) + assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "1024Gi", "", operator.Equal)) + assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "gii", "1024Gi", operator.Equal)) } func TestValidateQuantity_Equal(t *testing.T) { - assert.Assert(t, validateNumberWithStr(log.Log, "1024Gi", "1024Gi", operator.Equal)) - assert.Assert(t, validateNumberWithStr(log.Log, "1024Mi", "1Gi", operator.Equal)) - assert.Assert(t, validateNumberWithStr(log.Log, "0.2", "200m", operator.Equal)) - assert.Assert(t, validateNumberWithStr(log.Log, "500", "500", operator.Equal)) - assert.Assert(t, !validateNumberWithStr(log.Log, "2048", "1024", operator.Equal)) - assert.Assert(t, validateNumberWithStr(log.Log, 1024, "1024", operator.Equal)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1024Gi", "1024Gi", operator.Equal)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1024Mi", "1Gi", operator.Equal)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", "200m", operator.Equal)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "500", "500", operator.Equal)) + assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "2048", "1024", operator.Equal)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 1024, "1024", operator.Equal)) } func TestValidateQuantity_Operation(t *testing.T) { - assert.Assert(t, validateNumberWithStr(log.Log, "1Gi", "1000Mi", operator.More)) - assert.Assert(t, validateNumberWithStr(log.Log, "1G", "1Gi", operator.Less)) - assert.Assert(t, validateNumberWithStr(log.Log, "500m", "0.5", operator.MoreEqual)) - assert.Assert(t, validateNumberWithStr(log.Log, "1", "500m", operator.MoreEqual)) - assert.Assert(t, validateNumberWithStr(log.Log, "0.5", ".5", operator.LessEqual)) - assert.Assert(t, validateNumberWithStr(log.Log, "0.2", ".5", operator.LessEqual)) - assert.Assert(t, validateNumberWithStr(log.Log, "0.2", ".5", operator.NotEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1Gi", "1000Mi", operator.More)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1G", "1Gi", operator.Less)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "500m", "0.5", operator.MoreEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1", "500m", operator.MoreEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.5", ".5", operator.LessEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", ".5", operator.LessEqual)) + assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", ".5", operator.NotEqual)) } func TestGetOperatorFromStringPattern_OneChar(t *testing.T) { @@ -387,9 +387,9 @@ func TestGetOperatorFromStringPattern_EmptyString(t *testing.T) { } func TestValidateKernelVersion_NotEquals(t *testing.T) { - assert.Assert(t, validateValueWithStringPattern(log.Log, "5.16.5-arch1-1", "!5.10.84-1")) - assert.Assert(t, !validateValueWithStringPattern(log.Log, "5.10.84-1", "!5.10.84-1")) - assert.Assert(t, validateValueWithStringPatterns(log.Log, "5.16.5-arch1-1", "!5.10.84-1 & !5.15.2-1")) - assert.Assert(t, !validateValueWithStringPatterns(log.Log, "5.10.84-1", "!5.10.84-1 & !5.15.2-1")) - assert.Assert(t, !validateValueWithStringPatterns(log.Log, "5.15.2-1", "!5.10.84-1 & !5.15.2-1")) + assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "5.16.5-arch1-1", "!5.10.84-1")) + assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "5.10.84-1", "!5.10.84-1")) + assert.Assert(t, validateValueWithStringPatterns(logging.GlobalLogger(), "5.16.5-arch1-1", "!5.10.84-1 & !5.15.2-1")) + assert.Assert(t, !validateValueWithStringPatterns(logging.GlobalLogger(), "5.10.84-1", "!5.10.84-1 & !5.15.2-1")) + assert.Assert(t, !validateValueWithStringPatterns(logging.GlobalLogger(), "5.15.2-1", "!5.10.84-1 & !5.15.2-1")) } diff --git a/pkg/engine/context/context.go b/pkg/engine/context/context.go index 2cfbe3cbaa..2291dc369b 100644 --- a/pkg/engine/context/context.go +++ b/pkg/engine/context/context.go @@ -8,14 +8,14 @@ import ( jsonpatch "github.com/evanphx/json-patch/v5" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" + "github.com/kyverno/kyverno/pkg/logging" apiutils "github.com/kyverno/kyverno/pkg/utils/api" "github.com/pkg/errors" admissionv1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) -var logger = log.Log.WithName("context") +var logger = logging.WithName("context") // EvalInterface is used to query and inspect context data type EvalInterface interface { @@ -262,7 +262,7 @@ func (ctx *context) AddImageInfos(resource *unstructured.Unstructured) error { } ctx.images = images - log.Log.V(4).Info("updated image info", "images", images) + logging.V(4).Info("updated image info", "images", images) return addToContext(ctx, images, "images") } diff --git a/pkg/engine/forceMutate.go b/pkg/engine/forceMutate.go index 1cd1270511..a8f8f1019d 100644 --- a/pkg/engine/forceMutate.go +++ b/pkg/engine/forceMutate.go @@ -8,14 +8,14 @@ import ( "github.com/kyverno/kyverno/pkg/engine/mutate" "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/variables" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) // ForceMutate does not check any conditions, it simply mutates the given resource // It is used to validate mutation logic, and for tests. func ForceMutate(ctx context.Interface, policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) { - logger := log.Log.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(), + logger := logging.WithName("EngineForceMutate").WithValues("policy", policy.GetName(), "kind", resource.GetKind(), "namespace", resource.GetNamespace(), "name", resource.GetName()) patchedResource := resource diff --git a/pkg/engine/generation.go b/pkg/engine/generation.go index 63bec27bcd..c13fe0f8b9 100644 --- a/pkg/engine/generation.go +++ b/pkg/engine/generation.go @@ -6,8 +6,8 @@ import ( kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" "github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/engine/response" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/client-go/tools/cache" - "sigs.k8s.io/controller-runtime/pkg/log" ) // GenerateResponse checks for validity of generate rule on the resource @@ -23,7 +23,7 @@ func filterGenerateRules(policyContext *PolicyContext, policyNameKey string, sta apiVersion := policyContext.NewResource.GetAPIVersion() pNamespace, pName, err := cache.SplitMetaNamespaceKey(policyNameKey) if err != nil { - log.Log.Error(err, "failed to spilt name and namespace", policyNameKey) + logging.Error(err, "failed to spilt name and namespace", policyNameKey) } resp := &response.EngineResponse{ @@ -45,7 +45,7 @@ func filterGenerateRules(policyContext *PolicyContext, policyNameKey string, sta } if policyContext.ExcludeResourceFunc(kind, namespace, name) { - log.Log.WithName("Generate").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name) + logging.WithName("Generate").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name) return resp } diff --git a/pkg/engine/imageVerify.go b/pkg/engine/imageVerify.go index e4d54f5b64..d57d86d98e 100644 --- a/pkg/engine/imageVerify.go +++ b/pkg/engine/imageVerify.go @@ -16,13 +16,13 @@ import ( "github.com/kyverno/kyverno/pkg/engine/response" engineUtils "github.com/kyverno/kyverno/pkg/engine/utils" "github.com/kyverno/kyverno/pkg/engine/variables" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/registryclient" apiutils "github.com/kyverno/kyverno/pkg/utils/api" "github.com/kyverno/kyverno/pkg/utils/wildcard" "github.com/pkg/errors" "go.uber.org/multierr" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineResponse, *ImageVerificationMetadata) { @@ -31,7 +31,7 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineRespons policy := policyContext.Policy patchedResource := policyContext.NewResource - logger := log.Log.WithName("EngineVerifyImages").WithValues("policy", policy.GetName(), + logger := logging.WithName("EngineVerifyImages").WithValues("policy", policy.GetName(), "kind", patchedResource.GetKind(), "namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName()) startTime := time.Now() diff --git a/pkg/engine/imageVerify_test.go b/pkg/engine/imageVerify_test.go index 1c5ebe7b90..4682cd8c7b 100644 --- a/pkg/engine/imageVerify_test.go +++ b/pkg/engine/imageVerify_test.go @@ -6,8 +6,8 @@ import ( "strings" "testing" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" kyverno "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/cosign" @@ -564,18 +564,18 @@ func Test_ChangedAnnotation(t *testing.T) { policyContext := buildContext(t, testPolicyGood, testResource, testResource) - hasChanged := hasImageVerifiedAnnotationChanged(policyContext, log.Log) + hasChanged := hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger()) assert.Equal(t, hasChanged, false) policyContext = buildContext(t, testPolicyGood, newResource, testResource) - hasChanged = hasImageVerifiedAnnotationChanged(policyContext, log.Log) + hasChanged = hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger()) assert.Equal(t, hasChanged, true) annotationOld := fmt.Sprintf("\"annotations\": {\"%s\": \"%s\"}", annotationKey, "false") oldResource := strings.ReplaceAll(testResource, "\"annotations\": {}", annotationOld) policyContext = buildContext(t, testPolicyGood, newResource, oldResource) - hasChanged = hasImageVerifiedAnnotationChanged(policyContext, log.Log) + hasChanged = hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger()) assert.Equal(t, hasChanged, true) } @@ -596,7 +596,7 @@ func Test_MarkImageVerified(t *testing.T) { assert.Equal(t, len(verifiedImages.Data), 1) assert.Equal(t, verifiedImages.isVerified(image), true) - patches, err := verifiedImages.Patches(false, log.Log) + patches, err := verifiedImages.Patches(false, logging.GlobalLogger()) assert.NilError(t, err) assert.Equal(t, len(patches), 2) @@ -607,7 +607,7 @@ func Test_MarkImageVerified(t *testing.T) { json := patchedAnnotations[imageVerifyAnnotationKey] assert.Assert(t, json != "") - verified, err := isImageVerified(resource, image, log.Log) + verified, err := isImageVerified(resource, image, logging.GlobalLogger()) assert.NilError(t, err) assert.Equal(t, verified, true) } diff --git a/pkg/engine/mutate/mutation_test.go b/pkg/engine/mutate/mutation_test.go index 6832b1a6e2..ff55835325 100644 --- a/pkg/engine/mutate/mutation_test.go +++ b/pkg/engine/mutate/mutation_test.go @@ -10,9 +10,9 @@ import ( types "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/engine/response" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" "github.com/kyverno/kyverno/pkg/engine/utils" ) @@ -50,7 +50,7 @@ const endpointsDocument string = `{ }` func applyPatches(rule *types.Rule, resource unstructured.Unstructured) (*response.RuleResponse, unstructured.Unstructured) { - mutateResp := Mutate(rule, context.NewContext(), resource, log.Log) + mutateResp := Mutate(rule, context.NewContext(), resource, logging.GlobalLogger()) if mutateResp.Status != response.RuleStatusPass { return &response.RuleResponse{ diff --git a/pkg/engine/mutate/patch/patchJSON6902_test.go b/pkg/engine/mutate/patch/patchJSON6902_test.go index b1b2c6e314..c8fb4f563b 100644 --- a/pkg/engine/mutate/patch/patchJSON6902_test.go +++ b/pkg/engine/mutate/patch/patchJSON6902_test.go @@ -7,9 +7,9 @@ import ( "github.com/kyverno/kyverno/pkg/engine/response" "github.com/ghodss/yaml" + "github.com/kyverno/kyverno/pkg/logging" assert "github.com/stretchr/testify/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) var inputBytes = []byte(` @@ -51,7 +51,7 @@ func TestTypeConversion(t *testing.T) { jsonPatches, err := yaml.YAMLToJSON(patchesJSON6902) assert.Nil(t, err) // apply patches - resp, _ := ProcessPatchJSON6902("type-conversion", jsonPatches, resource, log.Log) + resp, _ := ProcessPatchJSON6902("type-conversion", jsonPatches, resource, logging.GlobalLogger()) if !assert.Equal(t, response.RuleStatusPass, resp.Status) { t.Fatal(resp.Message) } diff --git a/pkg/engine/mutate/patch/patchesUtils_test.go b/pkg/engine/mutate/patch/patchesUtils_test.go index 56e25bab7e..f65e41db4d 100644 --- a/pkg/engine/mutate/patch/patchesUtils_test.go +++ b/pkg/engine/mutate/patch/patchesUtils_test.go @@ -4,15 +4,15 @@ import ( "fmt" "testing" + "github.com/kyverno/kyverno/pkg/logging" "github.com/mattbaird/jsonpatch" assertnew "github.com/stretchr/testify/assert" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func Test_GeneratePatches(t *testing.T) { - out, err := strategicMergePatch(log.Log, string(baseBytes), string(overlayBytes)) + out, err := strategicMergePatch(logging.GlobalLogger(), string(baseBytes), string(overlayBytes)) assert.NilError(t, err) expectedPatches := map[string]bool{ diff --git a/pkg/engine/mutate/patch/strategicMergePatch_test.go b/pkg/engine/mutate/patch/strategicMergePatch_test.go index 55d0cd7328..42b2519f71 100644 --- a/pkg/engine/mutate/patch/strategicMergePatch_test.go +++ b/pkg/engine/mutate/patch/strategicMergePatch_test.go @@ -6,10 +6,10 @@ import ( kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/autogen" + "github.com/kyverno/kyverno/pkg/logging" assertnew "github.com/stretchr/testify/assert" "gotest.tools/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) func TestMergePatch(t *testing.T) { @@ -163,7 +163,7 @@ func TestMergePatch(t *testing.T) { for i, test := range testCases { t.Logf("Running test %d...", i+1) - out, err := strategicMergePatch(log.Log, string(test.rawResource), string(test.rawPolicy)) + out, err := strategicMergePatch(logging.GlobalLogger(), string(test.rawResource), string(test.rawPolicy)) assert.NilError(t, err) assert.DeepEqual(t, toJSON(t, test.expected), toJSON(t, out)) } @@ -247,7 +247,7 @@ func Test_PolicyDeserilize(t *testing.T) { patchString, err := json.Marshal(overlayPatches) assert.NilError(t, err) - out, err := strategicMergePatch(log.Log, string(baseBytes), string(patchString)) + out, err := strategicMergePatch(logging.GlobalLogger(), string(baseBytes), string(patchString)) assert.NilError(t, err) var ep unstructured.Unstructured diff --git a/pkg/engine/mutate/patch/strategicPreprocessing_test.go b/pkg/engine/mutate/patch/strategicPreprocessing_test.go index cb15fcbc30..bd70e7c5e7 100644 --- a/pkg/engine/mutate/patch/strategicPreprocessing_test.go +++ b/pkg/engine/mutate/patch/strategicPreprocessing_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/kyverno/kyverno/pkg/engine/anchor" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" yaml "sigs.k8s.io/kustomize/kyaml/yaml" ) @@ -842,7 +842,7 @@ func Test_preProcessStrategicMergePatch_multipleAnchors(t *testing.T) { for i, test := range testCases { t.Logf("Running test %d...", i) - preProcessedPolicy, err := preProcessStrategicMergePatch(log.Log, string(test.rawPolicy), string(test.rawResource)) + preProcessedPolicy, err := preProcessStrategicMergePatch(logging.GlobalLogger(), string(test.rawPolicy), string(test.rawResource)) assert.NilError(t, err) output, err := preProcessedPolicy.MarshalJSON() @@ -904,7 +904,7 @@ func Test_CheckConditionAnchor_Matches(t *testing.T) { pattern := yaml.MustParse(string(patternRaw)) resource := yaml.MustParse(string(resourceRaw)) - err := checkCondition(log.Log, pattern, resource) + err := checkCondition(logging.GlobalLogger(), pattern, resource) assert.Equal(t, err, nil) } @@ -915,7 +915,7 @@ func Test_CheckConditionAnchor_DoesNotMatch(t *testing.T) { pattern := yaml.MustParse(string(patternRaw)) resource := yaml.MustParse(string(resourceRaw)) - err := checkCondition(log.Log, pattern, resource) + err := checkCondition(logging.GlobalLogger(), pattern, resource) assert.Error(t, err, "resource value 'sample' does not match 'value*' at path /key1/") } @@ -933,7 +933,7 @@ func Test_ValidateConditions_MapWithOneCondition_Matches(t *testing.T) { pattern := yaml.MustParse(string(patternRaw)) resource := yaml.MustParse(string(resourceRaw)) - err := validateConditions(log.Log, pattern, resource) + err := validateConditions(logging.GlobalLogger(), pattern, resource) assert.NilError(t, err) } @@ -951,7 +951,7 @@ func Test_ValidateConditions_MapWithOneCondition_DoesNotMatch(t *testing.T) { pattern := yaml.MustParse(string(patternRaw)) resource := yaml.MustParse(string(resourceRaw)) - err := validateConditions(log.Log, pattern, resource) + err := validateConditions(logging.GlobalLogger(), pattern, resource) _, ok := err.(ConditionError) assert.Assert(t, ok) } @@ -1088,7 +1088,7 @@ func Test_ConditionCheck_SeveralElementsMatchExceptOne(t *testing.T) { pattern := yaml.MustParse(string(patternRaw)) containers := yaml.MustParse(string(containersRaw)) - err := preProcessPattern(log.Log, pattern, containers) + err := preProcessPattern(logging.GlobalLogger(), pattern, containers) assert.NilError(t, err) patternContainers := pattern.Field("containers") @@ -1141,7 +1141,7 @@ func Test_NonExistingKeyMustFailPreprocessing(t *testing.T) { pattern := yaml.MustParse(string(rawPattern)) resource := yaml.MustParse(string(rawResource)) - err := preProcessPattern(log.Log, pattern, resource) + err := preProcessPattern(logging.GlobalLogger(), pattern, resource) assert.Error(t, err, "condition failed: could not found \"key1\" key in the resource") } @@ -1152,7 +1152,7 @@ func Test_NestedConditionals(t *testing.T) { pattern := yaml.MustParse(rawPattern) resource := yaml.MustParse(rawResource) - err := preProcessPattern(log.Log, pattern, resource) + err := preProcessPattern(logging.GlobalLogger(), pattern, resource) assert.NilError(t, err) resultPattern, _ := pattern.String() diff --git a/pkg/engine/mutation.go b/pkg/engine/mutation.go index f0d6b4a486..120e5daa8c 100644 --- a/pkg/engine/mutation.go +++ b/pkg/engine/mutation.go @@ -12,8 +12,8 @@ import ( "github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/engine/mutate" "github.com/kyverno/kyverno/pkg/engine/response" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) // Mutate performs mutation. Overlay first and then mutation patches @@ -27,7 +27,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) { ctx := policyContext.JSONContext var skippedRules []string - logger := log.Log.WithName("EngineMutate").WithValues("policy", policy.GetName(), "kind", matchedResource.GetKind(), + logger := logging.WithName("EngineMutate").WithValues("policy", policy.GetName(), "kind", matchedResource.GetKind(), "namespace", matchedResource.GetNamespace(), "name", matchedResource.GetName()) logger.V(4).Info("start mutate policy processing", "startTime", startTime) @@ -100,7 +100,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) { if !policyContext.AdmissionOperation && rule.IsMutateExisting() { policyContext := policyContext.Copy() if err := policyContext.JSONContext.AddTargetResource(patchedResource.Object); err != nil { - log.Log.Error(err, "failed to add target resource to the context") + logging.Error(err, "failed to add target resource to the context") continue } } diff --git a/pkg/engine/utils.go b/pkg/engine/utils.go index 881b45522c..ff5a108e43 100644 --- a/pkg/engine/utils.go +++ b/pkg/engine/utils.go @@ -15,6 +15,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/wildcards" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/utils" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" "github.com/pkg/errors" @@ -27,7 +28,6 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/log" ) // EngineStats stores in the statistics for a single application of resource @@ -111,7 +111,7 @@ func checkSelector(labelSelector *metav1.LabelSelector, resourceLabels map[strin wildcards.ReplaceInSelector(labelSelector, resourceLabels) selector, err := metav1.LabelSelectorAsSelector(labelSelector) if err != nil { - log.Log.Error(err, "failed to build label selector") + logging.Error(err, "failed to build label selector") return false, err } diff --git a/pkg/engine/utils/utils.go b/pkg/engine/utils/utils.go index a91ae26430..6df018b33f 100644 --- a/pkg/engine/utils/utils.go +++ b/pkg/engine/utils/utils.go @@ -7,9 +7,9 @@ import ( jsonpatch "github.com/evanphx/json-patch/v5" commonAnchor "github.com/kyverno/kyverno/pkg/engine/anchor" + "github.com/kyverno/kyverno/pkg/logging" jsonutils "github.com/kyverno/kyverno/pkg/utils/json" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) // ApplyPatches patches given resource with given patches and returns patched document @@ -21,17 +21,17 @@ func ApplyPatches(resource []byte, patches [][]byte) ([]byte, error) { joinedPatches := jsonutils.JoinPatches(patches...) patch, err := jsonpatch.DecodePatch(joinedPatches) if err != nil { - log.Log.V(4).Info("failed to decode JSON patch", "patch", patch) + logging.V(4).Info("failed to decode JSON patch", "patch", patch) return resource, err } patchedDocument, err := patch.Apply(resource) if err != nil { - log.Log.V(4).Info("failed to apply JSON patch", "patch", patch) + logging.V(4).Info("failed to apply JSON patch", "patch", patch) return resource, err } - log.Log.V(4).Info("applied JSON patch", "patch", patch) + logging.V(4).Info("applied JSON patch", "patch", patch) return patchedDocument, err } diff --git a/pkg/engine/validate/validate_test.go b/pkg/engine/validate/validate_test.go index b39d5faef1..c7558d31c5 100644 --- a/pkg/engine/validate/validate_test.go +++ b/pkg/engine/validate/validate_test.go @@ -10,8 +10,8 @@ import ( "github.com/kyverno/kyverno/pkg/engine/anchor" "github.com/kyverno/kyverno/pkg/engine/variables" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func TestValidateMap(t *testing.T) { @@ -107,7 +107,7 @@ func TestValidateMap(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -203,7 +203,7 @@ func TestValidateMap_AsteriskForInt(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) t.Log(path) assert.NilError(t, err) } @@ -296,7 +296,7 @@ func TestValidateMap_AsteriskForMap(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -384,7 +384,7 @@ func TestValidateMap_AsteriskForArray(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -475,7 +475,7 @@ func TestValidateMap_AsteriskFieldIsMissing(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/template/spec/containers/0/") assert.Assert(t, err != nil) } @@ -567,7 +567,7 @@ func TestValidateMap_livenessProbeIsNull(t *testing.T) { err := json.Unmarshal(rawMap, &resource) assert.NilError(t, err) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -657,7 +657,7 @@ func TestValidateMap_livenessProbeIsMissing(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateMap(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateMap(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -703,7 +703,7 @@ func TestValidateMapElement_TwoElementsInArrayOnePass(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") // assert.Equal(t, path, "/1/object/0/key2/") // assert.NilError(t, err) @@ -738,7 +738,7 @@ func TestValidateMapElement_OneElementInArrayPass(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -792,10 +792,10 @@ func TestValidateMap_CorrectRelativePathInConfig(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - pattern, err := variables.SubstituteAll(log.Log, nil, pattern) + pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern) assert.NilError(t, err) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -849,7 +849,7 @@ func TestValidateMap_RelativePathDoesNotExists(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/") assert.Assert(t, err != nil) } @@ -903,7 +903,7 @@ func TestValidateMap_OnlyAnchorsInPath(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/") assert.Assert(t, err != nil) } @@ -957,7 +957,7 @@ func TestValidateMap_MalformedReferenceOnlyDolarMark(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/") assert.Assert(t, err != nil) } @@ -1011,10 +1011,10 @@ func TestValidateMap_RelativePathWithParentheses(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - pattern, err := variables.SubstituteAll(log.Log, nil, pattern) + pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern) assert.NilError(t, err) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.NilError(t, err) } @@ -1068,7 +1068,7 @@ func TestValidateMap_MalformedPath(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/") assert.Assert(t, err != nil) } @@ -1122,10 +1122,10 @@ func TestValidateMap_AbosolutePathExists(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - pattern, err := variables.SubstituteAll(log.Log, nil, pattern) + pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern) assert.NilError(t, err) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.Assert(t, err == nil) } @@ -1157,7 +1157,7 @@ func TestValidateMap_AbsolutePathToMetadata(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "") assert.Assert(t, err == nil) } @@ -1199,10 +1199,10 @@ func TestValidateMap_AbsolutePathToMetadata_fail(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - pattern, err := variables.SubstituteAll(log.Log, nil, pattern) + pattern, err := variables.SubstituteAll(logging.GlobalLogger(), nil, pattern) assert.NilError(t, err) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/image/") assert.Assert(t, err != nil) } @@ -1256,7 +1256,7 @@ func TestValidateMap_AbosolutePathDoesNotExists(t *testing.T) { assert.Assert(t, json.Unmarshal(rawPattern, &pattern)) assert.Assert(t, json.Unmarshal(rawMap, &resource)) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/spec/containers/0/resources/requests/memory/") assert.Assert(t, err != nil) } @@ -1291,7 +1291,7 @@ func TestValidateMapElement_OneElementInArrayNotPass(t *testing.T) { err = json.Unmarshal(rawMap, &resource) assert.NilError(t, err) - path, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + path, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, path, "/0/object/0/key2/") assert.Assert(t, err != nil) } @@ -1349,7 +1349,7 @@ func testValidationPattern(t *testing.T, num string, patternBytes []byte, resour err = json.Unmarshal(resourceBytes, &resource) assert.NilError(t, err) - p, err := validateResourceElement(log.Log, resource, pattern, pattern, "/", anchor.NewAnchorMap()) + p, err := validateResourceElement(logging.GlobalLogger(), resource, pattern, pattern, "/", anchor.NewAnchorMap()) assert.Equal(t, p, path, num) if nilErr { assert.NilError(t, err, num) @@ -1674,7 +1674,7 @@ func testMatchPattern(t *testing.T, testCase struct { err = json.Unmarshal(testCase.resource, &resource) assert.NilError(t, err) - err = MatchPattern(log.Log, resource, pattern) + err = MatchPattern(logging.GlobalLogger(), resource, pattern) if testCase.status == response.RuleStatusPass { assert.NilError(t, err, fmt.Sprintf("\nexpected pass - test: %s\npattern: %s\nresource: %s\n", testCase.name, pattern, resource)) diff --git a/pkg/engine/validation.go b/pkg/engine/validation.go index 276edf7e81..7208df4f23 100644 --- a/pkg/engine/validation.go +++ b/pkg/engine/validation.go @@ -17,6 +17,7 @@ import ( "github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/validate" "github.com/kyverno/kyverno/pkg/engine/variables" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/pss" "github.com/kyverno/kyverno/pkg/utils" "github.com/pkg/errors" @@ -26,7 +27,6 @@ import ( "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) // Validate applies validation rules from policy on the resource @@ -46,7 +46,7 @@ func Validate(policyContext *PolicyContext) (resp *response.EngineResponse) { } func buildLogger(ctx *PolicyContext) logr.Logger { - logger := log.Log.WithName("EngineValidate").WithValues("policy", ctx.Policy.GetName()) + logger := logging.WithName("EngineValidate").WithValues("policy", ctx.Policy.GetName()) if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) { logger = logger.WithValues("kind", ctx.OldResource.GetKind(), "namespace", ctx.OldResource.GetNamespace(), "name", ctx.OldResource.GetName()) } else { diff --git a/pkg/engine/variables/evaluate_test.go b/pkg/engine/variables/evaluate_test.go index da2f8ca3f8..e934cf5b8c 100644 --- a/pkg/engine/variables/evaluate_test.go +++ b/pkg/engine/variables/evaluate_test.go @@ -6,8 +6,8 @@ import ( kyverno "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/engine/context" + "github.com/kyverno/kyverno/pkg/logging" "github.com/stretchr/testify/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func TestEvaluate(t *testing.T) { @@ -378,7 +378,7 @@ func TestEvaluate(t *testing.T) { ctx := context.NewContext() for _, tc := range testCases { - if Evaluate(log.Log, ctx, tc.Condition) != tc.Result { + if Evaluate(logging.GlobalLogger(), ctx, tc.Condition) != tc.Result { t.Errorf("%v - expected result to be %v", tc.Condition, tc.Result) } } @@ -419,13 +419,13 @@ func Test_Eval_Equal_Var_Pass(t *testing.T) { err = json.Unmarshal(conditionJSON, &conditionMap) assert.Nil(t, err) - conditionWithResolvedVars, _ := SubstituteAllInPreconditions(log.Log, ctx, conditionMap) + conditionWithResolvedVars, _ := SubstituteAllInPreconditions(logging.GlobalLogger(), ctx, conditionMap) conditionJSON, err = json.Marshal(conditionWithResolvedVars) assert.Nil(t, err) err = json.Unmarshal(conditionJSON, &condition) assert.Nil(t, err) - assert.True(t, Evaluate(log.Log, ctx, condition)) + assert.True(t, Evaluate(logging.GlobalLogger(), ctx, condition)) } func Test_Eval_Equal_Var_Fail(t *testing.T) { @@ -454,7 +454,7 @@ func Test_Eval_Equal_Var_Fail(t *testing.T) { RawValue: kyverno.ToJSON("temp1"), } - if Evaluate(log.Log, ctx, condition) { + if Evaluate(logging.GlobalLogger(), ctx, condition) { t.Error("expected to fail") } } diff --git a/pkg/engine/variables/variables_test.go b/pkg/engine/variables/variables_test.go index a03e3dc091..ce5c23440e 100644 --- a/pkg/engine/variables/variables_test.go +++ b/pkg/engine/variables/variables_test.go @@ -7,9 +7,9 @@ import ( urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1" "github.com/kyverno/kyverno/pkg/engine/context" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" authenticationv1 "k8s.io/api/authentication/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) func Test_variablesub1(t *testing.T) { @@ -85,7 +85,7 @@ func Test_variablesub1(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -175,7 +175,7 @@ func Test_variablesub_multiple(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -262,7 +262,7 @@ func Test_variablesubstitution(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -323,7 +323,7 @@ func Test_variableSubstitutionValue(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -381,7 +381,7 @@ func Test_variableSubstitutionValueOperatorNotEqual(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -440,7 +440,7 @@ func Test_variableSubstitutionValueFail(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err == nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err == nil { t.Log("expected to fails") t.Fail() } @@ -498,7 +498,7 @@ func Test_variableSubstitutionObject(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) @@ -562,7 +562,7 @@ func Test_variableSubstitutionObjectOperatorNotEqualFail(t *testing.T) { t.Error(err) } - patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy) + patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy) assert.NilError(t, err) patternMapCopy, ok := patternCopy.(map[string]interface{}) @@ -637,7 +637,7 @@ func Test_variableSubstitutionMultipleObject(t *testing.T) { t.Error(err) } - if patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy); err != nil { + if patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy); err != nil { t.Error(err) } resultRaw, err := json.Marshal(patternCopy) diff --git a/pkg/engine/variables/vars_test.go b/pkg/engine/variables/vars_test.go index e9c443256b..445bf2cf86 100644 --- a/pkg/engine/variables/vars_test.go +++ b/pkg/engine/variables/vars_test.go @@ -10,8 +10,8 @@ import ( v1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/engine/context" ju "github.com/kyverno/kyverno/pkg/engine/jsonutils" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func Test_subVars_success(t *testing.T) { @@ -70,7 +70,7 @@ func Test_subVars_success(t *testing.T) { t.Error(err) } - if _, err := SubstituteAll(log.Log, ctx, pattern); err != nil { + if _, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern); err != nil { t.Error(err) } } @@ -131,7 +131,7 @@ func Test_subVars_failed(t *testing.T) { t.Error(err) } - if _, err := SubstituteAll(log.Log, ctx, pattern); err == nil { + if _, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern); err == nil { t.Error("error is expected") } } @@ -223,7 +223,7 @@ func Test_subVars_with_JMESPath_At(t *testing.T) { err = context.AddResource(ctx, resourceRaw) assert.NilError(t, err) - output, err := SubstituteAll(log.Log, ctx, pattern) + output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) out, err := json.Marshal(output) assert.NilError(t, err) @@ -282,7 +282,7 @@ func Test_subVars_withRegexMatch(t *testing.T) { err = context.AddResource(ctx, resourceRaw) assert.NilError(t, err) - output, err := SubstituteAll(log.Log, ctx, pattern) + output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) out, err := json.Marshal(output) assert.NilError(t, err) @@ -312,7 +312,7 @@ func Test_subVars_withMerge(t *testing.T) { err = context.AddResource(ctx, resourceRaw) assert.NilError(t, err) - output, err := SubstituteAll(log.Log, ctx, pattern) + output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) out, err := json.Marshal(output) assert.NilError(t, err) @@ -355,7 +355,7 @@ func Test_subVars_withRegexReplaceAll(t *testing.T) { err = context.AddResource(ctx, resourceRaw) assert.NilError(t, err) - output, err := SubstituteAll(log.Log, ctx, pattern) + output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) out, err := json.Marshal(output) assert.NilError(t, err) @@ -399,7 +399,7 @@ func Test_ReplacingPathWhenDeleting(t *testing.T) { ctx := context.NewContextFromRaw(resourceRaw) assert.NilError(t, err) - pattern, err = SubstituteAll(log.Log, ctx, pattern) + pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) assert.Equal(t, fmt.Sprintf("%v", pattern), "bar") @@ -434,7 +434,7 @@ func Test_ReplacingNestedVariableWhenDeleting(t *testing.T) { ctx := context.NewContextFromRaw(resourceRaw) assert.NilError(t, err) - pattern, err = SubstituteAll(log.Log, ctx, pattern) + pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) assert.Equal(t, fmt.Sprintf("%v", pattern), "nested_target") @@ -464,7 +464,7 @@ func Test_SubstituteSuccess(t *testing.T) { patternRaw := []byte(`"{{request.object.metadata.annotations.test}}"`) assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) - action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) + action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver) results, err := action(&ju.ActionData{ Document: nil, Element: string(patternRaw), @@ -488,7 +488,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) { patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test2}}}}"`) assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) - action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) + action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver) results, err := action(&ju.ActionData{ Document: nil, Element: string(patternRaw), @@ -501,7 +501,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) { patternRaw = []byte(`"{{request.object.metadata2.{{request.object.metadata.annotations.test}}}}"`) assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) - action = substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) + action = substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver) results, err = action(&ju.ActionData{ Document: nil, Element: string(patternRaw), @@ -520,7 +520,7 @@ func Test_SubstituteRecursive(t *testing.T) { patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test}}}}"`) assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) - action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) + action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver) results, err := action(&ju.ActionData{ Document: nil, Element: string(patternRaw), @@ -556,7 +556,7 @@ func Test_policyContextValidation(t *testing.T) { ctx := context.NewMockContext(nil, "request.object") - _, err = SubstituteAll(log.Log, ctx, contextMap) + _, err = SubstituteAll(logging.GlobalLogger(), ctx, contextMap) assert.Assert(t, err != nil, err) } @@ -634,7 +634,7 @@ func Test_variableSubstitution_array(t *testing.T) { ctx := context.NewContextFromRaw(configmapRaw) context.AddResource(ctx, resourceRaw) - vars, err := SubstituteAllInRule(log.Log, ctx, rule) + vars, err := SubstituteAllInRule(logging.GlobalLogger(), ctx, rule) assert.NilError(t, err) assert.DeepEqual(t, vars.Validation.Message, "The animal cow is not in the allowed list of animals: snake\nbear\ncat\ndog.") @@ -680,7 +680,7 @@ func Test_SubstituteNull(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -709,7 +709,7 @@ func Test_SubstituteNullInString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -738,7 +738,7 @@ func Test_SubstituteArray(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -767,7 +767,7 @@ func Test_SubstituteArrayInString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -796,7 +796,7 @@ func Test_SubstituteInt(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -825,7 +825,7 @@ func Test_SubstituteIntInString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -854,7 +854,7 @@ func Test_SubstituteBool(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -883,7 +883,7 @@ func Test_SubstituteBoolInString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -912,7 +912,7 @@ func Test_SubstituteString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -941,7 +941,7 @@ func Test_SubstituteStringInString(t *testing.T) { ctx := context.NewContext() context.AddResource(ctx, variableObject) - resolved, err := SubstituteAll(log.Log, ctx, pattern) + resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] @@ -993,7 +993,7 @@ func Test_ReferenceSubstitution(t *testing.T) { err = context.AddResource(ctx, jsonRaw) assert.NilError(t, err) - actualDocument, err := SubstituteAll(log.Log, ctx, document) + actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document) assert.NilError(t, err) assert.DeepEqual(t, expectedDocument, actualDocument) @@ -1066,7 +1066,7 @@ func TestActualizePattern_GivenRelativePathThatExists(t *testing.T) { // pattern, err := actualizePattern(log.Log, pattern, referencePath, absolutePath) - pattern, err := resolveReference(log.Log, pattern, referencePath, absolutePath) + pattern, err := resolveReference(logging.GlobalLogger(), pattern, referencePath, absolutePath) assert.NilError(t, err) assert.DeepEqual(t, resolvedReference, pattern) @@ -1075,7 +1075,7 @@ func TestActualizePattern_GivenRelativePathThatExists(t *testing.T) { func TestFindAndShiftReferences_PositiveCase(t *testing.T) { message := "Message with $(./../../pattern/spec/containers/0/image) reference inside. Or maybe even two $(./../../pattern/spec/containers/0/image), but they are same." expectedMessage := strings.Replace(message, "$(./../../pattern/spec/containers/0/image)", "$(./../../pattern/spec/jobTemplate/spec/containers/0/image)", -1) - actualMessage := FindAndShiftReferences(log.Log, message, "spec/jobTemplate", "pattern") + actualMessage := FindAndShiftReferences(logging.GlobalLogger(), message, "spec/jobTemplate", "pattern") assert.Equal(t, expectedMessage, actualMessage) } @@ -1083,7 +1083,7 @@ func TestFindAndShiftReferences_PositiveCase(t *testing.T) { func TestFindAndShiftReferences_AnyPatternPositiveCase(t *testing.T) { message := "Message with $(./../../anyPattern/0/spec/containers/0/image)." expectedMessage := strings.Replace(message, "$(./../../anyPattern/0/spec/containers/0/image)", "$(./../../anyPattern/0/spec/jobTemplate/spec/containers/0/image)", -1) - actualMessage := FindAndShiftReferences(log.Log, message, "spec/jobTemplate", "anyPattern") + actualMessage := FindAndShiftReferences(logging.GlobalLogger(), message, "spec/jobTemplate", "anyPattern") assert.Equal(t, expectedMessage, actualMessage) } @@ -1137,7 +1137,7 @@ func Test_EscpReferenceSubstitution(t *testing.T) { err = context.AddResource(ctx, jsonRaw) assert.NilError(t, err) - actualDocument, err := SubstituteAll(log.Log, ctx, document) + actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document) assert.NilError(t, err) assert.DeepEqual(t, expectedDocument, actualDocument) @@ -1172,7 +1172,7 @@ func Test_ReplacingEscpNestedVariableWhenDeleting(t *testing.T) { ctx := context.NewContextFromRaw(resourceRaw) assert.NilError(t, err) - pattern, err = SubstituteAll(log.Log, ctx, pattern) + pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern) assert.NilError(t, err) assert.Equal(t, fmt.Sprintf("%v", pattern), "{{request.object.metadata.annotations.target}}") diff --git a/pkg/metrics/log.go b/pkg/metrics/log.go index 0c9fe0c3bc..04b5981651 100644 --- a/pkg/metrics/log.go +++ b/pkg/metrics/log.go @@ -2,10 +2,10 @@ package metrics import ( "github.com/go-logr/logr" - "sigs.k8s.io/controller-runtime/pkg/log" + "github.com/kyverno/kyverno/pkg/logging" ) -var logger = log.Log.WithName("metrics") +var logger = logging.WithName("metrics") func Logger() logr.Logger { return logger diff --git a/pkg/openapi/crdSync.go b/pkg/openapi/crdSync.go index 247042d8ce..4bc860b477 100644 --- a/pkg/openapi/crdSync.go +++ b/pkg/openapi/crdSync.go @@ -10,6 +10,7 @@ import ( "github.com/googleapis/gnostic/compiler" openapiv2 "github.com/googleapis/gnostic/openapiv2" "github.com/kyverno/kyverno/pkg/clients/dclient" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/metrics" util "github.com/kyverno/kyverno/pkg/utils" "github.com/pkg/errors" @@ -19,7 +20,6 @@ import ( runtimeSchema "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/discovery" - "sigs.k8s.io/controller-runtime/pkg/log" ) type crdSync struct { @@ -72,17 +72,17 @@ func NewCRDSync(client dclient.Interface, controller *Controller) *crdSync { func (c *crdSync) Run(ctx context.Context, workers int) { if err := c.updateInClusterKindToAPIVersions(); err != nil { - log.Log.Error(err, "failed to update in-cluster api versions") + logging.Error(err, "failed to update in-cluster api versions") } newDoc, err := c.client.Discovery().OpenAPISchema() if err != nil { - log.Log.Error(err, "cannot get OpenAPI schema") + logging.Error(err, "cannot get OpenAPI schema") } err = c.controller.useOpenAPIDocument(newDoc) if err != nil { - log.Log.Error(err, "Could not set custom OpenAPI document") + logging.Error(err, "Could not set custom OpenAPI document") } // Sync CRD before kyverno starts c.sync() @@ -101,7 +101,7 @@ func (c *crdSync) sync() { c.client.RecordClientQuery(metrics.ClientList, metrics.KubeDynamicClient, "CustomResourceDefinition", "") if err != nil { - log.Log.Error(err, "could not fetch crd's from server") + logging.Error(err, "could not fetch crd's from server") return } @@ -112,17 +112,17 @@ func (c *crdSync) sync() { } if err := c.updateInClusterKindToAPIVersions(); err != nil { - log.Log.Error(err, "sync failed, unable to update in-cluster api versions") + logging.Error(err, "sync failed, unable to update in-cluster api versions") } newDoc, err := c.client.Discovery().OpenAPISchema() if err != nil { - log.Log.Error(err, "cannot get OpenAPI schema") + logging.Error(err, "cannot get OpenAPI schema") } err = c.controller.useOpenAPIDocument(newDoc) if err != nil { - log.Log.Error(err, "Could not set custom OpenAPI document") + logging.Error(err, "Could not set custom OpenAPI document") } } @@ -173,19 +173,19 @@ func (o *Controller) ParseCRD(crd unstructured.Unstructured) { } if openV3schema == nil { - log.Log.V(4).Info("skip adding schema, CRD has no properties", "name", crdName) + logging.V(4).Info("skip adding schema, CRD has no properties", "name", crdName) return } schemaRaw, _ := json.Marshal(openV3schema) if len(schemaRaw) < 1 { - log.Log.V(4).Info("failed to parse crd schema", "name", crdName) + logging.V(4).Info("failed to parse crd schema", "name", crdName) return } schemaRaw, err = addingDefaultFieldsToSchema(crdName, schemaRaw) if err != nil { - log.Log.Error(err, "failed to parse crd schema", "name", crdName) + logging.Error(err, "failed to parse crd schema", "name", crdName) return } @@ -196,7 +196,7 @@ func (o *Controller) ParseCRD(crd unstructured.Unstructured) { if err != nil { v3valueFound := isOpenV3Error(err) if !v3valueFound { - log.Log.Error(err, "failed to parse crd schema", "name", crdName) + logging.Error(err, "failed to parse crd schema", "name", crdName) } return } @@ -226,7 +226,7 @@ func addingDefaultFieldsToSchema(crdName string, schemaRaw []byte) ([]byte, erro _ = json.Unmarshal(schemaRaw, &schema) if len(schema.Properties) < 1 { - log.Log.V(6).Info("crd schema has no properties", "name", crdName) + logging.V(6).Info("crd schema has no properties", "name", crdName) return schemaRaw, nil } @@ -256,7 +256,7 @@ func (c *crdSync) CheckSync(ctx context.Context) { Resource: "customresourcedefinitions", }).List(ctx, metav1.ListOptions{}) if err != nil { - log.Log.Error(err, "could not fetch crd's from server") + logging.Error(err, "could not fetch crd's from server") return } if len(c.controller.crdList) != len(crds.Items) { diff --git a/pkg/openapi/validation.go b/pkg/openapi/validation.go index 9a800d6666..534ffc433b 100644 --- a/pkg/openapi/validation.go +++ b/pkg/openapi/validation.go @@ -13,6 +13,7 @@ import ( "github.com/kyverno/kyverno/data" "github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/engine" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/utils" cmap "github.com/orcaman/concurrent-map" "github.com/pkg/errors" @@ -21,7 +22,6 @@ import ( "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/kube-openapi/pkg/util/proto" "k8s.io/kube-openapi/pkg/util/proto/validation" - "sigs.k8s.io/controller-runtime/pkg/log" ) type concurrentMap struct{ cmap.ConcurrentMap } @@ -156,7 +156,7 @@ func (o *Controller) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) er k := o.gvkToDefinitionName.GetKind(kind) resource, _ := o.generateEmptyResource(o.definitions.GetSchema(k)).(map[string]interface{}) if len(resource) == 0 { - log.Log.V(2).Info("unable to validate resource. OpenApi definition not found", "kind", kind) + logging.V(2).Info("unable to validate resource. OpenApi definition not found", "kind", kind) return nil } @@ -187,7 +187,7 @@ func (o *Controller) useOpenAPIDocument(doc *openapiv2.Document) error { gvk, preferredGVK, err := o.getGVKByDefinitionName(definitionName) if err != nil { - log.Log.V(5).Info("unable to cache OpenAPISchema", "definitionName", definitionName, "reason", err.Error()) + logging.V(5).Info("unable to cache OpenAPISchema", "definitionName", definitionName, "reason", err.Error()) continue } @@ -368,7 +368,7 @@ func (o *Controller) generateEmptyResource(kindSchema *openapiv2.Schema) interfa return getBoolValue(kindSchema) } - log.Log.V(2).Info("unknown type", types[0]) + logging.V(2).Info("unknown type", types[0]) return nil } diff --git a/pkg/policy/actions.go b/pkg/policy/actions.go index 200d6eb932..0f07c474e7 100644 --- a/pkg/policy/actions.go +++ b/pkg/policy/actions.go @@ -5,11 +5,11 @@ import ( kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/clients/dclient" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/policy/generate" "github.com/kyverno/kyverno/pkg/policy/mutate" "github.com/kyverno/kyverno/pkg/policy/validate" "github.com/kyverno/kyverno/pkg/utils" - "sigs.k8s.io/controller-runtime/pkg/log" ) // Validation provides methods to validate a rule @@ -55,7 +55,7 @@ func validateActions(idx int, rule *kyvernov1.Rule, client dclient.Interface, mo return fmt.Errorf("path: spec.rules[%d].generate.%s.: %v", idx, path, err) } } else { - checker = generate.NewGenerateFactory(client, rule.Generation, log.Log) + checker = generate.NewGenerateFactory(client, rule.Generation, logging.GlobalLogger()) if path, err := checker.Validate(); err != nil { return fmt.Errorf("path: spec.rules[%d].generate.%s.: %v", idx, path, err) } diff --git a/pkg/policy/common.go b/pkg/policy/common.go index 14449a6741..e62ed67f05 100644 --- a/pkg/policy/common.go +++ b/pkg/policy/common.go @@ -7,19 +7,19 @@ import ( "github.com/go-logr/logr" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/config" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/utils" kubeutils "github.com/kyverno/kyverno/pkg/utils/kube" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/labels" - "sigs.k8s.io/controller-runtime/pkg/log" ) func transformResource(resource unstructured.Unstructured) []byte { data, err := resource.MarshalJSON() if err != nil { - log.Log.Error(err, "failed to marshal resource") + logging.Error(err, "failed to marshal resource") return nil } return data diff --git a/pkg/policy/generate/fake.go b/pkg/policy/generate/fake.go index eca357e140..7f32fde287 100644 --- a/pkg/policy/generate/fake.go +++ b/pkg/policy/generate/fake.go @@ -2,8 +2,8 @@ package generate import ( kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/policy/generate/fake" - "sigs.k8s.io/controller-runtime/pkg/log" ) // FakeGenerate provides implementation for generate rule processing @@ -18,6 +18,6 @@ func NewFakeGenerate(rule kyvernov1.Generation) *FakeGenerate { g := FakeGenerate{} g.rule = rule g.authCheck = fake.NewFakeAuth() - g.log = log.Log + g.log = logging.GlobalLogger() return &g } diff --git a/pkg/policy/validate_test.go b/pkg/policy/validate_test.go index 52fb5a920e..98db0ad691 100644 --- a/pkg/policy/validate_test.go +++ b/pkg/policy/validate_test.go @@ -6,9 +6,9 @@ import ( "testing" kyverno "github.com/kyverno/kyverno/api/kyverno/v1" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/openapi" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" - "sigs.k8s.io/controller-runtime/pkg/log" "gotest.tools/assert" ) @@ -983,7 +983,7 @@ func Test_checkAutoGenRules(t *testing.T) { err := json.Unmarshal(test.policy, &policy) assert.NilError(t, err) - res := missingAutoGenRules(&policy, log.Log) + res := missingAutoGenRules(&policy, logging.GlobalLogger()) assert.Equal(t, test.expectedResult, res, fmt.Sprintf("test %s failed", test.name)) } } diff --git a/pkg/policycache/log.go b/pkg/policycache/log.go index 066e9ca4c8..1994883f6b 100644 --- a/pkg/policycache/log.go +++ b/pkg/policycache/log.go @@ -1,5 +1,5 @@ package policycache -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("policycache") +var logger = logging.WithName("policycache") diff --git a/pkg/testrunner/utils.go b/pkg/testrunner/utils.go index 13b32452cc..ed420cc45c 100644 --- a/pkg/testrunner/utils.go +++ b/pkg/testrunner/utils.go @@ -4,8 +4,8 @@ import ( "os" "path/filepath" + "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) // LoadFile loads file in byte buffer @@ -40,7 +40,7 @@ func ConvertToUnstructured(data []byte) (*unstructured.Unstructured, error) { resource := &unstructured.Unstructured{} err := resource.UnmarshalJSON(data) if err != nil { - log.Log.Error(err, "failed to unmarshal resource") + logging.Error(err, "failed to unmarshal resource") return nil, err } return resource, nil diff --git a/pkg/tls/log.go b/pkg/tls/log.go index f260ce06a7..aa125ac405 100644 --- a/pkg/tls/log.go +++ b/pkg/tls/log.go @@ -1,5 +1,5 @@ package tls -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("tls") +var logger = logging.WithName("tls") diff --git a/pkg/userinfo/roleRef.go b/pkg/userinfo/roleRef.go index 08fd73a59f..37d3ba3ecc 100644 --- a/pkg/userinfo/roleRef.go +++ b/pkg/userinfo/roleRef.go @@ -5,13 +5,13 @@ import ( "strings" "github.com/kyverno/kyverno/pkg/config" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/utils" admissionv1 "k8s.io/api/admission/v1" authenticationv1 "k8s.io/api/authentication/v1" rbacv1 "k8s.io/api/rbac/v1" labels "k8s.io/apimachinery/pkg/labels" rbacv1listers "k8s.io/client-go/listers/rbac/v1" - "sigs.k8s.io/controller-runtime/pkg/log" ) const ( @@ -89,7 +89,7 @@ func matchServiceAccount(subject rbacv1.Subject, userInfo authenticationv1.UserI if userInfo.Username[len(saPrefix):] != subjectServiceAccount { return false } - log.Log.V(3).Info(fmt.Sprintf("found a matched service account not match: %s", subjectServiceAccount)) + logging.V(3).Info(fmt.Sprintf("found a matched service account not match: %s", subjectServiceAccount)) return true } @@ -98,7 +98,7 @@ func matchUserOrGroup(subject rbacv1.Subject, userInfo authenticationv1.UserInfo keys := append(userInfo.Groups, userInfo.Username) for _, key := range keys { if subject.Name == key { - log.Log.V(3).Info(fmt.Sprintf("found a matched user/group '%v' in request userInfo: %v", subject.Name, keys)) + logging.V(3).Info(fmt.Sprintf("found a matched user/group '%v' in request userInfo: %v", subject.Name, keys)) return true } } diff --git a/pkg/utils/annotations_test.go b/pkg/utils/annotations_test.go index 8246e50b80..716c0b835c 100644 --- a/pkg/utils/annotations_test.go +++ b/pkg/utils/annotations_test.go @@ -4,9 +4,9 @@ import ( "testing" "github.com/kyverno/kyverno/pkg/engine/response" + "github.com/kyverno/kyverno/pkg/logging" "gotest.tools/assert" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) func newPolicyResponse(policy, rule string, patchesStr []string, status response.RuleStatus) response.PolicyResponse { @@ -43,7 +43,7 @@ func newEngineResponse(policy, rule string, patchesStr []string, status response func Test_empty_annotation(t *testing.T) { patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }` engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, nil) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) expectedPatches := `{"path":"/metadata/annotations","op":"add","value":{"policies.kyverno.io/last-applied-patches":"default-imagepullpolicy.mutate-container.kyverno.io: replaced /spec/containers/0/imagePullPolicy\n"}}` assert.Equal(t, string(annPatches[0]), expectedPatches) } @@ -54,7 +54,7 @@ func Test_exist_annotation(t *testing.T) { } patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }` engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) expectedPatches := `{"path":"/metadata/annotations/policies.kyverno.io~1last-applied-patches","op":"add","value":"default-imagepullpolicy.mutate-container.kyverno.io: replaced /spec/containers/0/imagePullPolicy\n"}` assert.Equal(t, string(annPatches[0]), expectedPatches) } @@ -65,7 +65,7 @@ func Test_exist_kyverno_annotation(t *testing.T) { } patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }` engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) expectedPatches := `{"path":"/metadata/annotations/policies.kyverno.io~1last-applied-patches","op":"add","value":"default-imagepullpolicy.mutate-container.kyverno.io: replaced /spec/containers/0/imagePullPolicy\n"}` assert.Equal(t, string(annPatches[0]), expectedPatches) } @@ -75,10 +75,10 @@ func Test_annotation_nil_patch(t *testing.T) { "policies.kyverno.patches": "old-annotation", } engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", nil, response.RuleStatusPass, annotation) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) assert.Assert(t, annPatches == nil) engineResponseNew := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{""}, response.RuleStatusPass, annotation) - annPatchesNew := GenerateAnnotationPatches([]*response.EngineResponse{engineResponseNew}, log.Log) + annPatchesNew := GenerateAnnotationPatches([]*response.EngineResponse{engineResponseNew}, logging.GlobalLogger()) assert.Assert(t, annPatchesNew == nil) } @@ -87,7 +87,7 @@ func Test_annotation_failed_Patch(t *testing.T) { "policies.kyverno.patches": "old-annotation", } engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", nil, response.RuleStatusFail, annotation) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) assert.Assert(t, annPatches == nil) } @@ -97,7 +97,7 @@ func Test_exist_patches(t *testing.T) { } patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }` engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) - annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, log.Log) + annPatches := GenerateAnnotationPatches([]*response.EngineResponse{engineResponse}, logging.GlobalLogger()) expectedPatches1 := `{"path":"/metadata/annotations/policies.kyverno.io~1patches","op":"remove"}` expectedPatches2 := `{"path":"/metadata/annotations/policies.kyverno.io~1last-applied-patches","op":"add","value":"default-imagepullpolicy.mutate-container.kyverno.io: replaced /spec/containers/0/imagePullPolicy\n"}` assert.Equal(t, string(annPatches[0]), expectedPatches1) diff --git a/pkg/utils/util.go b/pkg/utils/util.go index 684926c2db..6e98792566 100644 --- a/pkg/utils/util.go +++ b/pkg/utils/util.go @@ -10,6 +10,7 @@ import ( kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/clients/dclient" engineutils "github.com/kyverno/kyverno/pkg/engine/utils" + "github.com/kyverno/kyverno/pkg/logging" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" "github.com/pkg/errors" admissionv1 "k8s.io/api/admission/v1" @@ -19,7 +20,6 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/discovery" - "sigs.k8s.io/controller-runtime/pkg/log" ) var regexVersion = regexp.MustCompile(`v(\d+).(\d+).(\d+)\.*`) @@ -122,11 +122,11 @@ func isCRDInstalled(discoveryClient dclient.IDiscovery, kind string) bool { err = fmt.Errorf("not found") } - log.Log.Error(err, "failed to retrieve CRD", "kind", kind) + logging.Error(err, "failed to retrieve CRD", "kind", kind) return false } - log.Log.V(2).Info("CRD found", "gvr", gvr.String()) + logging.V(2).Info("CRD found", "gvr", gvr.String()) return true } @@ -345,7 +345,7 @@ func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interfac } func OverrideRuntimeErrorHandler() { - logger := log.Log.WithName("RuntimeErrorHandler") + logger := logging.WithName("RuntimeErrorHandler") if len(runtime.ErrorHandlers) > 0 { runtime.ErrorHandlers[0] = func(err error) { logger.V(6).Info("runtime error", "msg", err.Error()) diff --git a/pkg/utils/yaml/loadpolicy.go b/pkg/utils/yaml/loadpolicy.go index f9985e3584..af72b92c9e 100644 --- a/pkg/utils/yaml/loadpolicy.go +++ b/pkg/utils/yaml/loadpolicy.go @@ -5,8 +5,8 @@ import ( "fmt" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" + log "github.com/kyverno/kyverno/pkg/logging" "k8s.io/apimachinery/pkg/util/yaml" - "sigs.k8s.io/controller-runtime/pkg/log" ) // GetPolicy extracts policies from YAML bytes @@ -25,7 +25,7 @@ func GetPolicy(bytes []byte) (policies []kyvernov1.PolicyInterface, err error) { return nil, fmt.Errorf("failed to decode policy: %v", err) } if policy.TypeMeta.Kind == "" { - log.Log.V(3).Info("skipping file as policy.TypeMeta.Kind not found") + log.V(3).Info("skipping file as policy.TypeMeta.Kind not found") continue } if policy.TypeMeta.Kind != "ClusterPolicy" && policy.TypeMeta.Kind != "Policy" { diff --git a/pkg/webhooks/log.go b/pkg/webhooks/log.go index d86ff28e87..66ac9ec7a2 100644 --- a/pkg/webhooks/log.go +++ b/pkg/webhooks/log.go @@ -1,5 +1,5 @@ package webhooks -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("webhooks") +var logger = logging.WithName("webhooks") diff --git a/pkg/webhooks/policy/handlers_test.go b/pkg/webhooks/policy/handlers_test.go index 00a63d4261..2e069ce453 100644 --- a/pkg/webhooks/policy/handlers_test.go +++ b/pkg/webhooks/policy/handlers_test.go @@ -8,9 +8,9 @@ import ( "github.com/kyverno/kyverno/pkg/engine/utils" "github.com/kyverno/kyverno/pkg/policymutation" + log "github.com/kyverno/kyverno/pkg/logging" assertnew "github.com/stretchr/testify/assert" "gotest.tools/assert" - "sigs.k8s.io/controller-runtime/pkg/log" ) func compareJSONAsMap(t *testing.T, expected, actual []byte) { @@ -34,7 +34,7 @@ func TestGeneratePodControllerRule_NilAnnotation(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) p, err := utils.ApplyPatches(policyRaw, patches) @@ -67,7 +67,7 @@ func TestGeneratePodControllerRule_PredefinedAnnotation(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) assert.Assert(t, len(patches) == 1) } @@ -118,7 +118,7 @@ func TestGeneratePodControllerRule_DisableFeature(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) assert.Assert(t, len(patches) == 0) } @@ -169,7 +169,7 @@ func TestGeneratePodControllerRule_Mutate(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) p, err := utils.ApplyPatches(policyRaw, patches) @@ -303,7 +303,7 @@ func TestGeneratePodControllerRule_ExistOtherAnnotation(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) p, err := utils.ApplyPatches(policyRaw, patches) @@ -375,7 +375,7 @@ func TestGeneratePodControllerRule_ValidateAnyPattern(t *testing.T) { var policy kyverno.ClusterPolicy assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) p, err := utils.ApplyPatches(policyRaw, patches) @@ -514,7 +514,7 @@ func TestGeneratePodControllerRule_ValidatePattern(t *testing.T) { var policy kyverno.ClusterPolicy // var policy, generatePolicy unstructured.Unstructured assert.Assert(t, json.Unmarshal(policyRaw, &policy)) - patches, errs := policymutation.GeneratePodControllerRule(&policy, log.Log) + patches, errs := policymutation.GeneratePodControllerRule(&policy, log.GlobalLogger()) assert.Assert(t, len(errs) == 0) p, err := utils.ApplyPatches(policyRaw, patches) diff --git a/pkg/webhooks/resource/handlers_test.go b/pkg/webhooks/resource/handlers_test.go index de317d4bfa..19995a4c16 100644 --- a/pkg/webhooks/resource/handlers_test.go +++ b/pkg/webhooks/resource/handlers_test.go @@ -7,11 +7,11 @@ import ( "time" kyverno "github.com/kyverno/kyverno/api/kyverno/v1" + log "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/pkg/policycache" "gotest.tools/assert" v1 "k8s.io/api/admission/v1" "k8s.io/apimachinery/pkg/runtime" - log "sigs.k8s.io/controller-runtime/pkg/log" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -153,7 +153,7 @@ var pod = `{ func Test_AdmissionResponseValid(t *testing.T) { policyCache := policycache.NewCache() - logger := log.Log.WithName("Test_AdmissionResponseValid") + logger := log.WithName("Test_AdmissionResponseValid") ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -196,7 +196,7 @@ func Test_AdmissionResponseValid(t *testing.T) { func Test_AdmissionResponseInvalid(t *testing.T) { policyCache := policycache.NewCache() - logger := log.Log.WithName("Test_AdmissionResponseInvalid") + logger := log.WithName("Test_AdmissionResponseInvalid") ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -235,7 +235,7 @@ func Test_AdmissionResponseInvalid(t *testing.T) { func Test_ImageVerify(t *testing.T) { policyCache := policycache.NewCache() - logger := log.Log.WithName("Test_ImageVerify") + logger := log.WithName("Test_ImageVerify") ctx, cancel := context.WithCancel(context.Background()) defer cancel() diff --git a/pkg/webhooks/resource/validation_test.go b/pkg/webhooks/resource/validation_test.go index 692332776f..2141af6ec4 100644 --- a/pkg/webhooks/resource/validation_test.go +++ b/pkg/webhooks/resource/validation_test.go @@ -5,7 +5,7 @@ import ( "fmt" "testing" - log "sigs.k8s.io/controller-runtime/pkg/log" + log "github.com/kyverno/kyverno/pkg/logging" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" "github.com/kyverno/kyverno/pkg/engine" @@ -540,7 +540,7 @@ func TestValidate_failure_action_overrides(t *testing.T) { } failurePolicy := kyvernov1.Fail - blocked := webhookutils.BlockRequest([]*response.EngineResponse{er}, failurePolicy, log.Log.WithName("WebhookServer")) + blocked := webhookutils.BlockRequest([]*response.EngineResponse{er}, failurePolicy, log.WithName("WebhookServer")) assert.Assert(t, tc.blocked == blocked) }) } @@ -594,7 +594,7 @@ func Test_RuleSelector(t *testing.T) { assert.Assert(t, resp.PolicyResponse.RulesAppliedCount == 2) assert.Assert(t, resp.PolicyResponse.RulesErrorCount == 0) - log := log.Log.WithName("Test_RuleSelector") + log := log.WithName("Test_RuleSelector") blocked := webhookutils.BlockRequest([]*response.EngineResponse{resp}, kyvernov1.Fail, log) assert.Assert(t, blocked == true) diff --git a/pkg/webhooks/updaterequest/log.go b/pkg/webhooks/updaterequest/log.go index b0dc6feca2..d60021a46d 100644 --- a/pkg/webhooks/updaterequest/log.go +++ b/pkg/webhooks/updaterequest/log.go @@ -1,5 +1,5 @@ package updaterequest -import "sigs.k8s.io/controller-runtime/pkg/log" +import "github.com/kyverno/kyverno/pkg/logging" -var logger = log.Log.WithName("updaterequest-generator") +var logger = logging.WithName("updaterequest-generator") diff --git a/test/e2e/mutate/mutate_test.go b/test/e2e/mutate/mutate_test.go index 4b04ff47bc..6bcb841467 100644 --- a/test/e2e/mutate/mutate_test.go +++ b/test/e2e/mutate/mutate_test.go @@ -8,13 +8,13 @@ import ( "time" "github.com/kyverno/kyverno/pkg/engine/validate" + "github.com/kyverno/kyverno/pkg/logging" "github.com/kyverno/kyverno/test/e2e" commonE2E "github.com/kyverno/kyverno/test/e2e/common" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "gopkg.in/yaml.v2" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" - "sigs.k8s.io/controller-runtime/pkg/log" ) var ( @@ -216,7 +216,7 @@ func Test_Mutate(t *testing.T) { Expect(err).NotTo(HaveOccurred()) By("Validating created resource with the expected pattern...") - err = validate.MatchPattern(log.Log, actual, expected) + err = validate.MatchPattern(logging.GlobalLogger(), actual, expected) Expect(err).NotTo(HaveOccurred()) By("Deleting Cluster Policies...") @@ -439,7 +439,7 @@ func Test_Mutate_Existing(t *testing.T) { Expect(err).NotTo(HaveOccurred()) By("Validating created resource with the expected pattern...") - err = validate.MatchPattern(log.Log, actual, expected) + err = validate.MatchPattern(logging.GlobalLogger(), actual, expected) Expect(err).NotTo(HaveOccurred()) case deleteTrigger: @@ -486,7 +486,7 @@ func Test_Mutate_Existing(t *testing.T) { Expect(err).NotTo(HaveOccurred()) By("Validating created resource with the expected pattern...") - err = validate.MatchPattern(log.Log, actual, expected) + err = validate.MatchPattern(logging.GlobalLogger(), actual, expected) Expect(err).NotTo(HaveOccurred()) case createPolicy: @@ -530,7 +530,7 @@ func Test_Mutate_Existing(t *testing.T) { Expect(err).NotTo(HaveOccurred()) By("Validating created resource with the expected pattern...") - err = validate.MatchPattern(log.Log, actual, expected) + err = validate.MatchPattern(logging.GlobalLogger(), actual, expected) Expect(err).NotTo(HaveOccurred()) }