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

131 lines
4.6 KiB
Go
Raw Normal View History

2019-05-14 01:17:28 +00:00
package engine
2019-05-10 05:26:22 +00:00
import (
2019-08-19 23:40:10 +00:00
"time"
2020-03-17 18:05:20 +00:00
"github.com/go-logr/logr"
kyverno "github.com/kyverno/kyverno/pkg/api/kyverno/v1"
"github.com/kyverno/kyverno/pkg/engine/mutate"
"github.com/kyverno/kyverno/pkg/engine/response"
"github.com/kyverno/kyverno/pkg/engine/variables"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2020-03-17 23:25:34 +00:00
"sigs.k8s.io/controller-runtime/pkg/log"
2019-05-10 05:26:22 +00:00
)
const (
// PodControllerCronJob represent CronJob string
PodControllerCronJob = "CronJob"
//PodControllers stores the list of Pod-controllers in csv string
PodControllers = "DaemonSet,Deployment,Job,StatefulSet,CronJob"
//PodControllersAnnotation defines the annotation key for Pod-Controllers
PodControllersAnnotation = "pod-policies.kyverno.io/autogen-controllers"
)
// Mutate performs mutation. Overlay first and then mutation patches
2020-12-23 23:10:07 +00:00
func Mutate(policyContext *PolicyContext) (resp *response.EngineResponse) {
resp = &response.EngineResponse{}
2019-08-24 01:34:23 +00:00
startTime := time.Now()
policy := policyContext.Policy
patchedResource := policyContext.NewResource
2020-12-23 23:10:07 +00:00
ctx := policyContext.JSONContext
resCache := policyContext.ResourceCache
logger := log.Log.WithName("EngineMutate").WithValues("policy", policy.Name, "kind", patchedResource.GetKind(),
"namespace", patchedResource.GetNamespace(), "name", patchedResource.GetName())
logger.V(4).Info("start policy processing", "startTime", startTime)
2020-12-23 23:10:07 +00:00
startMutateResultResponse(resp, policy, patchedResource)
defer endMutateResultResponse(logger, resp, startTime)
2020-12-23 23:10:07 +00:00
if ManagedPodResource(policy, patchedResource) {
2020-12-09 22:41:20 +00:00
logger.V(5).Info("skip applying policy as direct changes to pods managed by workload controllers are not allowed", "policy", policy.GetName())
resp.PatchedResource = patchedResource
return
}
policyContext.JSONContext.Checkpoint()
defer policyContext.JSONContext.Restore()
2019-08-24 01:34:23 +00:00
for _, rule := range policy.Spec.Rules {
2020-02-14 19:59:28 +00:00
var ruleResponse response.RuleResponse
2020-03-17 18:05:20 +00:00
logger := logger.WithValues("rule", rule.Name)
if !rule.HasMutate() {
2019-08-24 01:34:23 +00:00
continue
}
2019-08-24 01:34:23 +00:00
// check if the resource satisfies the filter conditions defined in the rule
//TODO: this needs to be extracted, to filter the resource so that we can avoid passing resources that
2020-05-19 20:04:06 +00:00
// dont satisfy a policy rule resource description
excludeResource := []string{}
if len(policyContext.ExcludeGroupRole) > 0 {
excludeResource = policyContext.ExcludeGroupRole
}
2020-12-23 23:10:07 +00:00
if err := MatchesResourceDescription(patchedResource, rule, policyContext.AdmissionInfo, excludeResource, policyContext.NamespaceLabels); err != nil {
logger.V(4).Info("rule not matched", "reason", err.Error())
2019-08-24 01:34:23 +00:00
continue
}
2020-10-15 00:39:45 +00:00
logger.V(3).Info("matched mutate rule")
policyContext.JSONContext.Restore()
api server lookups (#1514) * initial commit for api server lookups Signed-off-by: Jim Bugwadia <jim@nirmata.com> * initial commit for API server lookups Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Enhancing dockerfiles (multi-stage) of kyverno components and adding non-root user to the docker images (#1495) * Dockerfile refactored Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * Adding non-root commands to docker images and enhanced the dockerfiles Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * changing base image to scratch Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * Minor typo fix Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * changing dockerfiles to use /etc/passwd to use non-root user' Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * minor typo Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> * minor typo Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> Signed-off-by: Jim Bugwadia <jim@nirmata.com> * revert cli image name (#1507) Signed-off-by: Raj Babu Das <mail.rajdas@gmail.com> Signed-off-by: Jim Bugwadia <jim@nirmata.com> * Refactor resourceCache; Reduce throttling requests (background controller) (#1500) * skip sending API request for filtered resource * fix PR comment Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fixes https://github.com/kyverno/kyverno/issues/1490 Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix bug - namespace is not returned properly Signed-off-by: Shuting Zhao <shutting06@gmail.com> * reduce throttling - list resource using lister * refactor resource cache * fix test Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix label selector Signed-off-by: Shuting Zhao <shutting06@gmail.com> * fix build failure Signed-off-by: Shuting Zhao <shutting06@gmail.com> Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix merge issues Signed-off-by: Jim Bugwadia <jim@nirmata.com> * fix unit test Signed-off-by: Jim Bugwadia <jim@nirmata.com> * add nil check for API client Signed-off-by: Jim Bugwadia <jim@nirmata.com> Co-authored-by: Raj Babu Das <mail.rajdas@gmail.com> Co-authored-by: shuting <shutting06@gmail.com>
2021-02-01 20:59:13 +00:00
if err := LoadContext(logger, rule.Context, resCache, policyContext); err != nil {
logger.Error(err, "failed to load context")
continue
}
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
// operate on the copy of the conditions, as we perform variable substitution
copyConditions := copyConditions(rule.Conditions)
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
// evaluate pre-conditions
// - handle variable substitutions
2020-03-17 18:05:20 +00:00
if !variables.EvaluateConditions(logger, ctx, copyConditions) {
logger.V(3).Info("resource fails the preconditions")
593 feature (#594) * initial commit * background policy validation * correct message * skip non-background policy process for add/update * add Generate Request CR * generate Request Generator Initial * test generate request CR generation * initial commit gr generator * generate controller initial framework * add crd for generate request * gr cleanup controller initial commit * cleanup controller initial * generate mid-commit * generate rule processing * create PV on generate error * embed resource type * testing phase 1- generate resources with variable substitution * fix tests * comment broken test #586 * add printer column for state * return if existing resource for clone * set resync time to 2 mins & remove resource version check in update handler for gr * generate events for reporting * fix logs * initial commit * fix trailing quote in patch * remove comments * initial condition (equal & notequal) * initial support for conditions * initial support fo conditions in generate * support precondition checks * cleanup * re-evaluate GR on namespace update using dynamic informers * add status for generated resources * display loaded variable SA * support delete cleanup of generate request main resources * fix log * remove namespace from SA username * support multiple variables per statement for scalar values * fix fail variables * add check for userInfo * validation checks for conditions * update policy * refactor logs * code review * add openapispec for clusterpolicy preconditions * Update documentation * CR fixes * documentation * CR fixes * update variable * fix logs * update policy * pre-defined variables (serviceAccountName & serviceAccountNamespace) * update test
2020-01-07 23:13:57 +00:00
continue
}
2020-02-14 19:59:28 +00:00
mutation := rule.Mutation.DeepCopy()
mutateHandler := mutate.CreateMutateHandler(rule.Name, mutation, patchedResource, ctx, logger)
ruleResponse, patchedResource = mutateHandler.Handle()
if ruleResponse.Success {
// - overlay pattern does not match the resource conditions
if ruleResponse.Patches == nil {
continue
2019-08-24 01:34:23 +00:00
}
2020-12-23 23:10:07 +00:00
logger.V(4).Info("mutate rule applied successfully", "ruleName", rule.Name)
2019-08-24 01:34:23 +00:00
}
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResponse)
2020-12-23 23:10:07 +00:00
incrementAppliedRuleCount(resp)
}
resp.PatchedResource = patchedResource
return resp
2019-08-24 01:34:23 +00:00
}
2020-04-04 17:09:21 +00:00
2020-02-14 19:59:28 +00:00
func incrementAppliedRuleCount(resp *response.EngineResponse) {
resp.PolicyResponse.RulesAppliedCount++
}
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.ClusterPolicy, resource unstructured.Unstructured) {
2020-12-23 23:10:07 +00:00
if resp == nil {
return
}
resp.PolicyResponse.Policy = policy.Name
resp.PolicyResponse.Resource.Name = resource.GetName()
resp.PolicyResponse.Resource.Namespace = resource.GetNamespace()
resp.PolicyResponse.Resource.Kind = resource.GetKind()
resp.PolicyResponse.Resource.APIVersion = resource.GetAPIVersion()
}
2020-03-17 18:05:20 +00:00
func endMutateResultResponse(logger logr.Logger, resp *response.EngineResponse, startTime time.Time) {
2020-12-23 23:10:07 +00:00
if resp == nil {
return
}
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
logger.V(5).Info("finished processing policy", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "mutationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
}