mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-31 03:45:17 +00:00
refactor: return structs instead of pointer in engine api (#6647)
* refactor: return structs instead of pointer in engine api 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 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> --------- Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
parent
6249ab70e8
commit
6a0a336755
15 changed files with 53 additions and 60 deletions
|
@ -492,15 +492,10 @@ OuterLoop:
|
|||
WithAdmissionInfo(c.UserInfo).
|
||||
WithResourceKind(gvk, subresource)
|
||||
|
||||
mutateResponse := eng.Mutate(
|
||||
context.Background(),
|
||||
policyContext,
|
||||
)
|
||||
if mutateResponse != nil {
|
||||
engineResponses = append(engineResponses, mutateResponse)
|
||||
}
|
||||
mutateResponse := eng.Mutate(context.Background(), policyContext)
|
||||
engineResponses = append(engineResponses, &mutateResponse)
|
||||
|
||||
err = processMutateEngineResponse(c, mutateResponse, resPath)
|
||||
err = processMutateEngineResponse(c, &mutateResponse, resPath)
|
||||
if err != nil {
|
||||
if !sanitizederror.IsErrorSanitized(err) {
|
||||
return engineResponses, Info{}, sanitizederror.NewWithError("failed to print mutated result", err)
|
||||
|
@ -517,17 +512,14 @@ OuterLoop:
|
|||
policyContext = policyContext.WithNewResource(mutateResponse.PatchedResource)
|
||||
|
||||
var info Info
|
||||
var validateResponse *engineapi.EngineResponse
|
||||
var validateResponse engineapi.EngineResponse
|
||||
if policyHasValidate {
|
||||
validateResponse = eng.Validate(
|
||||
context.Background(),
|
||||
policyContext,
|
||||
)
|
||||
info = ProcessValidateEngineResponse(c.Policy, validateResponse, resPath, c.Rc, c.PolicyReport, c.AuditWarn)
|
||||
validateResponse = eng.Validate(context.Background(), policyContext)
|
||||
info = ProcessValidateEngineResponse(c.Policy, &validateResponse, resPath, c.Rc, c.PolicyReport, c.AuditWarn)
|
||||
}
|
||||
|
||||
if validateResponse != nil && !validateResponse.IsEmpty() {
|
||||
engineResponses = append(engineResponses, validateResponse)
|
||||
if !validateResponse.IsEmpty() {
|
||||
engineResponses = append(engineResponses, &validateResponse)
|
||||
}
|
||||
|
||||
verifyImageResponse, _ := eng.VerifyAndPatchImages(context.TODO(), policyContext)
|
||||
|
@ -545,16 +537,16 @@ OuterLoop:
|
|||
|
||||
if policyHasGenerate {
|
||||
generateResponse := eng.ApplyBackgroundChecks(context.TODO(), policyContext)
|
||||
if generateResponse != nil && !generateResponse.IsEmpty() {
|
||||
newRuleResponse, err := handleGeneratePolicy(generateResponse, *policyContext, c.RuleToCloneSourceResource)
|
||||
if !generateResponse.IsEmpty() {
|
||||
newRuleResponse, err := handleGeneratePolicy(&generateResponse, *policyContext, c.RuleToCloneSourceResource)
|
||||
if err != nil {
|
||||
log.Log.Error(err, "failed to apply generate policy")
|
||||
} else {
|
||||
generateResponse.PolicyResponse.Rules = newRuleResponse
|
||||
}
|
||||
engineResponses = append(engineResponses, generateResponse)
|
||||
engineResponses = append(engineResponses, &generateResponse)
|
||||
}
|
||||
updateResultCounts(c.Policy, generateResponse, resPath, c.Rc, c.AuditWarn)
|
||||
updateResultCounts(c.Policy, &generateResponse, resPath, c.Rc, c.AuditWarn)
|
||||
}
|
||||
|
||||
return engineResponses, info, nil
|
||||
|
|
|
@ -85,7 +85,8 @@ func (s *scanner) validateResource(ctx context.Context, resource unstructured.Un
|
|||
WithNewResource(resource).
|
||||
WithPolicy(policy).
|
||||
WithNamespaceLabels(nsLabels)
|
||||
return s.engine.Validate(ctx, policyCtx), nil
|
||||
response := s.engine.Validate(ctx, policyCtx)
|
||||
return &response, nil
|
||||
}
|
||||
|
||||
func (s *scanner) validateImages(ctx context.Context, resource unstructured.Unstructured, nsLabels map[string]string, policy kyvernov1.PolicyInterface) (*engineapi.EngineResponse, error) {
|
||||
|
|
|
@ -16,13 +16,13 @@ type Engine interface {
|
|||
Validate(
|
||||
ctx context.Context,
|
||||
policyContext PolicyContext,
|
||||
) *EngineResponse
|
||||
) EngineResponse
|
||||
|
||||
// Mutate performs mutation. Overlay first and then mutation patches
|
||||
Mutate(
|
||||
ctx context.Context,
|
||||
policyContext PolicyContext,
|
||||
) *EngineResponse
|
||||
) EngineResponse
|
||||
|
||||
// VerifyAndPatchImages ...
|
||||
VerifyAndPatchImages(
|
||||
|
@ -38,14 +38,14 @@ type Engine interface {
|
|||
ApplyBackgroundChecks(
|
||||
ctx context.Context,
|
||||
policyContext PolicyContext,
|
||||
) *EngineResponse
|
||||
) EngineResponse
|
||||
|
||||
// GenerateResponse checks for validity of generate rule on the resource
|
||||
GenerateResponse(
|
||||
ctx context.Context,
|
||||
policyContext PolicyContext,
|
||||
gr kyvernov1beta1.UpdateRequest,
|
||||
) *EngineResponse
|
||||
) EngineResponse
|
||||
|
||||
ContextLoader(
|
||||
policy kyvernov1.PolicyInterface,
|
||||
|
|
|
@ -22,7 +22,7 @@ func (e *engine) applyBackgroundChecks(
|
|||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
) engineapi.EngineResponse {
|
||||
return e.filterRules(policyContext, logger, time.Now())
|
||||
}
|
||||
|
||||
|
@ -30,7 +30,7 @@ func (e *engine) filterRules(
|
|||
policyContext engineapi.PolicyContext,
|
||||
logger logr.Logger,
|
||||
startTime time.Time,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
newResource := policyContext.NewResource()
|
||||
policy := policyContext.Policy()
|
||||
kind := newResource.GetKind()
|
||||
|
@ -47,7 +47,7 @@ func (e *engine) filterRules(
|
|||
|
||||
if e.configuration.ToFilter(kind, namespace, name) {
|
||||
logger.Info("resource excluded")
|
||||
return resp
|
||||
return *resp
|
||||
}
|
||||
|
||||
applyRules := policy.GetSpec().GetApplyRules()
|
||||
|
@ -61,7 +61,7 @@ func (e *engine) filterRules(
|
|||
}
|
||||
}
|
||||
|
||||
return resp
|
||||
return *resp
|
||||
}
|
||||
|
||||
func (e *engine) filterRule(
|
||||
|
|
|
@ -41,7 +41,7 @@ func NewEngine(
|
|||
func (e *engine) Validate(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.validate"), policyContext)
|
||||
return e.validate(ctx, logger, policyContext)
|
||||
}
|
||||
|
@ -49,7 +49,7 @@ func (e *engine) Validate(
|
|||
func (e *engine) Mutate(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.mutate"), policyContext)
|
||||
return e.mutate(ctx, logger, policyContext)
|
||||
}
|
||||
|
@ -65,7 +65,7 @@ func (e *engine) VerifyAndPatchImages(
|
|||
func (e *engine) ApplyBackgroundChecks(
|
||||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.background"), policyContext)
|
||||
return e.applyBackgroundChecks(ctx, logger, policyContext)
|
||||
}
|
||||
|
@ -74,7 +74,7 @@ func (e *engine) GenerateResponse(
|
|||
ctx context.Context,
|
||||
policyContext engineapi.PolicyContext,
|
||||
gr kyvernov1beta1.UpdateRequest,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
logger := internal.LoggerWithPolicyContext(logging.WithName("engine.generate"), policyContext)
|
||||
return e.generateResponse(ctx, logger, policyContext, gr)
|
||||
}
|
||||
|
|
|
@ -17,7 +17,7 @@ func (e *engine) generateResponse(
|
|||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
gr kyvernov1beta1.UpdateRequest,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
) engineapi.EngineResponse {
|
||||
return e.filterGenerateRules(policyContext, logger, gr.Spec.Policy, time.Now())
|
||||
}
|
||||
|
||||
|
@ -26,7 +26,7 @@ func (e *engine) filterGenerateRules(
|
|||
logger logr.Logger,
|
||||
policyNameKey string,
|
||||
startTime time.Time,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
newResource := policyContext.NewResource()
|
||||
kind := newResource.GetKind()
|
||||
name := newResource.GetName()
|
||||
|
@ -41,7 +41,7 @@ func (e *engine) filterGenerateRules(
|
|||
}
|
||||
if e.configuration.ToFilter(kind, namespace, name) {
|
||||
logger.Info("resource excluded")
|
||||
return resp
|
||||
return *resp
|
||||
}
|
||||
for _, rule := range autogen.ComputeRules(policyContext.Policy()) {
|
||||
logger := internal.LoggerWithRule(logger, rule)
|
||||
|
@ -49,5 +49,5 @@ func (e *engine) filterGenerateRules(
|
|||
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
|
||||
}
|
||||
}
|
||||
return resp
|
||||
return *resp
|
||||
}
|
||||
|
|
|
@ -24,10 +24,10 @@ func (e *engine) mutate(
|
|||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) (resp *engineapi.EngineResponse) {
|
||||
) engineapi.EngineResponse {
|
||||
startTime := time.Now()
|
||||
policy := policyContext.Policy()
|
||||
resp = engineapi.NewEngineResponseFromPolicyContext(policyContext, nil)
|
||||
resp := engineapi.NewEngineResponseFromPolicyContext(policyContext, nil)
|
||||
matchedResource := policyContext.NewResource()
|
||||
var skippedRules []string
|
||||
|
||||
|
@ -167,7 +167,7 @@ func (e *engine) mutate(
|
|||
}
|
||||
|
||||
resp.PatchedResource = matchedResource
|
||||
return resp
|
||||
return *resp
|
||||
}
|
||||
|
||||
func mutateResource(rule *kyvernov1.Rule, ctx engineapi.PolicyContext, resource unstructured.Unstructured, logger logr.Logger) *mutate.Response {
|
||||
|
|
|
@ -26,7 +26,7 @@ func testMutate(
|
|||
rclient registryclient.Client,
|
||||
pContext *PolicyContext,
|
||||
contextLoader engineapi.ContextLoaderFactory,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
if contextLoader == nil {
|
||||
contextLoader = engineapi.DefaultContextLoaderFactory(nil)
|
||||
}
|
||||
|
@ -1023,7 +1023,7 @@ func Test_foreach_order_mutation_(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
func testApplyPolicyToResource(t *testing.T, policyRaw, resourceRaw []byte) *engineapi.EngineResponse {
|
||||
func testApplyPolicyToResource(t *testing.T, policyRaw, resourceRaw []byte) engineapi.EngineResponse {
|
||||
var policy kyverno.ClusterPolicy
|
||||
err := json.Unmarshal(policyRaw, &policy)
|
||||
assert.NilError(t, err)
|
||||
|
|
|
@ -33,14 +33,14 @@ func (e *engine) validate(
|
|||
ctx context.Context,
|
||||
logger logr.Logger,
|
||||
policyContext engineapi.PolicyContext,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
startTime := time.Now()
|
||||
logger.V(4).Info("start validate policy processing", "startTime", startTime)
|
||||
policyResponse := e.validateResource(ctx, logger, policyContext)
|
||||
defer logger.V(4).Info("finished policy processing", "processingTime", policyResponse.Stats.ProcessingTime.String(), "validationRulesApplied", policyResponse.Stats.RulesAppliedCount)
|
||||
engineResponse := engineapi.NewEngineResponseFromPolicyContext(policyContext, nil)
|
||||
engineResponse.PolicyResponse = *policyResponse
|
||||
return internal.BuildResponse(policyContext, engineResponse, startTime)
|
||||
return *internal.BuildResponse(policyContext, engineResponse, startTime)
|
||||
}
|
||||
|
||||
func (e *engine) validateResource(
|
||||
|
|
|
@ -25,7 +25,7 @@ func testValidate(
|
|||
pContext *PolicyContext,
|
||||
cfg config.Configuration,
|
||||
contextLoader engineapi.ContextLoaderFactory,
|
||||
) *engineapi.EngineResponse {
|
||||
) engineapi.EngineResponse {
|
||||
if contextLoader == nil {
|
||||
contextLoader = engineapi.DefaultContextLoaderFactory(nil)
|
||||
}
|
||||
|
|
|
@ -124,8 +124,8 @@ func (h *generationHandler) handleTrigger(
|
|||
h.applyGeneration(ctx, request, policy, appliedRules, policyContext)
|
||||
h.syncTriggerAction(ctx, request, policy, failedRules, policyContext)
|
||||
|
||||
go webhookutils.RegisterPolicyResultsMetricGeneration(ctx, h.log, h.metrics, string(request.Operation), policy, *engineResponse)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricGenerate(ctx, h.log, h.metrics, string(request.Operation), policy, *engineResponse)
|
||||
go webhookutils.RegisterPolicyResultsMetricGeneration(ctx, h.log, h.metrics, string(request.Operation), policy, engineResponse)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricGenerate(ctx, h.log, h.metrics, string(request.Operation), policy, engineResponse)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -168,7 +168,7 @@ func (h *mutationHandler) applyMutation(ctx context.Context, request *admissionv
|
|||
}
|
||||
}
|
||||
|
||||
return engineResponse, policyPatches, nil
|
||||
return &engineResponse, policyPatches, nil
|
||||
}
|
||||
|
||||
func logMutationResponse(patches [][]byte, engineResponses []*engineapi.EngineResponse, logger logr.Logger) {
|
||||
|
|
|
@ -58,13 +58,13 @@ func (h *handlers) handleMutateExisting(ctx context.Context, logger logr.Logger,
|
|||
|
||||
if len(rules) > 0 {
|
||||
engineResponse.PolicyResponse.Rules = rules
|
||||
engineResponses = append(engineResponses, engineResponse)
|
||||
engineResponses = append(engineResponses, &engineResponse)
|
||||
}
|
||||
|
||||
// registering the kyverno_policy_results_total metric concurrently
|
||||
go webhookutils.RegisterPolicyResultsMetricMutation(context.TODO(), logger, h.metricsConfig, string(request.Operation), policy, *engineResponse)
|
||||
go webhookutils.RegisterPolicyResultsMetricMutation(context.TODO(), logger, h.metricsConfig, string(request.Operation), policy, engineResponse)
|
||||
// registering the kyverno_policy_execution_duration_seconds metric concurrently
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricMutate(context.TODO(), logger, h.metricsConfig, string(request.Operation), policy, *engineResponse)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricMutate(context.TODO(), logger, h.metricsConfig, string(request.Operation), policy, engineResponse)
|
||||
}
|
||||
|
||||
if failedResponse := applyUpdateRequest(ctx, request, kyvernov1beta1.Mutate, h.urGenerator, policyContext.AdmissionInfo(), request.Operation, engineResponses...); failedResponse != nil {
|
||||
|
|
|
@ -109,10 +109,10 @@ func (v *validationHandler) HandleValidation(
|
|||
return
|
||||
}
|
||||
|
||||
go webhookutils.RegisterPolicyResultsMetricValidation(ctx, logger, v.metrics, string(request.Operation), policyContext.Policy(), *engineResponse)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricValidate(ctx, logger, v.metrics, string(request.Operation), policyContext.Policy(), *engineResponse)
|
||||
go webhookutils.RegisterPolicyResultsMetricValidation(ctx, logger, v.metrics, string(request.Operation), policyContext.Policy(), engineResponse)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricValidate(ctx, logger, v.metrics, string(request.Operation), policyContext.Policy(), engineResponse)
|
||||
|
||||
engineResponses = append(engineResponses, engineResponse)
|
||||
engineResponses = append(engineResponses, &engineResponse)
|
||||
if !engineResponse.IsSuccessful() {
|
||||
logger.V(2).Info("validation failed", "action", policy.GetSpec().ValidationFailureAction, "policy", policy.GetName(), "failed rules", engineResponse.GetFailedRules())
|
||||
return
|
||||
|
@ -163,9 +163,9 @@ func (v *validationHandler) buildAuditResponses(
|
|||
func(ctx context.Context, span trace.Span) {
|
||||
policyContext := policyContext.WithPolicy(policy).WithNamespaceLabels(namespaceLabels)
|
||||
response := v.engine.Validate(ctx, policyContext)
|
||||
responses = append(responses, response)
|
||||
go webhookutils.RegisterPolicyResultsMetricValidation(ctx, v.log, v.metrics, string(request.Operation), policyContext.Policy(), *response)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricValidate(ctx, v.log, v.metrics, string(request.Operation), policyContext.Policy(), *response)
|
||||
responses = append(responses, &response)
|
||||
go webhookutils.RegisterPolicyResultsMetricValidation(ctx, v.log, v.metrics, string(request.Operation), policyContext.Policy(), response)
|
||||
go webhookutils.RegisterPolicyExecutionDurationMetricValidate(ctx, v.log, v.metrics, string(request.Operation), policyContext.Policy(), response)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
|
|
@ -1077,7 +1077,7 @@ func TestValidate_failure_action_overrides(t *testing.T) {
|
|||
}
|
||||
|
||||
failurePolicy := kyvernov1.Fail
|
||||
blocked := webhookutils.BlockRequest([]*engineapi.EngineResponse{er}, failurePolicy, log.WithName("WebhookServer"))
|
||||
blocked := webhookutils.BlockRequest([]*engineapi.EngineResponse{&er}, failurePolicy, log.WithName("WebhookServer"))
|
||||
assert.Assert(t, tc.blocked == blocked)
|
||||
})
|
||||
}
|
||||
|
@ -1143,7 +1143,7 @@ func Test_RuleSelector(t *testing.T) {
|
|||
assert.Assert(t, resp.PolicyResponse.Stats.RulesErrorCount == 0)
|
||||
|
||||
log := log.WithName("Test_RuleSelector")
|
||||
blocked := webhookutils.BlockRequest([]*engineapi.EngineResponse{resp}, kyvernov1.Fail, log)
|
||||
blocked := webhookutils.BlockRequest([]*engineapi.EngineResponse{&resp}, kyvernov1.Fail, log)
|
||||
assert.Assert(t, blocked == true)
|
||||
|
||||
applyOne := kyvernov1.ApplyOne
|
||||
|
@ -1155,6 +1155,6 @@ func Test_RuleSelector(t *testing.T) {
|
|||
assert.Assert(t, resp.PolicyResponse.Stats.RulesAppliedCount == 1)
|
||||
assert.Assert(t, resp.PolicyResponse.Stats.RulesErrorCount == 0)
|
||||
|
||||
blocked = webhookutils.BlockRequest([]*engineapi.EngineResponse{resp}, kyvernov1.Fail, log)
|
||||
blocked = webhookutils.BlockRequest([]*engineapi.EngineResponse{&resp}, kyvernov1.Fail, log)
|
||||
assert.Assert(t, blocked == false)
|
||||
}
|
||||
|
|
Loading…
Add table
Reference in a new issue