run.go 8.1 KB

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