run.go 7.2 KB

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