Skip to content

Commit

Permalink
feat(customresourcestate): Support percentages
Browse files Browse the repository at this point in the history
  • Loading branch information
mrueg committed Feb 27, 2023
1 parent 093cfb6 commit 3c40f03
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/customresourcestate-metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,7 @@ Supported types are:
* `"true"` and `"yes"` are mapped to `1.0` and `"false"` and `"no"` are mapped to `0.0` (all case insensitive)
* RFC3339 times are parsed to float timestamp
* Quantities like "250m" or "512Gi" are parsed to float using https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go
* Percentages ending with a "%" are parsed to float
* finally the string is parsed to float using https://pkg.go.dev/strconv#ParseFloat which should support all common number formats. If that fails an error is yielded

##### Example for status conditions on Kubernetes Controllers
Expand Down
7 changes: 7 additions & 0 deletions pkg/customresourcestate/registry_factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (

"k8s.io/apimachinery/pkg/api/resource"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/validation"
"k8s.io/klog/v2"

"k8s.io/kube-state-metrics/v2/pkg/metric"
Expand Down Expand Up @@ -701,6 +702,12 @@ func toFloat64(value interface{}, nilIsZero bool) (float64, error) {
if t, e := resource.ParseQuantity(value.(string)); e == nil {
return t.AsApproximateFloat64(), nil
}
// The string contains a percentage with a suffix "%"
if e := validation.IsValidPercent(value.(string)); len(e) == 0 {
t, e := strconv.ParseFloat(strings.TrimRight(value.(string), "%"), 64)
return t / 100, e
}

return strconv.ParseFloat(value.(string), 64)
case byte:
v = float64(vv)
Expand Down
9 changes: 9 additions & 0 deletions pkg/customresourcestate/registry_factory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ func init() {
"uptime": 43.21,
"quantity_milli": "250m",
"quantity_binarySI": "5Gi",
"percentage": "28%",
"condition_values": Array{
Obj{
"name": "a",
Expand Down Expand Up @@ -229,6 +230,14 @@ func Test_values(t *testing.T) {
}, wantResult: []eachValue{
newEachValue(t, 5.36870912e+09),
}},
{name: "percentage", each: &compiledGauge{
compiledCommon: compiledCommon{
path: mustCompilePath(t, "status", "percentage"),
},
}, wantResult: []eachValue{
newEachValue(t, 0.28),
}},

{name: "boolean_string", each: &compiledGauge{
compiledCommon: compiledCommon{
path: mustCompilePath(t, "spec", "paused"),
Expand Down

0 comments on commit 3c40f03

Please sign in to comment.