diff --git a/api/v1alpha3/machinehealthcheck_webhook.go b/api/v1alpha3/machinehealthcheck_webhook.go index 2ed1344a4b33..f48cc638a323 100644 --- a/api/v1alpha3/machinehealthcheck_webhook.go +++ b/api/v1alpha3/machinehealthcheck_webhook.go @@ -90,7 +90,7 @@ func (m *MachineHealthCheck) validate(old *MachineHealthCheck) error { var allErrs field.ErrorList // Validate selector parses as Selector - _, err := metav1.LabelSelectorAsSelector(&m.Spec.Selector) + selector, err := metav1.LabelSelectorAsSelector(&m.Spec.Selector) if err != nil { allErrs = append( allErrs, @@ -98,6 +98,14 @@ func (m *MachineHealthCheck) validate(old *MachineHealthCheck) error { ) } + // Validate that the selector isn't empty. + if selector != nil && selector.Empty() { + allErrs = append( + allErrs, + field.Invalid(field.NewPath("spec", "selector"), m.Spec.Selector, "selector must not be empty"), + ) + } + if old != nil && old.Spec.ClusterName != m.Spec.ClusterName { allErrs = append( allErrs, diff --git a/api/v1alpha3/machinehealthcheck_webhook_test.go b/api/v1alpha3/machinehealthcheck_webhook_test.go index 75108df1a531..881b1d640dd9 100644 --- a/api/v1alpha3/machinehealthcheck_webhook_test.go +++ b/api/v1alpha3/machinehealthcheck_webhook_test.go @@ -105,11 +105,21 @@ func TestMachineHealthCheckClusterNameImmutable(t *testing.T) { newMHC := &MachineHealthCheck{ Spec: MachineHealthCheckSpec{ ClusterName: tt.newClusterName, + Selector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "test": "test", + }, + }, }, } oldMHC := &MachineHealthCheck{ Spec: MachineHealthCheckSpec{ ClusterName: tt.oldClusterName, + Selector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "test": "test", + }, + }, }, } @@ -172,6 +182,11 @@ func TestMachineHealthCheckNodeStartupTimeout(t *testing.T) { mhc := &MachineHealthCheck{ Spec: MachineHealthCheckSpec{ NodeStartupTimeout: tt.timeout, + Selector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "test": "test", + }, + }, }, } @@ -220,6 +235,11 @@ func TestMachineHealthCheckMaxUnhealthy(t *testing.T) { mhc := &MachineHealthCheck{ Spec: MachineHealthCheckSpec{ MaxUnhealthy: &maxUnhealthy, + Selector: metav1.LabelSelector{ + MatchLabels: map[string]string{ + "test": "test", + }, + }, }, } @@ -232,3 +252,11 @@ func TestMachineHealthCheckMaxUnhealthy(t *testing.T) { } } } + +func TestMachineHealthCheckSelectorValidation(t *testing.T) { + g := NewWithT(t) + mhc := &MachineHealthCheck{} + err := mhc.validate(nil) + g.Expect(err).ToNot(BeNil()) + g.Expect(err.Error()).To(ContainSubstring("selector must not be empty")) +}