From 268498a3e599d469bfe24f3b78af3dca7f4b4da7 Mon Sep 17 00:00:00 2001 From: whitewindmills Date: Mon, 24 Jul 2023 11:07:24 +0800 Subject: [PATCH] validate resourceSelectors if Preemption is enabled Signed-off-by: whitewindmills --- pkg/util/validation/validation.go | 16 ++++++++++++++++ pkg/util/validation/validation_test.go | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/pkg/util/validation/validation.go b/pkg/util/validation/validation.go index fd00f75f7854..809e8395b055 100644 --- a/pkg/util/validation/validation.go +++ b/pkg/util/validation/validation.go @@ -26,6 +26,22 @@ func ValidatePropagationSpec(spec policyv1alpha1.PropagationSpec) field.ErrorLis allErrs = append(allErrs, field.Invalid(field.NewPath("spec").Child("propagateDeps"), spec.PropagateDeps, "application failover is set, propagateDeps must be true")) } allErrs = append(allErrs, ValidateFailover(spec.Failover, field.NewPath("spec").Child("failover"))...) + allErrs = append(allErrs, validateResourceSelectorsIfPreemptionEnabled(spec, field.NewPath("spec").Child("resourceSelectors"))...) + return allErrs +} + +// validateResourceSelectorsIfPreemptionEnabled validates ResourceSelectors if Preemption is Always. +func validateResourceSelectorsIfPreemptionEnabled(spec policyv1alpha1.PropagationSpec, fldPath *field.Path) field.ErrorList { + if spec.Preemption != policyv1alpha1.PreemptAlways { + return nil + } + + var allErrs field.ErrorList + for index, resourceSelector := range spec.ResourceSelectors { + if len(resourceSelector.Name) == 0 { + allErrs = append(allErrs, field.Invalid(fldPath.Index(index).Child("name"), resourceSelector.Name, "name can not be empty if preemption is Always, the empty name may cause unexpected resources preemption")) + } + } return allErrs } diff --git a/pkg/util/validation/validation_test.go b/pkg/util/validation/validation_test.go index 19666ce5eeb4..ec32d5d53a21 100644 --- a/pkg/util/validation/validation_test.go +++ b/pkg/util/validation/validation_test.go @@ -536,6 +536,20 @@ func TestValidatePropagationSpec(t *testing.T) { }}, expectedErr: "the cluster spread constraint must be enabled in one of the constraints in case of SpreadByField is enabled", }, + { + name: "resourceSelector name is empty when preemption is enabled", + spec: policyv1alpha1.PropagationSpec{ + ResourceSelectors: []policyv1alpha1.ResourceSelector{ + { + APIVersion: "v1", + Kind: "Pod", + Namespace: "default", + }, + }, + Preemption: policyv1alpha1.PreemptAlways, + }, + expectedErr: "name can not be empty if preemption is Always, the empty name may cause unexpected resources preemption", + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) {