1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-15 17:51:20 +00:00
kyverno/pkg/policy/policy_controller.go

442 lines
14 KiB
Go
Raw Normal View History

package policy
import (
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
"context"
"fmt"
"os"
"time"
2020-03-17 18:05:20 +00:00
"github.com/go-logr/logr"
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
backgroundcommon "github.com/kyverno/kyverno/pkg/background/common"
"github.com/kyverno/kyverno/pkg/client/clientset/versioned"
"github.com/kyverno/kyverno/pkg/client/clientset/versioned/scheme"
kyvernov1informers "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1"
kyvernov1beta1informers "github.com/kyverno/kyverno/pkg/client/informers/externalversions/kyverno/v1beta1"
kyvernov1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1"
kyvernov1beta1listers "github.com/kyverno/kyverno/pkg/client/listers/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/clients/dclient"
"github.com/kyverno/kyverno/pkg/config"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/engine/jmespath"
"github.com/kyverno/kyverno/pkg/event"
"github.com/kyverno/kyverno/pkg/metrics"
datautils "github.com/kyverno/kyverno/pkg/utils/data"
engineutils "github.com/kyverno/kyverno/pkg/utils/engine"
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
policyvalidation "github.com/kyverno/kyverno/pkg/validation/policy"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/apimachinery/pkg/util/wait"
corev1informers "k8s.io/client-go/informers/core/v1"
corev1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/events"
"k8s.io/client-go/util/workqueue"
)
const (
2019-08-08 20:59:50 +00:00
// maxRetries is the number of times a Policy will be retried before it is dropped out of the queue.
// With the current rate-limiter in use (5ms*2^(maxRetries-1)) the following numbers represent the times
// a deployment is going to be requeued:
//
// 5ms, 10ms, 20ms, 40ms, 80ms, 160ms, 320ms, 640ms, 1.3s, 2.6s, 5.1s, 10.2s, 20.4s, 41s, 82s
maxRetries = 15
)
// policyController is responsible for synchronizing Policy objects stored
// in the system with the corresponding policy violations
type policyController struct {
client dclient.Interface
kyvernoClient versioned.Interface
engine engineapi.Engine
pInformer kyvernov1informers.ClusterPolicyInformer
npInformer kyvernov1informers.PolicyInformer
feat: HA (#1931) * Fix Dev setup * webhook monitor - start webhook monitor in main process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leaderelection Signed-off-by: Jim Bugwadia <jim@nirmata.com> * - add isLeader; - update to use configmap lock Signed-off-by: Shuting Zhao <shutting06@gmail.com> * - add initialization method - add methods to get attributes Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * remove newContext in runLeaderElection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to GenerateController Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add leader election to generate cleanup controller Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Gracefully drain request * HA - Webhook Register / Webhook Monitor / Certificate Renewer (#1920) * enable leader election for webhook register Signed-off-by: Shuting Zhao <shutting06@gmail.com> * extract certManager to its own process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * leader election for cert manager Signed-off-by: Shuting Zhao <shutting06@gmail.com> * certManager - init certs by the leader Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update log message Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy report controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * rebuild leader election config Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start informers in leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start policy informers in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * enable leader election in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * move eventHandler to the leader election start method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add clusterrole leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixed generate flow (#1936) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * - init separate kubeclient for leaderelection - fix webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * cleanup Kyverno managed resources on stopLeading Signed-off-by: Shuting Zhao <shutting06@gmail.com> * tag v1.4.0-beta1 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix cleanup process on Kyverno stops Signed-off-by: Shuting Zhao <shutting06@gmail.com> * bump kind to 0.11.0, k8s v1.21 (#1980) Co-authored-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: vyankatesh <vyankateshkd@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com>
2021-06-08 19:37:19 +00:00
2019-08-13 20:15:04 +00:00
eventGen event.Interface
eventRecorder events.EventRecorder
// Policies that need to be synced
queue workqueue.RateLimitingInterface
// pLister can list/get policy from the shared informer's store
pLister kyvernov1listers.ClusterPolicyLister
// npLister can list/get namespace policy from the shared informer's store
npLister kyvernov1listers.PolicyLister
feat: mutate existing resources (#3669) * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix missing policy.kyverno.io/policy-name label (#3599) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * refactor cli code from pkg to cmd (#3591) * refactor cli code from pkg to cmd Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes in imports Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes tests Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixed conflicts Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * moved non-commands to utils Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * add-kms-libraries for cosign (#3603) * add-kms-libraries Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> * Shifted providers to cosign package Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Add support for custom image extractors (#3596) Signed-off-by: Sambhav Kothari <skothari44@bloomberg.net> * Update vulnerable dependencies (#3577) Signed-off-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * updating version in Chart.yaml (#3618) * updatimg version in Chart.yaml Signed-off-by: Prateeknandle <prateeknandle@gmail.com> * changes from, make gen-helm Signed-off-by: Prateeknandle <prateeknandle@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Allow kyverno-policies to have preconditions defined (#3606) * Allow kyverno-policies to have preconditions defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Fix docs Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * Image verify attestors (#3614) * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * support multiple attestors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rm CLI tests (not currently supported) Signed-off-by: Jim Bugwadia <jim@nirmata.com> * apply attestor repo Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix entryError assignment Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add intermediary certs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Allow defining imagePullSecrets (#3633) * Allow defining imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Use dict for imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Simplify how imagePullSecrets is defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Fix race condition in pCache (#3632) * fix race condition in pCache Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact: remove unused Run function from generate (#3638) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * Remove helm mode setting (#3628) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * refactor: image utils (#3630) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * -resolve lift comments; -fix informer sync issue Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact the update request cleanup controller Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - fix delete request for mutateExisting; - fix context variable substitution; - improve logging Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable events; - add last applied annotation Signed-off-by: ShutingZhao <shuting@nirmata.com> * enable mutate existing on policy creation Signed-off-by: ShutingZhao <shuting@nirmata.com> * update autogen code Signed-off-by: ShutingZhao <shuting@nirmata.com> * merge main Signed-off-by: ShutingZhao <shuting@nirmata.com> * add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * address list comments Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix "Implicit memory aliasing in for loop" Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove unused definitions Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com> Co-authored-by: Mritunjay Kumar Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Co-authored-by: Anushka Mittal <55237170+anushkamittal20@users.noreply.github.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com> Co-authored-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Prateek Nandle <56027872+Prateeknandle@users.noreply.github.com> Co-authored-by: treydock <tdockendorf@osc.edu> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-04-25 12:20:40 +00:00
// urLister can list/get update request from the shared informer's store
urLister kyvernov1beta1listers.UpdateRequestLister
feat: mutate existing resources (#3669) * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix missing policy.kyverno.io/policy-name label (#3599) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * refactor cli code from pkg to cmd (#3591) * refactor cli code from pkg to cmd Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes in imports Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes tests Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixed conflicts Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * moved non-commands to utils Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * add-kms-libraries for cosign (#3603) * add-kms-libraries Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> * Shifted providers to cosign package Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Add support for custom image extractors (#3596) Signed-off-by: Sambhav Kothari <skothari44@bloomberg.net> * Update vulnerable dependencies (#3577) Signed-off-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * updating version in Chart.yaml (#3618) * updatimg version in Chart.yaml Signed-off-by: Prateeknandle <prateeknandle@gmail.com> * changes from, make gen-helm Signed-off-by: Prateeknandle <prateeknandle@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Allow kyverno-policies to have preconditions defined (#3606) * Allow kyverno-policies to have preconditions defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Fix docs Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * Image verify attestors (#3614) * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * support multiple attestors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rm CLI tests (not currently supported) Signed-off-by: Jim Bugwadia <jim@nirmata.com> * apply attestor repo Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix entryError assignment Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add intermediary certs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Allow defining imagePullSecrets (#3633) * Allow defining imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Use dict for imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Simplify how imagePullSecrets is defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Fix race condition in pCache (#3632) * fix race condition in pCache Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact: remove unused Run function from generate (#3638) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * Remove helm mode setting (#3628) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * refactor: image utils (#3630) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * -resolve lift comments; -fix informer sync issue Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact the update request cleanup controller Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - fix delete request for mutateExisting; - fix context variable substitution; - improve logging Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable events; - add last applied annotation Signed-off-by: ShutingZhao <shuting@nirmata.com> * enable mutate existing on policy creation Signed-off-by: ShutingZhao <shuting@nirmata.com> * update autogen code Signed-off-by: ShutingZhao <shuting@nirmata.com> * merge main Signed-off-by: ShutingZhao <shuting@nirmata.com> * add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * address list comments Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix "Implicit memory aliasing in for loop" Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove unused definitions Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com> Co-authored-by: Mritunjay Kumar Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Co-authored-by: Anushka Mittal <55237170+anushkamittal20@users.noreply.github.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com> Co-authored-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Prateek Nandle <56027872+Prateeknandle@users.noreply.github.com> Co-authored-by: treydock <tdockendorf@osc.edu> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-04-25 12:20:40 +00:00
// nsLister can list/get namespaces from the shared informer's store
nsLister corev1listers.NamespaceLister
2020-05-27 05:26:07 +00:00
informersSynced []cache.InformerSynced
2019-10-19 00:38:46 +00:00
// helpers to validate against current loaded configuration
configuration config.Configuration
reconcilePeriod time.Duration
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
log logr.Logger
metricsConfig metrics.MetricsConfigManager
jp jmespath.Interface
}
// NewPolicyController create a new PolicyController
feat: HA (#1931) * Fix Dev setup * webhook monitor - start webhook monitor in main process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leaderelection Signed-off-by: Jim Bugwadia <jim@nirmata.com> * - add isLeader; - update to use configmap lock Signed-off-by: Shuting Zhao <shutting06@gmail.com> * - add initialization method - add methods to get attributes Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * remove newContext in runLeaderElection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to GenerateController Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add leader election to generate cleanup controller Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Gracefully drain request * HA - Webhook Register / Webhook Monitor / Certificate Renewer (#1920) * enable leader election for webhook register Signed-off-by: Shuting Zhao <shutting06@gmail.com> * extract certManager to its own process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * leader election for cert manager Signed-off-by: Shuting Zhao <shutting06@gmail.com> * certManager - init certs by the leader Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update log message Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy report controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * rebuild leader election config Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start informers in leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start policy informers in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * enable leader election in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * move eventHandler to the leader election start method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add clusterrole leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixed generate flow (#1936) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * - init separate kubeclient for leaderelection - fix webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * cleanup Kyverno managed resources on stopLeading Signed-off-by: Shuting Zhao <shutting06@gmail.com> * tag v1.4.0-beta1 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix cleanup process on Kyverno stops Signed-off-by: Shuting Zhao <shutting06@gmail.com> * bump kind to 0.11.0, k8s v1.21 (#1980) Co-authored-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: vyankatesh <vyankateshkd@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com>
2021-06-08 19:37:19 +00:00
func NewPolicyController(
kyvernoClient versioned.Interface,
client dclient.Interface,
engine engineapi.Engine,
pInformer kyvernov1informers.ClusterPolicyInformer,
npInformer kyvernov1informers.PolicyInformer,
urInformer kyvernov1beta1informers.UpdateRequestInformer,
configuration config.Configuration,
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
eventGen event.Interface,
namespaces corev1informers.NamespaceInformer,
log logr.Logger,
reconcilePeriod time.Duration,
metricsConfig metrics.MetricsConfigManager,
jp jmespath.Interface,
) (*policyController, error) {
// Event broad caster
eventInterface := client.GetEventsInterface()
eventBroadcaster := events.NewBroadcaster(
&events.EventSinkImpl{
Interface: eventInterface,
},
)
eventBroadcaster.StartStructuredLogging(0)
stopCh := make(chan struct{})
eventBroadcaster.StartRecordingToSink(stopCh)
pc := policyController{
client: client,
kyvernoClient: kyvernoClient,
engine: engine,
pInformer: pInformer,
npInformer: npInformer,
eventGen: eventGen,
eventRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, "policy_controller"),
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "policy"),
configuration: configuration,
reconcilePeriod: reconcilePeriod,
metricsConfig: metricsConfig,
log: log,
jp: jp,
}
pc.pLister = pInformer.Lister()
pc.npLister = npInformer.Lister()
2020-05-27 05:26:07 +00:00
pc.nsLister = namespaces.Lister()
feat: mutate existing resources (#3669) * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing, replace GR by UR in webhook server (#3601) * add attributes for post mutation Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR informer to webhook server Signed-off-by: ShutingZhao <shuting@nirmata.com> * - replace gr with ur in the webhook server; - create ur for mutateExsiting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace gr by ur across entire packages Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix missing policy.kyverno.io/policy-name label (#3599) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * refactor cli code from pkg to cmd (#3591) * refactor cli code from pkg to cmd Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes in imports Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixes tests Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * fixed conflicts Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> * moved non-commands to utils Signed-off-by: Mritunjay Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> * add YAMLs Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs & fix unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * add UR deletion handler Signed-off-by: ShutingZhao <shuting@nirmata.com> * add api docs for v1beta1 Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix clientset method Signed-off-by: ShutingZhao <shuting@nirmata.com> * add-kms-libraries for cosign (#3603) * add-kms-libraries Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> * Shifted providers to cosign package Signed-off-by: anushkamittal20 <anumittal4641@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Add support for custom image extractors (#3596) Signed-off-by: Sambhav Kothari <skothari44@bloomberg.net> * Update vulnerable dependencies (#3577) Signed-off-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix v1beta1 client registration Signed-off-by: ShutingZhao <shuting@nirmata.com> * feat: mutate existing - generates UR for admission requests (#3623) Signed-off-by: ShutingZhao <shuting@nirmata.com> * updating version in Chart.yaml (#3618) * updatimg version in Chart.yaml Signed-off-by: Prateeknandle <prateeknandle@gmail.com> * changes from, make gen-helm Signed-off-by: Prateeknandle <prateeknandle@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Allow kyverno-policies to have preconditions defined (#3606) * Allow kyverno-policies to have preconditions defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Fix docs Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * replace with UR in policy controller generate rules (#3635) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable mutate engine to process mutateExisting rules; - add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * implemented ur background reconciliation for mutateExisting policies Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix webhook update error Signed-off-by: ShutingZhao <shuting@nirmata.com> * temporary comment out new unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * Image verify attestors (#3614) * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix logs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * support multiple attestors Signed-off-by: Jim Bugwadia <jim@nirmata.com> * rm CLI tests (not currently supported) Signed-off-by: Jim Bugwadia <jim@nirmata.com> * apply attestor repo Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix linter issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix entryError assignment Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix tests Signed-off-by: Jim Bugwadia <jim@nirmata.com> * format Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add intermediary certs Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Allow defining imagePullSecrets (#3633) * Allow defining imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Use dict for imagePullSecrets Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> * Simplify how imagePullSecrets is defined Signed-off-by: Trey Dockendorf <tdockendorf@osc.edu> Signed-off-by: ShutingZhao <shuting@nirmata.com> * Fix race condition in pCache (#3632) * fix race condition in pCache Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact: remove unused Run function from generate (#3638) Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * Remove helm mode setting (#3628) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * refactor: image utils (#3630) Signed-off-by: Charles-Edouard Brétéché <charled.breteche@gmail.com> Signed-off-by: ShutingZhao <shuting@nirmata.com> * -resolve lift comments; -fix informer sync issue Signed-off-by: ShutingZhao <shuting@nirmata.com> * refact the update request cleanup controller Signed-off-by: prateekpandey14 <prateek.pandey@nirmata.com> * - fix delete request for mutateExisting; - fix context variable substitution; - improve logging Signed-off-by: ShutingZhao <shuting@nirmata.com> * - enable events; - add last applied annotation Signed-off-by: ShutingZhao <shuting@nirmata.com> * enable mutate existing on policy creation Signed-off-by: ShutingZhao <shuting@nirmata.com> * update autogen code Signed-off-by: ShutingZhao <shuting@nirmata.com> * merge main Signed-off-by: ShutingZhao <shuting@nirmata.com> * add unit tests Signed-off-by: ShutingZhao <shuting@nirmata.com> * address list comments Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix "Implicit memory aliasing in for loop" Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove unused definitions Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Prateek Pandey <prateek.pandey@nirmata.com> Co-authored-by: Mritunjay Kumar Sharma <mritunjaysharma394@gmail.com> Co-authored-by: Vyankatesh Kudtarkar <vyankateshkd@gmail.com> Co-authored-by: Anushka Mittal <55237170+anushkamittal20@users.noreply.github.com> Co-authored-by: Sambhav Kothari <sambhavs.email@gmail.com> Co-authored-by: Shubham Gupta <shubham.gupta2956@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Prateek Nandle <56027872+Prateeknandle@users.noreply.github.com> Co-authored-by: treydock <tdockendorf@osc.edu> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2022-04-25 12:20:40 +00:00
pc.urLister = urInformer.Lister()
feat: HA (#1931) * Fix Dev setup * webhook monitor - start webhook monitor in main process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leaderelection Signed-off-by: Jim Bugwadia <jim@nirmata.com> * - add isLeader; - update to use configmap lock Signed-off-by: Shuting Zhao <shutting06@gmail.com> * - add initialization method - add methods to get attributes Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * remove newContext in runLeaderElection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to GenerateController Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add leader election to generate cleanup controller Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Gracefully drain request * HA - Webhook Register / Webhook Monitor / Certificate Renewer (#1920) * enable leader election for webhook register Signed-off-by: Shuting Zhao <shutting06@gmail.com> * extract certManager to its own process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * leader election for cert manager Signed-off-by: Shuting Zhao <shutting06@gmail.com> * certManager - init certs by the leader Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update log message Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy report controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * rebuild leader election config Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start informers in leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start policy informers in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * enable leader election in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * move eventHandler to the leader election start method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add clusterrole leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixed generate flow (#1936) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * - init separate kubeclient for leaderelection - fix webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * cleanup Kyverno managed resources on stopLeading Signed-off-by: Shuting Zhao <shutting06@gmail.com> * tag v1.4.0-beta1 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix cleanup process on Kyverno stops Signed-off-by: Shuting Zhao <shutting06@gmail.com> * bump kind to 0.11.0, k8s v1.21 (#1980) Co-authored-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: vyankatesh <vyankateshkd@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com>
2021-06-08 19:37:19 +00:00
pc.informersSynced = []cache.InformerSynced{pInformer.Informer().HasSynced, npInformer.Informer().HasSynced, urInformer.Informer().HasSynced, namespaces.Informer().HasSynced}
2019-08-13 16:37:02 +00:00
return &pc, nil
}
func (pc *policyController) canBackgroundProcess(p kyvernov1.PolicyInterface) bool {
logger := pc.log.WithValues("policy", p.GetName())
if !p.GetSpec().HasGenerate() && !p.GetSpec().HasMutateExisting() {
logger.V(4).Info("policy does not have background rules for reconciliation")
return false
}
if err := policyvalidation.ValidateVariables(p, true); err != nil {
logger.V(4).Info("policy cannot be processed in the background")
return false
}
if p.GetSpec().HasMutateExisting() {
val := os.Getenv("BACKGROUND_SCAN_INTERVAL")
interval, err := time.ParseDuration(val)
if err != nil {
logger.V(4).Info("failed to parse BACKGROUND_SCAN_INTERVAL env variable, falling to default 1h", "msg", err.Error())
interval = time.Hour
}
if p.GetCreationTimestamp().Add(interval).After(time.Now()) {
return p.GetSpec().GetMutateExistingOnPolicyUpdate()
}
}
return true
}
func (pc *policyController) addPolicy(obj interface{}) {
2020-03-17 18:05:20 +00:00
logger := pc.log
p := castPolicy(obj)
logger.Info("policy created", "uid", p.GetUID(), "kind", p.GetKind(), "namespace", p.GetNamespace(), "name", p.GetName())
if !pc.canBackgroundProcess(p) {
return
}
logger.V(4).Info("queuing policy for background processing", "name", p.GetName())
pc.enqueuePolicy(p)
}
func (pc *policyController) updatePolicy(old, cur interface{}) {
2020-03-17 18:05:20 +00:00
logger := pc.log
oldP := castPolicy(old)
curP := castPolicy(cur)
if !pc.canBackgroundProcess(curP) {
return
}
if datautils.DeepEqual(oldP.GetSpec(), curP.GetSpec()) {
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
return
}
logger.V(2).Info("updating policy", "name", oldP.GetName())
fix: delete downstream for a generate rule removal, with data and sync (#6393) * remove policy handler for updates Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove policy update handler from the ur controller Signed-off-by: ShutingZhao <shuting@nirmata.com> * rework cleanup downstream on policy deletion Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix downstream deletion on data rule removal Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for clusterpolicy Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fix Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * add delays Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix name assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> * delete downstream when deletes the clone source Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-source Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fixes Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-downstream Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-data-sync-modify-rule Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix labels Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix policy assertions Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix annotation missing names Signed-off-by: ShutingZhao <shuting@nirmata.com> * rename policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove dead code Signed-off-by: ShutingZhao <shuting@nirmata.com> * create unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * create more unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2023-03-01 03:48:18 +00:00
if deleted, ok := ruleDeletion(oldP, curP); ok {
err := pc.createURForDownstreamDeletion(deleted)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to create UR on rule deletion, clean up downstream resource may be failed: %v", err))
}
}
pc.enqueuePolicy(curP)
}
func (pc *policyController) deletePolicy(obj interface{}) {
logger := pc.log
var p kyvernov1.PolicyInterface
switch kubeutils.GetObjectWithTombstone(obj).(type) {
case *kyvernov1.ClusterPolicy:
p = kubeutils.GetObjectWithTombstone(obj).(*kyvernov1.ClusterPolicy)
case *kyvernov1.Policy:
p = kubeutils.GetObjectWithTombstone(obj).(*kyvernov1.Policy)
default:
logger.Info("Failed to get deleted object", "obj", obj)
return
}
logger.Info("policy deleted", "uid", p.GetUID(), "kind", p.GetKind(), "namespace", p.GetNamespace(), "name", p.GetName())
fix: delete downstream for a generate rule removal, with data and sync (#6393) * remove policy handler for updates Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove policy update handler from the ur controller Signed-off-by: ShutingZhao <shuting@nirmata.com> * rework cleanup downstream on policy deletion Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix downstream deletion on data rule removal Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for clusterpolicy Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fix Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * add delays Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix name assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> * delete downstream when deletes the clone source Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-source Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fixes Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-downstream Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-data-sync-modify-rule Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix labels Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix policy assertions Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix annotation missing names Signed-off-by: ShutingZhao <shuting@nirmata.com> * rename policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove dead code Signed-off-by: ShutingZhao <shuting@nirmata.com> * create unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * create more unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2023-03-01 03:48:18 +00:00
err := pc.createURForDownstreamDeletion(p)
if err != nil {
utilruntime.HandleError(fmt.Errorf("failed to create UR on policy deletion, clean up downstream resource may be failed: %v", err))
}
}
func (pc *policyController) enqueuePolicy(policy kyvernov1.PolicyInterface) {
2020-03-17 18:05:20 +00:00
logger := pc.log
key, err := cache.MetaNamespaceKeyFunc(policy)
if err != nil {
logger.Error(err, "failed to enqueue policy")
return
}
pc.queue.Add(key)
}
// Run begins watching and syncing.
func (pc *policyController) Run(ctx context.Context, workers int) {
2020-03-17 18:05:20 +00:00
logger := pc.log
defer utilruntime.HandleCrash()
defer pc.queue.ShutDown()
2020-03-17 18:05:20 +00:00
logger.Info("starting")
defer logger.Info("shutting down")
if !cache.WaitForNamedCacheSync("PolicyController", ctx.Done(), pc.informersSynced...) {
return
}
_, _ = pc.pInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
feat: HA (#1931) * Fix Dev setup * webhook monitor - start webhook monitor in main process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leaderelection Signed-off-by: Jim Bugwadia <jim@nirmata.com> * - add isLeader; - update to use configmap lock Signed-off-by: Shuting Zhao <shutting06@gmail.com> * - add initialization method - add methods to get attributes Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * remove newContext in runLeaderElection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to GenerateController Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add leader election to generate cleanup controller Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Gracefully drain request * HA - Webhook Register / Webhook Monitor / Certificate Renewer (#1920) * enable leader election for webhook register Signed-off-by: Shuting Zhao <shutting06@gmail.com> * extract certManager to its own process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * leader election for cert manager Signed-off-by: Shuting Zhao <shutting06@gmail.com> * certManager - init certs by the leader Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update log message Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy report controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * rebuild leader election config Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start informers in leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start policy informers in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * enable leader election in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * move eventHandler to the leader election start method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add clusterrole leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixed generate flow (#1936) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * - init separate kubeclient for leaderelection - fix webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * cleanup Kyverno managed resources on stopLeading Signed-off-by: Shuting Zhao <shutting06@gmail.com> * tag v1.4.0-beta1 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix cleanup process on Kyverno stops Signed-off-by: Shuting Zhao <shutting06@gmail.com> * bump kind to 0.11.0, k8s v1.21 (#1980) Co-authored-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: vyankatesh <vyankateshkd@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com>
2021-06-08 19:37:19 +00:00
AddFunc: pc.addPolicy,
UpdateFunc: pc.updatePolicy,
DeleteFunc: pc.deletePolicy,
})
_, _ = pc.npInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: pc.addPolicy,
UpdateFunc: pc.updatePolicy,
DeleteFunc: pc.deletePolicy,
feat: HA (#1931) * Fix Dev setup * webhook monitor - start webhook monitor in main process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leaderelection Signed-off-by: Jim Bugwadia <jim@nirmata.com> * - add isLeader; - update to use configmap lock Signed-off-by: Shuting Zhao <shutting06@gmail.com> * - add initialization method - add methods to get attributes Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * remove newContext in runLeaderElection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to GenerateController Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * skip processing for non-leaders Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add leader election to generate cleanup controller Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Gracefully drain request * HA - Webhook Register / Webhook Monitor / Certificate Renewer (#1920) * enable leader election for webhook register Signed-off-by: Shuting Zhao <shutting06@gmail.com> * extract certManager to its own process Signed-off-by: Shuting Zhao <shutting06@gmail.com> * leader election for cert manager Signed-off-by: Shuting Zhao <shutting06@gmail.com> * certManager - init certs by the leader Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * update log message Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add leader election to policy report controller Signed-off-by: Shuting Zhao <shutting06@gmail.com> * rebuild leader election config Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start informers in leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * start policy informers in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * enable leader election in main Signed-off-by: Shuting Zhao <shutting06@gmail.com> * move eventHandler to the leader election start method Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * add clusterrole leaderelection Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixed generate flow (#1936) Signed-off-by: NoSkillGirl <singhpooja240393@gmail.com> * - init separate kubeclient for leaderelection - fix webhook monitor Signed-off-by: Shuting Zhao <shutting06@gmail.com> * address reviewdog comments Signed-off-by: Shuting Zhao <shutting06@gmail.com> * cleanup Kyverno managed resources on stopLeading Signed-off-by: Shuting Zhao <shutting06@gmail.com> * tag v1.4.0-beta1 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix cleanup process on Kyverno stops Signed-off-by: Shuting Zhao <shutting06@gmail.com> * bump kind to 0.11.0, k8s v1.21 (#1980) Co-authored-by: vyankatesh <vyankatesh@neualto.com> Co-authored-by: vyankatesh <vyankateshkd@gmail.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Pooja Singh <36136335+NoSkillGirl@users.noreply.github.com>
2021-06-08 19:37:19 +00:00
})
for i := 0; i < workers; i++ {
go wait.UntilWithContext(ctx, pc.worker, time.Second)
}
go pc.forceReconciliation(ctx)
<-ctx.Done()
}
// worker runs a worker thread that just dequeues items, processes them, and marks them done.
// It enforces that the syncHandler is never invoked concurrently with the same key.
func (pc *policyController) worker(ctx context.Context) {
for pc.processNextWorkItem() {
}
}
func (pc *policyController) processNextWorkItem() bool {
key, quit := pc.queue.Get()
if quit {
return false
}
defer pc.queue.Done(key)
err := pc.syncPolicy(key.(string))
pc.handleErr(err, key)
return true
}
func (pc *policyController) handleErr(err error, key interface{}) {
2020-03-17 18:05:20 +00:00
logger := pc.log
if err == nil {
pc.queue.Forget(key)
return
}
if pc.queue.NumRequeues(key) < maxRetries {
2020-03-17 18:05:20 +00:00
logger.Error(err, "failed to sync policy", "key", key)
pc.queue.AddRateLimited(key)
return
}
utilruntime.HandleError(err)
2020-03-17 18:05:20 +00:00
logger.V(2).Info("dropping policy out of queue", "key", key)
pc.queue.Forget(key)
}
func (pc *policyController) syncPolicy(key string) error {
logger := pc.log.WithName("syncPolicy")
startTime := time.Now()
2020-03-17 18:05:20 +00:00
logger.V(4).Info("started syncing policy", "key", key, "startTime", startTime)
defer func() {
logger.V(4).Info("finished syncing policy", "key", key, "processingTime", time.Since(startTime).String())
}()
2020-05-17 16:51:46 +00:00
policy, err := pc.getPolicy(key)
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
if err != nil {
if apierrors.IsNotFound(err) {
Add Policy Report (#1229) * add report in cli * policy report crd added * policy report added * configmap added * added jobs * added jobs * bug fixed * added logic for cli * common function added * sub command added for policy report * subcommand added for report * common package changed * configmap added * added logic for kyverno cli * added logic for jobs * added logic for jobs * added logic for jobs * added logic for cli * buf fix * cli changes * count bug fix * docs added for command * go fmt * refactor codebase * remove policy controller for policyreport * policy report removed * bug fixes * bug fixes * added job trigger if needed * job deletation logic added * build failed fix * fixed e2e test * remove hard coded variables * packages adde * improvment added in jobs sheduler * policy report yaml added * cronjob added * small fixes * remove background sync * documentation added for report command * remove extra log * small improvement * tested policy report * revert hardcoded changes * changes for demo * demo changes * resource aggrigation added * More changes * More changes * - resolve PR comments; - refactor jobs controller * set rbac for jobs * add clean up in job controller * add short names * remove application scope for policyreport * move job controller to policyreport * add report logic in command apply * - update policy report types; - upgrade k8s library; - update code gen * temporarily comment out code to pass CI build * generate / update policyreport to cluster * add unit test for CLI report * add test for apply - generate policy report * fix unit test * - remove job controller; - remove in-memory configmap; - clean up kustomize manifest * remove dependency * add reportRequest / clusterReportRequest * clean up policy report * generate report request * update crd clusterReportRequest * - update json tag of report summary; - update definition manifests; - fix dclient creation * aggregate reportRequest into policy report * fix unit tests * - update report summary to optional; - generate clusterPolicyReport; - remove reportRequests after merged to report * remove * generate reportRequest in kyverno namespace * update resource filter in helm chart * - rename reportRequest to reportChangeRequest; -rename clusterReportRequest to clusterReportChangeRequest * generate policy report in background scan * skip generating report change request if there's entry results * fix results entry removal when policy / rule gets deleted * rename apiversion from policy.kubernetes.io to policy.k8s.io * update summary.* to lower case * move reportChangeRequest to kyverno.io/v1alpha1 * remove policy report flag * fix report update * clean up policy violation CRD * remove violation CRD from manifest * clean up policy violation code - remove pvGenerator * change severity fields to lower case * update import library * set report category Co-authored-by: Yuvraj <yuvraj.yad001@gmail.com> Co-authored-by: Yuvraj <10830562+evalsocket@users.noreply.github.com> Co-authored-by: Jim Bugwadia <jim@nirmata.com>
2020-11-09 19:26:12 +00:00
return nil
}
return err
} else {
err = pc.handleMutate(key, policy)
if err != nil {
logger.Error(err, "failed to updateUR on mutate policy update")
}
err = pc.handleGenerate(key, policy)
if err != nil {
logger.Error(err, "failed to updateUR on generate policy update")
}
}
return nil
}
func (pc *policyController) getPolicy(key string) (kyvernov1.PolicyInterface, error) {
if ns, name, err := cache.SplitMetaNamespaceKey(key); err != nil {
pc.log.Error(err, "failed to parse policy name", "policyName", key)
return nil, err
} else {
isNamespacedPolicy := ns != ""
if !isNamespacedPolicy {
return pc.pLister.Get(name)
}
return pc.npLister.Policies(ns).Get(name)
}
}
// forceReconciliation forces a background scan by adding all policies to the workqueue
func (pc *policyController) forceReconciliation(ctx context.Context) {
logger := pc.log.WithName("forceReconciliation")
ticker := time.NewTicker(pc.reconcilePeriod)
for {
select {
case <-ticker.C:
logger.Info("reconciling generate and mutateExisting policies", "scan interval", pc.reconcilePeriod.String())
pc.requeuePolicies()
case <-ctx.Done():
return
}
}
}
func (pc *policyController) requeuePolicies() {
logger := pc.log.WithName("requeuePolicies")
if cpols, err := pc.pLister.List(labels.Everything()); err == nil {
for _, cpol := range cpols {
if !pc.canBackgroundProcess(cpol) {
continue
}
pc.enqueuePolicy(cpol)
}
} else {
logger.Error(err, "unable to list ClusterPolicies")
}
if pols, err := pc.npLister.Policies(metav1.NamespaceAll).List(labels.Everything()); err == nil {
for _, p := range pols {
if !pc.canBackgroundProcess(p) {
continue
}
pc.enqueuePolicy(p)
}
} else {
logger.Error(err, "unable to list Policies")
}
}
func (pc *policyController) handleUpdateRequest(ur *kyvernov1beta1.UpdateRequest, triggerResource *unstructured.Unstructured, rule kyvernov1.Rule, policy kyvernov1.PolicyInterface) (skip bool, err error) {
namespaceLabels := engineutils.GetNamespaceSelectorsFromNamespaceLister(triggerResource.GetKind(), triggerResource.GetNamespace(), pc.nsLister, pc.log)
policyContext, err := backgroundcommon.NewBackgroundContext(pc.log, pc.client, ur, policy, triggerResource, pc.configuration, pc.jp, namespaceLabels)
if err != nil {
return false, fmt.Errorf("failed to build policy context for rule %s: %w", rule.Name, err)
}
engineResponse := pc.engine.ApplyBackgroundChecks(context.TODO(), policyContext)
if len(engineResponse.PolicyResponse.Rules) == 0 {
return true, nil
}
for _, ruleResponse := range engineResponse.PolicyResponse.Rules {
refactor: engine rule response creation (#6784) * refactor: engine rule response creation Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * private fields Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * more private Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> * fix unit tests Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
2023-04-05 10:35:38 +00:00
if ruleResponse.Status() != engineapi.RuleStatusPass {
pc.log.V(4).Info("skip creating URs on policy update", "policy", policy.GetName(), "rule", rule.Name, "rule.Status", ruleResponse.Status())
continue
}
pc.log.V(2).Info("creating new UR for generate")
fix: delete downstream for a generate rule removal, with data and sync (#6393) * remove policy handler for updates Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove policy update handler from the ur controller Signed-off-by: ShutingZhao <shuting@nirmata.com> * rework cleanup downstream on policy deletion Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix downstream deletion on data rule removal Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for clusterpolicy Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fix Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test for policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * update api docs Signed-off-by: ShutingZhao <shuting@nirmata.com> * add delays Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix name assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> * delete downstream when deletes the clone source Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-source Signed-off-by: ShutingZhao <shuting@nirmata.com> * linter fixes Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-clone-sync-delete-downstream Signed-off-by: ShutingZhao <shuting@nirmata.com> * add kuttl test pol-data-sync-modify-rule Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix panic Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix labels Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix policy assertions Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix annotation missing names Signed-off-by: ShutingZhao <shuting@nirmata.com> * rename policy Signed-off-by: ShutingZhao <shuting@nirmata.com> * remove dead code Signed-off-by: ShutingZhao <shuting@nirmata.com> * create unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * create more unique namespaces Signed-off-by: ShutingZhao <shuting@nirmata.com> * fix assertion Signed-off-by: ShutingZhao <shuting@nirmata.com> --------- Signed-off-by: ShutingZhao <shuting@nirmata.com> Co-authored-by: Charles-Edouard Brétéché <charled.breteche@gmail.com>
2023-03-01 03:48:18 +00:00
created, err := pc.kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).Create(context.TODO(), ur, metav1.CreateOptions{})
if err != nil {
return false, err
}
updated := created.DeepCopy()
updated.Status.State = kyvernov1beta1.Pending
_, err = pc.kyvernoClient.KyvernoV1beta1().UpdateRequests(config.KyvernoNamespace()).UpdateStatus(context.TODO(), updated, metav1.UpdateOptions{})
if err != nil {
return false, err
}
}
return false, err
}
func generateTriggers(client dclient.Interface, rule kyvernov1.Rule, log logr.Logger) []*unstructured.Unstructured {
list := &unstructured.UnstructuredList{}
kinds := fetchUniqueKinds(rule)
for _, kind := range kinds {
mlist, err := client.ListResource(context.TODO(), "", kind, "", rule.MatchResources.Selector)
if err != nil {
log.Error(err, "failed to list matched resource")
continue
}
list.Items = append(list.Items, mlist.Items...)
}
return convertlist(list.Items)
}