start.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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. checkpoint string
  20. checkpointDir string
  21. containers []string
  22. }
  23. // NewStartCommand creates a new cobra.Command for `docker start`
  24. func NewStartCommand(dockerCli *command.DockerCli) *cobra.Command {
  25. var opts startOptions
  26. cmd := &cobra.Command{
  27. Use: "start [OPTIONS] CONTAINER [CONTAINER...]",
  28. Short: "Start one or more stopped containers",
  29. Args: cli.RequiresMinArgs(1),
  30. RunE: func(cmd *cobra.Command, args []string) error {
  31. opts.containers = args
  32. return runStart(dockerCli, &opts)
  33. },
  34. }
  35. flags := cmd.Flags()
  36. flags.BoolVarP(&opts.attach, "attach", "a", false, "Attach STDOUT/STDERR and forward signals")
  37. flags.BoolVarP(&opts.openStdin, "interactive", "i", false, "Attach container's STDIN")
  38. flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
  39. flags.StringVar(&opts.checkpoint, "checkpoint", "", "Restore from this checkpoint")
  40. flags.SetAnnotation("checkpoint", "experimental", nil)
  41. flags.StringVar(&opts.checkpointDir, "checkpoint-dir", "", "Use a custom checkpoint storage directory")
  42. flags.SetAnnotation("checkpoint-dir", "experimental", nil)
  43. return cmd
  44. }
  45. func runStart(dockerCli *command.DockerCli, opts *startOptions) error {
  46. ctx, cancelFun := context.WithCancel(context.Background())
  47. if opts.attach || opts.openStdin {
  48. // We're going to attach to a container.
  49. // 1. Ensure we only have one container.
  50. if len(opts.containers) > 1 {
  51. return fmt.Errorf("You cannot start and attach multiple containers at once.")
  52. }
  53. // 2. Attach to the container.
  54. container := opts.containers[0]
  55. c, err := dockerCli.Client().ContainerInspect(ctx, container)
  56. if err != nil {
  57. return err
  58. }
  59. // We always use c.ID instead of container to maintain consistency during `docker start`
  60. if !c.Config.Tty {
  61. sigc := ForwardAllSignals(ctx, dockerCli, c.ID)
  62. defer signal.StopCatch(sigc)
  63. }
  64. if opts.detachKeys != "" {
  65. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  66. }
  67. options := types.ContainerAttachOptions{
  68. Stream: true,
  69. Stdin: opts.openStdin && c.Config.OpenStdin,
  70. Stdout: true,
  71. Stderr: true,
  72. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  73. }
  74. var in io.ReadCloser
  75. if options.Stdin {
  76. in = dockerCli.In()
  77. }
  78. resp, errAttach := dockerCli.Client().ContainerAttach(ctx, c.ID, options)
  79. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  80. // ContainerAttach return an ErrPersistEOF (connection closed)
  81. // means server met an error and already put it in Hijacked connection,
  82. // we would keep the error and read the detailed error message from hijacked connection
  83. return errAttach
  84. }
  85. defer resp.Close()
  86. cErr := promise.Go(func() error {
  87. errHijack := holdHijackedConnection(ctx, dockerCli, c.Config.Tty, in, dockerCli.Out(), dockerCli.Err(), resp)
  88. if errHijack == nil {
  89. return errAttach
  90. }
  91. return errHijack
  92. })
  93. // 3. We should open a channel for receiving status code of the container
  94. // no matter it's detached, removed on daemon side(--rm) or exit normally.
  95. statusChan := waitExitOrRemoved(ctx, dockerCli, c.ID, c.HostConfig.AutoRemove)
  96. startOptions := types.ContainerStartOptions{
  97. CheckpointID: opts.checkpoint,
  98. CheckpointDir: opts.checkpointDir,
  99. }
  100. // 4. Start the container.
  101. if err := dockerCli.Client().ContainerStart(ctx, c.ID, startOptions); err != nil {
  102. cancelFun()
  103. <-cErr
  104. if c.HostConfig.AutoRemove {
  105. // wait container to be removed
  106. <-statusChan
  107. }
  108. return err
  109. }
  110. // 5. Wait for attachment to break.
  111. if c.Config.Tty && dockerCli.Out().IsTerminal() {
  112. if err := MonitorTtySize(ctx, dockerCli, c.ID, false); err != nil {
  113. fmt.Fprintf(dockerCli.Err(), "Error monitoring TTY size: %s\n", err)
  114. }
  115. }
  116. if attchErr := <-cErr; attchErr != nil {
  117. return attchErr
  118. }
  119. if status := <-statusChan; status != 0 {
  120. return cli.StatusError{StatusCode: status}
  121. }
  122. } else if opts.checkpoint != "" {
  123. if len(opts.containers) > 1 {
  124. return fmt.Errorf("You cannot restore multiple containers at once.")
  125. }
  126. container := opts.containers[0]
  127. startOptions := types.ContainerStartOptions{
  128. CheckpointID: opts.checkpoint,
  129. CheckpointDir: opts.checkpointDir,
  130. }
  131. return dockerCli.Client().ContainerStart(ctx, container, startOptions)
  132. } else {
  133. // We're not going to attach to anything.
  134. // Start as many containers as we want.
  135. return startContainersWithoutAttachments(ctx, dockerCli, opts.containers)
  136. }
  137. return nil
  138. }
  139. func startContainersWithoutAttachments(ctx context.Context, dockerCli *command.DockerCli, containers []string) error {
  140. var failedContainers []string
  141. for _, container := range containers {
  142. if err := dockerCli.Client().ContainerStart(ctx, container, types.ContainerStartOptions{}); err != nil {
  143. fmt.Fprintf(dockerCli.Err(), "%s\n", err)
  144. failedContainers = append(failedContainers, container)
  145. } else {
  146. fmt.Fprintf(dockerCli.Out(), "%s\n", container)
  147. }
  148. }
  149. if len(failedContainers) > 0 {
  150. return fmt.Errorf("Error: failed to start containers: %v", strings.Join(failedContainers, ", "))
  151. }
  152. return nil
  153. }