2019-08-07 23:14:33 +00:00
|
|
|
package policy
|
|
|
|
|
|
|
|
import (
|
2020-11-09 19:26:12 +00:00
|
|
|
"context"
|
2020-09-03 21:34:23 +00:00
|
|
|
"fmt"
|
2023-12-20 16:29:37 +00:00
|
|
|
"os"
|
2019-08-07 23:14:33 +00:00
|
|
|
"time"
|
|
|
|
|
2020-03-17 18:05:20 +00:00
|
|
|
"github.com/go-logr/logr"
|
2022-05-17 11:12:43 +00:00
|
|
|
kyvernov1 "github.com/kyverno/kyverno/api/kyverno/v1"
|
|
|
|
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
2022-12-29 10:08:50 +00:00
|
|
|
backgroundcommon "github.com/kyverno/kyverno/pkg/background/common"
|
2022-09-07 04:01:43 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/client/clientset/versioned"
|
2020-10-07 18:12:31 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/client/clientset/versioned/scheme"
|
2022-05-18 04:02:31 +00:00
|
|
|
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"
|
2022-08-31 06:03:47 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/clients/dclient"
|
2020-10-07 18:12:31 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/config"
|
2023-01-30 11:41:09 +00:00
|
|
|
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
|
2023-04-13 11:29:40 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/engine/jmespath"
|
2020-10-07 18:12:31 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/event"
|
2021-05-04 19:11:13 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/metrics"
|
2023-03-24 10:01:49 +00:00
|
|
|
datautils "github.com/kyverno/kyverno/pkg/utils/data"
|
2023-02-02 08:56:00 +00:00
|
|
|
engineutils "github.com/kyverno/kyverno/pkg/utils/engine"
|
2022-08-03 16:17:07 +00:00
|
|
|
kubeutils "github.com/kyverno/kyverno/pkg/utils/kube"
|
2023-04-28 13:54:17 +00:00
|
|
|
policyvalidation "github.com/kyverno/kyverno/pkg/validation/policy"
|
2022-12-29 10:08:50 +00:00
|
|
|
apierrors "k8s.io/apimachinery/pkg/api/errors"
|
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
2022-05-09 07:13:11 +00:00
|
|
|
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
|
2022-12-29 10:08:50 +00:00
|
|
|
"k8s.io/apimachinery/pkg/labels"
|
2019-08-07 23:14:33 +00:00
|
|
|
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
|
|
|
|
"k8s.io/apimachinery/pkg/util/wait"
|
2022-05-17 15:51:03 +00:00
|
|
|
corev1informers "k8s.io/client-go/informers/core/v1"
|
|
|
|
corev1listers "k8s.io/client-go/listers/core/v1"
|
2019-08-07 23:14:33 +00:00
|
|
|
"k8s.io/client-go/tools/cache"
|
2023-07-26 14:06:51 +00:00
|
|
|
"k8s.io/client-go/tools/events"
|
2019-08-07 23:14:33 +00:00
|
|
|
"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.
|
2019-08-07 23:14:33 +00:00
|
|
|
// 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
|
|
|
|
)
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
// policyController is responsible for synchronizing Policy objects stored
|
2019-08-07 23:14:33 +00:00
|
|
|
// in the system with the corresponding policy violations
|
2023-04-13 11:29:40 +00:00
|
|
|
type policyController struct {
|
2022-05-17 14:40:51 +00:00
|
|
|
client dclient.Interface
|
2022-09-07 04:01:43 +00:00
|
|
|
kyvernoClient versioned.Interface
|
2023-02-03 05:01:11 +00:00
|
|
|
engine engineapi.Engine
|
2022-12-07 15:08:37 +00:00
|
|
|
|
|
|
|
pInformer kyvernov1informers.ClusterPolicyInformer
|
|
|
|
npInformer kyvernov1informers.PolicyInformer
|
2021-06-08 19:37:19 +00:00
|
|
|
|
2019-08-13 20:15:04 +00:00
|
|
|
eventGen event.Interface
|
2023-07-26 14:06:51 +00:00
|
|
|
eventRecorder events.EventRecorder
|
2019-08-07 23:14:33 +00:00
|
|
|
|
2020-12-21 19:04:19 +00:00
|
|
|
// Policies that need to be synced
|
2019-08-07 23:14:33 +00:00
|
|
|
queue workqueue.RateLimitingInterface
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2019-08-07 23:14:33 +00:00
|
|
|
// pLister can list/get policy from the shared informer's store
|
2022-05-18 04:02:31 +00:00
|
|
|
pLister kyvernov1listers.ClusterPolicyLister
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2020-08-19 16:07:23 +00:00
|
|
|
// npLister can list/get namespace policy from the shared informer's store
|
2022-05-18 04:02:31 +00:00
|
|
|
npLister kyvernov1listers.PolicyLister
|
2020-08-19 16:07:23 +00:00
|
|
|
|
2022-04-25 12:20:40 +00:00
|
|
|
// urLister can list/get update request from the shared informer's store
|
2022-05-18 04:02:31 +00:00
|
|
|
urLister kyvernov1beta1listers.UpdateRequestLister
|
2022-04-25 12:20:40 +00:00
|
|
|
|
2020-12-21 19:04:19 +00:00
|
|
|
// nsLister can list/get namespaces from the shared informer's store
|
2022-05-17 15:51:03 +00:00
|
|
|
nsLister corev1listers.NamespaceLister
|
2020-05-27 05:26:07 +00:00
|
|
|
|
2022-06-28 04:55:52 +00:00
|
|
|
informersSynced []cache.InformerSynced
|
|
|
|
|
2019-10-19 00:38:46 +00:00
|
|
|
// helpers to validate against current loaded configuration
|
2023-04-13 11:29:40 +00:00
|
|
|
configuration config.Configuration
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2021-03-25 19:28:03 +00:00
|
|
|
reconcilePeriod time.Duration
|
|
|
|
|
2020-11-09 19:26:12 +00:00
|
|
|
log logr.Logger
|
2021-05-04 19:11:13 +00:00
|
|
|
|
2022-11-30 13:37:53 +00:00
|
|
|
metricsConfig metrics.MetricsConfigManager
|
2023-04-13 11:29:40 +00:00
|
|
|
|
|
|
|
jp jmespath.Interface
|
2019-08-07 23:14:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewPolicyController create a new PolicyController
|
2021-06-08 19:37:19 +00:00
|
|
|
func NewPolicyController(
|
2022-09-07 04:01:43 +00:00
|
|
|
kyvernoClient versioned.Interface,
|
2022-05-17 14:40:51 +00:00
|
|
|
client dclient.Interface,
|
2023-02-03 05:01:11 +00:00
|
|
|
engine engineapi.Engine,
|
2022-05-18 04:02:31 +00:00
|
|
|
pInformer kyvernov1informers.ClusterPolicyInformer,
|
|
|
|
npInformer kyvernov1informers.PolicyInformer,
|
|
|
|
urInformer kyvernov1beta1informers.UpdateRequestInformer,
|
2023-04-13 11:29:40 +00:00
|
|
|
configuration config.Configuration,
|
2020-11-09 19:26:12 +00:00
|
|
|
eventGen event.Interface,
|
2022-05-17 15:51:03 +00:00
|
|
|
namespaces corev1informers.NamespaceInformer,
|
2020-09-22 21:11:49 +00:00
|
|
|
log logr.Logger,
|
2021-05-04 19:11:13 +00:00
|
|
|
reconcilePeriod time.Duration,
|
2022-11-30 13:37:53 +00:00
|
|
|
metricsConfig metrics.MetricsConfigManager,
|
2023-04-13 11:29:40 +00:00
|
|
|
jp jmespath.Interface,
|
|
|
|
) (*policyController, error) {
|
2019-08-07 23:14:33 +00:00
|
|
|
// Event broad caster
|
2022-11-22 13:37:27 +00:00
|
|
|
eventInterface := client.GetEventsInterface()
|
2023-07-26 14:06:51 +00:00
|
|
|
eventBroadcaster := events.NewBroadcaster(
|
|
|
|
&events.EventSinkImpl{
|
|
|
|
Interface: eventInterface,
|
|
|
|
},
|
|
|
|
)
|
|
|
|
eventBroadcaster.StartStructuredLogging(0)
|
|
|
|
stopCh := make(chan struct{})
|
|
|
|
eventBroadcaster.StartRecordingToSink(stopCh)
|
2019-08-07 23:14:33 +00:00
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
pc := policyController{
|
2023-04-11 07:12:05 +00:00
|
|
|
client: client,
|
|
|
|
kyvernoClient: kyvernoClient,
|
|
|
|
engine: engine,
|
|
|
|
pInformer: pInformer,
|
|
|
|
npInformer: npInformer,
|
|
|
|
eventGen: eventGen,
|
2023-07-26 14:06:51 +00:00
|
|
|
eventRecorder: eventBroadcaster.NewRecorder(scheme.Scheme, "policy_controller"),
|
2023-04-11 07:12:05 +00:00
|
|
|
queue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "policy"),
|
2023-04-13 11:29:40 +00:00
|
|
|
configuration: configuration,
|
2023-04-11 07:12:05 +00:00
|
|
|
reconcilePeriod: reconcilePeriod,
|
|
|
|
metricsConfig: metricsConfig,
|
|
|
|
log: log,
|
2023-04-13 11:29:40 +00:00
|
|
|
jp: jp,
|
2019-08-07 23:14:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pc.pLister = pInformer.Lister()
|
2020-08-19 16:07:23 +00:00
|
|
|
pc.npLister = npInformer.Lister()
|
2020-05-27 05:26:07 +00:00
|
|
|
pc.nsLister = namespaces.Lister()
|
2022-04-25 12:20:40 +00:00
|
|
|
pc.urLister = urInformer.Lister()
|
2021-06-08 19:37:19 +00:00
|
|
|
|
2022-06-28 04:55:52 +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
|
|
|
|
2019-08-07 23:14:33 +00:00
|
|
|
return &pc, nil
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) canBackgroundProcess(p kyvernov1.PolicyInterface) bool {
|
2022-03-31 06:44:00 +00:00
|
|
|
logger := pc.log.WithValues("policy", p.GetName())
|
2023-12-22 13:07:17 +00:00
|
|
|
if !p.GetSpec().HasGenerate() && !p.GetSpec().HasMutateExisting() {
|
2023-12-20 16:29:37 +00:00
|
|
|
logger.V(4).Info("policy does not have background rules for reconciliation")
|
|
|
|
return false
|
2020-05-26 17:36:56 +00:00
|
|
|
}
|
|
|
|
|
2023-04-28 13:54:17 +00:00
|
|
|
if err := policyvalidation.ValidateVariables(p, true); err != nil {
|
2020-05-26 17:36:56 +00:00
|
|
|
logger.V(4).Info("policy cannot be processed in the background")
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2023-12-22 13:07:17 +00:00
|
|
|
if p.GetSpec().HasMutateExisting() {
|
2023-12-20 16:29:37 +00:00
|
|
|
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()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-26 17:36:56 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) addPolicy(obj interface{}) {
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := pc.log
|
2023-06-14 13:52:27 +00:00
|
|
|
p := castPolicy(obj)
|
2023-02-22 10:49:09 +00:00
|
|
|
logger.Info("policy created", "uid", p.GetUID(), "kind", p.GetKind(), "namespace", p.GetNamespace(), "name", p.GetName())
|
2021-01-07 04:34:01 +00:00
|
|
|
|
2020-05-26 17:36:56 +00:00
|
|
|
if !pc.canBackgroundProcess(p) {
|
|
|
|
return
|
2019-12-31 01:08:50 +00:00
|
|
|
}
|
2020-05-26 17:36:56 +00:00
|
|
|
|
2023-02-22 10:49:09 +00:00
|
|
|
logger.V(4).Info("queuing policy for background processing", "name", p.GetName())
|
2019-08-07 23:14:33 +00:00
|
|
|
pc.enqueuePolicy(p)
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) updatePolicy(old, cur interface{}) {
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := pc.log
|
2023-06-14 13:52:27 +00:00
|
|
|
oldP := castPolicy(old)
|
|
|
|
curP := castPolicy(cur)
|
2022-03-31 06:44:00 +00:00
|
|
|
if !pc.canBackgroundProcess(curP) {
|
2020-08-19 16:07:23 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-03-24 10:01:49 +00:00
|
|
|
if datautils.DeepEqual(oldP.GetSpec(), curP.GetSpec()) {
|
2020-11-09 19:26:12 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2023-02-22 10:49:09 +00:00
|
|
|
logger.V(2).Info("updating policy", "name", oldP.GetName())
|
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))
|
|
|
|
}
|
|
|
|
}
|
2020-12-09 07:04:16 +00:00
|
|
|
|
2022-03-31 06:44:00 +00:00
|
|
|
pc.enqueuePolicy(curP)
|
2020-08-19 16:07:23 +00:00
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) deletePolicy(obj interface{}) {
|
2020-08-19 16:07:23 +00:00
|
|
|
logger := pc.log
|
2023-02-22 10:49:09 +00:00
|
|
|
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:
|
2022-08-03 16:17:07 +00:00
|
|
|
logger.Info("Failed to get deleted object", "obj", obj)
|
|
|
|
return
|
2020-08-19 16:07:23 +00:00
|
|
|
}
|
2021-01-07 04:34:01 +00:00
|
|
|
|
2023-02-22 10:49:09 +00:00
|
|
|
logger.Info("policy deleted", "uid", p.GetUID(), "kind", p.GetKind(), "namespace", p.GetNamespace(), "name", p.GetName())
|
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))
|
2022-04-26 19:18:24 +00:00
|
|
|
}
|
2020-08-19 16:07:23 +00:00
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) enqueuePolicy(policy kyvernov1.PolicyInterface) {
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := pc.log
|
2019-08-07 23:14:33 +00:00
|
|
|
key, err := cache.MetaNamespaceKeyFunc(policy)
|
|
|
|
if err != nil {
|
2020-06-30 18:53:27 +00:00
|
|
|
logger.Error(err, "failed to enqueue policy")
|
2019-08-07 23:14:33 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
pc.queue.Add(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Run begins watching and syncing.
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) Run(ctx context.Context, workers int) {
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := pc.log
|
2019-08-07 23:14:33 +00:00
|
|
|
|
|
|
|
defer utilruntime.HandleCrash()
|
|
|
|
defer pc.queue.ShutDown()
|
|
|
|
|
2020-03-17 18:05:20 +00:00
|
|
|
logger.Info("starting")
|
|
|
|
defer logger.Info("shutting down")
|
2019-08-07 23:14:33 +00:00
|
|
|
|
2022-10-03 09:19:01 +00:00
|
|
|
if !cache.WaitForNamedCacheSync("PolicyController", ctx.Done(), pc.informersSynced...) {
|
2022-06-28 04:55:52 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2022-12-21 22:33:51 +00:00
|
|
|
_, _ = pc.pInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
|
2021-06-08 19:37:19 +00:00
|
|
|
AddFunc: pc.addPolicy,
|
|
|
|
UpdateFunc: pc.updatePolicy,
|
|
|
|
DeleteFunc: pc.deletePolicy,
|
|
|
|
})
|
|
|
|
|
2022-12-21 22:33:51 +00:00
|
|
|
_, _ = pc.npInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{
|
2023-02-22 10:49:09 +00:00
|
|
|
AddFunc: pc.addPolicy,
|
|
|
|
UpdateFunc: pc.updatePolicy,
|
|
|
|
DeleteFunc: pc.deletePolicy,
|
2021-06-08 19:37:19 +00:00
|
|
|
})
|
|
|
|
|
2019-08-07 23:14:33 +00:00
|
|
|
for i := 0; i < workers; i++ {
|
2022-10-03 09:19:01 +00:00
|
|
|
go wait.UntilWithContext(ctx, pc.worker, time.Second)
|
2019-08-07 23:14:33 +00:00
|
|
|
}
|
2021-03-25 19:28:03 +00:00
|
|
|
|
2022-10-03 09:19:01 +00:00
|
|
|
go pc.forceReconciliation(ctx)
|
2021-03-25 19:28:03 +00:00
|
|
|
|
2022-10-03 09:19:01 +00:00
|
|
|
<-ctx.Done()
|
2019-08-07 23:14:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// 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.
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) worker(ctx context.Context) {
|
2019-08-07 23:14:33 +00:00
|
|
|
for pc.processNextWorkItem() {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) processNextWorkItem() bool {
|
2019-08-07 23:14:33 +00:00
|
|
|
key, quit := pc.queue.Get()
|
|
|
|
if quit {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
defer pc.queue.Done(key)
|
2020-06-30 18:53:27 +00:00
|
|
|
err := pc.syncPolicy(key.(string))
|
2019-08-07 23:14:33 +00:00
|
|
|
pc.handleErr(err, key)
|
|
|
|
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) handleErr(err error, key interface{}) {
|
2020-03-17 18:05:20 +00:00
|
|
|
logger := pc.log
|
2019-08-07 23:14:33 +00:00
|
|
|
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)
|
2019-08-07 23:14:33 +00:00
|
|
|
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)
|
2019-08-07 23:14:33 +00:00
|
|
|
pc.queue.Forget(key)
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) syncPolicy(key string) error {
|
2020-12-21 19:04:19 +00:00
|
|
|
logger := pc.log.WithName("syncPolicy")
|
2019-08-07 23:14:33 +00:00
|
|
|
startTime := time.Now()
|
2020-03-17 18:05:20 +00:00
|
|
|
logger.V(4).Info("started syncing policy", "key", key, "startTime", startTime)
|
2019-08-07 23:14:33 +00:00
|
|
|
defer func() {
|
2020-07-09 18:48:34 +00:00
|
|
|
logger.V(4).Info("finished syncing policy", "key", key, "processingTime", time.Since(startTime).String())
|
2019-08-07 23:14:33 +00:00
|
|
|
}()
|
2020-05-17 16:51:46 +00:00
|
|
|
|
2020-12-21 19:04:19 +00:00
|
|
|
policy, err := pc.getPolicy(key)
|
2020-11-09 19:26:12 +00:00
|
|
|
if err != nil {
|
2022-12-29 10:08:50 +00:00
|
|
|
if apierrors.IsNotFound(err) {
|
2020-11-09 19:26:12 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
return err
|
2022-04-29 05:31:02 +00:00
|
|
|
} else {
|
2023-02-22 10:49:09 +00:00
|
|
|
err = pc.handleMutate(key, policy)
|
|
|
|
if err != nil {
|
|
|
|
logger.Error(err, "failed to updateUR on mutate policy update")
|
|
|
|
}
|
|
|
|
|
|
|
|
err = pc.handleGenerate(key, policy)
|
2022-05-09 07:13:11 +00:00
|
|
|
if err != nil {
|
2023-02-22 10:49:09 +00:00
|
|
|
logger.Error(err, "failed to updateUR on generate policy update")
|
2022-05-09 07:13:11 +00:00
|
|
|
}
|
2019-08-07 23:14:33 +00:00
|
|
|
}
|
2020-12-21 19:04:19 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) getPolicy(key string) (kyvernov1.PolicyInterface, error) {
|
2022-12-21 16:44:02 +00:00
|
|
|
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)
|
2020-12-21 19:04:19 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-29 10:08:50 +00:00
|
|
|
// forceReconciliation forces a background scan by adding all policies to the workqueue
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) forceReconciliation(ctx context.Context) {
|
2022-12-29 10:08:50 +00:00
|
|
|
logger := pc.log.WithName("forceReconciliation")
|
|
|
|
ticker := time.NewTicker(pc.reconcilePeriod)
|
|
|
|
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2023-05-09 15:18:03 +00:00
|
|
|
logger.Info("reconciling generate and mutateExisting policies", "scan interval", pc.reconcilePeriod.String())
|
2022-12-29 10:08:50 +00:00
|
|
|
pc.requeuePolicies()
|
|
|
|
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) requeuePolicies() {
|
2022-12-29 10:08:50 +00:00
|
|
|
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")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-13 11:29:40 +00:00
|
|
|
func (pc *policyController) handleUpdateRequest(ur *kyvernov1beta1.UpdateRequest, triggerResource *unstructured.Unstructured, rule kyvernov1.Rule, policy kyvernov1.PolicyInterface) (skip bool, err error) {
|
2023-02-02 08:56:00 +00:00
|
|
|
namespaceLabels := engineutils.GetNamespaceSelectorsFromNamespaceLister(triggerResource.GetKind(), triggerResource.GetNamespace(), pc.nsLister, pc.log)
|
2023-04-13 11:29:40 +00:00
|
|
|
policyContext, err := backgroundcommon.NewBackgroundContext(pc.log, pc.client, ur, policy, triggerResource, pc.configuration, pc.jp, namespaceLabels)
|
2022-12-29 10:08:50 +00:00
|
|
|
if err != nil {
|
2023-02-01 06:38:04 +00:00
|
|
|
return false, fmt.Errorf("failed to build policy context for rule %s: %w", rule.Name, err)
|
2022-12-29 10:08:50 +00:00
|
|
|
}
|
|
|
|
|
2023-02-08 05:55:03 +00:00
|
|
|
engineResponse := pc.engine.ApplyBackgroundChecks(context.TODO(), policyContext)
|
2022-12-29 10:08:50 +00:00
|
|
|
if len(engineResponse.PolicyResponse.Rules) == 0 {
|
|
|
|
return true, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, ruleResponse := range engineResponse.PolicyResponse.Rules {
|
2023-04-05 10:35:38 +00:00
|
|
|
if ruleResponse.Status() != engineapi.RuleStatusPass {
|
2023-06-14 12:36:26 +00:00
|
|
|
pc.log.V(4).Info("skip creating URs on policy update", "policy", policy.GetName(), "rule", rule.Name, "rule.Status", ruleResponse.Status())
|
2022-12-29 10:08:50 +00:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
pc.log.V(2).Info("creating new UR for generate")
|
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{})
|
2022-12-29 10:08:50 +00:00
|
|
|
if err != nil {
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false, err
|
|
|
|
}
|
|
|
|
|
2022-05-17 14:40:51 +00:00
|
|
|
func generateTriggers(client dclient.Interface, rule kyvernov1.Rule, log logr.Logger) []*unstructured.Unstructured {
|
2022-05-09 07:13:11 +00:00
|
|
|
list := &unstructured.UnstructuredList{}
|
|
|
|
|
|
|
|
kinds := fetchUniqueKinds(rule)
|
|
|
|
|
|
|
|
for _, kind := range kinds {
|
2022-11-29 13:59:40 +00:00
|
|
|
mlist, err := client.ListResource(context.TODO(), "", kind, "", rule.MatchResources.Selector)
|
2022-05-09 07:13:11 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Error(err, "failed to list matched resource")
|
2022-08-31 06:03:47 +00:00
|
|
|
continue
|
2022-05-09 07:13:11 +00:00
|
|
|
}
|
|
|
|
list.Items = append(list.Items, mlist.Items...)
|
|
|
|
}
|
|
|
|
return convertlist(list.Items)
|
|
|
|
}
|