run.go 7.9 KB

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