helpers.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 helper
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strings"
  18. "k8s.io/apimachinery/pkg/api/resource"
  19. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  20. "k8s.io/apimachinery/pkg/conversion"
  21. "k8s.io/apimachinery/pkg/fields"
  22. "k8s.io/apimachinery/pkg/labels"
  23. "k8s.io/apimachinery/pkg/selection"
  24. "k8s.io/apimachinery/pkg/util/sets"
  25. "k8s.io/apimachinery/pkg/util/validation"
  26. "k8s.io/kubernetes/pkg/apis/core"
  27. )
  28. // IsHugePageResourceName returns true if the resource name has the huge page
  29. // resource prefix.
  30. func IsHugePageResourceName(name core.ResourceName) bool {
  31. return strings.HasPrefix(string(name), core.ResourceHugePagesPrefix)
  32. }
  33. // IsQuotaHugePageResourceName returns true if the resource name has the quota
  34. // related huge page resource prefix.
  35. func IsQuotaHugePageResourceName(name core.ResourceName) bool {
  36. return strings.HasPrefix(string(name), core.ResourceHugePagesPrefix) || strings.HasPrefix(string(name), core.ResourceRequestsHugePagesPrefix)
  37. }
  38. // HugePageResourceName returns a ResourceName with the canonical hugepage
  39. // prefix prepended for the specified page size. The page size is converted
  40. // to its canonical representation.
  41. func HugePageResourceName(pageSize resource.Quantity) core.ResourceName {
  42. return core.ResourceName(fmt.Sprintf("%s%s", core.ResourceHugePagesPrefix, pageSize.String()))
  43. }
  44. // HugePageSizeFromResourceName returns the page size for the specified huge page
  45. // resource name. If the specified input is not a valid huge page resource name
  46. // an error is returned.
  47. func HugePageSizeFromResourceName(name core.ResourceName) (resource.Quantity, error) {
  48. if !IsHugePageResourceName(name) {
  49. return resource.Quantity{}, fmt.Errorf("resource name: %s is an invalid hugepage name", name)
  50. }
  51. pageSize := strings.TrimPrefix(string(name), core.ResourceHugePagesPrefix)
  52. return resource.ParseQuantity(pageSize)
  53. }
  54. // NonConvertibleFields iterates over the provided map and filters out all but
  55. // any keys with the "non-convertible.kubernetes.io" prefix.
  56. func NonConvertibleFields(annotations map[string]string) map[string]string {
  57. nonConvertibleKeys := map[string]string{}
  58. for key, value := range annotations {
  59. if strings.HasPrefix(key, core.NonConvertibleAnnotationPrefix) {
  60. nonConvertibleKeys[key] = value
  61. }
  62. }
  63. return nonConvertibleKeys
  64. }
  65. // Semantic can do semantic deep equality checks for core objects.
  66. // Example: apiequality.Semantic.DeepEqual(aPod, aPodWithNonNilButEmptyMaps) == true
  67. var Semantic = conversion.EqualitiesOrDie(
  68. func(a, b resource.Quantity) bool {
  69. // Ignore formatting, only care that numeric value stayed the same.
  70. // TODO: if we decide it's important, it should be safe to start comparing the format.
  71. //
  72. // Uninitialized quantities are equivalent to 0 quantities.
  73. return a.Cmp(b) == 0
  74. },
  75. func(a, b metav1.MicroTime) bool {
  76. return a.UTC() == b.UTC()
  77. },
  78. func(a, b metav1.Time) bool {
  79. return a.UTC() == b.UTC()
  80. },
  81. func(a, b labels.Selector) bool {
  82. return a.String() == b.String()
  83. },
  84. func(a, b fields.Selector) bool {
  85. return a.String() == b.String()
  86. },
  87. )
  88. var standardResourceQuotaScopes = sets.NewString(
  89. string(core.ResourceQuotaScopeTerminating),
  90. string(core.ResourceQuotaScopeNotTerminating),
  91. string(core.ResourceQuotaScopeBestEffort),
  92. string(core.ResourceQuotaScopeNotBestEffort),
  93. string(core.ResourceQuotaScopePriorityClass),
  94. )
  95. // IsStandardResourceQuotaScope returns true if the scope is a standard value
  96. func IsStandardResourceQuotaScope(str string) bool {
  97. return standardResourceQuotaScopes.Has(str)
  98. }
  99. var podObjectCountQuotaResources = sets.NewString(
  100. string(core.ResourcePods),
  101. )
  102. var podComputeQuotaResources = sets.NewString(
  103. string(core.ResourceCPU),
  104. string(core.ResourceMemory),
  105. string(core.ResourceLimitsCPU),
  106. string(core.ResourceLimitsMemory),
  107. string(core.ResourceRequestsCPU),
  108. string(core.ResourceRequestsMemory),
  109. )
  110. // IsResourceQuotaScopeValidForResource returns true if the resource applies to the specified scope
  111. func IsResourceQuotaScopeValidForResource(scope core.ResourceQuotaScope, resource string) bool {
  112. switch scope {
  113. case core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating, core.ResourceQuotaScopeNotBestEffort, core.ResourceQuotaScopePriorityClass:
  114. return podObjectCountQuotaResources.Has(resource) || podComputeQuotaResources.Has(resource)
  115. case core.ResourceQuotaScopeBestEffort:
  116. return podObjectCountQuotaResources.Has(resource)
  117. default:
  118. return true
  119. }
  120. }
  121. var standardContainerResources = sets.NewString(
  122. string(core.ResourceCPU),
  123. string(core.ResourceMemory),
  124. string(core.ResourceEphemeralStorage),
  125. )
  126. // IsStandardContainerResourceName returns true if the container can make a resource request
  127. // for the specified resource
  128. func IsStandardContainerResourceName(str string) bool {
  129. return standardContainerResources.Has(str) || IsHugePageResourceName(core.ResourceName(str))
  130. }
  131. // IsExtendedResourceName returns true if:
  132. // 1. the resource name is not in the default namespace;
  133. // 2. resource name does not have "requests." prefix,
  134. // to avoid confusion with the convention in quota
  135. // 3. it satisfies the rules in IsQualifiedName() after converted into quota resource name
  136. func IsExtendedResourceName(name core.ResourceName) bool {
  137. if IsNativeResource(name) || strings.HasPrefix(string(name), core.DefaultResourceRequestsPrefix) {
  138. return false
  139. }
  140. // Ensure it satisfies the rules in IsQualifiedName() after converted into quota resource name
  141. nameForQuota := fmt.Sprintf("%s%s", core.DefaultResourceRequestsPrefix, string(name))
  142. if errs := validation.IsQualifiedName(string(nameForQuota)); len(errs) != 0 {
  143. return false
  144. }
  145. return true
  146. }
  147. // IsNativeResource returns true if the resource name is in the
  148. // *kubernetes.io/ namespace. Partially-qualified (unprefixed) names are
  149. // implicitly in the kubernetes.io/ namespace.
  150. func IsNativeResource(name core.ResourceName) bool {
  151. return !strings.Contains(string(name), "/") ||
  152. strings.Contains(string(name), core.ResourceDefaultNamespacePrefix)
  153. }
  154. // IsOvercommitAllowed returns true if the resource is in the default
  155. // namespace and is not hugepages.
  156. func IsOvercommitAllowed(name core.ResourceName) bool {
  157. return IsNativeResource(name) &&
  158. !IsHugePageResourceName(name)
  159. }
  160. var standardLimitRangeTypes = sets.NewString(
  161. string(core.LimitTypePod),
  162. string(core.LimitTypeContainer),
  163. string(core.LimitTypePersistentVolumeClaim),
  164. )
  165. // IsStandardLimitRangeType returns true if the type is Pod or Container
  166. func IsStandardLimitRangeType(str string) bool {
  167. return standardLimitRangeTypes.Has(str)
  168. }
  169. var standardQuotaResources = sets.NewString(
  170. string(core.ResourceCPU),
  171. string(core.ResourceMemory),
  172. string(core.ResourceEphemeralStorage),
  173. string(core.ResourceRequestsCPU),
  174. string(core.ResourceRequestsMemory),
  175. string(core.ResourceRequestsStorage),
  176. string(core.ResourceRequestsEphemeralStorage),
  177. string(core.ResourceLimitsCPU),
  178. string(core.ResourceLimitsMemory),
  179. string(core.ResourceLimitsEphemeralStorage),
  180. string(core.ResourcePods),
  181. string(core.ResourceQuotas),
  182. string(core.ResourceServices),
  183. string(core.ResourceReplicationControllers),
  184. string(core.ResourceSecrets),
  185. string(core.ResourcePersistentVolumeClaims),
  186. string(core.ResourceConfigMaps),
  187. string(core.ResourceServicesNodePorts),
  188. string(core.ResourceServicesLoadBalancers),
  189. )
  190. // IsStandardQuotaResourceName returns true if the resource is known to
  191. // the quota tracking system
  192. func IsStandardQuotaResourceName(str string) bool {
  193. return standardQuotaResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))
  194. }
  195. var standardResources = sets.NewString(
  196. string(core.ResourceCPU),
  197. string(core.ResourceMemory),
  198. string(core.ResourceEphemeralStorage),
  199. string(core.ResourceRequestsCPU),
  200. string(core.ResourceRequestsMemory),
  201. string(core.ResourceRequestsEphemeralStorage),
  202. string(core.ResourceLimitsCPU),
  203. string(core.ResourceLimitsMemory),
  204. string(core.ResourceLimitsEphemeralStorage),
  205. string(core.ResourcePods),
  206. string(core.ResourceQuotas),
  207. string(core.ResourceServices),
  208. string(core.ResourceReplicationControllers),
  209. string(core.ResourceSecrets),
  210. string(core.ResourceConfigMaps),
  211. string(core.ResourcePersistentVolumeClaims),
  212. string(core.ResourceStorage),
  213. string(core.ResourceRequestsStorage),
  214. string(core.ResourceServicesNodePorts),
  215. string(core.ResourceServicesLoadBalancers),
  216. )
  217. // IsStandardResourceName returns true if the resource is known to the system
  218. func IsStandardResourceName(str string) bool {
  219. return standardResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))
  220. }
  221. var integerResources = sets.NewString(
  222. string(core.ResourcePods),
  223. string(core.ResourceQuotas),
  224. string(core.ResourceServices),
  225. string(core.ResourceReplicationControllers),
  226. string(core.ResourceSecrets),
  227. string(core.ResourceConfigMaps),
  228. string(core.ResourcePersistentVolumeClaims),
  229. string(core.ResourceServicesNodePorts),
  230. string(core.ResourceServicesLoadBalancers),
  231. )
  232. // IsIntegerResourceName returns true if the resource is measured in integer values
  233. func IsIntegerResourceName(str string) bool {
  234. return integerResources.Has(str) || IsExtendedResourceName(core.ResourceName(str))
  235. }
  236. // IsServiceIPSet aims to check if the service's ClusterIP is set or not
  237. // the objective is not to perform validation here
  238. func IsServiceIPSet(service *core.Service) bool {
  239. return service.Spec.ClusterIP != core.ClusterIPNone && service.Spec.ClusterIP != ""
  240. }
  241. var standardFinalizers = sets.NewString(
  242. string(core.FinalizerKubernetes),
  243. metav1.FinalizerOrphanDependents,
  244. metav1.FinalizerDeleteDependents,
  245. )
  246. // IsStandardFinalizerName checks if the input string is a standard finalizer name
  247. func IsStandardFinalizerName(str string) bool {
  248. return standardFinalizers.Has(str)
  249. }
  250. // GetAccessModesAsString returns a string representation of an array of access modes.
  251. // modes, when present, are always in the same order: RWO,ROX,RWX.
  252. func GetAccessModesAsString(modes []core.PersistentVolumeAccessMode) string {
  253. modes = removeDuplicateAccessModes(modes)
  254. modesStr := []string{}
  255. if containsAccessMode(modes, core.ReadWriteOnce) {
  256. modesStr = append(modesStr, "RWO")
  257. }
  258. if containsAccessMode(modes, core.ReadOnlyMany) {
  259. modesStr = append(modesStr, "ROX")
  260. }
  261. if containsAccessMode(modes, core.ReadWriteMany) {
  262. modesStr = append(modesStr, "RWX")
  263. }
  264. return strings.Join(modesStr, ",")
  265. }
  266. // GetAccessModesFromString returns an array of AccessModes from a string created by GetAccessModesAsString
  267. func GetAccessModesFromString(modes string) []core.PersistentVolumeAccessMode {
  268. strmodes := strings.Split(modes, ",")
  269. accessModes := []core.PersistentVolumeAccessMode{}
  270. for _, s := range strmodes {
  271. s = strings.Trim(s, " ")
  272. switch {
  273. case s == "RWO":
  274. accessModes = append(accessModes, core.ReadWriteOnce)
  275. case s == "ROX":
  276. accessModes = append(accessModes, core.ReadOnlyMany)
  277. case s == "RWX":
  278. accessModes = append(accessModes, core.ReadWriteMany)
  279. }
  280. }
  281. return accessModes
  282. }
  283. // removeDuplicateAccessModes returns an array of access modes without any duplicates
  284. func removeDuplicateAccessModes(modes []core.PersistentVolumeAccessMode) []core.PersistentVolumeAccessMode {
  285. accessModes := []core.PersistentVolumeAccessMode{}
  286. for _, m := range modes {
  287. if !containsAccessMode(accessModes, m) {
  288. accessModes = append(accessModes, m)
  289. }
  290. }
  291. return accessModes
  292. }
  293. func containsAccessMode(modes []core.PersistentVolumeAccessMode, mode core.PersistentVolumeAccessMode) bool {
  294. for _, m := range modes {
  295. if m == mode {
  296. return true
  297. }
  298. }
  299. return false
  300. }
  301. // NodeSelectorRequirementsAsSelector converts the []NodeSelectorRequirement core type into a struct that implements
  302. // labels.Selector.
  303. func NodeSelectorRequirementsAsSelector(nsm []core.NodeSelectorRequirement) (labels.Selector, error) {
  304. if len(nsm) == 0 {
  305. return labels.Nothing(), nil
  306. }
  307. selector := labels.NewSelector()
  308. for _, expr := range nsm {
  309. var op selection.Operator
  310. switch expr.Operator {
  311. case core.NodeSelectorOpIn:
  312. op = selection.In
  313. case core.NodeSelectorOpNotIn:
  314. op = selection.NotIn
  315. case core.NodeSelectorOpExists:
  316. op = selection.Exists
  317. case core.NodeSelectorOpDoesNotExist:
  318. op = selection.DoesNotExist
  319. case core.NodeSelectorOpGt:
  320. op = selection.GreaterThan
  321. case core.NodeSelectorOpLt:
  322. op = selection.LessThan
  323. default:
  324. return nil, fmt.Errorf("%q is not a valid node selector operator", expr.Operator)
  325. }
  326. r, err := labels.NewRequirement(expr.Key, op, expr.Values)
  327. if err != nil {
  328. return nil, err
  329. }
  330. selector = selector.Add(*r)
  331. }
  332. return selector, nil
  333. }
  334. // NodeSelectorRequirementsAsFieldSelector converts the []NodeSelectorRequirement core type into a struct that implements
  335. // fields.Selector.
  336. func NodeSelectorRequirementsAsFieldSelector(nsm []core.NodeSelectorRequirement) (fields.Selector, error) {
  337. if len(nsm) == 0 {
  338. return fields.Nothing(), nil
  339. }
  340. selectors := []fields.Selector{}
  341. for _, expr := range nsm {
  342. switch expr.Operator {
  343. case core.NodeSelectorOpIn:
  344. if len(expr.Values) != 1 {
  345. return nil, fmt.Errorf("unexpected number of value (%d) for node field selector operator %q",
  346. len(expr.Values), expr.Operator)
  347. }
  348. selectors = append(selectors, fields.OneTermEqualSelector(expr.Key, expr.Values[0]))
  349. case core.NodeSelectorOpNotIn:
  350. if len(expr.Values) != 1 {
  351. return nil, fmt.Errorf("unexpected number of value (%d) for node field selector operator %q",
  352. len(expr.Values), expr.Operator)
  353. }
  354. selectors = append(selectors, fields.OneTermNotEqualSelector(expr.Key, expr.Values[0]))
  355. default:
  356. return nil, fmt.Errorf("%q is not a valid node field selector operator", expr.Operator)
  357. }
  358. }
  359. return fields.AndSelectors(selectors...), nil
  360. }
  361. // GetTolerationsFromPodAnnotations gets the json serialized tolerations data from Pod.Annotations
  362. // and converts it to the []Toleration type in core.
  363. func GetTolerationsFromPodAnnotations(annotations map[string]string) ([]core.Toleration, error) {
  364. var tolerations []core.Toleration
  365. if len(annotations) > 0 && annotations[core.TolerationsAnnotationKey] != "" {
  366. err := json.Unmarshal([]byte(annotations[core.TolerationsAnnotationKey]), &tolerations)
  367. if err != nil {
  368. return tolerations, err
  369. }
  370. }
  371. return tolerations, nil
  372. }
  373. // AddOrUpdateTolerationInPod tries to add a toleration to the pod's toleration list.
  374. // Returns true if something was updated, false otherwise.
  375. func AddOrUpdateTolerationInPod(pod *core.Pod, toleration *core.Toleration) bool {
  376. podTolerations := pod.Spec.Tolerations
  377. var newTolerations []core.Toleration
  378. updated := false
  379. for i := range podTolerations {
  380. if toleration.MatchToleration(&podTolerations[i]) {
  381. if Semantic.DeepEqual(toleration, podTolerations[i]) {
  382. return false
  383. }
  384. newTolerations = append(newTolerations, *toleration)
  385. updated = true
  386. continue
  387. }
  388. newTolerations = append(newTolerations, podTolerations[i])
  389. }
  390. if !updated {
  391. newTolerations = append(newTolerations, *toleration)
  392. }
  393. pod.Spec.Tolerations = newTolerations
  394. return true
  395. }
  396. // GetTaintsFromNodeAnnotations gets the json serialized taints data from Pod.Annotations
  397. // and converts it to the []Taint type in core.
  398. func GetTaintsFromNodeAnnotations(annotations map[string]string) ([]core.Taint, error) {
  399. var taints []core.Taint
  400. if len(annotations) > 0 && annotations[core.TaintsAnnotationKey] != "" {
  401. err := json.Unmarshal([]byte(annotations[core.TaintsAnnotationKey]), &taints)
  402. if err != nil {
  403. return []core.Taint{}, err
  404. }
  405. }
  406. return taints, nil
  407. }
  408. // GetPersistentVolumeClass returns StorageClassName.
  409. func GetPersistentVolumeClass(volume *core.PersistentVolume) string {
  410. // Use beta annotation first
  411. if class, found := volume.Annotations[core.BetaStorageClassAnnotation]; found {
  412. return class
  413. }
  414. return volume.Spec.StorageClassName
  415. }
  416. // GetPersistentVolumeClaimClass returns StorageClassName. If no storage class was
  417. // requested, it returns "".
  418. func GetPersistentVolumeClaimClass(claim *core.PersistentVolumeClaim) string {
  419. // Use beta annotation first
  420. if class, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {
  421. return class
  422. }
  423. if claim.Spec.StorageClassName != nil {
  424. return *claim.Spec.StorageClassName
  425. }
  426. return ""
  427. }
  428. // PersistentVolumeClaimHasClass returns true if given claim has set StorageClassName field.
  429. func PersistentVolumeClaimHasClass(claim *core.PersistentVolumeClaim) bool {
  430. // Use beta annotation first
  431. if _, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {
  432. return true
  433. }
  434. if claim.Spec.StorageClassName != nil {
  435. return true
  436. }
  437. return false
  438. }