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

78 lines
2.2 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 (
"github.com/golang/glog"
2019-05-22 18:28:38 +01:00
kubepolicy "github.com/nirmata/kyverno/pkg/apis/policy/v1alpha1"
"github.com/nirmata/kyverno/pkg/info"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2019-05-09 22:26:22 -07:00
)
// Mutate performs mutation. Overlay first and then mutation patches
func Mutate(policy kubepolicy.Policy, rawResource []byte, gvk metav1.GroupVersionKind) *EngineResponse {
var allPatches, rulePatches [][]byte
var err error
var errs []error
2019-07-19 20:30:55 -07:00
patchedDocument := rawResource
ris := []*info.RuleInfo{}
2019-05-09 22:26:22 -07:00
for _, rule := range policy.Spec.Rules {
if rule.Mutation == nil {
continue
2019-05-09 22:26:22 -07:00
}
2019-06-25 23:58:28 -07:00
ri := info.NewRuleInfo(rule.Name, info.Mutation)
2019-07-23 23:34:03 -04:00
ok := ResourceMeetsDescription(rawResource, rule.MatchResources.ResourceDescription, rule.ExcludeResources.ResourceDescription, gvk)
if !ok {
glog.V(3).Infof("Not applicable on specified resource kind%s", gvk.Kind)
continue
}
// Process Overlay
if rule.Mutation.Overlay != nil {
rulePatches, err = ProcessOverlay(rule, patchedDocument, gvk)
2019-07-25 16:20:22 -04:00
if err == nil {
if len(rulePatches) == 0 {
2019-07-24 14:25:51 -04:00
// if array elements dont match then we skip(nil patch, no error)
// or if acnohor is defined and doenst match
// policy is not applicable
continue
}
2019-07-19 20:30:55 -07:00
ri.Addf("Rule %s: Overlay succesfully applied.", rule.Name)
2019-07-25 16:20:22 -04:00
// merge the json patches
patch := JoinPatches(rulePatches)
2019-07-25 16:20:22 -04:00
// strip slashes from string
ri.Changes = string(patch)
allPatches = append(allPatches, rulePatches...)
2019-07-24 06:33:51 -04:00
} else {
ri.Fail()
ri.Addf("overlay application has failed, err %v.", err)
}
}
// Process Patches
if len(rule.Mutation.Patches) != 0 {
rulePatches, errs = ProcessPatches(rule, patchedDocument)
if len(errs) > 0 {
ri.Fail()
for _, err := range errs {
2019-07-19 17:52:24 -07:00
ri.Addf("patches application has failed, err %v.", err)
}
2019-06-05 16:44:53 +03:00
} else {
2019-07-19 20:30:55 -07:00
ri.Addf("Rule %s: Patches succesfully applied.", rule.Name)
allPatches = append(allPatches, rulePatches...)
}
}
patchedDocument, err = ApplyPatches(rawResource, rulePatches)
if err != nil {
glog.Errorf("Failed to apply patches on ruleName=%s, err%v\n:", rule.Name, err)
}
ris = append(ris, ri)
2019-05-09 22:26:22 -07:00
}
return &EngineResponse{
Patches: allPatches,
PatchedDocument: patchedDocument,
RuleInfos: ris,
}
2019-05-09 22:26:22 -07:00
}