rollout_restart.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. Copyright 2019 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. // RestartOptions 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 RestartOptions struct {
  32. PrintFlags *genericclioptions.PrintFlags
  33. ToPrinter func(string) (printers.ResourcePrinter, error)
  34. Resources []string
  35. Builder func() *resource.Builder
  36. Restarter polymorphichelpers.ObjectRestarterFunc
  37. Namespace string
  38. EnforceNamespace bool
  39. resource.FilenameOptions
  40. genericclioptions.IOStreams
  41. }
  42. var (
  43. restartLong = templates.LongDesc(`
  44. Restart a resource.
  45. Resource will be rollout restarted.`)
  46. restartExample = templates.Examples(`
  47. # Restart a deployment
  48. kubectl rollout restart deployment/nginx
  49. # Restart a daemonset
  50. kubectl rollout restart daemonset/abc`)
  51. )
  52. // NewRolloutRestartOptions returns an initialized RestartOptions instance
  53. func NewRolloutRestartOptions(streams genericclioptions.IOStreams) *RestartOptions {
  54. return &RestartOptions{
  55. PrintFlags: genericclioptions.NewPrintFlags("restarted").WithTypeSetter(scheme.Scheme),
  56. IOStreams: streams,
  57. }
  58. }
  59. // NewCmdRolloutRestart returns a Command instance for 'rollout restart' sub command
  60. func NewCmdRolloutRestart(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
  61. o := NewRolloutRestartOptions(streams)
  62. validArgs := []string{"deployment", "daemonset", "statefulset"}
  63. cmd := &cobra.Command{
  64. Use: "restart RESOURCE",
  65. DisableFlagsInUseLine: true,
  66. Short: i18n.T("Restart a resource"),
  67. Long: restartLong,
  68. Example: restartExample,
  69. Run: func(cmd *cobra.Command, args []string) {
  70. cmdutil.CheckErr(o.Complete(f, cmd, args))
  71. cmdutil.CheckErr(o.Validate())
  72. cmdutil.CheckErr(o.RunRestart())
  73. },
  74. ValidArgs: validArgs,
  75. }
  76. usage := "identifying the resource to get from a server."
  77. cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
  78. o.PrintFlags.AddFlags(cmd)
  79. return cmd
  80. }
  81. // Complete completes all the required options
  82. func (o *RestartOptions) Complete(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
  83. o.Resources = args
  84. o.Restarter = polymorphichelpers.ObjectRestarterFn
  85. var err error
  86. o.Namespace, o.EnforceNamespace, err = f.ToRawKubeConfigLoader().Namespace()
  87. if err != nil {
  88. return err
  89. }
  90. o.ToPrinter = func(operation string) (printers.ResourcePrinter, error) {
  91. o.PrintFlags.NamePrintFlags.Operation = operation
  92. return o.PrintFlags.ToPrinter()
  93. }
  94. o.Builder = f.NewBuilder
  95. return nil
  96. }
  97. func (o *RestartOptions) Validate() error {
  98. if len(o.Resources) == 0 && cmdutil.IsFilenameSliceEmpty(o.Filenames, o.Kustomize) {
  99. return fmt.Errorf("required resource not specified")
  100. }
  101. return nil
  102. }
  103. // RunRestart performs the execution of 'rollout restart' sub command
  104. func (o RestartOptions) RunRestart() error {
  105. r := o.Builder().
  106. WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
  107. NamespaceParam(o.Namespace).DefaultNamespace().
  108. FilenameParam(o.EnforceNamespace, &o.FilenameOptions).
  109. ResourceTypeOrNameArgs(true, o.Resources...).
  110. ContinueOnError().
  111. Latest().
  112. Flatten().
  113. Do()
  114. if err := r.Err(); err != nil {
  115. return err
  116. }
  117. allErrs := []error{}
  118. infos, err := r.Infos()
  119. if err != nil {
  120. // restore previous command behavior where
  121. // an error caused by retrieving infos due to
  122. // at least a single broken object did not result
  123. // in an immediate return, but rather an overall
  124. // aggregation of errors.
  125. allErrs = append(allErrs, err)
  126. }
  127. for _, patch := range set.CalculatePatches(infos, scheme.DefaultJSONEncoder(), set.PatchFn(o.Restarter)) {
  128. info := patch.Info
  129. if patch.Err != nil {
  130. resourceString := info.Mapping.Resource.Resource
  131. if len(info.Mapping.Resource.Group) > 0 {
  132. resourceString = resourceString + "." + info.Mapping.Resource.Group
  133. }
  134. allErrs = append(allErrs, fmt.Errorf("error: %s %q %v", resourceString, info.Name, patch.Err))
  135. continue
  136. }
  137. if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
  138. allErrs = append(allErrs, fmt.Errorf("failed to create patch for %v: empty patch", info.Name))
  139. }
  140. obj, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)
  141. if err != nil {
  142. allErrs = append(allErrs, fmt.Errorf("failed to patch: %v", err))
  143. continue
  144. }
  145. info.Refresh(obj, true)
  146. printer, err := o.ToPrinter("restarted")
  147. if err != nil {
  148. allErrs = append(allErrs, err)
  149. continue
  150. }
  151. if err = printer.PrintObj(info.Object, o.Out); err != nil {
  152. allErrs = append(allErrs, err)
  153. }
  154. }
  155. return utilerrors.NewAggregate(allErrs)
  156. }