2019-08-07 18:01:28 -07:00
|
|
|
package webhooks
|
|
|
|
|
|
|
|
import (
|
2019-08-20 17:01:47 -07:00
|
|
|
"reflect"
|
|
|
|
|
2019-08-07 18:01:28 -07:00
|
|
|
"github.com/golang/glog"
|
2019-08-14 19:00:37 -07:00
|
|
|
kyverno "github.com/nirmata/kyverno/pkg/api/kyverno/v1alpha1"
|
2019-08-08 13:09:40 -07:00
|
|
|
v1beta1 "k8s.io/api/admission/v1beta1"
|
|
|
|
"k8s.io/apimachinery/pkg/labels"
|
2019-08-07 18:01:28 -07:00
|
|
|
)
|
|
|
|
|
2019-08-08 13:09:40 -07:00
|
|
|
type policyType int
|
|
|
|
|
|
|
|
const (
|
|
|
|
none policyType = iota
|
|
|
|
mutate
|
|
|
|
validate
|
|
|
|
all
|
|
|
|
)
|
|
|
|
|
2019-08-14 19:00:37 -07:00
|
|
|
func (ws *WebhookServer) manageWebhookConfigurations(policy kyverno.Policy, op v1beta1.Operation) {
|
2019-08-08 13:09:40 -07:00
|
|
|
switch op {
|
|
|
|
case v1beta1.Create:
|
|
|
|
ws.registerWebhookConfigurations(policy)
|
|
|
|
case v1beta1.Delete:
|
|
|
|
ws.deregisterWebhookConfigurations(policy)
|
|
|
|
}
|
|
|
|
}
|
2019-08-07 18:01:28 -07:00
|
|
|
|
2019-08-14 19:00:37 -07:00
|
|
|
func (ws *WebhookServer) registerWebhookConfigurations(policy kyverno.Policy) error {
|
2019-08-20 17:01:47 -07:00
|
|
|
if !HasMutateOrValidate(policy) {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-08-14 15:18:46 -07:00
|
|
|
if !ws.webhookRegistrationClient.MutationRegistered.IsSet() {
|
|
|
|
if err := ws.webhookRegistrationClient.RegisterMutatingWebhook(); err != nil {
|
|
|
|
return err
|
2019-08-07 18:01:28 -07:00
|
|
|
}
|
2019-08-14 15:18:46 -07:00
|
|
|
glog.Infof("Mutating webhook registered")
|
2019-08-07 18:01:28 -07:00
|
|
|
}
|
2019-08-14 15:18:46 -07:00
|
|
|
|
2019-08-07 18:01:28 -07:00
|
|
|
return nil
|
|
|
|
}
|
2019-08-08 13:09:40 -07:00
|
|
|
|
2019-08-14 19:00:37 -07:00
|
|
|
func (ws *WebhookServer) deregisterWebhookConfigurations(policy kyverno.Policy) error {
|
|
|
|
policies, _ := ws.pLister.List(labels.NewSelector())
|
2019-08-08 13:09:40 -07:00
|
|
|
|
2019-08-20 17:01:47 -07:00
|
|
|
// deregister webhook if no mutate/validate policy found in cluster
|
|
|
|
if !HasMutateOrValidatePolicies(policies) {
|
2019-08-19 19:26:51 -07:00
|
|
|
ws.webhookRegistrationClient.DeregisterMutatingWebhook()
|
2019-08-14 11:51:01 -07:00
|
|
|
glog.Infoln("Mutating webhook deregistered")
|
2019-08-08 13:09:40 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
2019-08-20 17:01:47 -07:00
|
|
|
|
|
|
|
func HasMutateOrValidatePolicies(policies []*kyverno.Policy) bool {
|
|
|
|
for _, policy := range policies {
|
|
|
|
if HasMutateOrValidate(*policy) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
func HasMutateOrValidate(policy kyverno.Policy) bool {
|
|
|
|
for _, rule := range policy.Spec.Rules {
|
|
|
|
if !reflect.DeepEqual(rule.Mutation, kyverno.Mutation{}) || !reflect.DeepEqual(rule.Validation, kyverno.Validation{}) {
|
|
|
|
glog.Infoln(rule.Name)
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|