run.go 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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/client"
  13. "github.com/docker/docker/cli"
  14. opttypes "github.com/docker/docker/opts"
  15. "github.com/docker/docker/pkg/promise"
  16. "github.com/docker/docker/pkg/signal"
  17. runconfigopts "github.com/docker/docker/runconfig/opts"
  18. "github.com/docker/engine-api/types"
  19. "github.com/docker/libnetwork/resolvconf/dns"
  20. "github.com/spf13/cobra"
  21. "github.com/spf13/pflag"
  22. )
  23. type runOptions struct {
  24. autoRemove bool
  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 *client.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. cmd.SetFlagErrorFunc(flagErrorFunc)
  47. flags := cmd.Flags()
  48. flags.SetInterspersed(false)
  49. // These are flags not stored in Config/HostConfig
  50. flags.BoolVar(&opts.autoRemove, "rm", false, "Automatically remove the container when it exits")
  51. flags.BoolVarP(&opts.detach, "detach", "d", false, "Run container in background and print container ID")
  52. flags.BoolVar(&opts.sigProxy, "sig-proxy", true, "Proxy received signals to the process")
  53. flags.StringVar(&opts.name, "name", "", "Assign a name to the container")
  54. flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container")
  55. // Add an explicit help that doesn't have a `-h` to prevent the conflict
  56. // with hostname
  57. flags.Bool("help", false, "Print usage")
  58. client.AddTrustedFlags(flags, true)
  59. copts = runconfigopts.AddFlags(flags)
  60. return cmd
  61. }
  62. func flagErrorFunc(cmd *cobra.Command, err error) error {
  63. return cli.StatusError{
  64. Status: cli.FlagErrorFunc(cmd, err).Error(),
  65. StatusCode: 125,
  66. }
  67. }
  68. func runRun(dockerCli *client.DockerCli, flags *pflag.FlagSet, opts *runOptions, copts *runconfigopts.ContainerOptions) error {
  69. stdout, stderr, stdin := dockerCli.Out(), dockerCli.Err(), dockerCli.In()
  70. client := dockerCli.Client()
  71. // TODO: pass this as an argument
  72. cmdPath := "run"
  73. var (
  74. flAttach *opttypes.ListOpts
  75. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  76. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  77. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  78. )
  79. config, hostConfig, networkingConfig, err := runconfigopts.Parse(flags, copts)
  80. // just in case the Parse does not exit
  81. if err != nil {
  82. reportError(stderr, cmdPath, err.Error(), true)
  83. return cli.StatusError{StatusCode: 125}
  84. }
  85. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  86. fmt.Fprintf(stderr, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.\n")
  87. }
  88. if len(hostConfig.DNS) > 0 {
  89. // check the DNS settings passed via --dns against
  90. // localhost regexp to warn if they are trying to
  91. // set a DNS to a localhost address
  92. for _, dnsIP := range hostConfig.DNS {
  93. if dns.IsLocalhost(dnsIP) {
  94. fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  95. break
  96. }
  97. }
  98. }
  99. config.ArgsEscaped = false
  100. if !opts.detach {
  101. if err := dockerCli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil {
  102. return err
  103. }
  104. } else {
  105. if fl := flags.Lookup("attach"); fl != nil {
  106. flAttach = fl.Value.(*opttypes.ListOpts)
  107. if flAttach.Len() != 0 {
  108. return ErrConflictAttachDetach
  109. }
  110. }
  111. if opts.autoRemove {
  112. return ErrConflictDetachAutoRemove
  113. }
  114. config.AttachStdin = false
  115. config.AttachStdout = false
  116. config.AttachStderr = false
  117. config.StdinOnce = false
  118. }
  119. // Disable sigProxy when in TTY mode
  120. if config.Tty {
  121. opts.sigProxy = false
  122. }
  123. // Telling the Windows daemon the initial size of the tty during start makes
  124. // a far better user experience rather than relying on subsequent resizes
  125. // to cause things to catch up.
  126. if runtime.GOOS == "windows" {
  127. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = dockerCli.GetTtySize()
  128. }
  129. ctx, cancelFun := context.WithCancel(context.Background())
  130. createResponse, err := createContainer(ctx, dockerCli, config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, opts.name)
  131. if err != nil {
  132. reportError(stderr, cmdPath, err.Error(), true)
  133. return runStartContainerErr(err)
  134. }
  135. if opts.sigProxy {
  136. sigc := dockerCli.ForwardAllSignals(ctx, createResponse.ID)
  137. defer signal.StopCatch(sigc)
  138. }
  139. var (
  140. waitDisplayID chan struct{}
  141. errCh chan error
  142. )
  143. if !config.AttachStdout && !config.AttachStderr {
  144. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  145. waitDisplayID = make(chan struct{})
  146. go func() {
  147. defer close(waitDisplayID)
  148. fmt.Fprintf(stdout, "%s\n", createResponse.ID)
  149. }()
  150. }
  151. if opts.autoRemove && (hostConfig.RestartPolicy.IsAlways() || hostConfig.RestartPolicy.IsOnFailure()) {
  152. return ErrConflictRestartPolicyAndAutoRemove
  153. }
  154. attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
  155. if attach {
  156. var (
  157. out, cerr io.Writer
  158. in io.ReadCloser
  159. )
  160. if config.AttachStdin {
  161. in = stdin
  162. }
  163. if config.AttachStdout {
  164. out = stdout
  165. }
  166. if config.AttachStderr {
  167. if config.Tty {
  168. cerr = stdout
  169. } else {
  170. cerr = stderr
  171. }
  172. }
  173. if opts.detachKeys != "" {
  174. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  175. }
  176. options := types.ContainerAttachOptions{
  177. Stream: true,
  178. Stdin: config.AttachStdin,
  179. Stdout: config.AttachStdout,
  180. Stderr: config.AttachStderr,
  181. DetachKeys: dockerCli.ConfigFile().DetachKeys,
  182. }
  183. resp, errAttach := client.ContainerAttach(ctx, createResponse.ID, options)
  184. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  185. // ContainerAttach returns an ErrPersistEOF (connection closed)
  186. // means server met an error and put it in Hijacked connection
  187. // keep the error and read detailed error message from hijacked connection later
  188. return errAttach
  189. }
  190. defer resp.Close()
  191. errCh = promise.Go(func() error {
  192. errHijack := dockerCli.HoldHijackedConnection(ctx, config.Tty, in, out, cerr, resp)
  193. if errHijack == nil {
  194. return errAttach
  195. }
  196. return errHijack
  197. })
  198. }
  199. if opts.autoRemove {
  200. defer func() {
  201. // Explicitly not sharing the context as it could be "Done" (by calling cancelFun)
  202. // and thus the container would not be removed.
  203. if err := removeContainer(dockerCli, context.Background(), createResponse.ID, true, false, true); err != nil {
  204. fmt.Fprintf(stderr, "%v\n", err)
  205. }
  206. }()
  207. }
  208. //start the container
  209. if err := client.ContainerStart(ctx, createResponse.ID, types.ContainerStartOptions{}); err != nil {
  210. // If we have holdHijackedConnection, we should notify
  211. // holdHijackedConnection we are going to exit and wait
  212. // to avoid the terminal are not restored.
  213. if attach {
  214. cancelFun()
  215. <-errCh
  216. }
  217. reportError(stderr, cmdPath, err.Error(), false)
  218. return runStartContainerErr(err)
  219. }
  220. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && dockerCli.IsTerminalOut() {
  221. if err := dockerCli.MonitorTtySize(ctx, createResponse.ID, false); err != nil {
  222. fmt.Fprintf(stderr, "Error monitoring TTY size: %s\n", err)
  223. }
  224. }
  225. if errCh != nil {
  226. if err := <-errCh; err != nil {
  227. logrus.Debugf("Error hijack: %s", err)
  228. return err
  229. }
  230. }
  231. // Detached mode: wait for the id to be displayed and return.
  232. if !config.AttachStdout && !config.AttachStderr {
  233. // Detached mode
  234. <-waitDisplayID
  235. return nil
  236. }
  237. var status int
  238. // Attached mode
  239. if opts.autoRemove {
  240. // Autoremove: wait for the container to finish, retrieve
  241. // the exit code and remove the container
  242. if status, err = client.ContainerWait(ctx, createResponse.ID); err != nil {
  243. return runStartContainerErr(err)
  244. }
  245. if _, status, err = getExitCode(dockerCli, ctx, createResponse.ID); err != nil {
  246. return err
  247. }
  248. } else {
  249. // No Autoremove: Simply retrieve the exit code
  250. if !config.Tty && hostConfig.RestartPolicy.IsNone() {
  251. // In non-TTY mode, we can't detach, so we must wait for container exit
  252. if status, err = client.ContainerWait(ctx, createResponse.ID); err != nil {
  253. return err
  254. }
  255. } else {
  256. // In TTY mode, there is a race: if the process dies too slowly, the state could
  257. // be updated after the getExitCode call and result in the wrong exit code being reported
  258. if _, status, err = getExitCode(dockerCli, ctx, createResponse.ID); err != nil {
  259. return err
  260. }
  261. }
  262. }
  263. if status != 0 {
  264. return cli.StatusError{StatusCode: status}
  265. }
  266. return nil
  267. }
  268. // reportError is a utility method that prints a user-friendly message
  269. // containing the error that occurred during parsing and a suggestion to get help
  270. func reportError(stderr io.Writer, name string, str string, withHelp bool) {
  271. if withHelp {
  272. str += ".\nSee '" + os.Args[0] + " " + name + " --help'"
  273. }
  274. fmt.Fprintf(stderr, "%s: %s.\n", os.Args[0], str)
  275. }
  276. // if container start fails with 'not found'/'no such' error, return 127
  277. // if container start fails with 'permission denied' error, return 126
  278. // return 125 for generic docker daemon failures
  279. func runStartContainerErr(err error) error {
  280. trimmedErr := strings.TrimPrefix(err.Error(), "Error response from daemon: ")
  281. statusError := cli.StatusError{StatusCode: 125}
  282. if strings.Contains(trimmedErr, "executable file not found") ||
  283. strings.Contains(trimmedErr, "no such file or directory") ||
  284. strings.Contains(trimmedErr, "system cannot find the file specified") {
  285. statusError = cli.StatusError{StatusCode: 127}
  286. } else if strings.Contains(trimmedErr, syscall.EACCES.Error()) {
  287. statusError = cli.StatusError{StatusCode: 126}
  288. }
  289. return statusError
  290. }