utils.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. /*
  2. Copyright 2018 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 taints implements utilites for working with taints
  14. package taint
  15. import (
  16. "fmt"
  17. "strings"
  18. corev1 "k8s.io/api/core/v1"
  19. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  20. "k8s.io/apimachinery/pkg/util/sets"
  21. "k8s.io/apimachinery/pkg/util/validation"
  22. )
  23. // Exported taint constant strings
  24. const (
  25. MODIFIED = "modified"
  26. TAINTED = "tainted"
  27. UNTAINTED = "untainted"
  28. )
  29. // parseTaints takes a spec which is an array and creates slices for new taints to be added, taints to be deleted.
  30. // It also validates the spec. For example, the form `<key>` may be used to remove a taint, but not to add one.
  31. func parseTaints(spec []string) ([]corev1.Taint, []corev1.Taint, error) {
  32. var taints, taintsToRemove []corev1.Taint
  33. uniqueTaints := map[corev1.TaintEffect]sets.String{}
  34. for _, taintSpec := range spec {
  35. if strings.HasSuffix(taintSpec, "-") {
  36. taintToRemove, err := parseTaint(strings.TrimSuffix(taintSpec, "-"))
  37. if err != nil {
  38. return nil, nil, err
  39. }
  40. taintsToRemove = append(taintsToRemove, corev1.Taint{Key: taintToRemove.Key, Effect: taintToRemove.Effect})
  41. } else {
  42. newTaint, err := parseTaint(taintSpec)
  43. if err != nil {
  44. return nil, nil, err
  45. }
  46. // validate that the taint has an effect, which is required to add the taint
  47. if len(newTaint.Effect) == 0 {
  48. return nil, nil, fmt.Errorf("invalid taint spec: %v", taintSpec)
  49. }
  50. // validate if taint is unique by <key, effect>
  51. if len(uniqueTaints[newTaint.Effect]) > 0 && uniqueTaints[newTaint.Effect].Has(newTaint.Key) {
  52. return nil, nil, fmt.Errorf("duplicated taints with the same key and effect: %v", newTaint)
  53. }
  54. // add taint to existingTaints for uniqueness check
  55. if len(uniqueTaints[newTaint.Effect]) == 0 {
  56. uniqueTaints[newTaint.Effect] = sets.String{}
  57. }
  58. uniqueTaints[newTaint.Effect].Insert(newTaint.Key)
  59. taints = append(taints, newTaint)
  60. }
  61. }
  62. return taints, taintsToRemove, nil
  63. }
  64. // parseTaint parses a taint from a string, whose form must be either
  65. // '<key>=<value>:<effect>', '<key>:<effect>', or '<key>'.
  66. func parseTaint(st string) (corev1.Taint, error) {
  67. var taint corev1.Taint
  68. var key string
  69. var value string
  70. var effect corev1.TaintEffect
  71. parts := strings.Split(st, ":")
  72. switch len(parts) {
  73. case 1:
  74. key = parts[0]
  75. case 2:
  76. effect = corev1.TaintEffect(parts[1])
  77. if err := validateTaintEffect(effect); err != nil {
  78. return taint, err
  79. }
  80. partsKV := strings.Split(parts[0], "=")
  81. if len(partsKV) > 2 {
  82. return taint, fmt.Errorf("invalid taint spec: %v", st)
  83. }
  84. key = partsKV[0]
  85. if len(partsKV) == 2 {
  86. value = partsKV[1]
  87. if errs := validation.IsValidLabelValue(value); len(errs) > 0 {
  88. return taint, fmt.Errorf("invalid taint spec: %v, %s", st, strings.Join(errs, "; "))
  89. }
  90. }
  91. default:
  92. return taint, fmt.Errorf("invalid taint spec: %v", st)
  93. }
  94. if errs := validation.IsQualifiedName(key); len(errs) > 0 {
  95. return taint, fmt.Errorf("invalid taint spec: %v, %s", st, strings.Join(errs, "; "))
  96. }
  97. taint.Key = key
  98. taint.Value = value
  99. taint.Effect = effect
  100. return taint, nil
  101. }
  102. func validateTaintEffect(effect corev1.TaintEffect) error {
  103. if effect != corev1.TaintEffectNoSchedule && effect != corev1.TaintEffectPreferNoSchedule && effect != corev1.TaintEffectNoExecute {
  104. return fmt.Errorf("invalid taint effect: %v, unsupported taint effect", effect)
  105. }
  106. return nil
  107. }
  108. // ReorganizeTaints returns the updated set of taints, taking into account old taints that were not updated,
  109. // old taints that were updated, old taints that were deleted, and new taints.
  110. func reorganizeTaints(node *corev1.Node, overwrite bool, taintsToAdd []corev1.Taint, taintsToRemove []corev1.Taint) (string, []corev1.Taint, error) {
  111. newTaints := append([]corev1.Taint{}, taintsToAdd...)
  112. oldTaints := node.Spec.Taints
  113. // add taints that already existing but not updated to newTaints
  114. added := addTaints(oldTaints, &newTaints)
  115. allErrs, deleted := deleteTaints(taintsToRemove, &newTaints)
  116. if (added && deleted) || overwrite {
  117. return MODIFIED, newTaints, utilerrors.NewAggregate(allErrs)
  118. } else if added {
  119. return TAINTED, newTaints, utilerrors.NewAggregate(allErrs)
  120. }
  121. return UNTAINTED, newTaints, utilerrors.NewAggregate(allErrs)
  122. }
  123. // deleteTaints deletes the given taints from the node's taintlist.
  124. func deleteTaints(taintsToRemove []corev1.Taint, newTaints *[]corev1.Taint) ([]error, bool) {
  125. allErrs := []error{}
  126. var removed bool
  127. for _, taintToRemove := range taintsToRemove {
  128. removed = false
  129. if len(taintToRemove.Effect) > 0 {
  130. *newTaints, removed = deleteTaint(*newTaints, &taintToRemove)
  131. } else {
  132. *newTaints, removed = deleteTaintsByKey(*newTaints, taintToRemove.Key)
  133. }
  134. if !removed {
  135. allErrs = append(allErrs, fmt.Errorf("taint %q not found", taintToRemove.ToString()))
  136. }
  137. }
  138. return allErrs, removed
  139. }
  140. // addTaints adds the newTaints list to existing ones and updates the newTaints List.
  141. // TODO: This needs a rewrite to take only the new values instead of appended newTaints list to be consistent.
  142. func addTaints(oldTaints []corev1.Taint, newTaints *[]corev1.Taint) bool {
  143. for _, oldTaint := range oldTaints {
  144. existsInNew := false
  145. for _, taint := range *newTaints {
  146. if taint.MatchTaint(&oldTaint) {
  147. existsInNew = true
  148. break
  149. }
  150. }
  151. if !existsInNew {
  152. *newTaints = append(*newTaints, oldTaint)
  153. }
  154. }
  155. return len(oldTaints) != len(*newTaints)
  156. }
  157. // CheckIfTaintsAlreadyExists checks if the node already has taints that we want to add and returns a string with taint keys.
  158. func checkIfTaintsAlreadyExists(oldTaints []corev1.Taint, taints []corev1.Taint) string {
  159. var existingTaintList = make([]string, 0)
  160. for _, taint := range taints {
  161. for _, oldTaint := range oldTaints {
  162. if taint.Key == oldTaint.Key && taint.Effect == oldTaint.Effect {
  163. existingTaintList = append(existingTaintList, taint.Key)
  164. }
  165. }
  166. }
  167. return strings.Join(existingTaintList, ",")
  168. }
  169. // DeleteTaintsByKey removes all the taints that have the same key to given taintKey
  170. func deleteTaintsByKey(taints []corev1.Taint, taintKey string) ([]corev1.Taint, bool) {
  171. newTaints := []corev1.Taint{}
  172. deleted := false
  173. for i := range taints {
  174. if taintKey == taints[i].Key {
  175. deleted = true
  176. continue
  177. }
  178. newTaints = append(newTaints, taints[i])
  179. }
  180. return newTaints, deleted
  181. }
  182. // DeleteTaint removes all the taints that have the same key and effect to given taintToDelete.
  183. func deleteTaint(taints []corev1.Taint, taintToDelete *corev1.Taint) ([]corev1.Taint, bool) {
  184. newTaints := []corev1.Taint{}
  185. deleted := false
  186. for i := range taints {
  187. if taintToDelete.MatchTaint(&taints[i]) {
  188. deleted = true
  189. continue
  190. }
  191. newTaints = append(newTaints, taints[i])
  192. }
  193. return newTaints, deleted
  194. }