2019-05-14 01:17:28 +00:00
|
|
|
package engine
|
2019-05-13 18:27:47 +00:00
|
|
|
|
|
|
|
import (
|
2021-02-03 21:09:42 +00:00
|
|
|
"time"
|
|
|
|
|
2022-05-17 11:12:43 +00:00
|
|
|
kyvernov1beta1 "github.com/kyverno/kyverno/api/kyverno/v1beta1"
|
2022-03-28 14:01:27 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/autogen"
|
2020-10-07 18:12:31 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/engine/response"
|
2022-10-02 19:45:03 +00:00
|
|
|
"github.com/kyverno/kyverno/pkg/logging"
|
2022-04-25 12:20:40 +00:00
|
|
|
"k8s.io/client-go/tools/cache"
|
2019-05-13 18:27:47 +00:00
|
|
|
)
|
|
|
|
|
2022-03-29 13:04:33 +00:00
|
|
|
// GenerateResponse checks for validity of generate rule on the resource
|
2022-05-17 11:12:43 +00:00
|
|
|
func GenerateResponse(policyContext *PolicyContext, gr kyvernov1beta1.UpdateRequest) (resp *response.EngineResponse) {
|
2022-03-29 13:04:33 +00:00
|
|
|
policyStartTime := time.Now()
|
|
|
|
return filterGenerateRules(policyContext, gr.Spec.Policy, policyStartTime)
|
|
|
|
}
|
|
|
|
|
|
|
|
func filterGenerateRules(policyContext *PolicyContext, policyNameKey string, startTime time.Time) *response.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 {
|
2022-10-02 19:45:03 +00:00
|
|
|
logging.Error(err, "failed to spilt name and namespace", policyNameKey)
|
2022-03-29 13:04:33 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
resp := &response.EngineResponse{
|
|
|
|
PolicyResponse: response.PolicyResponse{
|
|
|
|
Policy: response.PolicySpec{
|
|
|
|
Name: pName,
|
|
|
|
Namespace: pNamespace,
|
|
|
|
},
|
|
|
|
PolicyStats: response.PolicyStats{
|
|
|
|
PolicyExecutionTimestamp: startTime.Unix(),
|
|
|
|
},
|
|
|
|
Resource: response.ResourceSpec{
|
|
|
|
Kind: kind,
|
|
|
|
Name: name,
|
|
|
|
Namespace: namespace,
|
|
|
|
APIVersion: apiVersion,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
if policyContext.ExcludeResourceFunc(kind, namespace, name) {
|
2022-10-02 19:45:03 +00:00
|
|
|
logging.WithName("Generate").Info("resource excluded", "kind", kind, "namespace", namespace, "name", name)
|
2022-03-29 13:04:33 +00:00
|
|
|
return resp
|
|
|
|
}
|
|
|
|
|
2022-03-30 13:04:30 +00:00
|
|
|
for _, rule := range autogen.ComputeRules(policyContext.Policy) {
|
2022-03-29 13:04:33 +00:00
|
|
|
if ruleResp := filterRule(rule, policyContext); ruleResp != nil {
|
|
|
|
resp.PolicyResponse.Rules = append(resp.PolicyResponse.Rules, *ruleResp)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp
|
|
|
|
}
|