robscott/kube-capacity

[Bug] 0% usage will cause wrong output

JobberRT opened this issue · 7 comments

Here kc set the resources unit:

cm.nodeMetrics[node.Name] = &nodeMetric{
name: node.Name,
cpu: &resourceMetric{
resourceType: "cpu",
allocatable: node.Status.Allocatable["cpu"],
},
memory: &resourceMetric{
resourceType: "memory",
allocatable: node.Status.Allocatable["memory"],
},

And if the cpu or memory unit is a blank string(0% usage for example), this code will do the wrong judgement(all the judgement about Format, here just a example):

if actual.Format == resource.DecimalSI {
actualStr = fmt.Sprintf("%dm", allocatable.MilliValue()-actual.MilliValue())
allocatableStr = fmt.Sprintf("%dm", allocatable.MilliValue())
} else {
actualStr = fmt.Sprintf("%dMi", formatToMegiBytes(allocatable)-formatToMegiBytes(actual))
allocatableStr = fmt.Sprintf("%dMi", formatToMegiBytes(allocatable))
}

Because the value of cpu or memory is a blank string, so it's type won't be resource.DecimalSI, and it will always do the else code block. And of couse its calculate progress will be wrong too since the else code block will call formatTomegiBytes and the unit is not correct:

func formatToMegiBytes(actual resource.Quantity) int64 {
value := actual.Value() / Mebibyte
if actual.Value()%Mebibyte != 0 {
value++
}
return value
}

The Wrong output will be like(those red ones):
image

I will try to fix it and provide a PR, but my skills are not good, will do my best

Thanks for reporting this! I've been pretty underwater recently but if anyone has time to fix this I'll try to review a PR ASAP.

Please let me know if I can work on this.

Hey @KR411-prog, thanks for volunteering! Appreciate any help with this.

When I checked the main branch, I dont see this if else condition anymore. I see switch case statement with also default condition check.

if availableFormat {
switch resourceType {
case "cpu":
actualStr = fmt.Sprintf("%dm", allocatable.MilliValue()-actual.MilliValue())
allocatableStr = fmt.Sprintf("%dm", allocatable.MilliValue())
case "memory":
actualStr = fmt.Sprintf("%dMi", formatToMegiBytes(allocatable)-formatToMegiBytes(actual))
allocatableStr = fmt.Sprintf("%dMi", formatToMegiBytes(allocatable))
default:
actualStr = fmt.Sprintf("%d", allocatable.Value()-actual.Value())
allocatableStr = fmt.Sprintf("%d", allocatable.Value())
}
return fmt.Sprintf("%s/%s", actualStr, allocatableStr)
}

I also dont find wrong unit in cpu for 0% usage now.
image

Please let me know if this issue reported is still valid.

@KR411-prog @robscott Sorry guys, I was late. Did this issue no longer exist? I've not using KC for a long time.

@JobberRT I think the issue is no longer valid as the main branch does not seem to have the code anymore.

Thanks @JobberRT and @KR411-prog, will close this out.