run.go 6.8 KB

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