attach.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. detachKeys := cmd.String([]string{"-detach-keys"}, "", "Override the key sequence for detaching a container")
  19. cmd.Require(flag.Exact, 1)
  20. cmd.ParseFlags(args, true)
  21. c, err := cli.client.ContainerInspect(cmd.Arg(0))
  22. if err != nil {
  23. return err
  24. }
  25. if !c.State.Running {
  26. return fmt.Errorf("You cannot attach to a stopped container, start it first")
  27. }
  28. if c.State.Paused {
  29. return fmt.Errorf("You cannot attach to a paused container, unpause it first")
  30. }
  31. if err := cli.CheckTtyInput(!*noStdin, c.Config.Tty); err != nil {
  32. return err
  33. }
  34. if c.Config.Tty && cli.isTerminalOut {
  35. if err := cli.monitorTtySize(cmd.Arg(0), false); err != nil {
  36. logrus.Debugf("Error monitoring TTY size: %s", err)
  37. }
  38. }
  39. if *detachKeys != "" {
  40. cli.configFile.DetachKeys = *detachKeys
  41. }
  42. options := types.ContainerAttachOptions{
  43. ContainerID: cmd.Arg(0),
  44. Stream: true,
  45. Stdin: !*noStdin && c.Config.OpenStdin,
  46. Stdout: true,
  47. Stderr: true,
  48. DetachKeys: cli.configFile.DetachKeys,
  49. }
  50. var in io.ReadCloser
  51. if options.Stdin {
  52. in = cli.in
  53. }
  54. if *proxy && !c.Config.Tty {
  55. sigc := cli.forwardAllSignals(options.ContainerID)
  56. defer signal.StopCatch(sigc)
  57. }
  58. resp, err := cli.client.ContainerAttach(options)
  59. if err != nil {
  60. return err
  61. }
  62. defer resp.Close()
  63. if err := cli.holdHijackedConnection(c.Config.Tty, in, cli.out, cli.err, resp); err != nil {
  64. return err
  65. }
  66. _, status, err := getExitCode(cli, options.ContainerID)
  67. if err != nil {
  68. return err
  69. }
  70. if status != 0 {
  71. return Cli.StatusError{StatusCode: status}
  72. }
  73. return nil
  74. }