resources.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. /*
  2. Copyright 2016 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 quota
  14. import (
  15. "sort"
  16. "strings"
  17. corev1 "k8s.io/api/core/v1"
  18. "k8s.io/apimachinery/pkg/api/resource"
  19. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  20. "k8s.io/apimachinery/pkg/util/sets"
  21. )
  22. // Equals returns true if the two lists are equivalent
  23. func Equals(a corev1.ResourceList, b corev1.ResourceList) bool {
  24. if len(a) != len(b) {
  25. return false
  26. }
  27. for key, value1 := range a {
  28. value2, found := b[key]
  29. if !found {
  30. return false
  31. }
  32. if value1.Cmp(value2) != 0 {
  33. return false
  34. }
  35. }
  36. return true
  37. }
  38. // LessThanOrEqual returns true if a < b for each key in b
  39. // If false, it returns the keys in a that exceeded b
  40. func LessThanOrEqual(a corev1.ResourceList, b corev1.ResourceList) (bool, []corev1.ResourceName) {
  41. result := true
  42. resourceNames := []corev1.ResourceName{}
  43. for key, value := range b {
  44. if other, found := a[key]; found {
  45. if other.Cmp(value) > 0 {
  46. result = false
  47. resourceNames = append(resourceNames, key)
  48. }
  49. }
  50. }
  51. return result, resourceNames
  52. }
  53. // Max returns the result of Max(a, b) for each named resource
  54. func Max(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {
  55. result := corev1.ResourceList{}
  56. for key, value := range a {
  57. if other, found := b[key]; found {
  58. if value.Cmp(other) <= 0 {
  59. result[key] = other.DeepCopy()
  60. continue
  61. }
  62. }
  63. result[key] = value.DeepCopy()
  64. }
  65. for key, value := range b {
  66. if _, found := result[key]; !found {
  67. result[key] = value.DeepCopy()
  68. }
  69. }
  70. return result
  71. }
  72. // Add returns the result of a + b for each named resource
  73. func Add(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {
  74. result := corev1.ResourceList{}
  75. for key, value := range a {
  76. quantity := value.DeepCopy()
  77. if other, found := b[key]; found {
  78. quantity.Add(other)
  79. }
  80. result[key] = quantity
  81. }
  82. for key, value := range b {
  83. if _, found := result[key]; !found {
  84. result[key] = value.DeepCopy()
  85. }
  86. }
  87. return result
  88. }
  89. // SubtractWithNonNegativeResult - subtracts and returns result of a - b but
  90. // makes sure we don't return negative values to prevent negative resource usage.
  91. func SubtractWithNonNegativeResult(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {
  92. zero := resource.MustParse("0")
  93. result := corev1.ResourceList{}
  94. for key, value := range a {
  95. quantity := value.DeepCopy()
  96. if other, found := b[key]; found {
  97. quantity.Sub(other)
  98. }
  99. if quantity.Cmp(zero) > 0 {
  100. result[key] = quantity
  101. } else {
  102. result[key] = zero
  103. }
  104. }
  105. for key := range b {
  106. if _, found := result[key]; !found {
  107. result[key] = zero
  108. }
  109. }
  110. return result
  111. }
  112. // Subtract returns the result of a - b for each named resource
  113. func Subtract(a corev1.ResourceList, b corev1.ResourceList) corev1.ResourceList {
  114. result := corev1.ResourceList{}
  115. for key, value := range a {
  116. quantity := value.DeepCopy()
  117. if other, found := b[key]; found {
  118. quantity.Sub(other)
  119. }
  120. result[key] = quantity
  121. }
  122. for key, value := range b {
  123. if _, found := result[key]; !found {
  124. quantity := value.DeepCopy()
  125. quantity.Neg()
  126. result[key] = quantity
  127. }
  128. }
  129. return result
  130. }
  131. // Mask returns a new resource list that only has the values with the specified names
  132. func Mask(resources corev1.ResourceList, names []corev1.ResourceName) corev1.ResourceList {
  133. nameSet := ToSet(names)
  134. result := corev1.ResourceList{}
  135. for key, value := range resources {
  136. if nameSet.Has(string(key)) {
  137. result[key] = value.DeepCopy()
  138. }
  139. }
  140. return result
  141. }
  142. // ResourceNames returns a list of all resource names in the ResourceList
  143. func ResourceNames(resources corev1.ResourceList) []corev1.ResourceName {
  144. result := []corev1.ResourceName{}
  145. for resourceName := range resources {
  146. result = append(result, resourceName)
  147. }
  148. return result
  149. }
  150. // Contains returns true if the specified item is in the list of items
  151. func Contains(items []corev1.ResourceName, item corev1.ResourceName) bool {
  152. for _, i := range items {
  153. if i == item {
  154. return true
  155. }
  156. }
  157. return false
  158. }
  159. // ContainsPrefix returns true if the specified item has a prefix that contained in given prefix Set
  160. func ContainsPrefix(prefixSet []string, item corev1.ResourceName) bool {
  161. for _, prefix := range prefixSet {
  162. if strings.HasPrefix(string(item), prefix) {
  163. return true
  164. }
  165. }
  166. return false
  167. }
  168. // Intersection returns the intersection of both list of resources, deduped and sorted
  169. func Intersection(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName {
  170. result := make([]corev1.ResourceName, 0, len(a))
  171. for _, item := range a {
  172. if Contains(result, item) {
  173. continue
  174. }
  175. if !Contains(b, item) {
  176. continue
  177. }
  178. result = append(result, item)
  179. }
  180. sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })
  181. return result
  182. }
  183. // Difference returns the list of resources resulting from a-b, deduped and sorted
  184. func Difference(a []corev1.ResourceName, b []corev1.ResourceName) []corev1.ResourceName {
  185. result := make([]corev1.ResourceName, 0, len(a))
  186. for _, item := range a {
  187. if Contains(b, item) || Contains(result, item) {
  188. continue
  189. }
  190. result = append(result, item)
  191. }
  192. sort.Slice(result, func(i, j int) bool { return result[i] < result[j] })
  193. return result
  194. }
  195. // IsZero returns true if each key maps to the quantity value 0
  196. func IsZero(a corev1.ResourceList) bool {
  197. zero := resource.MustParse("0")
  198. for _, v := range a {
  199. if v.Cmp(zero) != 0 {
  200. return false
  201. }
  202. }
  203. return true
  204. }
  205. // IsNegative returns the set of resource names that have a negative value.
  206. func IsNegative(a corev1.ResourceList) []corev1.ResourceName {
  207. results := []corev1.ResourceName{}
  208. zero := resource.MustParse("0")
  209. for k, v := range a {
  210. if v.Cmp(zero) < 0 {
  211. results = append(results, k)
  212. }
  213. }
  214. return results
  215. }
  216. // ToSet takes a list of resource names and converts to a string set
  217. func ToSet(resourceNames []corev1.ResourceName) sets.String {
  218. result := sets.NewString()
  219. for _, resourceName := range resourceNames {
  220. result.Insert(string(resourceName))
  221. }
  222. return result
  223. }
  224. // CalculateUsage calculates and returns the requested ResourceList usage.
  225. // If an error is returned, usage only contains the resources which encountered no calculation errors.
  226. func CalculateUsage(namespaceName string, scopes []corev1.ResourceQuotaScope, hardLimits corev1.ResourceList, registry Registry, scopeSelector *corev1.ScopeSelector) (corev1.ResourceList, error) {
  227. // find the intersection between the hard resources on the quota
  228. // and the resources this controller can track to know what we can
  229. // look to measure updated usage stats for
  230. hardResources := ResourceNames(hardLimits)
  231. potentialResources := []corev1.ResourceName{}
  232. evaluators := registry.List()
  233. for _, evaluator := range evaluators {
  234. potentialResources = append(potentialResources, evaluator.MatchingResources(hardResources)...)
  235. }
  236. // NOTE: the intersection just removes duplicates since the evaluator match intersects with hard
  237. matchedResources := Intersection(hardResources, potentialResources)
  238. errors := []error{}
  239. // sum the observed usage from each evaluator
  240. newUsage := corev1.ResourceList{}
  241. for _, evaluator := range evaluators {
  242. // only trigger the evaluator if it matches a resource in the quota, otherwise, skip calculating anything
  243. intersection := evaluator.MatchingResources(matchedResources)
  244. if len(intersection) == 0 {
  245. continue
  246. }
  247. usageStatsOptions := UsageStatsOptions{Namespace: namespaceName, Scopes: scopes, Resources: intersection, ScopeSelector: scopeSelector}
  248. stats, err := evaluator.UsageStats(usageStatsOptions)
  249. if err != nil {
  250. // remember the error
  251. errors = append(errors, err)
  252. // exclude resources which encountered calculation errors
  253. matchedResources = Difference(matchedResources, intersection)
  254. continue
  255. }
  256. newUsage = Add(newUsage, stats.Used)
  257. }
  258. // mask the observed usage to only the set of resources tracked by this quota
  259. // merge our observed usage with the quota usage status
  260. // if the new usage is different than the last usage, we will need to do an update
  261. newUsage = Mask(newUsage, matchedResources)
  262. return newUsage, utilerrors.NewAggregate(errors)
  263. }