2019-05-13 18:17:28 -07:00
|
|
|
package engine
|
2019-05-09 22:26:22 -07:00
|
|
|
|
|
|
|
import (
|
2019-05-30 12:28:56 -07:00
|
|
|
"github.com/golang/glog"
|
2019-05-22 18:28:38 +01:00
|
|
|
kubepolicy "github.com/nirmata/kyverno/pkg/apis/policy/v1alpha1"
|
2019-05-14 19:40:17 +03:00
|
|
|
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
2019-05-09 22:26:22 -07:00
|
|
|
)
|
|
|
|
|
2019-05-13 21:27:47 +03:00
|
|
|
// Mutate performs mutation. Overlay first and then mutation patches
|
2019-05-14 18:20:41 -07:00
|
|
|
// TODO: return events and violations
|
2019-05-21 18:27:56 +03:00
|
|
|
func Mutate(policy kubepolicy.Policy, rawResource []byte, gvk metav1.GroupVersionKind) ([]PatchBytes, []byte) {
|
|
|
|
var policyPatches []PatchBytes
|
|
|
|
var processedPatches []PatchBytes
|
2019-05-20 15:14:01 -07:00
|
|
|
var err error
|
2019-05-20 13:02:55 -07:00
|
|
|
patchedDocument := rawResource
|
2019-05-09 22:26:22 -07:00
|
|
|
|
2019-05-20 14:48:38 +03:00
|
|
|
for _, rule := range policy.Spec.Rules {
|
|
|
|
if rule.Mutation == nil {
|
2019-05-13 21:27:47 +03:00
|
|
|
continue
|
2019-05-09 22:26:22 -07:00
|
|
|
}
|
|
|
|
|
2019-05-20 14:48:38 +03:00
|
|
|
ok := ResourceMeetsDescription(rawResource, rule.ResourceDescription, gvk)
|
2019-05-13 21:27:47 +03:00
|
|
|
if !ok {
|
2019-05-30 12:28:56 -07:00
|
|
|
glog.Infof("Rule \"%s\" is not applicable to resource\n", rule.Name)
|
2019-05-14 18:10:25 +03:00
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
2019-05-13 21:27:47 +03:00
|
|
|
// Process Overlay
|
2019-05-09 22:26:22 -07:00
|
|
|
|
2019-05-13 21:27:47 +03:00
|
|
|
if rule.Mutation.Overlay != nil {
|
2019-05-22 22:54:38 +01:00
|
|
|
overlayPatches, err := ProcessOverlay(policy, rawResource, gvk)
|
2019-05-13 21:27:47 +03:00
|
|
|
if err != nil {
|
2019-05-30 12:28:56 -07:00
|
|
|
glog.Warningf("Overlay application has failed for rule %s in policy %s, err: %v\n", rule.Name, policy.ObjectMeta.Name, err)
|
2019-05-13 21:27:47 +03:00
|
|
|
} else {
|
2019-05-22 22:54:38 +01:00
|
|
|
policyPatches = append(policyPatches, overlayPatches...)
|
2019-05-13 21:27:47 +03:00
|
|
|
}
|
2019-05-09 22:26:22 -07:00
|
|
|
}
|
|
|
|
|
2019-05-13 21:27:47 +03:00
|
|
|
// Process Patches
|
2019-05-09 22:26:22 -07:00
|
|
|
|
2019-05-13 21:27:47 +03:00
|
|
|
if rule.Mutation.Patches != nil {
|
2019-05-21 18:27:56 +03:00
|
|
|
processedPatches, patchedDocument, err = ProcessPatches(rule.Mutation.Patches, patchedDocument)
|
2019-05-13 21:27:47 +03:00
|
|
|
if err != nil {
|
2019-05-30 12:28:56 -07:00
|
|
|
glog.Warningf("Patches application has failed for rule %s in policy %s, err: %v\n", rule.Name, policy.ObjectMeta.Name, err)
|
2019-05-13 21:27:47 +03:00
|
|
|
} else {
|
|
|
|
policyPatches = append(policyPatches, processedPatches...)
|
|
|
|
}
|
|
|
|
}
|
2019-05-09 22:26:22 -07:00
|
|
|
}
|
|
|
|
|
2019-05-20 13:02:55 -07:00
|
|
|
return policyPatches, patchedDocument
|
2019-05-09 22:26:22 -07:00
|
|
|
}
|