1
0
Fork 0
mirror of https://github.com/kyverno/kyverno.git synced 2024-12-14 11:57:48 +00:00
kyverno/pkg/engine/generation.go
Charles-Edouard Brétéché 848596ca8d
refactor: introduce context loader interface in engine api (#6164)
* refactor: introduce context loader interface in engine api

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* factory

Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>

* mock

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>

* test

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-01-31 22:30:40 +08:00

70 lines
2 KiB
Go

package engine
import (
"time"
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
"github.com/kyverno/kyverno/pkg/autogen"
engineapi "github.com/kyverno/kyverno/pkg/engine/api"
"github.com/kyverno/kyverno/pkg/logging"
"k8s.io/client-go/tools/cache"
)
// GenerateResponse checks for validity of generate rule on the resource
func GenerateResponse(
contextLoader ContextLoaderFactory,
policyContext *PolicyContext,
gr kyvernov1beta1.UpdateRequest,
) (resp *engineapi.EngineResponse) {
policyStartTime := time.Now()
return filterGenerateRules(contextLoader, policyContext, gr.Spec.Policy, policyStartTime)
}
func filterGenerateRules(
contextLoader ContextLoaderFactory,
policyContext *PolicyContext,
policyNameKey string,
startTime time.Time,
) *engineapi.EngineResponse {
kind := policyContext.newResource.GetKind()
name := policyContext.newResource.GetName()
namespace := policyContext.newResource.GetNamespace()
apiVersion := policyContext.newResource.GetAPIVersion()
pNamespace, pName, err := cache.SplitMetaNamespaceKey(policyNameKey)
if err != nil {
logging.Error(err, "failed to spilt name and namespace", policyNameKey)
}
resp := &engineapi.EngineResponse{
PolicyResponse: engineapi.PolicyResponse{
Policy: engineapi.PolicySpec{
Name: pName,
Namespace: pNamespace,
},
PolicyStats: engineapi.PolicyStats{
ExecutionStats: engineapi.ExecutionStats{
Timestamp: startTime.Unix(),
},
},
Resource: engineapi.ResourceSpec{
Kind: kind,
Name: name,
Namespace: namespace,
APIVersion: apiVersion,
},
},
}
if policyContext.excludeResourceFunc(kind, namespace, name) {
logging.WithName("Generate").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name)
return resp
}
for _, rule := range autogen.ComputeRules(policyContext.policy) {
if ruleResp := filterRule(contextLoader, rule, policyContext); ruleResp != nil {
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
}
}
return resp
}