From 1c655d8782556a0164bf0f9ebdb406250fd4d2b0 Mon Sep 17 00:00:00 2001 From: Claudio Netto Date: Fri, 4 Aug 2023 10:57:55 -0300 Subject: [PATCH] refactor: moving the check of resource validation to helper function Signed-off-by: Claudio Netto --- apis/keda/v1alpha1/scaledobject_webhook.go | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/apis/keda/v1alpha1/scaledobject_webhook.go b/apis/keda/v1alpha1/scaledobject_webhook.go index af97736e2d3..66d2c76d60a 100644 --- a/apis/keda/v1alpha1/scaledobject_webhook.go +++ b/apis/keda/v1alpha1/scaledobject_webhook.go @@ -318,16 +318,14 @@ func verifyCPUMemoryScalers(incomingSo *ScaledObject, action string, dryRun bool } if trigger.Type == cpuString { - if (container.Resources.Requests == nil || container.Resources.Requests.Cpu() == nil || container.Resources.Requests.Cpu().AsApproximateFloat64() == 0) && - (container.Resources.Limits == nil || container.Resources.Limits.Cpu() == nil || container.Resources.Limits.Cpu().AsApproximateFloat64() == 0) { + if !isWorkloadResourceSet(container.Resources, corev1.ResourceCPU) { err := fmt.Errorf("the scaledobject has a cpu trigger but the container %s doesn't have the cpu request defined", container.Name) scaledobjectlog.Error(err, "validation error") metricscollector.RecordScaledObjectValidatingErrors(incomingSo.Namespace, action, "missing-requests") return err } } else if trigger.Type == memoryString { - if (container.Resources.Requests == nil || container.Resources.Requests.Memory() == nil || container.Resources.Requests.Memory().AsApproximateFloat64() == 0) && - (container.Resources.Limits == nil || container.Resources.Limits.Memory() == nil || container.Resources.Limits.Memory().AsApproximateFloat64() == 0) { + if !isWorkloadResourceSet(container.Resources, corev1.ResourceMemory) { err := fmt.Errorf("the scaledobject has a memory trigger but the container %s doesn't have the memory request defined", container.Name) scaledobjectlog.Error(err, "validation error") metricscollector.RecordScaledObjectValidatingErrors(incomingSo.Namespace, action, "missing-requests") @@ -459,3 +457,9 @@ func castToFloatIfNecessary(formula string) string { } return "float(" + formula + ")" } + +func isWorkloadResourceSet(rr corev1.ResourceRequirements, name corev1.ResourceName) bool { + requests, requestsSet := rr.Requests[name] + limits, limitsSet := rr.Limits[name] + return (requestsSet || limitsSet) && (requests.AsApproximateFloat64() > 0 || limits.AsApproximateFloat64() > 0) +}