scale.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package service
  2. import (
  3. "fmt"
  4. "strconv"
  5. "strings"
  6. "golang.org/x/net/context"
  7. "github.com/docker/docker/api/client"
  8. "github.com/docker/docker/cli"
  9. "github.com/docker/engine-api/types"
  10. "github.com/spf13/cobra"
  11. )
  12. func newScaleCommand(dockerCli *client.DockerCli) *cobra.Command {
  13. return &cobra.Command{
  14. Use: "scale SERVICE=REPLICAS [SERVICE=REPLICAS...]",
  15. Short: "Scale one or multiple services",
  16. Args: scaleArgs,
  17. RunE: func(cmd *cobra.Command, args []string) error {
  18. return runScale(dockerCli, args)
  19. },
  20. }
  21. }
  22. func scaleArgs(cmd *cobra.Command, args []string) error {
  23. if err := cli.RequiresMinArgs(1)(cmd, args); err != nil {
  24. return err
  25. }
  26. for _, arg := range args {
  27. if parts := strings.SplitN(arg, "=", 2); len(parts) != 2 {
  28. return fmt.Errorf(
  29. "Invalid scale specifier '%s'.\nSee '%s --help'.\n\nUsage: %s\n\n%s",
  30. arg,
  31. cmd.CommandPath(),
  32. cmd.UseLine(),
  33. cmd.Short,
  34. )
  35. }
  36. }
  37. return nil
  38. }
  39. func runScale(dockerCli *client.DockerCli, args []string) error {
  40. var errors []string
  41. for _, arg := range args {
  42. parts := strings.SplitN(arg, "=", 2)
  43. serviceID, scale := parts[0], parts[1]
  44. if err := runServiceScale(dockerCli, serviceID, scale); err != nil {
  45. errors = append(errors, fmt.Sprintf("%s: %s", serviceID, err.Error()))
  46. }
  47. }
  48. if len(errors) == 0 {
  49. return nil
  50. }
  51. return fmt.Errorf(strings.Join(errors, "\n"))
  52. }
  53. func runServiceScale(dockerCli *client.DockerCli, serviceID string, scale string) error {
  54. client := dockerCli.Client()
  55. ctx := context.Background()
  56. service, _, err := client.ServiceInspectWithRaw(ctx, serviceID)
  57. if err != nil {
  58. return err
  59. }
  60. serviceMode := &service.Spec.Mode
  61. if serviceMode.Replicated == nil {
  62. return fmt.Errorf("scale can only be used with replicated mode")
  63. }
  64. uintScale, err := strconv.ParseUint(scale, 10, 64)
  65. if err != nil {
  66. return fmt.Errorf("invalid replicas value %s: %s", scale, err.Error())
  67. }
  68. serviceMode.Replicated.Replicas = &uintScale
  69. err = client.ServiceUpdate(ctx, service.ID, service.Version, service.Spec, types.ServiceUpdateOptions{})
  70. if err != nil {
  71. return err
  72. }
  73. fmt.Fprintf(dockerCli.Out(), "%s scaled to %s\n", serviceID, scale)
  74. return nil
  75. }