start.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http/httputil"
  6. "strings"
  7. "golang.org/x/net/context"
  8. "github.com/docker/docker/api/client"
  9. "github.com/docker/docker/cli"
  10. "github.com/docker/docker/pkg/promise"
  11. "github.com/docker/docker/pkg/signal"
  12. "github.com/docker/engine-api/types"
  13. "github.com/spf13/cobra"
  14. )
  15. type startOptions struct {
  16. attach bool
  17. openStdin bool
  18. detachKeys string
  19. containers []string
  20. }
  21. // NewStartCommand creats a new cobra.Command for `docker start`
  22. func NewStartCommand(dockerCli *client.DockerCli) *cobra.Command {
  23. var opts startOptions
  24. cmd := &cobra.Command{
  25. Use: "start [OPTIONS] CONTAINER [CONTAINER...]",
  26. Short: "Start one or more stopped containers",
  27. Args: cli.RequiresMinArgs(1),
  28. RunE: func(cmd *cobra.Command, args []string) error {
  29. opts.containers = args
  30. return runStart(dockerCli, &opts)
  31. },
  32. }
  33. cmd.SetFlagErrorFunc(flagErrorFunc)
  34. flags := cmd.Flags()
  35. flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals")
  36. flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN")
  37. flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
  38. return cmd
  39. }
  40. func runStart(dockerCli *client.DockerCli, opts *startOptions) error {
  41. ctx, cancelFun := context.WithCancel(context.Background())
  42. if opts.attach || opts.openStdin {
  43. // We're going to attach to a container.
  44. // 1. Ensure we only have one container.
  45. if len(opts.containers) > 1 {
  46. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  47. }
  48. // 2. Attach to the container.
  49. container := opts.containers[0]
  50. c, err := dockerCli.Client().ContainerInspect(ctx, container)
  51. if err != nil {
  52. return err
  53. }
  54. if !c.Config.Tty {
  55. sigc := dockerCli.ForwardAllSignals(ctx, container)
  56. defer signal.StopCatch(sigc)
  57. }
  58. if opts.detachKeys != "" {
  59. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  60. }
  61. options := types.ContainerAttachOptions{
  62. Stream: true,
  63. Stdin: opts.openStdin && c.Config.OpenStdin,
  64. Stdout: true,
  65. Stderr: true,
  66. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  67. }
  68. var in io.ReadCloser
  69. if options.Stdin {
  70. in = dockerCli.In()
  71. }
  72. resp, errAttach := dockerCli.Client().ContainerAttach(ctx, container, options)
  73. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  74. // ContainerAttach return an ErrPersistEOF (connection closed)
  75. // means server met an error and put it in Hijacked connection
  76. // keep the error and read detailed error message from hijacked connection
  77. return errAttach
  78. }
  79. defer resp.Close()
  80. cErr := promise.Go(func() error {
  81. errHijack := dockerCli.HoldHijackedConnection(ctx, c.Config.Tty, in, dockerCli.Out(), dockerCli.Err(), resp)
  82. if errHijack == nil {
  83. return errAttach
  84. }
  85. return errHijack
  86. })
  87. // 3. Start the container.
  88. if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil {
  89. cancelFun()
  90. <-cErr
  91. return err
  92. }
  93. // 4. Wait for attachment to break.
  94. if c.Config.Tty && dockerCli.IsTerminalOut() {
  95. if err := dockerCli.MonitorTtySize(ctx, container, false); err != nil {
  96. fmt.Fprintf(dockerCli.Err(), "Error monitoring TTY size: %s\n", err)
  97. }
  98. }
  99. if attchErr := <-cErr; attchErr != nil {
  100. return attchErr
  101. }
  102. _, status, err := getExitCode(dockerCli, ctx, container)
  103. if err != nil {
  104. return err
  105. }
  106. if status != 0 {
  107. return cli.StatusError{StatusCode: status}
  108. }
  109. } else {
  110. // We're not going to attach to anything.
  111. // Start as many containers as we want.
  112. return startContainersWithoutAttachments(dockerCli, ctx, opts.containers)
  113. }
  114. return nil
  115. }
  116. func startContainersWithoutAttachments(dockerCli *client.DockerCli, ctx context.Context, containers []string) error {
  117. var failedContainers []string
  118. for _, container := range containers {
  119. if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil {
  120. fmt.Fprintf(dockerCli.Err(), "%s\n", err)
  121. failedContainers = append(failedContainers, container)
  122. } else {
  123. fmt.Fprintf(dockerCli.Out(), "%s\n", container)
  124. }
  125. }
  126. if len(failedContainers) > 0 {
  127. return fmt.Errorf("Error: failed to start containers: %v", strings.Join(failedContainers, ", "))
  128. }
  129. return nil
  130. }