run.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package container
  2. import (
  3. "errors"
  4. "fmt"
  5. "io"
  6. "net/http/httputil"
  7. "os"
  8. "runtime"
  9. "strings"
  10. "syscall"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/api/types"
  13. "github.com/docker/docker/cli"
  14. "github.com/docker/docker/cli/command"
  15. opttypes "github.com/docker/docker/opts"
  16. "github.com/docker/docker/pkg/promise"
  17. "github.com/docker/docker/pkg/signal"
  18. runconfigopts "github.com/docker/docker/runconfig/opts"
  19. "github.com/docker/libnetwork/resolvconf/dns"
  20. "github.com/spf13/cobra"
  21. "github.com/spf13/pflag"
  22. "golang.org/x/net/context"
  23. )
  24. type runOptions struct {
  25. detach bool
  26. sigProxy bool
  27. name string
  28. detachKeys string
  29. }
  30. // NewRunCommand create a new `docker run` command
  31. func NewRunCommand(dockerCli *command.DockerCli) *cobra.Command {
  32. var opts runOptions
  33. var copts *runconfigopts.ContainerOptions
  34. cmd := &cobra.Command{
  35. Use: "run [OPTIONS] IMAGE [COMMAND] [ARG...]",
  36. Short: "Run a command in a new container",
  37. Args: cli.RequiresMinArgs(1),
  38. RunE: func(cmd *cobra.Command, args []string) error {
  39. copts.Image = args[0]
  40. if len(args) > 1 {
  41. copts.Args = args[1:]
  42. }
  43. return runRun(dockerCli, cmd.Flags(), &opts, copts)
  44. },
  45. }
  46. flags := cmd.Flags()
  47. flags.SetInterspersed(false)
  48. // These are flags not stored in Config/HostConfig
  49. flags.BoolVarP(&opts.detach, "detach", "d", false, "Run container in background and print container ID")
  50. flags.BoolVar(&opts.sigProxy, "sig-proxy", true, "Proxy received signals to the process")
  51. flags.StringVar(&opts.name, "name", "", "Assign a name to the container")
  52. flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
  53. // Add an explicit help that doesn't have a `-h` to prevent the conflict
  54. // with hostname
  55. flags.Bool("help", false, "Print usage")
  56. command.AddTrustedFlags(flags, true)
  57. copts = runconfigopts.AddFlags(flags)
  58. return cmd
  59. }
  60. func runRun(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts *runOptions, copts *runconfigopts.ContainerOptions) error {
  61. stdout, stderr, stdin := dockerCli.Out(), dockerCli.Err(), dockerCli.In()
  62. client := dockerCli.Client()
  63. // TODO: pass this as an argument
  64. cmdPath := "run"
  65. var (
  66. flAttach *opttypes.ListOpts
  67. ErrConflictAttachDetach = errors.New("Conflicting options: -a and -d")
  68. ErrConflictRestartPolicyAndAutoRemove = errors.New("Conflicting options: --restart and --rm")
  69. )
  70. config, hostConfig, networkingConfig, err := runconfigopts.Parse(flags, copts)
  71. // just in case the Parse does not exit
  72. if err != nil {
  73. reportError(stderr, cmdPath, err.Error(), true)
  74. return cli.StatusError{StatusCode: 125}
  75. }
  76. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  77. return ErrConflictRestartPolicyAndAutoRemove
  78. }
  79. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  80. fmt.Fprintln(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.")
  81. }
  82. if len(hostConfig.DNS) > 0 {
  83. // check the DNS settings passed via --dns against
  84. // localhost regexp to warn if they are trying to
  85. // set a DNS to a localhost address
  86. for _, dnsIP := range hostConfig.DNS {
  87. if dns.IsLocalhost(dnsIP) {
  88. fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  89. break
  90. }
  91. }
  92. }
  93. config.ArgsEscaped = false
  94. if !opts.detach {
  95. if err := dockerCli.In().CheckTty(config.AttachStdin, config.Tty); err != nil {
  96. return err
  97. }
  98. } else {
  99. if fl := flags.Lookup("attach"); fl != nil {
  100. flAttach = fl.Value.(*opttypes.ListOpts)
  101. if flAttach.Len() != 0 {
  102. return ErrConflictAttachDetach
  103. }
  104. }
  105. config.AttachStdin = false
  106. config.AttachStdout = false
  107. config.AttachStderr = false
  108. config.StdinOnce = false
  109. }
  110. // Disable sigProxy when in TTY mode
  111. if config.Tty {
  112. opts.sigProxy = false
  113. }
  114. // Telling the Windows daemon the initial size of the tty during start makes
  115. // a far better user experience rather than relying on subsequent resizes
  116. // to cause things to catch up.
  117. if runtime.GOOS == "windows" {
  118. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize()
  119. }
  120. ctx, cancelFun := context.WithCancel(context.Background())
  121. createResponse, err := createContainer(ctx, dockerCli, config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, opts.name)
  122. if err != nil {
  123. reportError(stderr, cmdPath, err.Error(), true)
  124. return runStartContainerErr(err)
  125. }
  126. if opts.sigProxy {
  127. sigc := ForwardAllSignals(ctx, dockerCli, createResponse.ID)
  128. defer signal.StopCatch(sigc)
  129. }
  130. var (
  131. waitDisplayID chan struct{}
  132. errCh chan error
  133. )
  134. if !config.AttachStdout && !config.AttachStderr {
  135. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  136. waitDisplayID = make(chan struct{})
  137. go func() {
  138. defer close(waitDisplayID)
  139. fmt.Fprintln(stdout, createResponse.ID)
  140. }()
  141. }
  142. attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
  143. if attach {
  144. var (
  145. out, cerr io.Writer
  146. in io.ReadCloser
  147. )
  148. if config.AttachStdin {
  149. in = stdin
  150. }
  151. if config.AttachStdout {
  152. out = stdout
  153. }
  154. if config.AttachStderr {
  155. if config.Tty {
  156. cerr = stdout
  157. } else {
  158. cerr = stderr
  159. }
  160. }
  161. if opts.detachKeys != "" {
  162. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  163. }
  164. options := types.ContainerAttachOptions{
  165. Stream: true,
  166. Stdin: config.AttachStdin,
  167. Stdout: config.AttachStdout,
  168. Stderr: config.AttachStderr,
  169. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  170. }
  171. resp, errAttach := client.ContainerAttach(ctx, createResponse.ID, options)
  172. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  173. // ContainerAttach returns an ErrPersistEOF (connection closed)
  174. // means server met an error and put it in Hijacked connection
  175. // keep the error and read detailed error message from hijacked connection later
  176. return errAttach
  177. }
  178. defer resp.Close()
  179. errCh = promise.Go(func() error {
  180. if errHijack := holdHijackedConnection(ctx, dockerCli, config.Tty, in, out, cerr, resp); errHijack != nil {
  181. return errHijack
  182. }
  183. return errAttach
  184. })
  185. }
  186. statusChan := waitExitOrRemoved(ctx, dockerCli, createResponse.ID, hostConfig.AutoRemove)
  187. //start the container
  188. if err := client.ContainerStart(ctx, createResponse.ID, types.ContainerStartOptions{}); err != nil {
  189. // If we have holdHijackedConnection, we should notify
  190. // holdHijackedConnection we are going to exit and wait
  191. // to avoid the terminal are not restored.
  192. if attach {
  193. cancelFun()
  194. <-errCh
  195. }
  196. reportError(stderr, cmdPath, err.Error(), false)
  197. if hostConfig.AutoRemove {
  198. // wait container to be removed
  199. <-statusChan
  200. }
  201. return runStartContainerErr(err)
  202. }
  203. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && dockerCli.Out().IsTerminal() {
  204. if err := MonitorTtySize(ctx, dockerCli, createResponse.ID, false); err != nil {
  205. fmt.Fprintln(stderr, "Error monitoring TTY size:", err)
  206. }
  207. }
  208. if errCh != nil {
  209. if err := <-errCh; err != nil {
  210. logrus.Debugf("Error hijack: %s", err)
  211. return err
  212. }
  213. }
  214. // Detached mode: wait for the id to be displayed and return.
  215. if !config.AttachStdout && !config.AttachStderr {
  216. // Detached mode
  217. <-waitDisplayID
  218. return nil
  219. }
  220. status := <-statusChan
  221. if status != 0 {
  222. return cli.StatusError{StatusCode: status}
  223. }
  224. return nil
  225. }
  226. // reportError is a utility method that prints a user-friendly message
  227. // containing the error that occurred during parsing and a suggestion to get help
  228. func reportError(stderr io.Writer, name string, str string, withHelp bool) {
  229. if withHelp {
  230. str += ".\nSee '" + os.Args[0] + " " + name + " --help'"
  231. }
  232. fmt.Fprintf(stderr, "%s: %s.\n", os.Args[0], str)
  233. }
  234. // if container start fails with 'not found'/'no such' error, return 127
  235. // if container start fails with 'permission denied' error, return 126
  236. // return 125 for generic docker daemon failures
  237. func runStartContainerErr(err error) error {
  238. trimmedErr := strings.TrimPrefix(err.Error(), "Error response from daemon: ")
  239. statusError := cli.StatusError{StatusCode: 125}
  240. if strings.Contains(trimmedErr, "executable file not found") ||
  241. strings.Contains(trimmedErr, "no such file or directory") ||
  242. strings.Contains(trimmedErr, "system cannot find the file specified") {
  243. statusError = cli.StatusError{StatusCode: 127}
  244. } else if strings.Contains(trimmedErr, syscall.EACCES.Error()) {
  245. statusError = cli.StatusError{StatusCode: 126}
  246. }
  247. return statusError
  248. }