run.go 10 KB

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