run.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package client
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "runtime"
  7. "strings"
  8. "golang.org/x/net/context"
  9. "github.com/Sirupsen/logrus"
  10. Cli "github.com/docker/docker/cli"
  11. derr "github.com/docker/docker/errors"
  12. "github.com/docker/docker/opts"
  13. "github.com/docker/docker/pkg/promise"
  14. "github.com/docker/docker/pkg/signal"
  15. "github.com/docker/docker/pkg/stringid"
  16. runconfigopts "github.com/docker/docker/runconfig/opts"
  17. "github.com/docker/engine-api/types"
  18. "github.com/docker/libnetwork/resolvconf/dns"
  19. )
  20. func (cid *cidFile) Close() error {
  21. cid.file.Close()
  22. if !cid.written {
  23. if err := os.Remove(cid.path); err != nil {
  24. return fmt.Errorf("failed to remove the CID file '%s': %s \n", cid.path, err)
  25. }
  26. }
  27. return nil
  28. }
  29. func (cid *cidFile) Write(id string) error {
  30. if _, err := cid.file.Write([]byte(id)); err != nil {
  31. return fmt.Errorf("Failed to write the container ID to the file: %s", err)
  32. }
  33. cid.written = true
  34. return nil
  35. }
  36. // if container start fails with 'command not found' error, return 127
  37. // if container start fails with 'command cannot be invoked' error, return 126
  38. // return 125 for generic docker daemon failures
  39. func runStartContainerErr(err error) error {
  40. trimmedErr := strings.Trim(err.Error(), "Error response from daemon: ")
  41. statusError := Cli.StatusError{}
  42. derrCmdNotFound := derr.ErrorCodeCmdNotFound.Message()
  43. derrCouldNotInvoke := derr.ErrorCodeCmdCouldNotBeInvoked.Message()
  44. derrNoSuchImage := derr.ErrorCodeNoSuchImageHash.Message()
  45. derrNoSuchImageTag := derr.ErrorCodeNoSuchImageTag.Message()
  46. switch trimmedErr {
  47. case derrCmdNotFound:
  48. statusError = Cli.StatusError{StatusCode: 127}
  49. case derrCouldNotInvoke:
  50. statusError = Cli.StatusError{StatusCode: 126}
  51. case derrNoSuchImage, derrNoSuchImageTag:
  52. statusError = Cli.StatusError{StatusCode: 125}
  53. default:
  54. statusError = Cli.StatusError{StatusCode: 125}
  55. }
  56. return statusError
  57. }
  58. // CmdRun runs a command in a new container.
  59. //
  60. // Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
  61. func (cli *DockerCli) CmdRun(args ...string) error {
  62. cmd := Cli.Subcmd("run", []string{"IMAGE [COMMAND] [ARG...]"}, Cli.DockerCommands["run"].Description, true)
  63. addTrustedFlags(cmd, true)
  64. // These are flags not stored in Config/HostConfig
  65. var (
  66. flAutoRemove = cmd.Bool([]string{"-rm"}, false, "Automatically remove the container when it exits")
  67. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Run container in background and print container ID")
  68. flSigProxy = cmd.Bool([]string{"-sig-proxy"}, true, "Proxy received signals to the process")
  69. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  70. flDetachKeys = cmd.String([]string{"-detach-keys"}, "", "Override the key sequence for detaching a container")
  71. flAttach *opts.ListOpts
  72. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  73. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  74. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  75. )
  76. config, hostConfig, networkingConfig, cmd, err := runconfigopts.Parse(cmd, args)
  77. // just in case the Parse does not exit
  78. if err != nil {
  79. cmd.ReportError(err.Error(), true)
  80. os.Exit(125)
  81. }
  82. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  83. fmt.Fprintf(cli.err, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.\n")
  84. }
  85. if len(hostConfig.DNS) > 0 {
  86. // check the DNS settings passed via --dns against
  87. // localhost regexp to warn if they are trying to
  88. // set a DNS to a localhost address
  89. for _, dnsIP := range hostConfig.DNS {
  90. if dns.IsLocalhost(dnsIP) {
  91. fmt.Fprintf(cli.err, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  92. break
  93. }
  94. }
  95. }
  96. if config.Image == "" {
  97. cmd.Usage()
  98. return nil
  99. }
  100. config.ArgsEscaped = false
  101. if !*flDetach {
  102. if err := cli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil {
  103. return err
  104. }
  105. } else {
  106. if fl := cmd.Lookup("-attach"); fl != nil {
  107. flAttach = fl.Value.(*opts.ListOpts)
  108. if flAttach.Len() != 0 {
  109. return ErrConflictAttachDetach
  110. }
  111. }
  112. if *flAutoRemove {
  113. return ErrConflictDetachAutoRemove
  114. }
  115. config.AttachStdin = false
  116. config.AttachStdout = false
  117. config.AttachStderr = false
  118. config.StdinOnce = false
  119. }
  120. // Disable flSigProxy when in TTY mode
  121. sigProxy := *flSigProxy
  122. if config.Tty {
  123. sigProxy = false
  124. }
  125. // Telling the Windows daemon the initial size of the tty during start makes
  126. // a far better user experience rather than relying on subsequent resizes
  127. // to cause things to catch up.
  128. if runtime.GOOS == "windows" {
  129. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = cli.getTtySize()
  130. }
  131. createResponse, err := cli.createContainer(config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, *flName)
  132. if err != nil {
  133. cmd.ReportError(err.Error(), true)
  134. return runStartContainerErr(err)
  135. }
  136. if sigProxy {
  137. sigc := cli.forwardAllSignals(createResponse.ID)
  138. defer signal.StopCatch(sigc)
  139. }
  140. var (
  141. waitDisplayID chan struct{}
  142. errCh chan error
  143. )
  144. if !config.AttachStdout && !config.AttachStderr {
  145. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  146. waitDisplayID = make(chan struct{})
  147. go func() {
  148. defer close(waitDisplayID)
  149. fmt.Fprintf(cli.out, "%s\n", createResponse.ID)
  150. }()
  151. }
  152. if *flAutoRemove && (hostConfig.RestartPolicy.IsAlways() || hostConfig.RestartPolicy.IsOnFailure()) {
  153. return ErrConflictRestartPolicyAndAutoRemove
  154. }
  155. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  156. var (
  157. out, stderr io.Writer
  158. in io.ReadCloser
  159. )
  160. if config.AttachStdin {
  161. in = cli.in
  162. }
  163. if config.AttachStdout {
  164. out = cli.out
  165. }
  166. if config.AttachStderr {
  167. if config.Tty {
  168. stderr = cli.out
  169. } else {
  170. stderr = cli.err
  171. }
  172. }
  173. if *flDetachKeys != "" {
  174. cli.configFile.DetachKeys = *flDetachKeys
  175. }
  176. options := types.ContainerAttachOptions{
  177. ContainerID: createResponse.ID,
  178. Stream: true,
  179. Stdin: config.AttachStdin,
  180. Stdout: config.AttachStdout,
  181. Stderr: config.AttachStderr,
  182. DetachKeys: cli.configFile.DetachKeys,
  183. }
  184. resp, err := cli.client.ContainerAttach(options)
  185. if err != nil {
  186. return err
  187. }
  188. if in != nil && config.Tty {
  189. if err := cli.setRawTerminal(); err != nil {
  190. return err
  191. }
  192. defer cli.restoreTerminal(in)
  193. }
  194. errCh = promise.Go(func() error {
  195. return cli.holdHijackedConnection(config.Tty, in, out, stderr, resp)
  196. })
  197. }
  198. if *flAutoRemove {
  199. defer func() {
  200. if err := cli.removeContainer(createResponse.ID, true, false, false); err != nil {
  201. fmt.Fprintf(cli.err, "%v\n", err)
  202. }
  203. }()
  204. }
  205. //start the container
  206. if err := cli.client.ContainerStart(createResponse.ID); err != nil {
  207. cmd.ReportError(err.Error(), false)
  208. return runStartContainerErr(err)
  209. }
  210. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  211. if err := cli.monitorTtySize(createResponse.ID, false); err != nil {
  212. fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err)
  213. }
  214. }
  215. if errCh != nil {
  216. if err := <-errCh; err != nil {
  217. logrus.Debugf("Error hijack: %s", err)
  218. return err
  219. }
  220. }
  221. // Detached mode: wait for the id to be displayed and return.
  222. if !config.AttachStdout && !config.AttachStderr {
  223. // Detached mode
  224. <-waitDisplayID
  225. return nil
  226. }
  227. var status int
  228. // Attached mode
  229. if *flAutoRemove {
  230. // Warn user if they detached us
  231. js, err := cli.client.ContainerInspect(createResponse.ID)
  232. if err != nil {
  233. return runStartContainerErr(err)
  234. }
  235. if js.State.Running == true || js.State.Paused == true {
  236. fmt.Fprintf(cli.out, "Detached from %s, awaiting its termination in order to uphold \"--rm\".\n",
  237. stringid.TruncateID(createResponse.ID))
  238. }
  239. // Autoremove: wait for the container to finish, retrieve
  240. // the exit code and remove the container
  241. if status, err = cli.client.ContainerWait(context.Background(), createResponse.ID); err != nil {
  242. return runStartContainerErr(err)
  243. }
  244. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  245. return err
  246. }
  247. } else {
  248. // No Autoremove: Simply retrieve the exit code
  249. if !config.Tty {
  250. // In non-TTY mode, we can't detach, so we must wait for container exit
  251. if status, err = cli.client.ContainerWait(context.Background(), createResponse.ID); err != nil {
  252. return err
  253. }
  254. } else {
  255. // In TTY mode, there is a race: if the process dies too slowly, the state could
  256. // be updated after the getExitCode call and result in the wrong exit code being reported
  257. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  258. return err
  259. }
  260. }
  261. }
  262. if status != 0 {
  263. return Cli.StatusError{StatusCode: status}
  264. }
  265. return nil
  266. }