run.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package client
  2. import (
  3. "fmt"
  4. "io"
  5. "net/http/httputil"
  6. "os"
  7. "runtime"
  8. "strings"
  9. "golang.org/x/net/context"
  10. "github.com/Sirupsen/logrus"
  11. Cli "github.com/docker/docker/cli"
  12. "github.com/docker/docker/opts"
  13. "github.com/docker/docker/pkg/promise"
  14. "github.com/docker/docker/pkg/signal"
  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 = "not found or does not exist"
  21. errCmdCouldNotBeInvoked = "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.TrimPrefix(err.Error(), "Error response from daemon: ")
  44. statusError := Cli.StatusError{StatusCode: 125}
  45. if strings.HasPrefix(trimmedErr, "Container command") {
  46. if strings.Contains(trimmedErr, errCmdNotFound) {
  47. statusError = Cli.StatusError{StatusCode: 127}
  48. } else if strings.Contains(trimmedErr, errCmdCouldNotBeInvoked) {
  49. statusError = Cli.StatusError{StatusCode: 126}
  50. }
  51. }
  52. return statusError
  53. }
  54. // CmdRun runs a command in a new container.
  55. //
  56. // Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
  57. func (cli *DockerCli) CmdRun(args ...string) error {
  58. cmd := Cli.Subcmd("run", []string{"IMAGE [COMMAND] [ARG...]"}, Cli.DockerCommands["run"].Description, true)
  59. addTrustedFlags(cmd, true)
  60. // These are flags not stored in Config/HostConfig
  61. var (
  62. flAutoRemove = cmd.Bool([]string{"-rm"}, false, "Automatically remove the container when it exits")
  63. flDetach = cmd.Bool([]string{"d", "-detach"}, false, "Run container in background and print container ID")
  64. flSigProxy = cmd.Bool([]string{"-sig-proxy"}, true, "Proxy received signals to the process")
  65. flName = cmd.String([]string{"-name"}, "", "Assign a name to the container")
  66. flDetachKeys = cmd.String([]string{"-detach-keys"}, "", "Override the key sequence for detaching a container")
  67. flAttach *opts.ListOpts
  68. ErrConflictAttachDetach = fmt.Errorf("Conflicting options: -a and -d")
  69. ErrConflictRestartPolicyAndAutoRemove = fmt.Errorf("Conflicting options: --restart and --rm")
  70. ErrConflictDetachAutoRemove = fmt.Errorf("Conflicting options: --rm and -d")
  71. )
  72. config, hostConfig, networkingConfig, cmd, err := runconfigopts.Parse(cmd, args)
  73. // just in case the Parse does not exit
  74. if err != nil {
  75. cmd.ReportError(err.Error(), true)
  76. os.Exit(125)
  77. }
  78. if hostConfig.OomKillDisable != nil && *hostConfig.OomKillDisable && hostConfig.Memory == 0 {
  79. fmt.Fprintf(cli.err, "WARNING: Disabling the OOM killer on containers without setting a '-m/--memory' limit may be dangerous.\n")
  80. }
  81. if len(hostConfig.DNS) > 0 {
  82. // check the DNS settings passed via --dns against
  83. // localhost regexp to warn if they are trying to
  84. // set a DNS to a localhost address
  85. for _, dnsIP := range hostConfig.DNS {
  86. if dns.IsLocalhost(dnsIP) {
  87. fmt.Fprintf(cli.err, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
  88. break
  89. }
  90. }
  91. }
  92. if config.Image == "" {
  93. cmd.Usage()
  94. return nil
  95. }
  96. config.ArgsEscaped = false
  97. if !*flDetach {
  98. if err := cli.CheckTtyInput(config.AttachStdin, config.Tty); err != nil {
  99. return err
  100. }
  101. } else {
  102. if fl := cmd.Lookup("-attach"); fl != nil {
  103. flAttach = fl.Value.(*opts.ListOpts)
  104. if flAttach.Len() != 0 {
  105. return ErrConflictAttachDetach
  106. }
  107. }
  108. if *flAutoRemove {
  109. return ErrConflictDetachAutoRemove
  110. }
  111. config.AttachStdin = false
  112. config.AttachStdout = false
  113. config.AttachStderr = false
  114. config.StdinOnce = false
  115. }
  116. // Disable flSigProxy when in TTY mode
  117. sigProxy := *flSigProxy
  118. if config.Tty {
  119. sigProxy = false
  120. }
  121. // Telling the Windows daemon the initial size of the tty during start makes
  122. // a far better user experience rather than relying on subsequent resizes
  123. // to cause things to catch up.
  124. if runtime.GOOS == "windows" {
  125. hostConfig.ConsoleSize[0], hostConfig.ConsoleSize[1] = cli.getTtySize()
  126. }
  127. createResponse, err := cli.createContainer(config, hostConfig, networkingConfig, hostConfig.ContainerIDFile, *flName)
  128. if err != nil {
  129. cmd.ReportError(err.Error(), true)
  130. return runStartContainerErr(err)
  131. }
  132. if sigProxy {
  133. sigc := cli.forwardAllSignals(createResponse.ID)
  134. defer signal.StopCatch(sigc)
  135. }
  136. var (
  137. waitDisplayID chan struct{}
  138. errCh chan error
  139. cancelFun context.CancelFunc
  140. ctx context.Context
  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. attach := config.AttachStdin || config.AttachStdout || config.AttachStderr
  154. if attach {
  155. var (
  156. out, stderr io.Writer
  157. in io.ReadCloser
  158. )
  159. if config.AttachStdin {
  160. in = cli.in
  161. }
  162. if config.AttachStdout {
  163. out = cli.out
  164. }
  165. if config.AttachStderr {
  166. if config.Tty {
  167. stderr = cli.out
  168. } else {
  169. stderr = cli.err
  170. }
  171. }
  172. if *flDetachKeys != "" {
  173. cli.configFile.DetachKeys = *flDetachKeys
  174. }
  175. options := types.ContainerAttachOptions{
  176. Stream: true,
  177. Stdin: config.AttachStdin,
  178. Stdout: config.AttachStdout,
  179. Stderr: config.AttachStderr,
  180. DetachKeys: cli.configFile.DetachKeys,
  181. }
  182. resp, errAttach := cli.client.ContainerAttach(context.Background(), createResponse.ID, options)
  183. if errAttach != nil && errAttach != httputil.ErrPersistEOF {
  184. // ContainerAttach returns an ErrPersistEOF (connection closed)
  185. // means server met an error and put it in Hijacked connection
  186. // keep the error and read detailed error message from hijacked connection later
  187. return errAttach
  188. }
  189. defer resp.Close()
  190. ctx, cancelFun = context.WithCancel(context.Background())
  191. errCh = promise.Go(func() error {
  192. errHijack := cli.holdHijackedConnection(ctx, config.Tty, in, out, stderr, resp)
  193. if errHijack == nil {
  194. return errAttach
  195. }
  196. return errHijack
  197. })
  198. }
  199. if *flAutoRemove {
  200. defer func() {
  201. if err := cli.removeContainer(createResponse.ID, true, false, true); err != nil {
  202. fmt.Fprintf(cli.err, "%v\n", err)
  203. }
  204. }()
  205. }
  206. //start the container
  207. if err := cli.client.ContainerStart(context.Background(), createResponse.ID); err != nil {
  208. // If we have holdHijackedConnection, we should notify
  209. // holdHijackedConnection we are going to exit and wait
  210. // to avoid the terminal are not restored.
  211. if attach {
  212. cancelFun()
  213. <-errCh
  214. }
  215. cmd.ReportError(err.Error(), false)
  216. return runStartContainerErr(err)
  217. }
  218. if (config.AttachStdin || config.AttachStdout || config.AttachStderr) && config.Tty && cli.isTerminalOut {
  219. if err := cli.monitorTtySize(createResponse.ID, false); err != nil {
  220. fmt.Fprintf(cli.err, "Error monitoring TTY size: %s\n", err)
  221. }
  222. }
  223. if errCh != nil {
  224. if err := <-errCh; err != nil {
  225. logrus.Debugf("Error hijack: %s", err)
  226. return err
  227. }
  228. }
  229. // Detached mode: wait for the id to be displayed and return.
  230. if !config.AttachStdout && !config.AttachStderr {
  231. // Detached mode
  232. <-waitDisplayID
  233. return nil
  234. }
  235. var status int
  236. // Attached mode
  237. if *flAutoRemove {
  238. // Autoremove: wait for the container to finish, retrieve
  239. // the exit code and remove the container
  240. if status, err = cli.client.ContainerWait(context.Background(), createResponse.ID); err != nil {
  241. return runStartContainerErr(err)
  242. }
  243. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  244. return err
  245. }
  246. } else {
  247. // No Autoremove: Simply retrieve the exit code
  248. if !config.Tty {
  249. // In non-TTY mode, we can't detach, so we must wait for container exit
  250. if status, err = cli.client.ContainerWait(context.Background(), createResponse.ID); err != nil {
  251. return err
  252. }
  253. } else {
  254. // In TTY mode, there is a race: if the process dies too slowly, the state could
  255. // be updated after the getExitCode call and result in the wrong exit code being reported
  256. if _, status, err = getExitCode(cli, createResponse.ID); err != nil {
  257. return err
  258. }
  259. }
  260. }
  261. if status != 0 {
  262. return Cli.StatusError{StatusCode: status}
  263. }
  264. return nil
  265. }