run.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http/httputil"
  6. "os"
  7. "runtime"
  8. "strings"
  9. "syscall"
  10. "golang.org/x/net/context"
  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. )
  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 *runconfigopts.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.AddTrustedFlags(flags, true)
  56. copts = runconfigopts.AddFlags(flags)
  57. return cmd
  58. }
  59. func runRun(dockerCli *command.DockerCli, flags *pflag.FlagSet, opts *runOptions, copts *runconfigopts.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 = fmt.Errorf("Conflicting options: -a and -d")
  67. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  68. )
  69. config, hostConfig, networkingConfig, err := runconfigopts.Parse(flags, copts)
  70. // just in case the Parse does not exit
  71. if err != nil {
  72. reportError(stderr, cmdPath, err.Error(), true)
  73. return cli.StatusError{StatusCode: 125}
  74. }
  75. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  76. return ErrConflictRestartPolicyAndAutoRemove
  77. }
  78. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  79. fmt.Fprintf(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.\n")
  80. }
  81. if len(hostConfig.DNS) > 0 {
  82. // check the DNS settings passed via --dns against
  83. // localhost regexp to warn if they are trying to
  84. // set a DNS to a localhost address
  85. for _, dnsIP := range hostConfig.DNS {
  86. if dns.IsLocalhost(dnsIP) {
  87. fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  88. break
  89. }
  90. }
  91. }
  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 fl := flags.Lookup("attach"); fl != nil {
  99. flAttach = fl.Value.(*opttypes.ListOpts)
  100. if flAttach.Len() != 0 {
  101. return ErrConflictAttachDetach
  102. }
  103. }
  104. config.AttachStdin = false
  105. config.AttachStdout = false
  106. config.AttachStderr = false
  107. config.StdinOnce = false
  108. }
  109. // Disable sigProxy when in TTY mode
  110. if config.Tty {
  111. opts.sigProxy = false
  112. }
  113. // Telling the Windows daemon the initial size of the tty during start makes
  114. // a far better user experience rather than relying on subsequent resizes
  115. // to cause things to catch up.
  116. if runtime.GOOS == "windows" {
  117. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.Out().GetTtySize()
  118. }
  119. ctx, cancelFun := context.WithCancel(context.Background())
  120. createResponse, err := createContainer(ctx, dockerCli, config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, opts.name)
  121. if err != nil {
  122. reportError(stderr, cmdPath, err.Error(), true)
  123. return runStartContainerErr(err)
  124. }
  125. if opts.sigProxy {
  126. sigc := ForwardAllSignals(ctx, dockerCli, createResponse.ID)
  127. defer signal.StopCatch(sigc)
  128. }
  129. var (
  130. waitDisplayID chan struct{}
  131. errCh chan error
  132. )
  133. if !config.AttachStdout && !config.AttachStderr {
  134. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  135. waitDisplayID = make(chan struct{})
  136. go func() {
  137. defer close(waitDisplayID)
  138. fmt.Fprintf(stdout, "%s\n", createResponse.ID)
  139. }()
  140. }
  141. attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
  142. if attach {
  143. var (
  144. out, cerr io.Writer
  145. in io.ReadCloser
  146. )
  147. if config.AttachStdin {
  148. in = stdin
  149. }
  150. if config.AttachStdout {
  151. out = stdout
  152. }
  153. if config.AttachStderr {
  154. if config.Tty {
  155. cerr = stdout
  156. } else {
  157. cerr = stderr
  158. }
  159. }
  160. if opts.detachKeys != "" {
  161. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  162. }
  163. options := types.ContainerAttachOptions{
  164. Stream: true,
  165. Stdin: config.AttachStdin,
  166. Stdout: config.AttachStdout,
  167. Stderr: config.AttachStderr,
  168. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  169. }
  170. resp, errAttach := client.ContainerAttach(ctx, createResponse.ID, options)
  171. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  172. // ContainerAttach returns an ErrPersistEOF (connection closed)
  173. // means server met an error and put it in Hijacked connection
  174. // keep the error and read detailed error message from hijacked connection later
  175. return errAttach
  176. }
  177. defer resp.Close()
  178. errCh = promise.Go(func() error {
  179. errHijack := holdHijackedConnection(ctx, dockerCli, config.Tty, in, out, cerr, resp)
  180. if errHijack == nil {
  181. return errAttach
  182. }
  183. return errHijack
  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.Fprintf(stderr, "Error monitoring TTY size: %s\n", 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. }