taint.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 taint
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strings"
  18. "github.com/spf13/cobra"
  19. "k8s.io/klog"
  20. "k8s.io/api/core/v1"
  21. "k8s.io/apimachinery/pkg/api/meta"
  22. "k8s.io/apimachinery/pkg/runtime"
  23. "k8s.io/apimachinery/pkg/types"
  24. "k8s.io/apimachinery/pkg/util/strategicpatch"
  25. "k8s.io/apimachinery/pkg/util/validation"
  26. "k8s.io/cli-runtime/pkg/genericclioptions"
  27. "k8s.io/cli-runtime/pkg/printers"
  28. "k8s.io/cli-runtime/pkg/resource"
  29. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  30. "k8s.io/kubernetes/pkg/kubectl/scheme"
  31. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  32. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  33. )
  34. // TaintOptions have the data required to perform the taint operation
  35. type TaintOptions struct {
  36. PrintFlags *genericclioptions.PrintFlags
  37. ToPrinter func(string) (printers.ResourcePrinter, error)
  38. resources []string
  39. taintsToAdd []v1.Taint
  40. taintsToRemove []v1.Taint
  41. builder *resource.Builder
  42. selector string
  43. overwrite bool
  44. all bool
  45. ClientForMapping func(*meta.RESTMapping) (resource.RESTClient, error)
  46. genericclioptions.IOStreams
  47. }
  48. var (
  49. taintLong = templates.LongDesc(i18n.T(`
  50. Update the taints on one or more nodes.
  51. * A taint consists of a key, value, and effect. As an argument here, it is expressed as key=value:effect.
  52. * The key must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[1]d characters.
  53. * Optionally, the key can begin with a DNS subdomain prefix and a single '/', like example.com/my-app
  54. * The value is optional. If given, it must begin with a letter or number, and may contain letters, numbers, hyphens, dots, and underscores, up to %[2]d characters.
  55. * The effect must be NoSchedule, PreferNoSchedule or NoExecute.
  56. * Currently taint can only apply to node.`))
  57. taintExample = templates.Examples(i18n.T(`
  58. # Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'.
  59. # If a taint with that key and effect already exists, its value is replaced as specified.
  60. kubectl taint nodes foo dedicated=special-user:NoSchedule
  61. # Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists.
  62. kubectl taint nodes foo dedicated:NoSchedule-
  63. # Remove from node 'foo' all the taints with key 'dedicated'
  64. kubectl taint nodes foo dedicated-
  65. # Add a taint with key 'dedicated' on nodes having label mylabel=X
  66. kubectl taint node -l myLabel=X dedicated=foo:PreferNoSchedule
  67. # Add to node 'foo' a taint with key 'bar' and no value
  68. kubectl taint nodes foo bar:NoSchedule`))
  69. )
  70. func NewCmdTaint(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  71. options := &TaintOptions{
  72. PrintFlags: genericclioptions.NewPrintFlags("tainted").WithTypeSetter(scheme.Scheme),
  73. IOStreams: streams,
  74. }
  75. validArgs := []string{"node"}
  76. cmd := &cobra.Command{
  77. Use: "taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N",
  78. DisableFlagsInUseLine: true,
  79. Short: i18n.T("Update the taints on one or more nodes"),
  80. Long: fmt.Sprintf(taintLong, validation.DNS1123SubdomainMaxLength, validation.LabelValueMaxLength),
  81. Example: taintExample,
  82. Run: func(cmd *cobra.Command, args []string) {
  83. cmdutil.CheckErr(options.Complete(f, cmd, args))
  84. cmdutil.CheckErr(options.Validate())
  85. cmdutil.CheckErr(options.RunTaint())
  86. },
  87. ValidArgs: validArgs,
  88. }
  89. options.PrintFlags.AddFlags(cmd)
  90. cmdutil.AddValidateFlags(cmd)
  91. cmd.Flags().StringVarP(&options.selector, "selector", "l", options.selector, "Selector (label query) to filter on, supports '=', '==', and '!='.(e.g. -l key1=value1,key2=value2)")
  92. cmd.Flags().BoolVar(&options.overwrite, "overwrite", options.overwrite, "If true, allow taints to be overwritten, otherwise reject taint updates that overwrite existing taints.")
  93. cmd.Flags().BoolVar(&options.all, "all", options.all, "Select all nodes in the cluster")
  94. return cmd
  95. }
  96. // Complete adapts from the command line args and factory to the data required.
  97. func (o *TaintOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) (err error) {
  98. namespace, _, err := f.ToRawKubeConfigLoader().Namespace()
  99. if err != nil {
  100. return err
  101. }
  102. // retrieves resource and taint args from args
  103. // also checks args to verify that all resources are specified before taints
  104. taintArgs := []string{}
  105. metTaintArg := false
  106. for _, s := range args {
  107. isTaint := strings.Contains(s, "=") || strings.HasSuffix(s, "-")
  108. switch {
  109. case !metTaintArg && isTaint:
  110. metTaintArg = true
  111. fallthrough
  112. case metTaintArg && isTaint:
  113. taintArgs = append(taintArgs, s)
  114. case !metTaintArg && !isTaint:
  115. o.resources = append(o.resources, s)
  116. case metTaintArg && !isTaint:
  117. return fmt.Errorf("all resources must be specified before taint changes: %s", s)
  118. }
  119. }
  120. o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
  121. o.PrintFlags.NamePrintFlags.Operation = operation
  122. return o.PrintFlags.ToPrinter()
  123. }
  124. if len(o.resources) < 1 {
  125. return fmt.Errorf("one or more resources must be specified as <resource> <name>")
  126. }
  127. if len(taintArgs) < 1 {
  128. return fmt.Errorf("at least one taint update is required")
  129. }
  130. if o.taintsToAdd, o.taintsToRemove, err = parseTaints(taintArgs); err != nil {
  131. return cmdutil.UsageErrorf(cmd, err.Error())
  132. }
  133. o.builder = f.NewBuilder().
  134. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  135. ContinueOnError().
  136. NamespaceParam(namespace).DefaultNamespace()
  137. if o.selector != "" {
  138. o.builder = o.builder.LabelSelectorParam(o.selector).ResourceTypes("node")
  139. }
  140. if o.all {
  141. o.builder = o.builder.SelectAllParam(o.all).ResourceTypes("node").Flatten().Latest()
  142. }
  143. if !o.all && o.selector == "" && len(o.resources) >= 2 {
  144. o.builder = o.builder.ResourceNames("node", o.resources[1:]...)
  145. }
  146. o.builder = o.builder.LabelSelectorParam(o.selector).
  147. Flatten().
  148. Latest()
  149. o.ClientForMapping = f.ClientForMapping
  150. return nil
  151. }
  152. // validateFlags checks for the validation of flags for kubectl taints.
  153. func (o TaintOptions) validateFlags() error {
  154. // Cannot have a non-empty selector and all flag set. They are mutually exclusive.
  155. if o.all && o.selector != "" {
  156. return fmt.Errorf("setting 'all' parameter with a non empty selector is prohibited.")
  157. }
  158. // If both selector and all are not set.
  159. if !o.all && o.selector == "" {
  160. if len(o.resources) < 2 {
  161. return fmt.Errorf("at least one resource name must be specified since 'all' parameter is not set")
  162. } else {
  163. return nil
  164. }
  165. }
  166. return nil
  167. }
  168. // Validate checks to the TaintOptions to see if there is sufficient information run the command.
  169. func (o TaintOptions) Validate() error {
  170. resourceType := strings.ToLower(o.resources[0])
  171. validResources, isValidResource := []string{"node", "nodes"}, false
  172. for _, validResource := range validResources {
  173. if resourceType == validResource {
  174. isValidResource = true
  175. break
  176. }
  177. }
  178. if !isValidResource {
  179. return fmt.Errorf("invalid resource type %s, only %q are supported", o.resources[0], validResources)
  180. }
  181. // check the format of taint args and checks removed taints aren't in the new taints list
  182. var conflictTaints []string
  183. for _, taintAdd := range o.taintsToAdd {
  184. for _, taintRemove := range o.taintsToRemove {
  185. if taintAdd.Key != taintRemove.Key {
  186. continue
  187. }
  188. if len(taintRemove.Effect) == 0 || taintAdd.Effect == taintRemove.Effect {
  189. conflictTaint := fmt.Sprintf("{\"%s\":\"%s\"}", taintRemove.Key, taintRemove.Effect)
  190. conflictTaints = append(conflictTaints, conflictTaint)
  191. }
  192. }
  193. }
  194. if len(conflictTaints) > 0 {
  195. return fmt.Errorf("can not both modify and remove the following taint(s) in the same command: %s", strings.Join(conflictTaints, ", "))
  196. }
  197. return o.validateFlags()
  198. }
  199. // RunTaint does the work
  200. func (o TaintOptions) RunTaint() error {
  201. r := o.builder.Do()
  202. if err := r.Err(); err != nil {
  203. return err
  204. }
  205. return r.Visit(func(info *resource.Info, err error) error {
  206. if err != nil {
  207. return err
  208. }
  209. obj := info.Object
  210. name, namespace := info.Name, info.Namespace
  211. oldData, err := json.Marshal(obj)
  212. if err != nil {
  213. return err
  214. }
  215. operation, err := o.updateTaints(obj)
  216. if err != nil {
  217. return err
  218. }
  219. newData, err := json.Marshal(obj)
  220. if err != nil {
  221. return err
  222. }
  223. patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, obj)
  224. createdPatch := err == nil
  225. if err != nil {
  226. klog.V(2).Infof("couldn't compute patch: %v", err)
  227. }
  228. mapping := info.ResourceMapping()
  229. client, err := o.ClientForMapping(mapping)
  230. if err != nil {
  231. return err
  232. }
  233. helper := resource.NewHelper(client, mapping)
  234. var outputObj runtime.Object
  235. if createdPatch {
  236. outputObj, err = helper.Patch(namespace, name, types.StrategicMergePatchType, patchBytes, nil)
  237. } else {
  238. outputObj, err = helper.Replace(namespace, name, false, obj)
  239. }
  240. if err != nil {
  241. return err
  242. }
  243. printer, err := o.ToPrinter(operation)
  244. if err != nil {
  245. return err
  246. }
  247. return printer.PrintObj(outputObj, o.Out)
  248. })
  249. }
  250. // updateTaints applies a taint option(o) to a node in cluster after computing the net effect of operation(i.e. does it result in an overwrite?), it reports back the end result in a way that user can easily interpret.
  251. func (o TaintOptions) updateTaints(obj runtime.Object) (string, error) {
  252. node, ok := obj.(*v1.Node)
  253. if !ok {
  254. return "", fmt.Errorf("unexpected type %T, expected Node", obj)
  255. }
  256. if !o.overwrite {
  257. if exists := checkIfTaintsAlreadyExists(node.Spec.Taints, o.taintsToAdd); len(exists) != 0 {
  258. return "", fmt.Errorf("Node %s already has %v taint(s) with same effect(s) and --overwrite is false", node.Name, exists)
  259. }
  260. }
  261. operation, newTaints, err := reorganizeTaints(node, o.overwrite, o.taintsToAdd, o.taintsToRemove)
  262. if err != nil {
  263. return "", err
  264. }
  265. node.Spec.Taints = newTaints
  266. return operation, nil
  267. }