run.go 6.8 KB

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