1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00

add package logger in files (#4766)

* add package logger in files

Signed-off-by: damilola olayinka <holayinkajr@gmail.com>

* add package logger to initContainer and other files

Signed-off-by: damilola olayinka <holayinkajr@gmail.com>

* helm docs

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>

* helm default values

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>

* release notes

Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>

Signed-off-by: damilola olayinka <holayinkajr@gmail.com>
Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
This commit is contained in:
yinka 2022-10-02 20:45:03 +01:00 committed by GitHub
parent 6e64d4fb1a
commit 688b4fb8e3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
67 changed files with 394 additions and 371 deletions

View file

@ -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 image.tag=$(IMAGE_TAG_DEV) \
--set initImage.repository=$(LOCAL_KYVERNOPRE_IMAGE) \ --set initImage.repository=$(LOCAL_KYVERNOPRE_IMAGE) \
--set initImage.tag=$(IMAGE_TAG_DEV) \ --set initImage.tag=$(IMAGE_TAG_DEV) \
--set initContainer.extraArgs={--loggingFormat=text}
--set "extraArgs={--autogenInternals=true,--loggingFormat=text}" --set "extraArgs={--autogenInternals=true,--loggingFormat=text}"
@echo Restart kyverno pods... >&2 @echo Restart kyverno pods... >&2
@kubectl rollout restart deployment -n kyverno kyverno @kubectl rollout restart deployment -n kyverno kyverno

View file

@ -1,16 +1,16 @@
package v1 package v1
import ( import (
log "github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/apimachinery/pkg/util/validation/field"
log "sigs.k8s.io/controller-runtime/pkg/log"
) )
func FromJSON(in *apiextv1.JSON) apiextensions.JSON { func FromJSON(in *apiextv1.JSON) apiextensions.JSON {
var out apiextensions.JSON var out apiextensions.JSON
if err := apiextv1.Convert_v1_JSON_To_apiextensions_JSON(in, &out, nil); err != nil { 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 return out
} }
@ -21,7 +21,7 @@ func ToJSON(in apiextensions.JSON) *apiextv1.JSON {
} }
var out apiextv1.JSON var out apiextv1.JSON
if err := apiextv1.Convert_apiextensions_JSON_To_v1_JSON(&in, &out, nil); err != nil { 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 return &out
} }

View file

@ -27,9 +27,9 @@ annotations:
# valid kinds are: added, changed, deprecated, removed, fixed and security # valid kinds are: added, changed, deprecated, removed, fixed and security
artifacthub.io/changes: | artifacthub.io/changes: |
- kind: added - kind: added
description: Added possibility to define additional init and sidecar container description: Added possibility to define additional init and sidecar container.
- kind: added - kind: added
description: Added ability to remove namespaces from default resourceFilters list description: Added ability to remove namespaces from default resourceFilters list.
- kind: added - kind: added
description: Prevent installing Kyverno in namespace kube-system. description: Prevent installing Kyverno in namespace kube-system.
- kind: fixed - kind: fixed
@ -38,3 +38,5 @@ annotations:
description: Enable autogen internals by default. description: Enable autogen internals by default.
- kind: fixed - kind: fixed
description: Self signed certificates not using SANs. description: Self signed certificates not using SANs.
- kind: added
description: Extra args support for init container.

View file

@ -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.repository | string | `"ghcr.io/kyverno/kyvernopre"` | Image repository |
| initImage.tag | string | `nil` | Image tag If initImage.tag is missing, defaults to image.tag | | 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 | | 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.repository | string | `nil` | Image repository Defaults to `busybox` if omitted |
| testImage.tag | string | `nil` | Image tag Defaults to `latest` 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 | | 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. | | 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. | | envVarsInit | object | `{}` | Env variables for initContainers. |
| envVars | object | `{}` | Env variables for containers. | | 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 | | extraInitContainers | list | `[]` | Array of extra init containers |
| extraContainers | list | `[]` | Array of extra containers to run alongside kyverno | | 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. | | imagePullSecrets | object | `{}` | Image pull secrets for image verify and imageData policies. This will define the `--imagePullSecrets` Kyverno argument. |

View file

@ -71,6 +71,10 @@ spec:
- name: kyverno-pre - name: kyverno-pre
image: {{ .Values.initImage.repository }}:{{ default .Chart.AppVersion (default .Values.image.tag .Values.initImage.tag) }} image: {{ .Values.initImage.repository }}:{{ default .Chart.AppVersion (default .Values.image.tag .Values.initImage.tag) }}
imagePullPolicy: {{ default .Values.image.pullPolicy .Values.initImage.pullPolicy }} imagePullPolicy: {{ default .Values.image.pullPolicy .Values.initImage.pullPolicy }}
{{- if .Values.initContainer.extraArgs }}
args:
{{ tpl (toYaml .Values.initContainer.extraArgs) . }}
{{- end }}
{{- with .Values.initResources }} {{- with .Values.initResources }}
resources: {{ tpl (toYaml .) $ | nindent 12 }} resources: {{ tpl (toYaml .) $ | nindent 12 }}
{{- end }} {{- end }}

View file

@ -44,6 +44,12 @@ initImage:
# If initImage.pullPolicy is missing, defaults to image.pullPolicy # If initImage.pullPolicy is missing, defaults to image.pullPolicy
pullPolicy: pullPolicy:
initContainer:
# -- Extra arguments to give to the kyvernopre binary.
extraArgs:
- --loggingFormat=text
testImage: testImage:
# -- Image repository # -- Image repository
# Defaults to `busybox` if omitted # Defaults to `busybox` if omitted
@ -142,6 +148,7 @@ envVars: {}
# -- Extra arguments to give to the binary. # -- Extra arguments to give to the binary.
extraArgs: extraArgs:
- --autogenInternals=true - --autogenInternals=true
- --loggingFormat=text
# -- Array of extra init containers # -- Array of extra init containers
extraInitContainers: [] extraInitContainers: []

View file

