Skip to content

Commit

Permalink
refactor: moving the check of resource validation to helper function
Browse files Browse the repository at this point in the history
Signed-off-by: Claudio Netto <[email protected]>
  • Loading branch information
nettoclaudio committed Dec 21, 2023
1 parent 13226a6 commit 1c655d8
Showing 1 changed file with 8 additions and 4 deletions.
12 changes: 8 additions & 4 deletions apis/keda/v1alpha1/scaledobject_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
}

0 comments on commit 1c655d8

Please sign in to comment.