helpers.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package resource
  14. import (
  15. "fmt"
  16. "math"
  17. "strconv"
  18. "k8s.io/api/core/v1"
  19. "k8s.io/apimachinery/pkg/api/resource"
  20. utilfeature "k8s.io/apiserver/pkg/util/feature"
  21. "k8s.io/kubernetes/pkg/features"
  22. )
  23. // addResourceList adds the resources in newList to list
  24. func addResourceList(list, newList v1.ResourceList) {
  25. for name, quantity := range newList {
  26. if value, ok := list[name]; !ok {
  27. list[name] = quantity.DeepCopy()
  28. } else {
  29. value.Add(quantity)
  30. list[name] = value
  31. }
  32. }
  33. }
  34. // maxResourceList sets list to the greater of list/newList for every resource
  35. // either list
  36. func maxResourceList(list, new v1.ResourceList) {
  37. for name, quantity := range new {
  38. if value, ok := list[name]; !ok {
  39. list[name] = quantity.DeepCopy()
  40. continue
  41. } else {
  42. if quantity.Cmp(value) > 0 {
  43. list[name] = quantity.DeepCopy()
  44. }
  45. }
  46. }
  47. }
  48. // PodRequestsAndLimits returns a dictionary of all defined resources summed up for all
  49. // containers of the pod. If PodOverhead feature is enabled, pod overhead is added to the
  50. // total container resource requests and to the total container limits which have a
  51. // non-zero quantity.
  52. func PodRequestsAndLimits(pod *v1.Pod) (reqs, limits v1.ResourceList) {
  53. reqs, limits = v1.ResourceList{}, v1.ResourceList{}
  54. for _, container := range pod.Spec.Containers {
  55. addResourceList(reqs, container.Resources.Requests)
  56. addResourceList(limits, container.Resources.Limits)
  57. }
  58. // init containers define the minimum of any resource
  59. for _, container := range pod.Spec.InitContainers {
  60. maxResourceList(reqs, container.Resources.Requests)
  61. maxResourceList(limits, container.Resources.Limits)
  62. }
  63. // if PodOverhead feature is supported, add overhead for running a pod
  64. // to the sum of reqeuests and to non-zero limits:
  65. if pod.Spec.Overhead != nil && utilfeature.DefaultFeatureGate.Enabled(features.PodOverhead) {
  66. addResourceList(reqs, pod.Spec.Overhead)
  67. for name, quantity := range pod.Spec.Overhead {
  68. if value, ok := limits[name]; ok && !value.IsZero() {
  69. value.Add(quantity)
  70. limits[name] = value
  71. }
  72. }
  73. }
  74. return
  75. }
  76. // GetResourceRequestQuantity finds and returns the request quantity for a specific resource.
  77. func GetResourceRequestQuantity(pod *v1.Pod, resourceName v1.ResourceName) resource.Quantity {
  78. requestQuantity := resource.Quantity{}
  79. switch resourceName {
  80. case v1.ResourceCPU:
  81. requestQuantity = resource.Quantity{Format: resource.DecimalSI}
  82. case v1.ResourceMemory, v1.ResourceStorage, v1.ResourceEphemeralStorage:
  83. requestQuantity = resource.Quantity{Format: resource.BinarySI}
  84. default:
  85. requestQuantity = resource.Quantity{Format: resource.DecimalSI}
  86. }
  87. if resourceName == v1.ResourceEphemeralStorage && !utilfeature.DefaultFeatureGate.Enabled(features.LocalStorageCapacityIsolation) {
  88. // if the local storage capacity isolation feature gate is disabled, pods request 0 disk
  89. return requestQuantity
  90. }
  91. for _, container := range pod.Spec.Containers {
  92. if rQuantity, ok := container.Resources.Requests[resourceName]; ok {
  93. requestQuantity.Add(rQuantity)
  94. }
  95. }
  96. for _, container := range pod.Spec.InitContainers {
  97. if rQuantity, ok := container.Resources.Requests[resourceName]; ok {
  98. if requestQuantity.Cmp(rQuantity) < 0 {
  99. requestQuantity = rQuantity.DeepCopy()
  100. }
  101. }
  102. }
  103. // if PodOverhead feature is supported, add overhead for running a pod
  104. // to the total requests if the resource total is non-zero
  105. if pod.Spec.Overhead != nil && utilfeature.DefaultFeatureGate.Enabled(features.PodOverhead) {
  106. if podOverhead, ok := pod.Spec.Overhead[resourceName]; ok && !requestQuantity.IsZero() {
  107. requestQuantity.Add(podOverhead)
  108. }
  109. }
  110. return requestQuantity
  111. }
  112. // GetResourceRequest finds and returns the request value for a specific resource.
  113. func GetResourceRequest(pod *v1.Pod, resource v1.ResourceName) int64 {
  114. if resource == v1.ResourcePods {
  115. return 1
  116. }
  117. requestQuantity := GetResourceRequestQuantity(pod, resource)
  118. if resource == v1.ResourceCPU {
  119. return requestQuantity.MilliValue()
  120. }
  121. return requestQuantity.Value()
  122. }
  123. // ExtractResourceValueByContainerName extracts the value of a resource
  124. // by providing container name
  125. func ExtractResourceValueByContainerName(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string) (string, error) {
  126. container, err := findContainerInPod(pod, containerName)
  127. if err != nil {
  128. return "", err
  129. }
  130. return ExtractContainerResourceValue(fs, container)
  131. }
  132. // ExtractResourceValueByContainerNameAndNodeAllocatable extracts the value of a resource
  133. // by providing container name and node allocatable
  134. func ExtractResourceValueByContainerNameAndNodeAllocatable(fs *v1.ResourceFieldSelector, pod *v1.Pod, containerName string, nodeAllocatable v1.ResourceList) (string, error) {
  135. realContainer, err := findContainerInPod(pod, containerName)
  136. if err != nil {
  137. return "", err
  138. }
  139. container := realContainer.DeepCopy()
  140. MergeContainerResourceLimits(container, nodeAllocatable)
  141. return ExtractContainerResourceValue(fs, container)
  142. }
  143. // ExtractContainerResourceValue extracts the value of a resource
  144. // in an already known container
  145. func ExtractContainerResourceValue(fs *v1.ResourceFieldSelector, container *v1.Container) (string, error) {
  146. divisor := resource.Quantity{}
  147. if divisor.Cmp(fs.Divisor) == 0 {
  148. divisor = resource.MustParse("1")
  149. } else {
  150. divisor = fs.Divisor
  151. }
  152. switch fs.Resource {
  153. case "limits.cpu":
  154. return convertResourceCPUToString(container.Resources.Limits.Cpu(), divisor)
  155. case "limits.memory":
  156. return convertResourceMemoryToString(container.Resources.Limits.Memory(), divisor)
  157. case "limits.ephemeral-storage":
  158. return convertResourceEphemeralStorageToString(container.Resources.Limits.StorageEphemeral(), divisor)
  159. case "requests.cpu":
  160. return convertResourceCPUToString(container.Resources.Requests.Cpu(), divisor)
  161. case "requests.memory":
  162. return convertResourceMemoryToString(container.Resources.Requests.Memory(), divisor)
  163. case "requests.ephemeral-storage":
  164. return convertResourceEphemeralStorageToString(container.Resources.Requests.StorageEphemeral(), divisor)
  165. }
  166. return "", fmt.Errorf("unsupported container resource : %v", fs.Resource)
  167. }
  168. // convertResourceCPUToString converts cpu value to the format of divisor and returns
  169. // ceiling of the value.
  170. func convertResourceCPUToString(cpu *resource.Quantity, divisor resource.Quantity) (string, error) {
  171. c := int64(math.Ceil(float64(cpu.MilliValue()) / float64(divisor.MilliValue())))
  172. return strconv.FormatInt(c, 10), nil
  173. }
  174. // convertResourceMemoryToString converts memory value to the format of divisor and returns
  175. // ceiling of the value.
  176. func convertResourceMemoryToString(memory *resource.Quantity, divisor resource.Quantity) (string, error) {
  177. m := int64(math.Ceil(float64(memory.Value()) / float64(divisor.Value())))
  178. return strconv.FormatInt(m, 10), nil
  179. }
  180. // convertResourceEphemeralStorageToString converts ephemeral storage value to the format of divisor and returns
  181. // ceiling of the value.
  182. func convertResourceEphemeralStorageToString(ephemeralStorage *resource.Quantity, divisor resource.Quantity) (string, error) {
  183. m := int64(math.Ceil(float64(ephemeralStorage.Value()) / float64(divisor.Value())))
  184. return strconv.FormatInt(m, 10), nil
  185. }
  186. // findContainerInPod finds a container by its name in the provided pod
  187. func findContainerInPod(pod *v1.Pod, containerName string) (*v1.Container, error) {
  188. for _, container := range pod.Spec.Containers {
  189. if container.Name == containerName {
  190. return &container, nil
  191. }
  192. }
  193. for _, container := range pod.Spec.InitContainers {
  194. if container.Name == containerName {
  195. return &container, nil
  196. }
  197. }
  198. return nil, fmt.Errorf("container %s not found", containerName)
  199. }
  200. // MergeContainerResourceLimits checks if a limit is applied for
  201. // the container, and if not, it sets the limit to the passed resource list.
  202. func MergeContainerResourceLimits(container *v1.Container,
  203. allocatable v1.ResourceList) {
  204. if container.Resources.Limits == nil {
  205. container.Resources.Limits = make(v1.ResourceList)
  206. }
  207. for _, resource := range []v1.ResourceName{v1.ResourceCPU, v1.ResourceMemory, v1.ResourceEphemeralStorage} {
  208. if quantity, exists := container.Resources.Limits[resource]; !exists || quantity.IsZero() {
  209. if cap, exists := allocatable[resource]; exists {
  210. container.Resources.Limits[resource] = cap.DeepCopy()
  211. }
  212. }
  213. }
  214. }