k8s resource.quantity json marshall

1/17/2020

Background

I create a k8s autoscaling/v2beta1 HorizontalPodAutoscaler using the following json:

{
  "kind": "HorizontalPodAutoscaler",
  "apiVersion": "autoscaling/v2beta1",
  ...
  "spec": {
    ...
    "metrics": [
      {
        "type": "Resource",
        "resource": {
          "targetAverageValue": 10000, //pay attention to this value
          "name": "cpu"
        }
      }
    ]
  }

but when I marshall the HorizontalPodAutoscaler I created, I get the following json:

{
  "kind": "HorizontalPodAutoscaler",
  "apiVersion": "autoscaling/v2beta1",
  ...
  "spec": {
    ...
    "metrics": [
      {
        "type": "Resource",
        "resource": {
          "targetAverageValue": "10k", // the value 10000 becomes "10k"
          "name": "cpu"
        }
      }
    ]
  }
}

The problem is that I want .spec.metrics.resource.targetAverageValue to keep its original value instead of being marshalled into a fixed-point representation.

Current Attempt

The problem is caused by the resource.Quantity struct. .spec.metrics.resource.targetAverageValue's type is resource.Quantity which has custom json marshall and unmarshall func.

I go through the source code but can't find a method to let resource.Quantity keep its original value when being marshalled.

resource.Quantity source code: https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go

Question

Is there any way to replace the custom marshaller of resource.Quantity when json.Marshall(hpa) or does resource.Quantity have a setting that can change the behaviour of func (q Quantity) MarshalJSON() ([]byte, error)?

-- kevin807210561
go
json
kubernetes

0 Answers