attach.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package client
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/Sirupsen/logrus"
  6. "github.com/docker/docker/api/types"
  7. Cli "github.com/docker/docker/cli"
  8. flag "github.com/docker/docker/pkg/mflag"
  9. "github.com/docker/docker/pkg/signal"
  10. )
  11. // CmdAttach attaches to a running container.
  12. //
  13. // Usage: docker attach [OPTIONS] CONTAINER
  14. func (cli *DockerCli) CmdAttach(args ...string) error {
  15. cmd := Cli.Subcmd("attach", []string{"CONTAINER"}, Cli.DockerCommands["attach"].Description, true)
  16. noStdin := cmd.Bool([]string{"-no-stdin"}, false, "Do not attach STDIN")
  17. proxy := cmd.Bool([]string{"-sig-proxy"}, true, "Proxy all received signals to the process")
  18. cmd.Require(flag.Exact, 1)
  19. cmd.ParseFlags(args, true)
  20. c, err := cli.client.ContainerInspect(cmd.Arg(0))
  21. if err != nil {
  22. return err
  23. }
  24. if !c.State.Running {
  25. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  26. }
  27. if c.State.Paused {
  28. return fmt.Errorf("You cannot attach to a paused container, unpause it first")
  29. }
  30. if err := cli.CheckTtyInput(!*noStdin, c.Config.Tty); err != nil {
  31. return err
  32. }
  33. if c.Config.Tty && cli.isTerminalOut {
  34. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  35. logrus.Debugf("Error monitoring TTY size: %s", err)
  36. }
  37. }
  38. options := types.ContainerAttachOptions{
  39. ContainerID: cmd.Arg(0),
  40. Stream: true,
  41. Stdin: !*noStdin && c.Config.OpenStdin,
  42. Stdout: true,
  43. Stderr: true,
  44. }
  45. var in io.ReadCloser
  46. if options.Stdin {
  47. in = cli.in
  48. }
  49. if *proxy && !c.Config.Tty {
  50. sigc := cli.forwardAllSignals(options.ContainerID)
  51. defer signal.StopCatch(sigc)
  52. }
  53. resp, err := cli.client.ContainerAttach(options)
  54. if err != nil {
  55. return err
  56. }
  57. defer resp.Close()
  58. if err := cli.holdHijackedConnection(c.Config.Tty, in, cli.out, cli.err, resp); err != nil {
  59. return err
  60. }
  61. _, status, err := getExitCode(cli, options.ContainerID)
  62. if err != nil {
  63. return err
  64. }
  65. if status != 0 {
  66. return Cli.StatusError{StatusCode: status}
  67. }
  68. return nil
  69. }