对 K8s 中的 NameSpace的ResourceList进行加减操作
背景
需要将命名空间内新家的STS所使用的配额自动加到NameSpace上, 就需要对NameSpace的ResourceList做加减操作
计算STS配额参考:
https://blog.csdn.net/qq_21047625/article/details/134946922
将STS配额转为NameSpace的配额参考:
https://blog.csdn.net/qq_21047625/article/details/135020443
代码
import (
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
)
var (
nsLabelArray []v1.ResourceName = []v1.ResourceName{"requests.cpu", "requests.memory", "requests.storage", "requests.nvidia.com/gpu", "limits.cpu", "limits.memory"}
)
func CalNsResourceList(data1 v1.ResourceList, data2 v1.ResourceList, calFunc func(resource.Quantity, resource.Quantity) resource.Quantity) (res v1.ResourceList) {
res = v1.ResourceList{}
for _, labelData := range nsLabelArray {
req1 := data1[labelData]
req2 := data2[labelData]
resQuota := calFunc(req1, req2)
if resQuota.CmpInt64(0) < 0 {
resQuota.Set(0)
}
res[labelData] = resQuota
}
return
}
func AddNsResourceList(data1 v1.ResourceList, data2 v1.ResourceList) v1.ResourceList {
return CalNsResourceList(data1, data2, func(q1, q2 resource.Quantity) resource.Quantity { q1.Add(q2); return q1 })
}
func SubNsResourceList(data1 v1.ResourceList, data2 v1.ResourceList) v1.ResourceList {
return CalNsResourceList(data1, data2, func(q1, q2 resource.Quantity) resource.Quantity { q1.Sub(q2); return q1 })
}