run.go 8.4 KB

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