From d969e0c6bc62e5e72f8d69a42232acc48dcf1475 Mon Sep 17 00:00:00 2001 From: huone1 Date: Mon, 16 May 2022 15:13:11 +0800 Subject: [PATCH] optimize the validating webhook for spreadconstraint Signed-off-by: huone1 --- pkg/util/helper/policy.go | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/pkg/util/helper/policy.go b/pkg/util/helper/policy.go index 9512d5cb2..fb5a6e62c 100644 --- a/pkg/util/helper/policy.go +++ b/pkg/util/helper/policy.go @@ -5,6 +5,7 @@ import ( discoveryv1 "k8s.io/api/discovery/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/sets" "k8s.io/klog/v2" "sigs.k8s.io/controller-runtime/pkg/client" @@ -33,8 +34,10 @@ func SetDefaultSpreadConstraints(spreadConstraints []policyv1alpha1.SpreadConstr // ValidateSpreadConstraint tests if the constraints is valid. func ValidateSpreadConstraint(spreadConstraints []policyv1alpha1.SpreadConstraint) error { - // SpreadByField and SpreadByLabel should not co-exist + spreadByFields := sets.NewString() + for _, constraint := range spreadConstraints { + // SpreadByField and SpreadByLabel should not co-exist if len(constraint.SpreadByField) > 0 && len(constraint.SpreadByLabel) > 0 { return fmt.Errorf("invalid constraints: SpreadByLabel(%s) should not co-exist with spreadByField(%s)", constraint.SpreadByLabel, constraint.SpreadByField) } @@ -43,7 +46,21 @@ func ValidateSpreadConstraint(spreadConstraints []policyv1alpha1.SpreadConstrain if constraint.MaxGroups > 0 && constraint.MaxGroups < constraint.MinGroups { return fmt.Errorf("maxGroups(%d) lower than minGroups(%d) is not allowed", constraint.MaxGroups, constraint.MinGroups) } + + if len(constraint.SpreadByField) > 0 { + spreadByFields.Insert(string(constraint.SpreadByField)) + } } + + if spreadByFields.Len() > 0 { + // If one of spread constraints are using 'SpreadByField', the 'SpreadByFieldCluster' must be included. + // For example, when using 'SpreadByFieldRegion' to specify region groups, at the meantime, you must use + // 'SpreadByFieldCluster' to specify how many clusters should be selected. + if !spreadByFields.Has(string(policyv1alpha1.SpreadByFieldCluster)) { + return fmt.Errorf("the cluster spread constraint must be enabled in one of the constraints in case of SpreadByField is enabled") + } + } + return nil }