run.go 6.9 KB

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