rollout_pause.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  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 rollout
  14. import (
  15. "fmt"
  16. "github.com/spf13/cobra"
  17. "k8s.io/apimachinery/pkg/types"
  18. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  19. "k8s.io/cli-runtime/pkg/genericclioptions"
  20. "k8s.io/cli-runtime/pkg/printers"
  21. "k8s.io/cli-runtime/pkg/resource"
  22. "k8s.io/kubernetes/pkg/kubectl/cmd/set"
  23. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  24. "k8s.io/kubernetes/pkg/kubectl/polymorphichelpers"
  25. "k8s.io/kubernetes/pkg/kubectl/scheme"
  26. "k8s.io/kubernetes/pkg/kubectl/util/i18n"
  27. "k8s.io/kubernetes/pkg/kubectl/util/templates"
  28. )
  29. // PauseOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  30. // referencing the cmd.Flags()
  31. type PauseOptions struct {
  32. PrintFlags *genericclioptions.PrintFlags
  33. ToPrinter func(string) (printers.ResourcePrinter, error)
  34. Pauser polymorphichelpers.ObjectPauserFunc
  35. Builder func() *resource.Builder
  36. Namespace string
  37. EnforceNamespace bool
  38. Resources []string
  39. resource.FilenameOptions
  40. genericclioptions.IOStreams
  41. }
  42. var (
  43. pauseLong = templates.LongDesc(`
  44. Mark the provided resource as paused
  45. Paused resources will not be reconciled by a controller.
  46. Use "kubectl rollout resume" to resume a paused resource.
  47. Currently only deployments support being paused.`)
  48. pauseExample = templates.Examples(`
  49. # Mark the nginx deployment as paused. Any current state of
  50. # the deployment will continue its function, new updates to the deployment will not
  51. # have an effect as long as the deployment is paused.
  52. kubectl rollout pause deployment/nginx`)
  53. )
  54. // NewCmdRolloutPause returns a Command instance for 'rollout pause' sub command
  55. func NewCmdRolloutPause(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  56. o := &PauseOptions{
  57. PrintFlags: genericclioptions.NewPrintFlags("paused").WithTypeSetter(scheme.Scheme),
  58. IOStreams: streams,
  59. }
  60. validArgs := []string{"deployment"}
  61. cmd := &cobra.Command{
  62. Use: "pause RESOURCE",
  63. DisableFlagsInUseLine: true,
  64. Short: i18n.T("Mark the provided resource as paused"),
  65. Long: pauseLong,
  66. Example: pauseExample,
  67. Run: func(cmd *cobra.Command, args []string) {
  68. cmdutil.CheckErr(o.Complete(f, cmd, args))
  69. cmdutil.CheckErr(o.Validate())
  70. cmdutil.CheckErr(o.RunPause())
  71. },
  72. ValidArgs: validArgs,
  73. }
  74. o.PrintFlags.AddFlags(cmd)
  75. usage := "identifying the resource to get from a server."
  76. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
  77. return cmd
  78. }
  79. // Complete completes all the required options
  80. func (o *PauseOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  81. o.Pauser = polymorphichelpers.ObjectPauserFn
  82. var err error
  83. o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
  84. if err != nil {
  85. return err
  86. }
  87. o.Resources = args
  88. o.Builder = f.NewBuilder
  89. o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
  90. o.PrintFlags.NamePrintFlags.Operation = operation
  91. return o.PrintFlags.ToPrinter()
  92. }
  93. return nil
  94. }
  95. func (o *PauseOptions) Validate() error {
  96. if len(o.Resources) == 0 && cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {
  97. return fmt.Errorf("required resource not specified")
  98. }
  99. return nil
  100. }
  101. // RunPause performs the execution of 'rollout pause' sub command
  102. func (o *PauseOptions) RunPause() error {
  103. r := o.Builder().
  104. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  105. NamespaceParam(o.Namespace).DefaultNamespace().
  106. FilenameParam(o.EnforceNamespace, &o.FilenameOptions).
  107. ResourceTypeOrNameArgs(true, o.Resources...).
  108. ContinueOnError().
  109. Latest().
  110. Flatten().
  111. Do()
  112. if err := r.Err(); err != nil {
  113. return err
  114. }
  115. allErrs := []error{}
  116. infos, err := r.Infos()
  117. if err != nil {
  118. // restore previous command behavior where
  119. // an error caused by retrieving infos due to
  120. // at least a single broken object did not result
  121. // in an immediate return, but rather an overall
  122. // aggregation of errors.
  123. allErrs = append(allErrs, err)
  124. }
  125. for _, patch := range set.CalculatePatches(infos, scheme.DefaultJSONEncoder(), set.PatchFn(o.Pauser)) {
  126. info := patch.Info
  127. if patch.Err != nil {
  128. resourceString := info.Mapping.Resource.Resource
  129. if len(info.Mapping.Resource.Group) > 0 {
  130. resourceString = resourceString + "." + info.Mapping.Resource.Group
  131. }
  132. allErrs = append(allErrs, fmt.Errorf("error: %s %q %v", resourceString, info.Name, patch.Err))
  133. continue
  134. }
  135. if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
  136. printer, err := o.ToPrinter("already paused")
  137. if err != nil {
  138. allErrs = append(allErrs, err)
  139. continue
  140. }
  141. if err = printer.PrintObj(info.Object, o.Out); err != nil {
  142. allErrs = append(allErrs, err)
  143. }
  144. continue
  145. }
  146. obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)
  147. if err != nil {
  148. allErrs = append(allErrs, fmt.Errorf("failed to patch: %v", err))
  149. continue
  150. }
  151. info.Refresh(obj, true)
  152. printer, err := o.ToPrinter("paused")
  153. if err != nil {
  154. allErrs = append(allErrs, err)
  155. continue
  156. }
  157. if err = printer.PrintObj(info.Object, o.Out); err != nil {
  158. allErrs = append(allErrs, err)
  159. }
  160. }
  161. return utilerrors.NewAggregate(allErrs)
  162. }