run.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http/httputil"
  6. "os"
  7. "runtime"
  8. "strings"
  9. "syscall"
  10. "github.com/Sirupsen/logrus"
  11. "github.com/docker/docker/api/types"
  12. "github.com/docker/docker/api/types/container"
  13. "github.com/docker/docker/cli"
  14. "github.com/docker/docker/cli/command"
  15. "github.com/docker/docker/pkg/promise"
  16. "github.com/docker/docker/pkg/signal"
  17. "github.com/docker/libnetwork/resolvconf/dns"
  18. "github.com/pkg/errors"
  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 warnOnOomKillDisable(hostConfig container.HostConfig, stderr io.Writer) {
  60. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  61. fmt.Fprintln(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.")
  62. }
  63. }
  64. // check the DNS settings passed via --dns against localhost regexp to warn if
  65. // they are trying to set a DNS to a localhost address
  66. func warnOnLocalhostDNS(hostConfig container.HostConfig, stderr io.Writer) {
  67. for _, dnsIP := range hostConfig.DNS {
  68. if dns.IsLocalhost(dnsIP) {
  69. fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  70. return
  71. }
  72. }
  73. }
  74. func runRun(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts *runOptions, copts *containerOptions) error {
  75. containerConfig, err := parse(flags, copts)
  76. // just in case the parse does not exit
  77. if err != nil {
  78. reportError(dockerCli.Err(), "run", err.Error(), true)
  79. return cli.StatusError{StatusCode: 125}
  80. }
  81. return runContainer(dockerCli, opts, copts, containerConfig)
  82. }
  83. func runContainer(dockerCli *command.DockerCli, opts *runOptions, copts *containerOptions, containerConfig *containerConfig) error {
  84. config := containerConfig.Config
  85. hostConfig := containerConfig.HostConfig
  86. stdout, stderr := dockerCli.Out(), dockerCli.Err()
  87. client := dockerCli.Client()
  88. // TODO: pass this as an argument
  89. cmdPath := "run"
  90. warnOnOomKillDisable(*hostConfig, stderr)
  91. warnOnLocalhostDNS(*hostConfig, stderr)
  92. config.ArgsEscaped = false
  93. if !opts.detach {
  94. if err := dockerCli.In().CheckTty(config.AttachStdin, config.Tty); err != nil {
  95. return err
  96. }
  97. } else {
  98. if copts.attach.Len() != 0 {
  99. return errors.New("Conflicting options: -a and -d")
  100. }
  101. config.AttachStdin = false
  102. config.AttachStdout = false
  103. config.AttachStderr = false
  104. config.StdinOnce = false
  105. }
  106. // Disable sigProxy when in TTY mode
  107. if config.Tty {
  108. opts.sigProxy = false
  109. }
  110. // Telling the Windows daemon the initial size of the tty during start makes
  111. // a far better user experience rather than relying on subsequent resizes
  112. // to cause things to catch up.
  113. if runtime.GOOS == "windows" {
  114. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize()
  115. }
  116. ctx, cancelFun := context.WithCancel(context.Background())
  117. createResponse, err := createContainer(ctx, dockerCli, containerConfig, opts.name)
  118. if err != nil {
  119. reportError(stderr, cmdPath, err.Error(), true)
  120. return runStartContainerErr(err)
  121. }
  122. if opts.sigProxy {
  123. sigc := ForwardAllSignals(ctx, dockerCli, createResponse.ID)
  124. defer signal.StopCatch(sigc)
  125. }
  126. var (
  127. waitDisplayID chan struct{}
  128. errCh chan error
  129. )
  130. if !config.AttachStdout && !config.AttachStderr {
  131. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  132. waitDisplayID = make(chan struct{})
  133. go func() {
  134. defer close(waitDisplayID)
  135. fmt.Fprintln(stdout, createResponse.ID)
  136. }()
  137. }
  138. attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
  139. if attach {
  140. if opts.detachKeys != "" {
  141. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  142. }
  143. close, err := attachContainer(ctx, dockerCli, &errCh, config, createResponse.ID)
  144. defer close()
  145. if err != nil {
  146. return err
  147. }
  148. }
  149. statusChan := waitExitOrRemoved(ctx, dockerCli, createResponse.ID, copts.autoRemove)
  150. //start the container
  151. if err := client.ContainerStart(ctx, createResponse.ID, types.ContainerStartOptions{}); err != nil {
  152. // If we have holdHijackedConnection, we should notify
  153. // holdHijackedConnection we are going to exit and wait
  154. // to avoid the terminal are not restored.
  155. if attach {
  156. cancelFun()
  157. <-errCh
  158. }
  159. reportError(stderr, cmdPath, err.Error(), false)
  160. if copts.autoRemove {
  161. // wait container to be removed
  162. <-statusChan
  163. }
  164. return runStartContainerErr(err)
  165. }
  166. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && dockerCli.Out().IsTerminal() {
  167. if err := MonitorTtySize(ctx, dockerCli, createResponse.ID, false); err != nil {
  168. fmt.Fprintln(stderr, "Error monitoring TTY size:", err)
  169. }
  170. }
  171. if errCh != nil {
  172. if err := <-errCh; err != nil {
  173. logrus.Debugf("Error hijack: %s", err)
  174. return err
  175. }
  176. }
  177. // Detached mode: wait for the id to be displayed and return.
  178. if !config.AttachStdout && !config.AttachStderr {
  179. // Detached mode
  180. <-waitDisplayID
  181. return nil
  182. }
  183. status := <-statusChan
  184. if status != 0 {
  185. return cli.StatusError{StatusCode: status}
  186. }
  187. return nil
  188. }
  189. func attachContainer(
  190. ctx context.Context,
  191. dockerCli *command.DockerCli,
  192. errCh *chan error,
  193. config *container.Config,
  194. containerID string,
  195. ) (func(), error) {
  196. stdout, stderr := dockerCli.Out(), dockerCli.Err()
  197. var (
  198. out, cerr io.Writer
  199. in io.ReadCloser
  200. )
  201. if config.AttachStdin {
  202. in = dockerCli.In()
  203. }
  204. if config.AttachStdout {
  205. out = stdout
  206. }
  207. if config.AttachStderr {
  208. if config.Tty {
  209. cerr = stdout
  210. } else {
  211. cerr = stderr
  212. }
  213. }
  214. options := types.ContainerAttachOptions{
  215. Stream: true,
  216. Stdin: config.AttachStdin,
  217. Stdout: config.AttachStdout,
  218. Stderr: config.AttachStderr,
  219. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  220. }
  221. resp, errAttach := dockerCli.Client().ContainerAttach(ctx, containerID, options)
  222. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  223. // ContainerAttach returns an ErrPersistEOF (connection closed)
  224. // means server met an error and put it in Hijacked connection
  225. // keep the error and read detailed error message from hijacked connection later
  226. return nil, errAttach
  227. }
  228. *errCh = promise.Go(func() error {
  229. if errHijack := holdHijackedConnection(ctx, dockerCli, config.Tty, in, out, cerr, resp); errHijack != nil {
  230. return errHijack
  231. }
  232. return errAttach
  233. })
  234. return resp.Close, nil
  235. }
  236. // reportError is a utility method that prints a user-friendly message
  237. // containing the error that occurred during parsing and a suggestion to get help
  238. func reportError(stderr io.Writer, name string, str string, withHelp bool) {
  239. str = strings.TrimSuffix(str, ".") + "."
  240. if withHelp {
  241. str += "\nSee '" + os.Args[0] + " " + name + " --help'."
  242. }
  243. fmt.Fprintf(stderr, "%s: %s\n", os.Args[0], str)
  244. }
  245. // if container start fails with 'not found'/'no such' error, return 127
  246. // if container start fails with 'permission denied' error, return 126
  247. // return 125 for generic docker daemon failures
  248. func runStartContainerErr(err error) error {
  249. trimmedErr := strings.TrimPrefix(err.Error(), "Error response from daemon: ")
  250. statusError := cli.StatusError{StatusCode: 125}
  251. if strings.Contains(trimmedErr, "executable file not found") ||
  252. strings.Contains(trimmedErr, "no such file or directory") ||
  253. strings.Contains(trimmedErr, "system cannot find the file specified") {
  254. statusError = cli.StatusError{StatusCode: 127}
  255. } else if strings.Contains(trimmedErr, syscall.EACCES.Error()) {
  256. statusError = cli.StatusError{StatusCode: 126}
  257. }
  258. return statusError
  259. }