run.go 6.8 KB

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