run.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. flDetachKeys = cmd.String([]string{"-detach-keys"}, "", "Override the key sequence for detaching a container")
  69. flAttach *opts.ListOpts
  70. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  71. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  72. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  73. )
  74. config, hostConfig, cmd, err := runconfig.Parse(cmd, args)
  75. // just in case the Parse does not exit
  76. if err != nil {
  77. cmd.ReportError(err.Error(), true)
  78. os.Exit(125)
  79. }
  80. if hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  81. fmt.Fprintf(cli.err, "WARNING: Dangerous only disable the OOM Killer on containers but not set the '-m/--memory' option\n")
  82. }
  83. if len(hostConfig.DNS) > 0 {
  84. // check the DNS settings passed via --dns against
  85. // localhost regexp to warn if they are trying to
  86. // set a DNS to a localhost address
  87. for _, dnsIP := range hostConfig.DNS {
  88. if dns.IsLocalhost(dnsIP) {
  89. fmt.Fprintf(cli.err, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  90. break
  91. }
  92. }
  93. }
  94. if config.Image == "" {
  95. cmd.Usage()
  96. return nil
  97. }
  98. config.ArgsEscaped = false
  99. if !*flDetach {
  100. if err := cli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil {
  101. return err
  102. }
  103. } else {
  104. if fl := cmd.Lookup("-attach"); fl != nil {
  105. flAttach = fl.Value.(*opts.ListOpts)
  106. if flAttach.Len() != 0 {
  107. return ErrConflictAttachDetach
  108. }
  109. }
  110. if *flAutoRemove {
  111. return ErrConflictDetachAutoRemove
  112. }
  113. config.AttachStdin = false
  114. config.AttachStdout = false
  115. config.AttachStderr = false
  116. config.StdinOnce = false
  117. }
  118. // Disable flSigProxy when in TTY mode
  119. sigProxy := *flSigProxy
  120. if config.Tty {
  121. 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] = cli.getTtySize()
  128. }
  129. createResponse, err := cli.createContainer(config, hostConfig, hostConfig.ContainerIDFile, *flName)
  130. if err != nil {
  131. cmd.ReportError(err.Error(), true)
  132. return runStartContainerErr(err)
  133. }
  134. if sigProxy {
  135. sigc := cli.forwardAllSignals(createResponse.ID)
  136. defer signal.StopCatch(sigc)
  137. }
  138. var (
  139. waitDisplayID chan struct{}
  140. errCh chan error
  141. )
  142. if !config.AttachStdout && !config.AttachStderr {
  143. // Make this asynchronous to allow the client to write to stdin before having to read the ID
  144. waitDisplayID = make(chan struct{})
  145. go func() {
  146. defer close(waitDisplayID)
  147. fmt.Fprintf(cli.out, "%s\n", createResponse.ID)
  148. }()
  149. }
  150. if *flAutoRemove && (hostConfig.RestartPolicy.IsAlways() || hostConfig.RestartPolicy.IsOnFailure()) {
  151. return ErrConflictRestartPolicyAndAutoRemove
  152. }
  153. if config.AttachStdin || config.AttachStdout || config.AttachStderr {
  154. var (
  155. out, stderr io.Writer
  156. in io.ReadCloser
  157. )
  158. if config.AttachStdin {
  159. in = cli.in
  160. }
  161. if config.AttachStdout {
  162. out = cli.out
  163. }
  164. if config.AttachStderr {
  165. if config.Tty {
  166. stderr = cli.out
  167. } else {
  168. stderr = cli.err
  169. }
  170. }
  171. if *flDetachKeys != "" {
  172. cli.configFile.DetachKeys = *flDetachKeys
  173. }
  174. options := types.ContainerAttachOptions{
  175. ContainerID: createResponse.ID,
  176. Stream: true,
  177. Stdin: config.AttachStdin,
  178. Stdout: config.AttachStdout,
  179. Stderr: config.AttachStderr,
  180. DetachKeys: cli.configFile.DetachKeys,
  181. }
  182. resp, err := cli.client.ContainerAttach(options)
  183. if err != nil {
  184. return err
  185. }
  186. errCh = promise.Go(func() error {
  187. return cli.holdHijackedConnection(config.Tty, in, out, stderr, resp)
  188. })
  189. }
  190. defer func() {
  191. if *flAutoRemove {
  192. options := types.ContainerRemoveOptions{
  193. ContainerID: createResponse.ID,
  194. RemoveVolumes: true,
  195. }
  196. if err := cli.client.ContainerRemove(options); err != nil {
  197. fmt.Fprintf(cli.err, "Error deleting container: %s\n", err)
  198. }
  199. }
  200. }()
  201. //start the container
  202. if err := cli.client.ContainerStart(createResponse.ID); err != nil {
  203. cmd.ReportError(err.Error(), false)
  204. return runStartContainerErr(err)
  205. }
  206. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  207. if err := cli.monitorTtySize(createResponse.ID, false); err != nil {
  208. fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err)
  209. }
  210. }
  211. if errCh != nil {
  212. if err := <-errCh; err != nil {
  213. logrus.Debugf("Error hijack: %s", err)
  214. return err
  215. }
  216. }
  217. // Detached mode: wait for the id to be displayed and return.
  218. if !config.AttachStdout && !config.AttachStderr {
  219. // Detached mode
  220. <-waitDisplayID
  221. return nil
  222. }
  223. var status int
  224. // Attached mode
  225. if *flAutoRemove {
  226. // Autoremove: wait for the container to finish, retrieve
  227. // the exit code and remove the container
  228. if status, err = cli.client.ContainerWait(createResponse.ID); err != nil {
  229. return runStartContainerErr(err)
  230. }
  231. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  232. return err
  233. }
  234. } else {
  235. // No Autoremove: Simply retrieve the exit code
  236. if !config.Tty {
  237. // In non-TTY mode, we can't detach, so we must wait for container exit
  238. if status, err = cli.client.ContainerWait(createResponse.ID); err != nil {
  239. return err
  240. }
  241. } else {
  242. // In TTY mode, there is a race: if the process dies too slowly, the state could
  243. // be updated after the getExitCode call and result in the wrong exit code being reported
  244. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  245. return err
  246. }
  247. }
  248. }
  249. if status != 0 {
  250. return Cli.StatusError{StatusCode: status}
  251. }
  252. return nil
  253. }