scale.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 cmd
  14. import (
  15. "fmt"
  16. "io"
  17. "os"
  18. "github.com/renstrom/dedent"
  19. "github.com/spf13/cobra"
  20. "k8s.io/kubernetes/pkg/api"
  21. "k8s.io/kubernetes/pkg/kubectl"
  22. cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
  23. "k8s.io/kubernetes/pkg/kubectl/resource"
  24. )
  25. // ScaleOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
  26. // referencing the cmd.Flags()
  27. type ScaleOptions struct {
  28. Filenames []string
  29. Recursive bool
  30. }
  31. var (
  32. scale_long = dedent.Dedent(`
  33. Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job.
  34. Scale also allows users to specify one or more preconditions for the scale action.
  35. If --current-replicas or --resource-version is specified, it is validated before the
  36. scale is attempted, and it is guaranteed that the precondition holds true when the
  37. scale is sent to the server.`)
  38. scale_example = dedent.Dedent(`
  39. # Scale a replicaset named 'foo' to 3.
  40. kubectl scale --replicas=3 rs/foo
  41. # Scale a resource identified by type and name specified in "foo.yaml" to 3.
  42. kubectl scale --replicas=3 -f foo.yaml
  43. # If the deployment named mysql's current size is 2, scale mysql to 3.
  44. kubectl scale --current-replicas=2 --replicas=3 deployment/mysql
  45. # Scale multiple replication controllers.
  46. kubectl scale --replicas=5 rc/foo rc/bar rc/baz
  47. # Scale job named 'cron' to 3.
  48. kubectl scale --replicas=3 job/cron`)
  49. )
  50. // NewCmdScale returns a cobra command with the appropriate configuration and flags to run scale
  51. func NewCmdScale(f *cmdutil.Factory, out io.Writer) *cobra.Command {
  52. options := &ScaleOptions{}
  53. validArgs := []string{"deployment", "replicaset", "replicationcontroller", "job"}
  54. argAliases := kubectl.ResourceAliases(validArgs)
  55. cmd := &cobra.Command{
  56. Use: "scale [--resource-version=version] [--current-replicas=count] --replicas=COUNT (-f FILENAME | TYPE NAME)",
  57. // resize is deprecated
  58. Aliases: []string{"resize"},
  59. Short: "Set a new size for a Deployment, ReplicaSet, Replication Controller, or Job",
  60. Long: scale_long,
  61. Example: scale_example,
  62. Run: func(cmd *cobra.Command, args []string) {
  63. cmdutil.CheckErr(cmdutil.ValidateOutputArgs(cmd))
  64. shortOutput := cmdutil.GetFlagString(cmd, "output") == "name"
  65. err := RunScale(f, out, cmd, args, shortOutput, options)
  66. cmdutil.CheckErr(err)
  67. },
  68. ValidArgs: validArgs,
  69. ArgAliases: argAliases,
  70. }
  71. cmd.Flags().String("resource-version", "", "Precondition for resource version. Requires that the current resource version match this value in order to scale.")
  72. cmd.Flags().Int("current-replicas", -1, "Precondition for current size. Requires that the current size of the resource match this value in order to scale.")
  73. cmd.Flags().Int("replicas", -1, "The new desired number of replicas. Required.")
  74. cmd.MarkFlagRequired("replicas")
  75. cmd.Flags().Duration("timeout", 0, "The length of time to wait before giving up on a scale operation, zero means don't wait. Any other values should contain a corresponding time unit (e.g. 1s, 2m, 3h).")
  76. cmdutil.AddOutputFlagsForMutation(cmd)
  77. cmdutil.AddRecordFlag(cmd)
  78. cmdutil.AddInclude3rdPartyFlags(cmd)
  79. usage := "Filename, directory, or URL to a file identifying the resource to set a new size"
  80. kubectl.AddJsonFilenameFlag(cmd, &options.Filenames, usage)
  81. cmdutil.AddRecursiveFlag(cmd, &options.Recursive)
  82. return cmd
  83. }
  84. // RunScale executes the scaling
  85. func RunScale(f *cmdutil.Factory, out io.Writer, cmd *cobra.Command, args []string, shortOutput bool, options *ScaleOptions) error {
  86. if len(os.Args) > 1 && os.Args[1] == "resize" {
  87. printDeprecationWarning("scale", "resize")
  88. }
  89. count := cmdutil.GetFlagInt(cmd, "replicas")
  90. if count < 0 {
  91. return cmdutil.UsageError(cmd, "--replicas=COUNT is required, and COUNT must be greater than or equal to 0")
  92. }
  93. cmdNamespace, enforceNamespace, err := f.DefaultNamespace()
  94. if err != nil {
  95. return err
  96. }
  97. mapper, typer := f.Object(cmdutil.GetIncludeThirdPartyAPIs(cmd))
  98. r := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), f.Decoder(true)).
  99. ContinueOnError().
  100. NamespaceParam(cmdNamespace).DefaultNamespace().
  101. FilenameParam(enforceNamespace, options.Recursive, options.Filenames...).
  102. ResourceTypeOrNameArgs(false, args...).
  103. Flatten().
  104. Do()
  105. err = r.Err()
  106. if err != nil {
  107. return err
  108. }
  109. infos := []*resource.Info{}
  110. err = r.Visit(func(info *resource.Info, err error) error {
  111. if err == nil {
  112. infos = append(infos, info)
  113. }
  114. return nil
  115. })
  116. resourceVersion := cmdutil.GetFlagString(cmd, "resource-version")
  117. if len(resourceVersion) != 0 && len(infos) > 1 {
  118. return fmt.Errorf("cannot use --resource-version with multiple resources")
  119. }
  120. counter := 0
  121. err = r.Visit(func(info *resource.Info, err error) error {
  122. if err != nil {
  123. return err
  124. }
  125. mapping := info.ResourceMapping()
  126. scaler, err := f.Scaler(mapping)
  127. if err != nil {
  128. return err
  129. }
  130. currentSize := cmdutil.GetFlagInt(cmd, "current-replicas")
  131. precondition := &kubectl.ScalePrecondition{Size: currentSize, ResourceVersion: resourceVersion}
  132. retry := kubectl.NewRetryParams(kubectl.Interval, kubectl.Timeout)
  133. var waitForReplicas *kubectl.RetryParams
  134. if timeout := cmdutil.GetFlagDuration(cmd, "timeout"); timeout != 0 {
  135. waitForReplicas = kubectl.NewRetryParams(kubectl.Interval, timeout)
  136. }
  137. if err := scaler.Scale(info.Namespace, info.Name, uint(count), precondition, retry, waitForReplicas); err != nil {
  138. return err
  139. }
  140. if cmdutil.ShouldRecord(cmd, info) {
  141. patchBytes, err := cmdutil.ChangeResourcePatch(info, f.Command())
  142. if err != nil {
  143. return err
  144. }
  145. mapping := info.ResourceMapping()
  146. client, err := f.ClientForMapping(mapping)
  147. if err != nil {
  148. return err
  149. }
  150. helper := resource.NewHelper(client, mapping)
  151. _, err = helper.Patch(info.Namespace, info.Name, api.StrategicMergePatchType, patchBytes)
  152. if err != nil {
  153. return err
  154. }
  155. }
  156. counter++
  157. cmdutil.PrintSuccess(mapper, shortOutput, out, info.Mapping.Resource, info.Name, "scaled")
  158. return nil
  159. })
  160. if err != nil {
  161. return err
  162. }
  163. if counter == 0 {
  164. return fmt.Errorf("no objects passed to scale")
  165. }
  166. return nil
  167. }