@ -7,6 +7,7 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"flag" "flag"
"fmt"
"os" "os"
"os/signal" "os/signal"
"sync" "sync"
@ -18,6 +19,7 @@ import (
"github.com/kyverno/kyverno/pkg/clients/dclient" "github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config" "github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/leaderelection" "github.com/kyverno/kyverno/pkg/leaderelection"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/tls" "github.com/kyverno/kyverno/pkg/tls"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
"go.uber.org/multierr" "go.uber.org/multierr"
@ -26,16 +28,14 @@ import (
"k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var ( var (
kubeconfig string kubeconfig string
setupLog = log.Log.WithName("setup") setupLog = logging.WithName("setup")
clientRateLimitQPS float64 clientRateLimitQPS float64
clientRateLimitBurst int clientRateLimitBurst int
logFormat string
) )
const ( const (
@ -44,23 +44,31 @@ const (
convertGenerateRequest string = "ConvertGenerateRequest" convertGenerateRequest string = "ConvertGenerateRequest"
) )
func main() { func parseFlags() error {
// clear flags initialized in static dependencies logging.Init(nil)
if flag.CommandLine.Lookup("log_dir") != nil { flag.StringVar(&logFormat, "loggingFormat", logging.TextFormat, "This determines the output format of the logger.")
flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
}
klog.InitFlags(nil) // add the block above before invoking klog.InitFlags()
log.SetLogger(klogr.New())
flag.StringVar(&kubeconfig, "kubeconfig", "", "Path to a kubeconfig. Only required if out-of-cluster.") 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.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.") 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 { if err := flag.Set("v", "2"); err != nil {
klog.Fatalf("failed to set log level: %v", err) return err
} }
flag.Parse() 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 // os signal handler
signalCtx, signalCancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) signalCtx, signalCancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer signalCancel() defer signalCancel()
@ -95,7 +103,7 @@ func main() {
} }
// Exit for unsupported version of kubernetes cluster // 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) os.Exit(1)
} }
@ -118,7 +126,7 @@ func main() {
name := tls.GenerateRootCASecretName() name := tls.GenerateRootCASecretName()
_, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{}) _, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil { 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) { if !errors.IsNotFound(err) {
os.Exit(1) os.Exit(1)
} }
@ -127,14 +135,14 @@ func main() {
name = tls.GenerateTLSPairSecretName() name = tls.GenerateTLSPairSecretName()
_, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{}) _, err = kubeClient.CoreV1().Secrets(config.KyvernoNamespace()).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil { 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) { if !errors.IsNotFound(err) {
os.Exit(1) os.Exit(1)
} }
} }
if err = acquireLeader(signalCtx, kubeClient); err != nil { 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) os.Exit(1)
} }
@ -148,19 +156,19 @@ func main() {
for err := range merge(done, stopCh, p1, p2) { for err := range merge(done, stopCh, p1, p2) {
if err != nil { if err != nil {
failure = true 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 there is any failure then we fail process
if failure { 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(1)
} }
os.Exit(0) 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 { if err != nil {
setupLog.Error(err, "failed to elect a leader") setupLog.Error(err, "failed to elect a leader")
os.Exit(1) os.Exit(1)
@ -172,9 +180,9 @@ func main() {
func acquireLeader(ctx context.Context, kubeClient kubernetes.Interface) error { func acquireLeader(ctx context.Context, kubeClient kubernetes.Interface) error {
_, err := kubeClient.CoordinationV1().Leases(config.KyvernoNamespace()).Get(ctx, "kyvernopre-lock", metav1.GetOptions{}) _, err := kubeClient.CoordinationV1().Leases(config.KyvernoNamespace()).Get(ctx, "kyvernopre-lock", metav1.GetOptions{})
if err != nil { 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 { } else {
log.Log.V(2).Info("Leader was elected, quitting") logging.V(2).Info("Leader was elected, quitting")
os.Exit(0) os.Exit(0)
} }
@ -231,7 +239,7 @@ func gen(done <-chan struct{}, stopCh <-chan struct{}, requests ...request) <-ch
// processes the requests // processes the requests
func process(client dclient.Interface, kyvernoclient kyvernoclient.Interface, done <-chan struct{}, stopCh <-chan struct{}, requests <-chan request) <-chan error { 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) out := make(chan error)
go func() { go func() {
defer close(out) 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 // waits for all processes to be complete and merges result
func merge(done <-chan struct{}, stopCh <-chan struct{}, processes ...<-chan error) <-chan error { 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 var wg sync.WaitGroup
out := make(chan error) out := make(chan error)
// gets the output from each process // 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 { func convertGR(pclient kyvernoclient.Interface) error {
logger := log.Log.WithName("convertGenerateRequest") logger := logging.WithName("convertGenerateRequest")
var errors []error var errors []error
grs, err := pclient.KyvernoV1().GenerateRequests(config.KyvernoNamespace()).List(context.TODO(), metav1.ListOptions{}) grs, err := pclient.KyvernoV1().GenerateRequests(config.KyvernoNamespace()).List(context.TODO(), metav1.ListOptions{})

View file

@ -94,7 +94,7 @@ var (
func parseFlags() error { func parseFlags() error {
logging.Init(nil) 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(&webhookTimeout, "webhookTimeout", int(webhookconfig.DefaultWebhookTimeout), "Timeout for webhook configurations.")
flag.IntVar(&genWorkers, "genWorkers", 10, "Workers for generate controller.") flag.IntVar(&genWorkers, "genWorkers", 10, "Workers for generate controller.")
flag.IntVar(&maxQueuedEvents, "maxQueuedEvents", 1000, "Maximum events to be queued.") flag.IntVar(&maxQueuedEvents, "maxQueuedEvents", 1000, "Maximum events to be queued.")

View file

@ -1,5 +1,5 @@
package auth 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")

View file

@ -1,5 +1,5 @@
package autogen 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")

View file

@ -7,10 +7,10 @@ import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
pkglabels "k8s.io/apimachinery/pkg/labels" pkglabels "k8s.io/apimachinery/pkg/labels"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
type Object interface { type Object interface {
@ -76,7 +76,7 @@ func managedBy(labels map[string]string) {
val, ok := labels[key] val, ok := labels[key]
if ok { if ok {
if val != value { 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 return
} }
} }
@ -104,7 +104,7 @@ func checkGeneratedBy(labels map[string]string, key, value string) {
val, ok := labels[key] val, ok := labels[key]
if ok { if ok {
if val != value { 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 return
} }
} }

View file

@ -9,10 +9,10 @@ import (
"github.com/kyverno/kyverno/pkg/client/clientset/versioned" "github.com/kyverno/kyverno/pkg/client/clientset/versioned"
kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1" kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/config" "github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/logging"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/util/retry" "k8s.io/client-go/util/retry"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var DefaultRetry = wait.Backoff{ var DefaultRetry = wait.Backoff{
@ -27,21 +27,21 @@ func Update(client versioned.Interface, urLister kyvernov1beta1listers.UpdateReq
err := retry.RetryOnConflict(DefaultRetry, func() error { err := retry.RetryOnConflict(DefaultRetry, func() error {
ur, err := urLister.Get(name) ur, err := urLister.Get(name)
if err != nil { 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 return err
} }
ur = ur.DeepCopy() ur = ur.DeepCopy()
mutator(ur) mutator(ur)
_, err = client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Update(context.TODO(), ur, metav1.UpdateOptions{}) _, err = client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Update(context.TODO(), ur, metav1.UpdateOptions{})
if err != nil { 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 return err
}) })
if err != nil { 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 { } 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 return ur, err
} }
@ -51,7 +51,7 @@ func UpdateStatus(client versioned.Interface, urLister kyvernov1beta1listers.Upd
err := retry.RetryOnConflict(DefaultRetry, func() error { err := retry.RetryOnConflict(DefaultRetry, func() error {
ur, err := urLister.Get(name) ur, err := urLister.Get(name)
if err != nil { 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 return err
} }
ur = ur.DeepCopy() 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{}) _, err = client.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), ur, metav1.UpdateOptions{})
if err != nil { 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
} }
return err return err
}) })
if err != nil { 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 { } 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 return ur, err
} }

View file

@ -8,7 +8,7 @@ import (
"github.com/go-logr/logr" "github.com/go-logr/logr"
"github.com/kyverno/kyverno/pkg/engine/common" "github.com/kyverno/kyverno/pkg/engine/common"
"github.com/kyverno/kyverno/pkg/engine/wildcards" "github.com/kyverno/kyverno/pkg/engine/wildcards"
"sigs.k8s.io/controller-runtime/pkg/log" "github.com/kyverno/kyverno/pkg/logging"
) )
type Handler struct { type Handler struct {
@ -147,7 +147,7 @@ func (dh Handler) Handle(handler resourceElementHandler, resourceMap map[string]
} else if dh.pattern == "*" && resourceMap[dh.element] == nil { } 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) return dh.path, fmt.Errorf("failed at path %s, field %s is not present", dh.path, dh.element)
} else { } 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 { if err != nil {
return path, err return path, err
} }

View file

@ -1,5 +1,5 @@
package background 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")

View file

@ -1,5 +1,5 @@
package dclient 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")

View file

@ -11,11 +11,11 @@ import (
kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1" kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/clients/dclient" "github.com/kyverno/kyverno/pkg/clients/dclient"
enginutils "github.com/kyverno/kyverno/pkg/engine/utils" enginutils "github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/pkg/errors" "github.com/pkg/errors"
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors" apierrors "k8s.io/apimachinery/pkg/api/errors"
corev1listers "k8s.io/client-go/listers/core/v1" corev1listers "k8s.io/client-go/listers/core/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// Policy Reporting Types // Policy Reporting Types
@ -30,7 +30,7 @@ func GetNamespaceSelectorsFromNamespaceLister(kind, namespaceOfResource string,
if kind != "Namespace" && namespaceOfResource != "" { if kind != "Namespace" && namespaceOfResource != "" {
namespaceObj, err := nsLister.Get(namespaceOfResource) namespaceObj, err := nsLister.Get(namespaceOfResource)
if err != nil { 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 namespaceLabels
} }
return GetNamespaceLabels(namespaceObj, logger) return GetNamespaceLabels(namespaceObj, logger)

View file

@ -1,5 +1,5 @@
package config 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")

View file

@ -1,7 +1,7 @@
package certmanager package certmanager
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "certmanager-controller" const controllerName = "certmanager-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package config package config
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "config-controller" const controllerName = "config-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package policycache package policycache
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "policycache-controller" const controllerName = "policycache-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package admission package admission
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "admission-report-controller" const controllerName = "admission-report-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package aggregate package aggregate
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "aggregate-report-controller" const controllerName = "aggregate-report-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package background package background
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "background-scan-controller" const controllerName = "background-scan-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,7 +1,7 @@
package resource package resource
import "sigs.k8s.io/controller-runtime/pkg/log" import "github.com/kyverno/kyverno/pkg/logging"
const controllerName = "resource-report-controller" const controllerName = "resource-report-controller"
var logger = log.Log.WithName(controllerName) var logger = logging.WithName(controllerName)

View file

@ -1,5 +1,5 @@
package cosign 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")

View file

@ -5,7 +5,7 @@ import (
"strconv" "strconv"
"github.com/go-logr/logr" "github.com/go-logr/logr"
"sigs.k8s.io/controller-runtime/pkg/log" "github.com/kyverno/kyverno/pkg/logging"
) )
// ValidationHandler for element processes // ValidationHandler for element processes
@ -86,7 +86,7 @@ func (eh EqualityHandler) Handle(handler resourceElementHandler, resourceMap map
// check if anchor is present in resource // check if anchor is present in resource
if value, ok := resourceMap[anchorKey]; ok { if value, ok := resourceMap[anchorKey]; ok {
// validate the values of the pattern // 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 { if err != nil {
return returnPath, err return returnPath, err
} }
@ -119,7 +119,7 @@ func (dh DefaultHandler) Handle(handler resourceElementHandler, resourceMap map[
} else if dh.pattern == "*" && resourceMap[dh.element] == nil { } else if dh.pattern == "*" && resourceMap[dh.element] == nil {
return dh.path, fmt.Errorf("%s/%s not found", dh.path, dh.element) return dh.path, fmt.Errorf("%s/%s not found", dh.path, dh.element)
} else { } 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 { if err != nil {
return path, err return path, err
} }
@ -150,7 +150,7 @@ func (ch ConditionAnchorHandler) Handle(handler resourceElementHandler, resource
// check if anchor is present in resource // check if anchor is present in resource
if value, ok := resourceMap[anchorKey]; ok { if value, ok := resourceMap[anchorKey]; ok {
// validate the values of the pattern // 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 { if err != nil {
ac.AnchorError = NewConditionalAnchorError(err.Error()) ac.AnchorError = NewConditionalAnchorError(err.Error())
return returnPath, ac.AnchorError.Error() return returnPath, ac.AnchorError.Error()
@ -185,7 +185,7 @@ func (gh GlobalAnchorHandler) Handle(handler resourceElementHandler, resourceMap
// check if anchor is present in resource // check if anchor is present in resource
if value, ok := resourceMap[anchorKey]; ok { if value, ok := resourceMap[anchorKey]; ok {
// validate the values of the pattern // 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 { if err != nil {
ac.AnchorError = NewGlobalAnchorError(err.Error()) ac.AnchorError = NewGlobalAnchorError(err.Error())
return returnPath, ac.AnchorError.Error() return returnPath, ac.AnchorError.Error()
@ -251,7 +251,7 @@ func validateExistenceListResource(handler resourceElementHandler, resourceList
// if non satisfy then throw an error // if non satisfy then throw an error
for i, resourceElement := range resourceList { for i, resourceElement := range resourceList {
currentPath := path + strconv.Itoa(i) + "/" 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 { if err == nil {
// condition is satisfied, dont check further // condition is satisfied, dont check further
return "", nil return "", nil

View file

@ -6,11 +6,11 @@ import (
v1 "github.com/kyverno/kyverno/api/kyverno/v1" v1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/context" "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/api"
"github.com/kyverno/kyverno/pkg/utils/image" "github.com/kyverno/kyverno/pkg/utils/image"
"gotest.tools/assert" "gotest.tools/assert"
apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var scanPredicate = ` var scanPredicate = `
@ -258,7 +258,7 @@ func Test_Conditions(t *testing.T) {
err := json.Unmarshal([]byte(scanPredicate), &dataMap) err := json.Unmarshal([]byte(scanPredicate), &dataMap)
assert.NilError(t, err) 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.NilError(t, err)
assert.Equal(t, pass, true) assert.Equal(t, pass, true)
} }

View file

@ -8,7 +8,7 @@ import (
"github.com/kyverno/kyverno/pkg/engine/common" "github.com/kyverno/kyverno/pkg/engine/common"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/variables" "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 // 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) { 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 return resp
} }
@ -83,7 +83,7 @@ func filterRule(rule kyvernov1.Rule, policyContext *PolicyContext) *response.Rul
excludeGroupRole := policyContext.ExcludeGroupRole excludeGroupRole := policyContext.ExcludeGroupRole
namespaceLabels := policyContext.NamespaceLabels 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()) "kind", newResource.GetKind(), "namespace", newResource.GetNamespace(), "name", newResource.GetName())
if err = MatchesResourceDescription(newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err != nil { if err = MatchesResourceDescription(newResource, rule, admissionInfo, excludeGroupRole, namespaceLabels, ""); err != nil {

View file

@ -5,15 +5,15 @@ import (
"testing" "testing"
"github.com/kyverno/kyverno/pkg/engine/operator" "github.com/kyverno/kyverno/pkg/engine/operator"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func TestValidateValueWithPattern_Bool(t *testing.T) { func TestValidateValueWithPattern_Bool(t *testing.T) {
assert.Assert(t, ValidateValueWithPattern(log.Log, true, true)) assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), true, true))
assert.Assert(t, !ValidateValueWithPattern(log.Log, true, false)) assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), true, false))
assert.Assert(t, !ValidateValueWithPattern(log.Log, false, true)) assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), false, true))
assert.Assert(t, ValidateValueWithPattern(log.Log, false, false)) assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), false, false))
} }
func TestValidateString_AsteriskTest(t *testing.T) { func TestValidateString_AsteriskTest(t *testing.T) {
@ -21,8 +21,8 @@ func TestValidateString_AsteriskTest(t *testing.T) {
value := "anything" value := "anything"
empty := "" empty := ""
assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal))
assert.Assert(t, validateString(log.Log, empty, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), empty, pattern, operator.Equal))
} }
func TestValidateString_LeftAsteriskTest(t *testing.T) { func TestValidateString_LeftAsteriskTest(t *testing.T) {
@ -30,32 +30,32 @@ func TestValidateString_LeftAsteriskTest(t *testing.T) {
value := "leftright" value := "leftright"
right := "right" right := "right"
assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal))
assert.Assert(t, validateString(log.Log, right, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), right, pattern, operator.Equal))
value = "leftmiddle" value = "leftmiddle"
middle := "middle" middle := "middle"
assert.Assert(t, !validateString(log.Log, value, pattern, operator.Equal)) assert.Assert(t, !validateString(logging.GlobalLogger(), value, pattern, operator.Equal))
assert.Assert(t, !validateString(log.Log, middle, pattern, operator.Equal)) assert.Assert(t, !validateString(logging.GlobalLogger(), middle, pattern, operator.Equal))
} }
func TestValidateString_MiddleAsteriskTest(t *testing.T) { func TestValidateString_MiddleAsteriskTest(t *testing.T) {
pattern := "ab*ba" pattern := "ab*ba"
value := "abbeba" value := "abbeba"
assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal))
value = "abbca" 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) { func TestValidateString_QuestionMark(t *testing.T) {
pattern := "ab?ba" pattern := "ab?ba"
value := "abbba" value := "abbba"
assert.Assert(t, validateString(log.Log, value, pattern, operator.Equal)) assert.Assert(t, validateString(logging.GlobalLogger(), value, pattern, operator.Equal))
value = "abbbba" 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) { func TestValidateValueWithPattern_BoolInJson(t *testing.T) {
@ -77,7 +77,7 @@ func TestValidateValueWithPattern_BoolInJson(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_NullPatternStringValue(t *testing.T) {
@ -99,7 +99,7 @@ func TestValidateValueWithPattern_NullPatternStringValue(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_NullPatternDefaultString(t *testing.T) {
@ -121,7 +121,7 @@ func TestValidateValueWithPattern_NullPatternDefaultString(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_NullPatternDefaultFloat(t *testing.T) {
@ -143,7 +143,7 @@ func TestValidateValueWithPattern_NullPatternDefaultFloat(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_NullPatternDefaultInt(t *testing.T) {
@ -165,7 +165,7 @@ func TestValidateValueWithPattern_NullPatternDefaultInt(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_NullPatternDefaultBool(t *testing.T) {
@ -187,93 +187,93 @@ func TestValidateValueWithPattern_NullPatternDefaultBool(t *testing.T) {
err = json.Unmarshal(rawValue, &value) err = json.Unmarshal(rawValue, &value)
assert.Assert(t, err) 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) { func TestValidateValueWithPattern_StringsLogicalOr(t *testing.T) {
pattern := "192.168.88.1 | 10.100.11.*" pattern := "192.168.88.1 | 10.100.11.*"
value := "10.100.11.54" 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) { func TestValidateValueWithPattern_StringsLogicalAnd(t *testing.T) {
pattern := ">1 & <20" pattern := ">1 & <20"
value := "10" value := "10"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern))
} }
func TestValidateValueWithPattern_StringsAllLogicalOperators(t *testing.T) { func TestValidateValueWithPattern_StringsAllLogicalOperators(t *testing.T) {
pattern := ">1 & <20 | >31 & <33" pattern := ">1 & <20 | >31 & <33"
value := "10" value := "10"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern))
value = "32" value = "32"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern)) assert.Assert(t, ValidateValueWithPattern(logging.GlobalLogger(), value, pattern))
value = "21" value = "21"
assert.Assert(t, !ValidateValueWithPattern(log.Log, value, pattern)) assert.Assert(t, !ValidateValueWithPattern(logging.GlobalLogger(), value, pattern))
} }
func TestValidateValueWithPattern_EqualTwoFloats(t *testing.T) { 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) { 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) { func TestValidateValueWithNilPattern_NullPatternDefaultString(t *testing.T) {
assert.Assert(t, validateValueWithNilPattern(log.Log, "")) assert.Assert(t, validateValueWithNilPattern(logging.GlobalLogger(), ""))
} }
func TestValidateValueWithNilPattern_NullPatternDefaultFloat(t *testing.T) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { 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) { func TestGetNumberAndStringPartsFromPattern_NumberAndString(t *testing.T) {
@ -307,75 +307,75 @@ func TestGetNumberAndStringPartsFromPattern_Empty(t *testing.T) {
} }
func TestValidateValueWithStringPattern_WithSpace(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) { func TestValidateValueWithStringPattern_Ranges(t *testing.T) {
assert.Assert(t, validateValueWithStringPattern(log.Log, 0, "0-2")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 0, "0-2"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 1, "0-2")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 1, "0-2"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 2, "0-2")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2, "0-2"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, 3, "0-2")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 3, "0-2"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 0, "10!-20")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 0, "10!-20"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, 15, "10!-20")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 15, "10!-20"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 25, "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(logging.GlobalLogger(), 0, "0.00001-2.00001"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 1, "0.00001-2.00001")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 1, "0.00001-2.00001"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 2, "0.00001-2.00001")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2, "0.00001-2.00001"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, 2.0001, "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(logging.GlobalLogger(), 0, "0.00001!-2.00001"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, 1, "0.00001!-2.00001")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 1, "0.00001!-2.00001"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, 2, "0.00001!-2.00001")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), 2, "0.00001!-2.00001"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 2.0001, "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(logging.GlobalLogger(), 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(log.Log, 2.99999, "2.99998-3")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2.99999, "2.99998-3"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 2.99997, "2.99998!-3")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), 2.99997, "2.99998!-3"))
assert.Assert(t, validateValueWithStringPattern(log.Log, 3.00001, "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(logging.GlobalLogger(), "256Mi", "128Mi-512Mi"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, "1024Mi", "128Mi-512Mi")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "1024Mi", "128Mi-512Mi"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, "64Mi", "128Mi-512Mi")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "64Mi", "128Mi-512Mi"))
assert.Assert(t, !validateValueWithStringPattern(log.Log, "256Mi", "128Mi!-512Mi")) assert.Assert(t, !validateValueWithStringPattern(logging.GlobalLogger(), "256Mi", "128Mi!-512Mi"))
assert.Assert(t, validateValueWithStringPattern(log.Log, "1024Mi", "128Mi!-512Mi")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "1024Mi", "128Mi!-512Mi"))
assert.Assert(t, validateValueWithStringPattern(log.Log, "64Mi", "128Mi!-512Mi")) assert.Assert(t, validateValueWithStringPattern(logging.GlobalLogger(), "64Mi", "128Mi!-512Mi"))
} }
func TestValidateNumberWithStr_LessFloatAndInt(t *testing.T) { func TestValidateNumberWithStr_LessFloatAndInt(t *testing.T) {
assert.Assert(t, validateNumberWithStr(log.Log, 7.00001, "7.000001", operator.More)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 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", operator.NotEqual))
assert.Assert(t, validateNumberWithStr(log.Log, 7.0000, "7", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 7.0000, "7", operator.Equal))
assert.Assert(t, !validateNumberWithStr(log.Log, 6.000000001, "6", operator.Less)) assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), 6.000000001, "6", operator.Less))
} }
func TestValidateQuantity_InvalidQuantity(t *testing.T) { func TestValidateQuantity_InvalidQuantity(t *testing.T) {
assert.Assert(t, !validateNumberWithStr(log.Log, "1024Gi", "", operator.Equal)) assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "1024Gi", "", operator.Equal))
assert.Assert(t, !validateNumberWithStr(log.Log, "gii", "1024Gi", operator.Equal)) assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "gii", "1024Gi", operator.Equal))
} }
func TestValidateQuantity_Equal(t *testing.T) { func TestValidateQuantity_Equal(t *testing.T) {
assert.Assert(t, validateNumberWithStr(log.Log, "1024Gi", "1024Gi", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1024Gi", "1024Gi", operator.Equal))
assert.Assert(t, validateNumberWithStr(log.Log, "1024Mi", "1Gi", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1024Mi", "1Gi", operator.Equal))
assert.Assert(t, validateNumberWithStr(log.Log, "0.2", "200m", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", "200m", operator.Equal))
assert.Assert(t, validateNumberWithStr(log.Log, "500", "500", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "500", "500", operator.Equal))
assert.Assert(t, !validateNumberWithStr(log.Log, "2048", "1024", operator.Equal)) assert.Assert(t, !validateNumberWithStr(logging.GlobalLogger(), "2048", "1024", operator.Equal))
assert.Assert(t, validateNumberWithStr(log.Log, 1024, "1024", operator.Equal)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), 1024, "1024", operator.Equal))
} }
func TestValidateQuantity_Operation(t *testing.T) { func TestValidateQuantity_Operation(t *testing.T) {
assert.Assert(t, validateNumberWithStr(log.Log, "1Gi", "1000Mi", operator.More)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1Gi", "1000Mi", operator.More))
assert.Assert(t, validateNumberWithStr(log.Log, "1G", "1Gi", operator.Less)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1G", "1Gi", operator.Less))
assert.Assert(t, validateNumberWithStr(log.Log, "500m", "0.5", operator.MoreEqual)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "500m", "0.5", operator.MoreEqual))
assert.Assert(t, validateNumberWithStr(log.Log, "1", "500m", operator.MoreEqual)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "1", "500m", operator.MoreEqual))
assert.Assert(t, validateNumberWithStr(log.Log, "0.5", ".5", operator.LessEqual)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.5", ".5", operator.LessEqual))
assert.Assert(t, validateNumberWithStr(log.Log, "0.2", ".5", operator.LessEqual)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", ".5", operator.LessEqual))
assert.Assert(t, validateNumberWithStr(log.Log, "0.2", ".5", operator.NotEqual)) assert.Assert(t, validateNumberWithStr(logging.GlobalLogger(), "0.2", ".5", operator.NotEqual))
} }
func TestGetOperatorFromStringPattern_OneChar(t *testing.T) { func TestGetOperatorFromStringPattern_OneChar(t *testing.T) {
@ -387,9 +387,9 @@ func TestGetOperatorFromStringPattern_EmptyString(t *testing.T) {
} }
func TestValidateKernelVersion_NotEquals(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(logging.GlobalLogger(), "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, !validateValueWithStringPattern(logging.GlobalLogger(), "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(logging.GlobalLogger(), "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(logging.GlobalLogger(), "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, !validateValueWithStringPatterns(logging.GlobalLogger(), "5.15.2-1", "!5.10.84-1 & !5.15.2-1"))
} }

View file

@ -8,14 +8,14 @@ import (
jsonpatch "github.com/evanphx/json-patch/v5" jsonpatch "github.com/evanphx/json-patch/v5"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/logging"
apiutils "github.com/kyverno/kyverno/pkg/utils/api" apiutils "github.com/kyverno/kyverno/pkg/utils/api"
"github.com/pkg/errors" "github.com/pkg/errors"
admissionv1 "k8s.io/api/admission/v1" admissionv1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "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 // EvalInterface is used to query and inspect context data
type EvalInterface interface { type EvalInterface interface {
@ -262,7 +262,7 @@ func (ctx *context) AddImageInfos(resource *unstructured.Unstructured) error {
} }
ctx.images = images 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") return addToContext(ctx, images, "images")
} }

View file

@ -8,14 +8,14 @@ import (
"github.com/kyverno/kyverno/pkg/engine/mutate" "github.com/kyverno/kyverno/pkg/engine/mutate"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "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 // ForceMutate does not check any conditions, it simply mutates the given resource
// It is used to validate mutation logic, and for tests. // It is used to validate mutation logic, and for tests.
func ForceMutate(ctx context.Interface, policy kyvernov1.PolicyInterface, resource unstructured.Unstructured) (unstructured.Unstructured, error) { 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()) "namespace", resource.GetNamespace(), "name", resource.GetName())
patchedResource := resource patchedResource := resource

View file

@ -6,8 +6,8 @@ import (
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1" kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/client-go/tools/cache" "k8s.io/client-go/tools/cache"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// GenerateResponse checks for validity of generate rule on the resource // 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() apiVersion := policyContext.NewResource.GetAPIVersion()
pNamespace, pName, err := cache.SplitMetaNamespaceKey(policyNameKey) pNamespace, pName, err := cache.SplitMetaNamespaceKey(policyNameKey)
if err != nil { 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{ resp := &response.EngineResponse{
@ -45,7 +45,7 @@ func filterGenerateRules(policyContext *PolicyContext, policyNameKey string, sta
} }
if policyContext.ExcludeResourceFunc(kind, namespace, name) { 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 return resp
} }

View file

@ -16,13 +16,13 @@ import (
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
engineUtils "github.com/kyverno/kyverno/pkg/engine/utils" engineUtils "github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/registryclient" "github.com/kyverno/kyverno/pkg/registryclient"
apiutils "github.com/kyverno/kyverno/pkg/utils/api" apiutils "github.com/kyverno/kyverno/pkg/utils/api"
"github.com/kyverno/kyverno/pkg/utils/wildcard" "github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors" "github.com/pkg/errors"
"go.uber.org/multierr" "go.uber.org/multierr"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineResponse, *ImageVerificationMetadata) { func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineResponse, *ImageVerificationMetadata) {
@ -31,7 +31,7 @@ func VerifyAndPatchImages(policyContext *PolicyContext) (*response.EngineRespons
policy := policyContext.Policy policy := policyContext.Policy
patchedResource := policyContext.NewResource 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()) "kind", patchedResource.GetKind(), "namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName())
startTime := time.Now() startTime := time.Now()

View file

@ -6,8 +6,8 @@ import (
"strings" "strings"
"testing" "testing"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1" kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/cosign" "github.com/kyverno/kyverno/pkg/cosign"
@ -564,18 +564,18 @@ func Test_ChangedAnnotation(t *testing.T) {
policyContext := buildContext(t, testPolicyGood, testResource, testResource) policyContext := buildContext(t, testPolicyGood, testResource, testResource)
hasChanged := hasImageVerifiedAnnotationChanged(policyContext, log.Log) hasChanged := hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
assert.Equal(t, hasChanged, false) assert.Equal(t, hasChanged, false)
policyContext = buildContext(t, testPolicyGood, newResource, testResource) policyContext = buildContext(t, testPolicyGood, newResource, testResource)
hasChanged = hasImageVerifiedAnnotationChanged(policyContext, log.Log) hasChanged = hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
assert.Equal(t, hasChanged, true) assert.Equal(t, hasChanged, true)
annotationOld := fmt.Sprintf("\"annotations\": {\"%s\": \"%s\"}", annotationKey, "false") annotationOld := fmt.Sprintf("\"annotations\": {\"%s\": \"%s\"}", annotationKey, "false")
oldResource := strings.ReplaceAll(testResource, "\"annotations\": {}", annotationOld) oldResource := strings.ReplaceAll(testResource, "\"annotations\": {}", annotationOld)
policyContext = buildContext(t, testPolicyGood, newResource, oldResource) policyContext = buildContext(t, testPolicyGood, newResource, oldResource)
hasChanged = hasImageVerifiedAnnotationChanged(policyContext, log.Log) hasChanged = hasImageVerifiedAnnotationChanged(policyContext, logging.GlobalLogger())
assert.Equal(t, hasChanged, true) 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, len(verifiedImages.Data), 1)
assert.Equal(t, verifiedImages.isVerified(image), true) 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.NilError(t, err)
assert.Equal(t, len(patches), 2) assert.Equal(t, len(patches), 2)
@ -607,7 +607,7 @@ func Test_MarkImageVerified(t *testing.T) {
json := patchedAnnotations[imageVerifyAnnotationKey] json := patchedAnnotations[imageVerifyAnnotationKey]
assert.Assert(t, json != "") assert.Assert(t, json != "")
verified, err := isImageVerified(resource, image, log.Log) verified, err := isImageVerified(resource, image, logging.GlobalLogger())
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, verified, true) assert.Equal(t, verified, true)
} }

View file

@ -10,9 +10,9 @@ import (
types "github.com/kyverno/kyverno/api/kyverno/v1" types "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
"github.com/kyverno/kyverno/pkg/engine/utils" "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) { 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 { if mutateResp.Status != response.RuleStatusPass {
return &response.RuleResponse{ return &response.RuleResponse{

View file

@ -7,9 +7,9 @@ import (
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/ghodss/yaml" "github.com/ghodss/yaml"
"github.com/kyverno/kyverno/pkg/logging"
assert "github.com/stretchr/testify/assert" assert "github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var inputBytes = []byte(` var inputBytes = []byte(`
@ -51,7 +51,7 @@ func TestTypeConversion(t *testing.T) {
jsonPatches, err := yaml.YAMLToJSON(patchesJSON6902) jsonPatches, err := yaml.YAMLToJSON(patchesJSON6902)
assert.Nil(t, err) assert.Nil(t, err)
// apply patches // 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) { if !assert.Equal(t, response.RuleStatusPass, resp.Status) {
t.Fatal(resp.Message) t.Fatal(resp.Message)
} }

View file

@ -4,15 +4,15 @@ import (
"fmt" "fmt"
"testing" "testing"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/mattbaird/jsonpatch" "github.com/mattbaird/jsonpatch"
assertnew "github.com/stretchr/testify/assert" assertnew "github.com/stretchr/testify/assert"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func Test_GeneratePatches(t *testing.T) { 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) assert.NilError(t, err)
expectedPatches := map[string]bool{ expectedPatches := map[string]bool{

View file

@ -6,10 +6,10 @@ import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/logging"
assertnew "github.com/stretchr/testify/assert" assertnew "github.com/stretchr/testify/assert"
"gotest.tools/assert" "gotest.tools/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func TestMergePatch(t *testing.T) { func TestMergePatch(t *testing.T) {
@ -163,7 +163,7 @@ func TestMergePatch(t *testing.T) {
for i, test := range testCases { for i, test := range testCases {
t.Logf("Running test %d...", i+1) 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.NilError(t, err)
assert.DeepEqual(t, toJSON(t, test.expected), toJSON(t, out)) 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) patchString, err := json.Marshal(overlayPatches)
assert.NilError(t, err) 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) assert.NilError(t, err)
var ep unstructured.Unstructured var ep unstructured.Unstructured

View file

@ -5,8 +5,8 @@ import (
"testing" "testing"
"github.com/kyverno/kyverno/pkg/engine/anchor" "github.com/kyverno/kyverno/pkg/engine/anchor"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
yaml "sigs.k8s.io/kustomize/kyaml/yaml" yaml "sigs.k8s.io/kustomize/kyaml/yaml"
) )
@ -842,7 +842,7 @@ func Test_preProcessStrategicMergePatch_multipleAnchors(t *testing.T) {
for i, test := range testCases { for i, test := range testCases {
t.Logf("Running test %d...", i) 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) assert.NilError(t, err)
output, err := preProcessedPolicy.MarshalJSON() output, err := preProcessedPolicy.MarshalJSON()
@ -904,7 +904,7 @@ func Test_CheckConditionAnchor_Matches(t *testing.T) {
pattern := yaml.MustParse(string(patternRaw)) pattern := yaml.MustParse(string(patternRaw))
resource := yaml.MustParse(string(resourceRaw)) resource := yaml.MustParse(string(resourceRaw))
err := checkCondition(log.Log, pattern, resource) err := checkCondition(logging.GlobalLogger(), pattern, resource)
assert.Equal(t, err, nil) assert.Equal(t, err, nil)
} }
@ -915,7 +915,7 @@ func Test_CheckConditionAnchor_DoesNotMatch(t *testing.T) {
pattern := yaml.MustParse(string(patternRaw)) pattern := yaml.MustParse(string(patternRaw))
resource := yaml.MustParse(string(resourceRaw)) 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/") 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)) pattern := yaml.MustParse(string(patternRaw))
resource := yaml.MustParse(string(resourceRaw)) resource := yaml.MustParse(string(resourceRaw))
err := validateConditions(log.Log, pattern, resource) err := validateConditions(logging.GlobalLogger(), pattern, resource)
assert.NilError(t, err) assert.NilError(t, err)
} }
@ -951,7 +951,7 @@ func Test_ValidateConditions_MapWithOneCondition_DoesNotMatch(t *testing.T) {
pattern := yaml.MustParse(string(patternRaw)) pattern := yaml.MustParse(string(patternRaw))
resource := yaml.MustParse(string(resourceRaw)) resource := yaml.MustParse(string(resourceRaw))
err := validateConditions(log.Log, pattern, resource) err := validateConditions(logging.GlobalLogger(), pattern, resource)
_, ok := err.(ConditionError) _, ok := err.(ConditionError)
assert.Assert(t, ok) assert.Assert(t, ok)
} }
@ -1088,7 +1088,7 @@ func Test_ConditionCheck_SeveralElementsMatchExceptOne(t *testing.T) {
pattern := yaml.MustParse(string(patternRaw)) pattern := yaml.MustParse(string(patternRaw))
containers := yaml.MustParse(string(containersRaw)) containers := yaml.MustParse(string(containersRaw))
err := preProcessPattern(log.Log, pattern, containers) err := preProcessPattern(logging.GlobalLogger(), pattern, containers)
assert.NilError(t, err) assert.NilError(t, err)
patternContainers := pattern.Field("containers") patternContainers := pattern.Field("containers")
@ -1141,7 +1141,7 @@ func Test_NonExistingKeyMustFailPreprocessing(t *testing.T) {
pattern := yaml.MustParse(string(rawPattern)) pattern := yaml.MustParse(string(rawPattern))
resource := yaml.MustParse(string(rawResource)) 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") 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) pattern := yaml.MustParse(rawPattern)
resource := yaml.MustParse(rawResource) resource := yaml.MustParse(rawResource)
err := preProcessPattern(log.Log, pattern, resource) err := preProcessPattern(logging.GlobalLogger(), pattern, resource)
assert.NilError(t, err) assert.NilError(t, err)
resultPattern, _ := pattern.String() resultPattern, _ := pattern.String()

View file

@ -12,8 +12,8 @@ import (
"github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/engine/mutate" "github.com/kyverno/kyverno/pkg/engine/mutate"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// Mutate performs mutation. Overlay first and then mutation patches // Mutate performs mutation. Overlay first and then mutation patches
@ -27,7 +27,7 @@ func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
ctx := policyContext.JSONContext ctx := policyContext.JSONContext
var skippedRules []string 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()) "namespace", matchedResource.GetNamespace(), "name", matchedResource.GetName())
logger.V(4).Info("start mutate policy processing", "startTime", startTime) 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() { if !policyContext.AdmissionOperation && rule.IsMutateExisting() {
policyContext := policyContext.Copy() policyContext := policyContext.Copy()
if err := policyContext.JSONContext.AddTargetResource(patchedResource.Object); err != nil { 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 continue
} }
} }

View file

@ -15,6 +15,7 @@ import (
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/engine/wildcards" "github.com/kyverno/kyverno/pkg/engine/wildcards"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -27,7 +28,6 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// EngineStats stores in the statistics for a single application of resource // 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) wildcards.ReplaceInSelector(labelSelector, resourceLabels)
selector, err := metav1.LabelSelectorAsSelector(labelSelector) selector, err := metav1.LabelSelectorAsSelector(labelSelector)
if err != nil { if err != nil {
log.Log.Error(err, "failed to build label selector") logging.Error(err, "failed to build label selector")
return false, err return false, err
} }

View file

@ -7,9 +7,9 @@ import (
jsonpatch "github.com/evanphx/json-patch/v5" jsonpatch "github.com/evanphx/json-patch/v5"
commonAnchor "github.com/kyverno/kyverno/pkg/engine/anchor" commonAnchor "github.com/kyverno/kyverno/pkg/engine/anchor"
"github.com/kyverno/kyverno/pkg/logging"
jsonutils "github.com/kyverno/kyverno/pkg/utils/json" jsonutils "github.com/kyverno/kyverno/pkg/utils/json"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "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 // 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...) joinedPatches := jsonutils.JoinPatches(patches...)
patch, err := jsonpatch.DecodePatch(joinedPatches) patch, err := jsonpatch.DecodePatch(joinedPatches)
if err != nil { 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 return resource, err
} }
patchedDocument, err := patch.Apply(resource) patchedDocument, err := patch.Apply(resource)
if err != nil { 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 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 return patchedDocument, err
} }

View file

@ -10,8 +10,8 @@ import (
"github.com/kyverno/kyverno/pkg/engine/anchor" "github.com/kyverno/kyverno/pkg/engine/anchor"
"github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func TestValidateMap(t *testing.T) { 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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) t.Log(path)
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/template/spec/containers/0/")
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
} }
@ -567,7 +567,7 @@ func TestValidateMap_livenessProbeIsNull(t *testing.T) {
err := json.Unmarshal(rawMap, &resource) err := json.Unmarshal(rawMap, &resource)
assert.NilError(t, err) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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, "")
// assert.Equal(t, path, "/1/object/0/key2/") // assert.Equal(t, path, "/1/object/0/key2/")
// assert.NilError(t, err) // 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
assert.Assert(t, err != nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
assert.Assert(t, err != nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
assert.Assert(t, err != nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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) 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.Equal(t, path, "")
assert.NilError(t, err) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
assert.Assert(t, err != nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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) 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.Equal(t, path, "")
assert.Assert(t, err == nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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, "")
assert.Assert(t, err == nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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) 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.Equal(t, path, "/spec/containers/0/image/")
assert.Assert(t, err != nil) 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(rawPattern, &pattern))
assert.Assert(t, json.Unmarshal(rawMap, &resource)) 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.Equal(t, path, "/spec/containers/0/resources/requests/memory/")
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
} }
@ -1291,7 +1291,7 @@ func TestValidateMapElement_OneElementInArrayNotPass(t *testing.T) {
err = json.Unmarshal(rawMap, &resource) err = json.Unmarshal(rawMap, &resource)
assert.NilError(t, err) 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.Equal(t, path, "/0/object/0/key2/")
assert.Assert(t, err != nil) assert.Assert(t, err != nil)
} }
@ -1349,7 +1349,7 @@ func testValidationPattern(t *testing.T, num string, patternBytes []byte, resour
err = json.Unmarshal(resourceBytes, &resource) err = json.Unmarshal(resourceBytes, &resource)
assert.NilError(t, err) 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) assert.Equal(t, p, path, num)
if nilErr { if nilErr {
assert.NilError(t, err, num) assert.NilError(t, err, num)
@ -1674,7 +1674,7 @@ func testMatchPattern(t *testing.T, testCase struct {
err = json.Unmarshal(testCase.resource, &resource) err = json.Unmarshal(testCase.resource, &resource)
assert.NilError(t, err) assert.NilError(t, err)
err = MatchPattern(log.Log, resource, pattern) err = MatchPattern(logging.GlobalLogger(), resource, pattern)
if testCase.status == response.RuleStatusPass { if testCase.status == response.RuleStatusPass {
assert.NilError(t, err, fmt.Sprintf("\nexpected pass - test: %s\npattern: %s\nresource: %s\n", testCase.name, pattern, resource)) assert.NilError(t, err, fmt.Sprintf("\nexpected pass - test: %s\npattern: %s\nresource: %s\n", testCase.name, pattern, resource))

View file

@ -17,6 +17,7 @@ import (
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/validate" "github.com/kyverno/kyverno/pkg/engine/validate"
"github.com/kyverno/kyverno/pkg/engine/variables" "github.com/kyverno/kyverno/pkg/engine/variables"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/pss" "github.com/kyverno/kyverno/pkg/pss"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -26,7 +27,6 @@ import (
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// Validate applies validation rules from policy on the resource // 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 { 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{}) { if reflect.DeepEqual(ctx.NewResource, unstructured.Unstructured{}) {
logger = logger.WithValues("kind", ctx.OldResource.GetKind(), "namespace", ctx.OldResource.GetNamespace(), "name", ctx.OldResource.GetName()) logger = logger.WithValues("kind", ctx.OldResource.GetKind(), "namespace", ctx.OldResource.GetNamespace(), "name", ctx.OldResource.GetName())
} else { } else {

View file

@ -6,8 +6,8 @@ import (
kyverno "github.com/kyverno/kyverno/api/kyverno/v1" kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/context" "github.com/kyverno/kyverno/pkg/engine/context"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func TestEvaluate(t *testing.T) { func TestEvaluate(t *testing.T) {
@ -378,7 +378,7 @@ func TestEvaluate(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
for _, tc := range testCases { 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) 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) err = json.Unmarshal(conditionJSON, &conditionMap)
assert.Nil(t, err) assert.Nil(t, err)
conditionWithResolvedVars, _ := SubstituteAllInPreconditions(log.Log, ctx, conditionMap) conditionWithResolvedVars, _ := SubstituteAllInPreconditions(logging.GlobalLogger(), ctx, conditionMap)
conditionJSON, err = json.Marshal(conditionWithResolvedVars) conditionJSON, err = json.Marshal(conditionWithResolvedVars)
assert.Nil(t, err) assert.Nil(t, err)
err = json.Unmarshal(conditionJSON, &condition) err = json.Unmarshal(conditionJSON, &condition)
assert.Nil(t, err) 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) { 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"), RawValue: kyverno.ToJSON("temp1"),
} }
if Evaluate(log.Log, ctx, condition) { if Evaluate(logging.GlobalLogger(), ctx, condition) {
t.Error("expected to fail") t.Error("expected to fail")
} }
} }

View file

@ -7,9 +7,9 @@ import (
urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1" urkyverno "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/engine/context" "github.com/kyverno/kyverno/pkg/engine/context"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
authenticationv1 "k8s.io/api/authentication/v1" authenticationv1 "k8s.io/api/authentication/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func Test_variablesub1(t *testing.T) { func Test_variablesub1(t *testing.T) {
@ -85,7 +85,7 @@ func Test_variablesub1(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -175,7 +175,7 @@ func Test_variablesub_multiple(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -262,7 +262,7 @@ func Test_variablesubstitution(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -323,7 +323,7 @@ func Test_variableSubstitutionValue(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -381,7 +381,7 @@ func Test_variableSubstitutionValueOperatorNotEqual(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -440,7 +440,7 @@ func Test_variableSubstitutionValueFail(t *testing.T) {
t.Error(err) 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.Log("expected to fails")
t.Fail() t.Fail()
} }
@ -498,7 +498,7 @@ func Test_variableSubstitutionObject(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)
@ -562,7 +562,7 @@ func Test_variableSubstitutionObjectOperatorNotEqualFail(t *testing.T) {
t.Error(err) t.Error(err)
} }
patternCopy, err = SubstituteAll(log.Log, ctx, patternCopy) patternCopy, err = SubstituteAll(logging.GlobalLogger(), ctx, patternCopy)
assert.NilError(t, err) assert.NilError(t, err)
patternMapCopy, ok := patternCopy.(map[string]interface{}) patternMapCopy, ok := patternCopy.(map[string]interface{})
@ -637,7 +637,7 @@ func Test_variableSubstitutionMultipleObject(t *testing.T) {
t.Error(err) 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) t.Error(err)
} }
resultRaw, err := json.Marshal(patternCopy) resultRaw, err := json.Marshal(patternCopy)

View file

@ -10,8 +10,8 @@ import (
v1 "github.com/kyverno/kyverno/api/kyverno/v1" v1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/context" "github.com/kyverno/kyverno/pkg/engine/context"
ju "github.com/kyverno/kyverno/pkg/engine/jsonutils" ju "github.com/kyverno/kyverno/pkg/engine/jsonutils"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func Test_subVars_success(t *testing.T) { func Test_subVars_success(t *testing.T) {
@ -70,7 +70,7 @@ func Test_subVars_success(t *testing.T) {
t.Error(err) t.Error(err)
} }
if _, err := SubstituteAll(log.Log, ctx, pattern); err != nil { if _, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern); err != nil {
t.Error(err) t.Error(err)
} }
} }
@ -131,7 +131,7 @@ func Test_subVars_failed(t *testing.T) {
t.Error(err) 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") t.Error("error is expected")
} }
} }
@ -223,7 +223,7 @@ func Test_subVars_with_JMESPath_At(t *testing.T) {
err = context.AddResource(ctx, resourceRaw) err = context.AddResource(ctx, resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
output, err := SubstituteAll(log.Log, ctx, pattern) output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
out, err := json.Marshal(output) out, err := json.Marshal(output)
assert.NilError(t, err) assert.NilError(t, err)
@ -282,7 +282,7 @@ func Test_subVars_withRegexMatch(t *testing.T) {
err = context.AddResource(ctx, resourceRaw) err = context.AddResource(ctx, resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
output, err := SubstituteAll(log.Log, ctx, pattern) output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
out, err := json.Marshal(output) out, err := json.Marshal(output)
assert.NilError(t, err) assert.NilError(t, err)
@ -312,7 +312,7 @@ func Test_subVars_withMerge(t *testing.T) {
err = context.AddResource(ctx, resourceRaw) err = context.AddResource(ctx, resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
output, err := SubstituteAll(log.Log, ctx, pattern) output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
out, err := json.Marshal(output) out, err := json.Marshal(output)
assert.NilError(t, err) assert.NilError(t, err)
@ -355,7 +355,7 @@ func Test_subVars_withRegexReplaceAll(t *testing.T) {
err = context.AddResource(ctx, resourceRaw) err = context.AddResource(ctx, resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
output, err := SubstituteAll(log.Log, ctx, pattern) output, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
out, err := json.Marshal(output) out, err := json.Marshal(output)
assert.NilError(t, err) assert.NilError(t, err)
@ -399,7 +399,7 @@ func Test_ReplacingPathWhenDeleting(t *testing.T) {
ctx := context.NewContextFromRaw(resourceRaw) ctx := context.NewContextFromRaw(resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
pattern, err = SubstituteAll(log.Log, ctx, pattern) pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, fmt.Sprintf("%v", pattern), "bar") assert.Equal(t, fmt.Sprintf("%v", pattern), "bar")
@ -434,7 +434,7 @@ func Test_ReplacingNestedVariableWhenDeleting(t *testing.T) {
ctx := context.NewContextFromRaw(resourceRaw) ctx := context.NewContextFromRaw(resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
pattern, err = SubstituteAll(log.Log, ctx, pattern) pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, fmt.Sprintf("%v", pattern), "nested_target") 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}}"`) patternRaw := []byte(`"{{request.object.metadata.annotations.test}}"`)
assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
results, err := action(&ju.ActionData{ results, err := action(&ju.ActionData{
Document: nil, Document: nil,
Element: string(patternRaw), Element: string(patternRaw),
@ -488,7 +488,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) {
patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test2}}}}"`) patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test2}}}}"`)
assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
results, err := action(&ju.ActionData{ results, err := action(&ju.ActionData{
Document: nil, Document: nil,
Element: string(patternRaw), Element: string(patternRaw),
@ -501,7 +501,7 @@ func Test_SubstituteRecursiveErrors(t *testing.T) {
patternRaw = []byte(`"{{request.object.metadata2.{{request.object.metadata.annotations.test}}}}"`) patternRaw = []byte(`"{{request.object.metadata2.{{request.object.metadata.annotations.test}}}}"`)
assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
action = substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) action = substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
results, err = action(&ju.ActionData{ results, err = action(&ju.ActionData{
Document: nil, Document: nil,
Element: string(patternRaw), Element: string(patternRaw),
@ -520,7 +520,7 @@ func Test_SubstituteRecursive(t *testing.T) {
patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test}}}}"`) patternRaw := []byte(`"{{request.object.metadata.{{request.object.metadata.annotations.test}}}}"`)
assert.Assert(t, json.Unmarshal(patternRaw, &pattern)) assert.Assert(t, json.Unmarshal(patternRaw, &pattern))
action := substituteVariablesIfAny(log.Log, ctx, DefaultVariableResolver) action := substituteVariablesIfAny(logging.GlobalLogger(), ctx, DefaultVariableResolver)
results, err := action(&ju.ActionData{ results, err := action(&ju.ActionData{
Document: nil, Document: nil,
Element: string(patternRaw), Element: string(patternRaw),
@ -556,7 +556,7 @@ func Test_policyContextValidation(t *testing.T) {
ctx := context.NewMockContext(nil, "request.object") ctx := context.NewMockContext(nil, "request.object")
_, err = SubstituteAll(log.Log, ctx, contextMap) _, err = SubstituteAll(logging.GlobalLogger(), ctx, contextMap)
assert.Assert(t, err != nil, err) assert.Assert(t, err != nil, err)
} }
@ -634,7 +634,7 @@ func Test_variableSubstitution_array(t *testing.T) {
ctx := context.NewContextFromRaw(configmapRaw) ctx := context.NewContextFromRaw(configmapRaw)
context.AddResource(ctx, resourceRaw) context.AddResource(ctx, resourceRaw)
vars, err := SubstituteAllInRule(log.Log, ctx, rule) vars, err := SubstituteAllInRule(logging.GlobalLogger(), ctx, rule)
assert.NilError(t, err) 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.") 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() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -709,7 +709,7 @@ func Test_SubstituteNullInString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -738,7 +738,7 @@ func Test_SubstituteArray(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -767,7 +767,7 @@ func Test_SubstituteArrayInString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -796,7 +796,7 @@ func Test_SubstituteInt(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -825,7 +825,7 @@ func Test_SubstituteIntInString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -854,7 +854,7 @@ func Test_SubstituteBool(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -883,7 +883,7 @@ func Test_SubstituteBoolInString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -912,7 +912,7 @@ func Test_SubstituteString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"]
@ -941,7 +941,7 @@ func Test_SubstituteStringInString(t *testing.T) {
ctx := context.NewContext() ctx := context.NewContext()
context.AddResource(ctx, variableObject) context.AddResource(ctx, variableObject)
resolved, err := SubstituteAll(log.Log, ctx, pattern) resolved, err := SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
content := resolved.(map[string]interface{})["spec"].(map[string]interface{})["content"] 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) err = context.AddResource(ctx, jsonRaw)
assert.NilError(t, err) assert.NilError(t, err)
actualDocument, err := SubstituteAll(log.Log, ctx, document) actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document)
assert.NilError(t, err) assert.NilError(t, err)
assert.DeepEqual(t, expectedDocument, actualDocument) 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 := 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.NilError(t, err)
assert.DeepEqual(t, resolvedReference, pattern) assert.DeepEqual(t, resolvedReference, pattern)
@ -1075,7 +1075,7 @@ func TestActualizePattern_GivenRelativePathThatExists(t *testing.T) {
func TestFindAndShiftReferences_PositiveCase(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." 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) 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) assert.Equal(t, expectedMessage, actualMessage)
} }
@ -1083,7 +1083,7 @@ func TestFindAndShiftReferences_PositiveCase(t *testing.T) {
func TestFindAndShiftReferences_AnyPatternPositiveCase(t *testing.T) { func TestFindAndShiftReferences_AnyPatternPositiveCase(t *testing.T) {
message := "Message with $(./../../anyPattern/0/spec/containers/0/image)." 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) 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) assert.Equal(t, expectedMessage, actualMessage)
} }
@ -1137,7 +1137,7 @@ func Test_EscpReferenceSubstitution(t *testing.T) {
err = context.AddResource(ctx, jsonRaw) err = context.AddResource(ctx, jsonRaw)
assert.NilError(t, err) assert.NilError(t, err)
actualDocument, err := SubstituteAll(log.Log, ctx, document) actualDocument, err := SubstituteAll(logging.GlobalLogger(), ctx, document)
assert.NilError(t, err) assert.NilError(t, err)
assert.DeepEqual(t, expectedDocument, actualDocument) assert.DeepEqual(t, expectedDocument, actualDocument)
@ -1172,7 +1172,7 @@ func Test_ReplacingEscpNestedVariableWhenDeleting(t *testing.T) {
ctx := context.NewContextFromRaw(resourceRaw) ctx := context.NewContextFromRaw(resourceRaw)
assert.NilError(t, err) assert.NilError(t, err)
pattern, err = SubstituteAll(log.Log, ctx, pattern) pattern, err = SubstituteAll(logging.GlobalLogger(), ctx, pattern)
assert.NilError(t, err) assert.NilError(t, err)
assert.Equal(t, fmt.Sprintf("%v", pattern), "{{request.object.metadata.annotations.target}}") assert.Equal(t, fmt.Sprintf("%v", pattern), "{{request.object.metadata.annotations.target}}")

View file

@ -2,10 +2,10 @@ package metrics
import ( import (
"github.com/go-logr/logr" "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 { func Logger() logr.Logger {
return logger return logger

View file

@ -10,6 +10,7 @@ import (
"github.com/googleapis/gnostic/compiler" "github.com/googleapis/gnostic/compiler"
openapiv2 "github.com/googleapis/gnostic/openapiv2" openapiv2 "github.com/googleapis/gnostic/openapiv2"
"github.com/kyverno/kyverno/pkg/clients/dclient" "github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/metrics" "github.com/kyverno/kyverno/pkg/metrics"
util "github.com/kyverno/kyverno/pkg/utils" util "github.com/kyverno/kyverno/pkg/utils"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -19,7 +20,6 @@ import (
runtimeSchema "k8s.io/apimachinery/pkg/runtime/schema" runtimeSchema "k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/wait" "k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/discovery" "k8s.io/client-go/discovery"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
type crdSync struct { type crdSync struct {
@ -72,17 +72,17 @@ func NewCRDSync(client dclient.Interface, controller *Controller) *crdSync {
func (c *crdSync) Run(ctx context.Context, workers int) { func (c *crdSync) Run(ctx context.Context, workers int) {
if err := c.updateInClusterKindToAPIVersions(); err != nil { 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() newDoc, err := c.client.Discovery().OpenAPISchema()
if err != nil { if err != nil {
log.Log.Error(err, "cannot get OpenAPI schema") logging.Error(err, "cannot get OpenAPI schema")
} }
err = c.controller.useOpenAPIDocument(newDoc) err = c.controller.useOpenAPIDocument(newDoc)
if err != nil { 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 // Sync CRD before kyverno starts
c.sync() c.sync()
@ -101,7 +101,7 @@ func (c *crdSync) sync() {
c.client.RecordClientQuery(metrics.ClientList, metrics.KubeDynamicClient, "CustomResourceDefinition", "") c.client.RecordClientQuery(metrics.ClientList, metrics.KubeDynamicClient, "CustomResourceDefinition", "")
if err != nil { 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 return
} }
@ -112,17 +112,17 @@ func (c *crdSync) sync() {
} }
if err := c.updateInClusterKindToAPIVersions(); err != nil { 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() newDoc, err := c.client.Discovery().OpenAPISchema()
if err != nil { if err != nil {
log.Log.Error(err, "cannot get OpenAPI schema") logging.Error(err, "cannot get OpenAPI schema")
} }
err = c.controller.useOpenAPIDocument(newDoc) err = c.controller.useOpenAPIDocument(newDoc)
if err != nil { 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 { 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 return
} }
schemaRaw, _ := json.Marshal(openV3schema) schemaRaw, _ := json.Marshal(openV3schema)
if len(schemaRaw) < 1 { 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 return
} }
schemaRaw, err = addingDefaultFieldsToSchema(crdName, schemaRaw) schemaRaw, err = addingDefaultFieldsToSchema(crdName, schemaRaw)
if err != nil { 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 return
} }
@ -196,7 +196,7 @@ func (o *Controller) ParseCRD(crd unstructured.Unstructured) {
if err != nil { if err != nil {
v3valueFound := isOpenV3Error(err) v3valueFound := isOpenV3Error(err)
if !v3valueFound { if !v3valueFound {
log.Log.Error(err, "failed to parse crd schema", "name", crdName) logging.Error(err, "failed to parse crd schema", "name", crdName)
} }
return return
} }
@ -226,7 +226,7 @@ func addingDefaultFieldsToSchema(crdName string, schemaRaw []byte) ([]byte, erro
_ = json.Unmarshal(schemaRaw, &schema) _ = json.Unmarshal(schemaRaw, &schema)
if len(schema.Properties) < 1 { 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 return schemaRaw, nil
} }
@ -256,7 +256,7 @@ func (c *crdSync) CheckSync(ctx context.Context) {
Resource: "customresourcedefinitions", Resource: "customresourcedefinitions",
}).List(ctx, metav1.ListOptions{}) }).List(ctx, metav1.ListOptions{})
if err != nil { 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 return
} }
if len(c.controller.crdList) != len(crds.Items) { if len(c.controller.crdList) != len(crds.Items) {

View file

@ -13,6 +13,7 @@ import (
"github.com/kyverno/kyverno/data" "github.com/kyverno/kyverno/data"
"github.com/kyverno/kyverno/pkg/autogen" "github.com/kyverno/kyverno/pkg/autogen"
"github.com/kyverno/kyverno/pkg/engine" "github.com/kyverno/kyverno/pkg/engine"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
cmap "github.com/orcaman/concurrent-map" cmap "github.com/orcaman/concurrent-map"
"github.com/pkg/errors" "github.com/pkg/errors"
@ -21,7 +22,6 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/kube-openapi/pkg/util/proto" "k8s.io/kube-openapi/pkg/util/proto"
"k8s.io/kube-openapi/pkg/util/proto/validation" "k8s.io/kube-openapi/pkg/util/proto/validation"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
type concurrentMap struct{ cmap.ConcurrentMap } type concurrentMap struct{ cmap.ConcurrentMap }
@ -156,7 +156,7 @@ func (o *Controller) ValidatePolicyMutation(policy kyvernov1.PolicyInterface) er
k := o.gvkToDefinitionName.GetKind(kind) k := o.gvkToDefinitionName.GetKind(kind)
resource, _ := o.generateEmptyResource(o.definitions.GetSchema(k)).(map[string]interface{}) resource, _ := o.generateEmptyResource(o.definitions.GetSchema(k)).(map[string]interface{})
if len(resource) == 0 { 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 return nil
} }
@ -187,7 +187,7 @@ func (o *Controller) useOpenAPIDocument(doc *openapiv2.Document) error {
gvk, preferredGVK, err := o.getGVKByDefinitionName(definitionName) gvk, preferredGVK, err := o.getGVKByDefinitionName(definitionName)
if err != nil { 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 continue
} }
@ -368,7 +368,7 @@ func (o *Controller) generateEmptyResource(kindSchema *openapiv2.Schema) interfa
return getBoolValue(kindSchema) return getBoolValue(kindSchema)
} }
log.Log.V(2).Info("unknown type", types[0]) logging.V(2).Info("unknown type", types[0])
return nil return nil
} }

View file

@ -5,11 +5,11 @@ import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/clients/dclient" "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/generate"
"github.com/kyverno/kyverno/pkg/policy/mutate" "github.com/kyverno/kyverno/pkg/policy/mutate"
"github.com/kyverno/kyverno/pkg/policy/validate" "github.com/kyverno/kyverno/pkg/policy/validate"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// Validation provides methods to validate a rule // 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) return fmt.Errorf("path: spec.rules[%d].generate.%s.: %v", idx, path, err)
} }
} else { } else {
checker = generate.NewGenerateFactory(client, rule.Generation, log.Log) checker = generate.NewGenerateFactory(client, rule.Generation, logging.GlobalLogger())
if path, err := checker.Validate(); err != nil { if path, err := checker.Validate(); err != nil {
return fmt.Errorf("path: spec.rules[%d].generate.%s.: %v", idx, path, err) return fmt.Errorf("path: spec.rules[%d].generate.%s.: %v", idx, path, err)
} }

View file

@ -7,19 +7,19 @@ import (
"github.com/go-logr/logr" "github.com/go-logr/logr"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/config" "github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube" kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/labels"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func transformResource(resource unstructured.Unstructured) []byte { func transformResource(resource unstructured.Unstructured) []byte {
data, err := resource.MarshalJSON() data, err := resource.MarshalJSON()
if err != nil { if err != nil {
log.Log.Error(err, "failed to marshal resource") logging.Error(err, "failed to marshal resource")
return nil return nil
} }
return data return data

View file

@ -2,8 +2,8 @@ package generate
import ( import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/policy/generate/fake" "github.com/kyverno/kyverno/pkg/policy/generate/fake"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// FakeGenerate provides implementation for generate rule processing // FakeGenerate provides implementation for generate rule processing
@ -18,6 +18,6 @@ func NewFakeGenerate(rule kyvernov1.Generation) *FakeGenerate {
g := FakeGenerate{} g := FakeGenerate{}
g.rule = rule g.rule = rule
g.authCheck = fake.NewFakeAuth() g.authCheck = fake.NewFakeAuth()
g.log = log.Log g.log = logging.GlobalLogger()
return &g return &g
} }

View file

@ -6,9 +6,9 @@ import (
"testing" "testing"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1" kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/openapi" "github.com/kyverno/kyverno/pkg/openapi"
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions" "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions"
"sigs.k8s.io/controller-runtime/pkg/log"
"gotest.tools/assert" "gotest.tools/assert"
) )
@ -983,7 +983,7 @@ func Test_checkAutoGenRules(t *testing.T) {
err := json.Unmarshal(test.policy, &policy) err := json.Unmarshal(test.policy, &policy)
assert.NilError(t, err) 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)) assert.Equal(t, test.expectedResult, res, fmt.Sprintf("test %s failed", test.name))
} }
} }

View file

@ -1,5 +1,5 @@
package policycache 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")

View file

@ -4,8 +4,8 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// LoadFile loads file in byte buffer // LoadFile loads file in byte buffer
@ -40,7 +40,7 @@ func ConvertToUnstructured(data []byte) (*unstructured.Unstructured, error) {
resource := &unstructured.Unstructured{} resource := &unstructured.Unstructured{}
err := resource.UnmarshalJSON(data) err := resource.UnmarshalJSON(data)
if err != nil { if err != nil {
log.Log.Error(err, "failed to unmarshal resource") logging.Error(err, "failed to unmarshal resource")
return nil, err return nil, err
} }
return resource, nil return resource, nil

View file

@ -1,5 +1,5 @@
package tls 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")

View file

@ -5,13 +5,13 @@ import (
"strings" "strings"
"github.com/kyverno/kyverno/pkg/config" "github.com/kyverno/kyverno/pkg/config"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/utils" "github.com/kyverno/kyverno/pkg/utils"
admissionv1 "k8s.io/api/admission/v1" admissionv1 "k8s.io/api/admission/v1"
authenticationv1 "k8s.io/api/authentication/v1" authenticationv1 "k8s.io/api/authentication/v1"
rbacv1 "k8s.io/api/rbac/v1" rbacv1 "k8s.io/api/rbac/v1"
labels "k8s.io/apimachinery/pkg/labels" labels "k8s.io/apimachinery/pkg/labels"
rbacv1listers "k8s.io/client-go/listers/rbac/v1" rbacv1listers "k8s.io/client-go/listers/rbac/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
const ( const (
@ -89,7 +89,7 @@ func matchServiceAccount(subject rbacv1.Subject, userInfo authenticationv1.UserI
if userInfo.Username[len(saPrefix):] != subjectServiceAccount { if userInfo.Username[len(saPrefix):] != subjectServiceAccount {
return false 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 return true
} }
@ -98,7 +98,7 @@ func matchUserOrGroup(subject rbacv1.Subject, userInfo authenticationv1.UserInfo
keys := append(userInfo.Groups, userInfo.Username) keys := append(userInfo.Groups, userInfo.Username)
for _, key := range keys { for _, key := range keys {
if subject.Name == key { 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 return true
} }
} }

View file

@ -4,9 +4,9 @@ import (
"testing" "testing"
"github.com/kyverno/kyverno/pkg/engine/response" "github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/logging"
"gotest.tools/assert" "gotest.tools/assert"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "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 { 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) { func Test_empty_annotation(t *testing.T) {
patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }` patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }`
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, nil) 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"}}` 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) 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" }` patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }`
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) 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"}` 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) 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" }` patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }`
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) 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"}` 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) assert.Equal(t, string(annPatches[0]), expectedPatches)
} }
@ -75,10 +75,10 @@ func Test_annotation_nil_patch(t *testing.T) {
"policies.kyverno.patches": "old-annotation", "policies.kyverno.patches": "old-annotation",
} }
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", nil, response.RuleStatusPass, 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) assert.Assert(t, annPatches == nil)
engineResponseNew := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{""}, response.RuleStatusPass, annotation) 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) assert.Assert(t, annPatchesNew == nil)
} }
@ -87,7 +87,7 @@ func Test_annotation_failed_Patch(t *testing.T) {
"policies.kyverno.patches": "old-annotation", "policies.kyverno.patches": "old-annotation",
} }
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", nil, response.RuleStatusFail, 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) 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" }` patchStr := `{ "op": "replace", "path": "/spec/containers/0/imagePullPolicy", "value": "IfNotPresent" }`
engineResponse := newEngineResponse("mutate-container", "default-imagepullpolicy", []string{patchStr}, response.RuleStatusPass, annotation) 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"}` 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"}` 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) assert.Equal(t, string(annPatches[0]), expectedPatches1)

View file

@ -10,6 +10,7 @@ import (
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/clients/dclient" "github.com/kyverno/kyverno/pkg/clients/dclient"
engineutils "github.com/kyverno/kyverno/pkg/engine/utils" engineutils "github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/logging"
wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard" wildcard "github.com/kyverno/kyverno/pkg/utils/wildcard"
"github.com/pkg/errors" "github.com/pkg/errors"
admissionv1 "k8s.io/api/admission/v1" admissionv1 "k8s.io/api/admission/v1"
@ -19,7 +20,6 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/discovery" "k8s.io/client-go/discovery"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var regexVersion = regexp.MustCompile(`v(\d+).(\d+).(\d+)\.*`) 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") 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 return false
} }
log.Log.V(2).Info("CRD found", "gvr", gvr.String()) logging.V(2).Info("CRD found", "gvr", gvr.String())
return true return true
} }
@ -345,7 +345,7 @@ func ApiextensionsJsonToKyvernoConditions(original apiextensions.JSON) (interfac
} }
func OverrideRuntimeErrorHandler() { func OverrideRuntimeErrorHandler() {
logger := log.Log.WithName("RuntimeErrorHandler") logger := logging.WithName("RuntimeErrorHandler")
if len(runtime.ErrorHandlers) > 0 { if len(runtime.ErrorHandlers) > 0 {
runtime.ErrorHandlers[0] = func(err error) { runtime.ErrorHandlers[0] = func(err error) {
logger.V(6).Info("runtime error", "msg", err.Error()) logger.V(6).Info("runtime error", "msg", err.Error())

View file

@ -5,8 +5,8 @@ import (
"fmt" "fmt"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
log "github.com/kyverno/kyverno/pkg/logging"
"k8s.io/apimachinery/pkg/util/yaml" "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
// GetPolicy extracts policies from YAML bytes // 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) return nil, fmt.Errorf("failed to decode policy: %v", err)
} }
if policy.TypeMeta.Kind == "" { 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 continue
} }
if policy.TypeMeta.Kind != "ClusterPolicy" && policy.TypeMeta.Kind != "Policy" { if policy.TypeMeta.Kind != "ClusterPolicy" && policy.TypeMeta.Kind != "Policy" {

View file

@ -1,5 +1,5 @@
package webhooks 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")

View file

@ -8,9 +8,9 @@ import (
"github.com/kyverno/kyverno/pkg/engine/utils" "github.com/kyverno/kyverno/pkg/engine/utils"
"github.com/kyverno/kyverno/pkg/policymutation" "github.com/kyverno/kyverno/pkg/policymutation"
log "github.com/kyverno/kyverno/pkg/logging"
assertnew "github.com/stretchr/testify/assert" assertnew "github.com/stretchr/testify/assert"
"gotest.tools/assert" "gotest.tools/assert"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
func compareJSONAsMap(t *testing.T, expected, actual []byte) { func compareJSONAsMap(t *testing.T, expected, actual []byte) {
@ -34,7 +34,7 @@ func TestGeneratePodControllerRule_NilAnnotation(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
p, err := utils.ApplyPatches(policyRaw, patches) p, err := utils.ApplyPatches(policyRaw, patches)
@ -67,7 +67,7 @@ func TestGeneratePodControllerRule_PredefinedAnnotation(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
assert.Assert(t, len(patches) == 1) assert.Assert(t, len(patches) == 1)
} }
@ -118,7 +118,7 @@ func TestGeneratePodControllerRule_DisableFeature(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
assert.Assert(t, len(patches) == 0) assert.Assert(t, len(patches) == 0)
} }
@ -169,7 +169,7 @@ func TestGeneratePodControllerRule_Mutate(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
p, err := utils.ApplyPatches(policyRaw, patches) p, err := utils.ApplyPatches(policyRaw, patches)
@ -303,7 +303,7 @@ func TestGeneratePodControllerRule_ExistOtherAnnotation(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
p, err := utils.ApplyPatches(policyRaw, patches) p, err := utils.ApplyPatches(policyRaw, patches)
@ -375,7 +375,7 @@ func TestGeneratePodControllerRule_ValidateAnyPattern(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
p, err := utils.ApplyPatches(policyRaw, patches) p, err := utils.ApplyPatches(policyRaw, patches)
@ -514,7 +514,7 @@ func TestGeneratePodControllerRule_ValidatePattern(t *testing.T) {
var policy kyverno.ClusterPolicy var policy kyverno.ClusterPolicy
// var policy, generatePolicy unstructured.Unstructured // var policy, generatePolicy unstructured.Unstructured
assert.Assert(t, json.Unmarshal(policyRaw, &policy)) 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(errs) == 0)
p, err := utils.ApplyPatches(policyRaw, patches) p, err := utils.ApplyPatches(policyRaw, patches)

View file

@ -7,11 +7,11 @@ import (
"time" "time"
kyverno "github.com/kyverno/kyverno/api/kyverno/v1" kyverno "github.com/kyverno/kyverno/api/kyverno/v1"
log "github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/pkg/policycache" "github.com/kyverno/kyverno/pkg/policycache"
"gotest.tools/assert" "gotest.tools/assert"
v1 "k8s.io/api/admission/v1" v1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime"
log "sigs.k8s.io/controller-runtime/pkg/log"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
) )
@ -153,7 +153,7 @@ var pod = `{
func Test_AdmissionResponseValid(t *testing.T) { func Test_AdmissionResponseValid(t *testing.T) {
policyCache := policycache.NewCache() policyCache := policycache.NewCache()
logger := log.Log.WithName("Test_AdmissionResponseValid") logger := log.WithName("Test_AdmissionResponseValid")
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -196,7 +196,7 @@ func Test_AdmissionResponseValid(t *testing.T) {
func Test_AdmissionResponseInvalid(t *testing.T) { func Test_AdmissionResponseInvalid(t *testing.T) {
policyCache := policycache.NewCache() policyCache := policycache.NewCache()
logger := log.Log.WithName("Test_AdmissionResponseInvalid") logger := log.WithName("Test_AdmissionResponseInvalid")
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -235,7 +235,7 @@ func Test_AdmissionResponseInvalid(t *testing.T) {
func Test_ImageVerify(t *testing.T) { func Test_ImageVerify(t *testing.T) {
policyCache := policycache.NewCache() policyCache := policycache.NewCache()
logger := log.Log.WithName("Test_ImageVerify") logger := log.WithName("Test_ImageVerify")
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()

View file

@ -5,7 +5,7 @@ import (
"fmt" "fmt"
"testing" "testing"
log "sigs.k8s.io/controller-runtime/pkg/log" log "github.com/kyverno/kyverno/pkg/logging"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1" kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine" "github.com/kyverno/kyverno/pkg/engine"
@ -540,7 +540,7 @@ func TestValidate_failure_action_overrides(t *testing.T) {
} }
failurePolicy := kyvernov1.Fail 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) 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.RulesAppliedCount == 2)
assert.Assert(t, resp.PolicyResponse.RulesErrorCount == 0) 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) blocked := webhookutils.BlockRequest([]*response.EngineResponse{resp}, kyvernov1.Fail, log)
assert.Assert(t, blocked == true) assert.Assert(t, blocked == true)

View file

@ -1,5 +1,5 @@
package updaterequest 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")

View file

@ -8,13 +8,13 @@ import (
"time" "time"
"github.com/kyverno/kyverno/pkg/engine/validate" "github.com/kyverno/kyverno/pkg/engine/validate"
"github.com/kyverno/kyverno/pkg/logging"
"github.com/kyverno/kyverno/test/e2e" "github.com/kyverno/kyverno/test/e2e"
commonE2E "github.com/kyverno/kyverno/test/e2e/common" commonE2E "github.com/kyverno/kyverno/test/e2e/common"
. "github.com/onsi/ginkgo" . "github.com/onsi/ginkgo"
. "github.com/onsi/gomega" . "github.com/onsi/gomega"
"gopkg.in/yaml.v2" "gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"sigs.k8s.io/controller-runtime/pkg/log"
) )
var ( var (
@ -216,7 +216,7 @@ func Test_Mutate(t *testing.T) {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
By("Validating created resource with the expected pattern...") 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()) Expect(err).NotTo(HaveOccurred())
By("Deleting Cluster Policies...") By("Deleting Cluster Policies...")
@ -439,7 +439,7 @@ func Test_Mutate_Existing(t *testing.T) {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
By("Validating created resource with the expected pattern...") 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()) Expect(err).NotTo(HaveOccurred())
case deleteTrigger: case deleteTrigger:
@ -486,7 +486,7 @@ func Test_Mutate_Existing(t *testing.T) {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
By("Validating created resource with the expected pattern...") 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()) Expect(err).NotTo(HaveOccurred())
case createPolicy: case createPolicy:
@ -530,7 +530,7 @@ func Test_Mutate_Existing(t *testing.T) {
Expect(err).NotTo(HaveOccurred()) Expect(err).NotTo(HaveOccurred())
By("Validating created resource with the expected pattern...") 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()) Expect(err).NotTo(HaveOccurred())
} }