start.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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/types"
  9. "github.com/docker/docker/cli"
  10. "github.com/docker/docker/cli/command"
  11. "github.com/docker/docker/pkg/promise"
  12. "github.com/docker/docker/pkg/signal"
  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 creates a new cobra.Command for `docker start`
  22. func NewStartCommand(dockerCli *command.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. flags := cmd.Flags()
  34. flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals")
  35. flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN")
  36. flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
  37. return cmd
  38. }
  39. func runStart(dockerCli *command.DockerCli, opts *startOptions) error {
  40. ctx, cancelFun := context.WithCancel(context.Background())
  41. if opts.attach || opts.openStdin {
  42. // We're going to attach to a container.
  43. // 1. Ensure we only have one container.
  44. if len(opts.containers) > 1 {
  45. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  46. }
  47. // 2. Attach to the container.
  48. container := opts.containers[0]
  49. c, err := dockerCli.Client().ContainerInspect(ctx, container)
  50. if err != nil {
  51. return err
  52. }
  53. // We always use c.ID instead of container to maintain consistency during `docker start`
  54. if !c.Config.Tty {
  55. sigc := ForwardAllSignals(ctx, dockerCli, c.ID)
  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, c.ID, options)
  73. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  74. // ContainerAttach return an ErrPersistEOF (connection closed)
  75. // means server met an error and already put it in Hijacked connection,
  76. // we would keep the error and read the detailed error message from hijacked connection
  77. return errAttach
  78. }
  79. defer resp.Close()
  80. cErr := promise.Go(func() error {
  81. errHijack := holdHijackedConnection(ctx, dockerCli, c.Config.Tty, in, dockerCli.Out(), dockerCli.Err(), resp)
  82. if errHijack == nil {
  83. return errAttach
  84. }
  85. return errHijack
  86. })
  87. // 3. We should open a channel for receiving status code of the container
  88. // no matter it's detached, removed on daemon side(--rm) or exit normally.
  89. statusChan, statusErr := waitExitOrRemoved(dockerCli, context.Background(), c.ID, c.HostConfig.AutoRemove)
  90. // 4. Start the container.
  91. if err := dockerCli.Client().ContainerStart(ctx, c.ID, types.ContainerStartOptions{}); err != nil {
  92. cancelFun()
  93. <-cErr
  94. if c.HostConfig.AutoRemove && statusErr == nil {
  95. // wait container to be removed
  96. <-statusChan
  97. }
  98. return err
  99. }
  100. // 5. Wait for attachment to break.
  101. if c.Config.Tty && dockerCli.Out().IsTerminal() {
  102. if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil {
  103. fmt.Fprintf(dockerCli.Err(), "Error monitoring TTY size: %s\n", err)
  104. }
  105. }
  106. if attchErr := <-cErr; attchErr != nil {
  107. return attchErr
  108. }
  109. if statusErr != nil {
  110. return fmt.Errorf("can't get container's exit code: %v", statusErr)
  111. }
  112. if status := <-statusChan; status != 0 {
  113. return cli.StatusError{StatusCode: status}
  114. }
  115. } else {
  116. // We're not going to attach to anything.
  117. // Start as many containers as we want.
  118. return startContainersWithoutAttachments(dockerCli, ctx, opts.containers)
  119. }
  120. return nil
  121. }
  122. func startContainersWithoutAttachments(dockerCli *command.DockerCli, ctx context.Context, containers []string) error {
  123. var failedContainers []string
  124. for _, container := range containers {
  125. if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil {
  126. fmt.Fprintf(dockerCli.Err(), "%s\n", err)
  127. failedContainers = append(failedContainers, container)
  128. } else {
  129. fmt.Fprintf(dockerCli.Out(), "%s\n", container)
  130. }
  131. }
  132. if len(failedContainers) > 0 {
  133. return fmt.Errorf("Error: failed to start containers: %v", strings.Join(failedContainers, ", "))
  134. }
  135. return nil
  136. }