1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2025-03-06 16:06:56 +00:00
kyverno/pkg/engine/mutation.go

160 lines
5.8 KiB
Go
Raw Normal View History

2019-05-13 18:17:28 -07:00
package engine
2019-05-09 22:26:22 -07:00
import (
2020-04-04 22:39:21 +05:30
"encoding/json"
"reflect"
"strings"
2019-08-19 16:40:10 -07:00
"time"
2020-03-17 11:05:20 -07:00
"github.com/go-logr/logr"
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1"
"github.com/nirmata/kyverno/pkg/engine/mutate"
"github.com/nirmata/kyverno/pkg/engine/response"
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 15:13:57 -08:00
"github.com/nirmata/kyverno/pkg/engine/variables"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
2020-03-17 16:25:34 -07:00
"sigs.k8s.io/controller-runtime/pkg/log"
2019-05-09 22:26:22 -07:00
)
const (
//PodControllers stores the list of Pod-controllers in csv string
PodControllers = "DaemonSet,Deployment,Job,StatefulSet"
//PodControllersAnnotation defines the annotation key for Pod-Controllers
PodControllersAnnotation = "pod-policies.kyverno.io/autogen-controllers"
//PodTemplateAnnotation defines the annotation key for Pod-Template
PodTemplateAnnotation = "pod-policies.kyverno.io/autogen-applied"
)
// Mutate performs mutation. Overlay first and then mutation patches
func Mutate(policyContext PolicyContext) (resp response.EngineResponse) {
2019-08-23 18:34:23 -07:00
startTime := time.Now()
policy := policyContext.Policy
patchedResource := policyContext.NewResource
ctx := policyContext.Context
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)
startMutateResultResponse(&resp, policy, patchedResource)
defer endMutateResultResponse(logger, &resp, startTime)
if policy.HasAutoGenAnnotation() && excludePod(patchedResource) {
logger.V(5).Info("Skip applying policy, Pod has ownerRef set", "policy", policy.GetName())
resp.PatchedResource = patchedResource
return
}
2019-08-23 18:34:23 -07:00
for _, rule := range policy.Spec.Rules {
2020-02-14 11:59:28 -08:00
var ruleResponse response.RuleResponse
2020-03-17 11:05:20 -07:00
logger := logger.WithValues("rule", rule.Name)
2019-08-23 18:34:23 -07:00
//TODO: to be checked before calling the resources as well
if !rule.HasMutate() && !strings.Contains(PodControllers, patchedResource.GetKind()) {
2019-08-23 18:34:23 -07:00
continue
}
2019-08-23 18:34:23 -07: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 13:04:06 -07:00
// dont satisfy a policy rule resource description
if err := MatchesResourceDescription(patchedResource, rule, policyContext.AdmissionInfo); err != nil {
logger.V(3).Info("resource not matched", "reason", err.Error())
2019-08-23 18:34:23 -07:00
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 15:13:57 -08: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 15:13:57 -08:00
// evaluate pre-conditions
// - handle variable substitutions
2020-03-17 11:05:20 -07: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 15:13:57 -08:00
continue
}
2020-02-14 11:59:28 -08:00
mutation := rule.Mutation.DeepCopy()
2019-08-23 18:34:23 -07:00
// Process Overlay
2020-02-14 11:59:28 -08:00
if mutation.Overlay != nil {
overlay := mutation.Overlay
// subsiitue the variables
var err error
2020-03-17 11:05:20 -07:00
if overlay, err = variables.SubstituteVars(logger, ctx, overlay); err != nil {
2020-02-14 11:59:28 -08:00
// variable subsitution failed
ruleResponse.Success = false
ruleResponse.Message = err.Error()
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResponse)
continue
}
2020-03-17 16:25:34 -07:00
ruleResponse, patchedResource = mutate.ProcessOverlay(logger, rule.Name, overlay, patchedResource)
2020-02-14 11:59:28 -08:00
if ruleResponse.Success {
// - overlay pattern does not match the resource conditions
if ruleResponse.Patches == nil {
continue
}
logger.V(4).Info("overlay applied successfully")
2019-08-23 18:34:23 -07:00
}
2019-11-13 17:56:56 -08:00
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResponse)
2020-02-14 11:59:28 -08:00
incrementAppliedRuleCount(&resp)
2019-08-23 18:34:23 -07:00
}
// Process Patches
if rule.Mutation.Patches != nil {
var ruleResponse response.RuleResponse
2020-03-17 16:25:34 -07:00
ruleResponse, patchedResource = mutate.ProcessPatches(logger, rule, patchedResource)
2020-03-17 11:05:20 -07:00
logger.V(4).Info("patches applied successfully")
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, ruleResponse)
2020-02-14 11:59:28 -08:00
incrementAppliedRuleCount(&resp)
2019-08-23 18:34:23 -07:00
}
2020-04-04 22:39:21 +05:30
}
2019-12-27 15:57:43 -08:00
// insert annotation to podtemplate if resource is pod controller
// skip inserting on UPDATE request
if !reflect.DeepEqual(policyContext.OldResource, unstructured.Unstructured{}) {
resp.PatchedResource = patchedResource
return resp
}
2019-08-23 18:34:23 -07:00
// send the patched resource
resp.PatchedResource = patchedResource
return resp
2019-08-23 18:34:23 -07:00
}
2020-04-04 22:39:21 +05:30
func patchedResourceHasPodControllerAnnotation(resource unstructured.Unstructured) bool {
var podController struct {
Spec struct {
Template struct {
Metadata struct {
Annotations map[string]interface{} `json:"annotations"`
} `json:"metadata"`
} `json:"template"`
} `json:"spec"`
}
resourceRaw, _ := json.Marshal(resource.Object)
2020-04-04 22:52:53 +05:30
_ = json.Unmarshal(resourceRaw, &podController)
2020-04-04 22:39:21 +05:30
val, ok := podController.Spec.Template.Metadata.Annotations[PodTemplateAnnotation]
2020-06-01 19:36:01 -07:00
log.Log.V(4).Info("patchedResourceHasPodControllerAnnotation", "resourceRaw", string(resourceRaw), "val", val, "ok", ok)
2020-04-04 22:39:21 +05:30
return ok
}
2020-02-14 11:59:28 -08:00
func incrementAppliedRuleCount(resp *response.EngineResponse) {
resp.PolicyResponse.RulesAppliedCount++
}
func startMutateResultResponse(resp *response.EngineResponse, policy kyverno.ClusterPolicy, resource unstructured.Unstructured) {
// set policy information
resp.PolicyResponse.Policy = policy.Name
// resource details
resp.PolicyResponse.Resource.Name = resource.GetName()
resp.PolicyResponse.Resource.Namespace = resource.GetNamespace()
resp.PolicyResponse.Resource.Kind = resource.GetKind()
resp.PolicyResponse.Resource.APIVersion = resource.GetAPIVersion()
// TODO(shuting): set response with mutationFailureAction
}
2020-03-17 11:05:20 -07:00
func endMutateResultResponse(logger logr.Logger, resp *response.EngineResponse, startTime time.Time) {
resp.PolicyResponse.ProcessingTime = time.Since(startTime)
logger.V(4).Info("finished processing policy", "processingTime", resp.PolicyResponse.ProcessingTime.String(), "mutationRulesApplied", resp.PolicyResponse.RulesAppliedCount)
}