From 3305a54b1162292eadbb9f55b7dfeaa114428591 Mon Sep 17 00:00:00 2001 From: RainbowMango Date: Fri, 5 Feb 2021 10:19:18 +0800 Subject: [PATCH] restrict policy spread constraints Signed-off-by: RainbowMango Co-authored-by: Kevin Wang --- pkg/webhook/propagationpolicy/mutating.go | 14 ++++++++++++++ pkg/webhook/propagationpolicy/validating.go | 17 ++++++++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/pkg/webhook/propagationpolicy/mutating.go b/pkg/webhook/propagationpolicy/mutating.go index d0a0ae1e1..8e32cb1e4 100644 --- a/pkg/webhook/propagationpolicy/mutating.go +++ b/pkg/webhook/propagationpolicy/mutating.go @@ -37,6 +37,20 @@ func (a *MutatingAdmission) Handle(ctx context.Context, req admission.Request) a } } + // Set default spread constraints if both 'SpreadByField' and 'SpreadByLabel' not set. + spreadConstraints := policy.Spec.Placement.SpreadConstraints + for i := range spreadConstraints { + if len(spreadConstraints[i].SpreadByLabel) == 0 && len(spreadConstraints[i].SpreadByField) == 0 { + klog.Infof("Setting default SpreadByField with %s", policyv1alpha1.SpreadByCluster) + spreadConstraints[i].SpreadByField = policyv1alpha1.SpreadByCluster + } + + if spreadConstraints[i].MinGroups == 0 { + klog.Infof("Setting default MinGroups to 1") + spreadConstraints[i].MinGroups = 1 + } + } + marshaledBytes, err := json.Marshal(policy) if err != nil { return admission.Errored(http.StatusInternalServerError, err) diff --git a/pkg/webhook/propagationpolicy/validating.go b/pkg/webhook/propagationpolicy/validating.go index 477fb5ff4..72a071fc6 100644 --- a/pkg/webhook/propagationpolicy/validating.go +++ b/pkg/webhook/propagationpolicy/validating.go @@ -2,6 +2,7 @@ package propagationpolicy import ( "context" + "fmt" "net/http" "k8s.io/klog/v2" @@ -30,7 +31,21 @@ func (v *ValidatingAdmission) Handle(ctx context.Context, req admission.Request) } klog.V(2).Infof("Validating PropagationPolicy(%s/%s) for request: %s", policy.Namespace, policy.Name, req.Operation) - // Currently do nothing + // SpreadByField and SpreadByLabel should not co-exist + for _, constraint := range policy.Spec.Placement.SpreadConstraints { + if len(constraint.SpreadByField) > 0 && len(constraint.SpreadByLabel) > 0 { + errMsg := fmt.Sprintf("invalid constraints: SpreadByLabel(%s) should not co-exist with spreadByField(%s)", constraint.SpreadByLabel, constraint.SpreadByField) + klog.Info(errMsg) + return admission.Denied(errMsg) + } + + // If MaxGroups provided, it should greater or equal than MinGroups. + if constraint.MaxGroups > 0 && constraint.MaxGroups < constraint.MinGroups { + errMsg := fmt.Sprintf("maxGroups(%d) lower than minGroups(%d) is not allowed", constraint.MaxGroups, constraint.MinGroups) + klog.Info(errMsg) + return admission.Denied(errMsg) + } + } return admission.Allowed("") }