exec.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package container
  2. import (
  3. "fmt"
  4. "io"
  5. "github.com/Sirupsen/logrus"
  6. "github.com/docker/docker/api/types"
  7. "github.com/docker/docker/cli"
  8. "github.com/docker/docker/cli/command"
  9. apiclient "github.com/docker/docker/client"
  10. options "github.com/docker/docker/opts"
  11. "github.com/docker/docker/pkg/promise"
  12. "github.com/spf13/cobra"
  13. "golang.org/x/net/context"
  14. )
  15. type execOptions struct {
  16. detachKeys string
  17. interactive bool
  18. tty bool
  19. detach bool
  20. user string
  21. privileged bool
  22. env *options.ListOpts
  23. }
  24. func newExecOptions() *execOptions {
  25. var values []string
  26. return &execOptions{
  27. env: options.NewListOptsRef(&values, options.ValidateEnv),
  28. }
  29. }
  30. // NewExecCommand creats a new cobra.Command for `docker exec`
  31. func NewExecCommand(dockerCli *command.DockerCli) *cobra.Command {
  32. opts := newExecOptions()
  33. cmd := &cobra.Command{
  34. Use: "exec [OPTIONS] CONTAINER COMMAND [ARG...]",
  35. Short: "Run a command in a running container",
  36. Args: cli.RequiresMinArgs(2),
  37. RunE: func(cmd *cobra.Command, args []string) error {
  38. container := args[0]
  39. execCmd := args[1:]
  40. return runExec(dockerCli, opts, container, execCmd)
  41. },
  42. }
  43. flags := cmd.Flags()
  44. flags.SetInterspersed(false)
  45. flags.StringVarP(&opts.detachKeys, "detach-keys", "", "", "Override the key sequence for detaching a container")
  46. flags.BoolVarP(&opts.interactive, "interactive", "i", false, "Keep STDIN open even if not attached")
  47. flags.BoolVarP(&opts.tty, "tty", "t", false, "Allocate a pseudo-TTY")
  48. flags.BoolVarP(&opts.detach, "detach", "d", false, "Detached mode: run command in the background")
  49. flags.StringVarP(&opts.user, "user", "u", "", "Username or UID (format: <name|uid>[:<group|gid>])")
  50. flags.BoolVarP(&opts.privileged, "privileged", "", false, "Give extended privileges to the command")
  51. flags.VarP(opts.env, "env", "e", "Set environment variables")
  52. flags.SetAnnotation("env", "version", []string{"1.25"})
  53. return cmd
  54. }
  55. func runExec(dockerCli *command.DockerCli, opts *execOptions, container string, execCmd []string) error {
  56. execConfig, err := parseExec(opts, execCmd)
  57. // just in case the ParseExec does not exit
  58. if container == "" || err != nil {
  59. return cli.StatusError{StatusCode: 1}
  60. }
  61. if opts.detachKeys != "" {
  62. dockerCli.ConfigFile().DetachKeys = opts.detachKeys
  63. }
  64. // Send client escape keys
  65. execConfig.DetachKeys = dockerCli.ConfigFile().DetachKeys
  66. ctx := context.Background()
  67. client := dockerCli.Client()
  68. response, err := client.ContainerExecCreate(ctx, container, *execConfig)
  69. if err != nil {
  70. return err
  71. }
  72. execID := response.ID
  73. if execID == "" {
  74. fmt.Fprintln(dockerCli.Out(), "exec ID empty")
  75. return nil
  76. }
  77. //Temp struct for execStart so that we don't need to transfer all the execConfig
  78. if !execConfig.Detach {
  79. if err := dockerCli.In().CheckTty(execConfig.AttachStdin, execConfig.Tty); err != nil {
  80. return err
  81. }
  82. } else {
  83. execStartCheck := types.ExecStartCheck{
  84. Detach: execConfig.Detach,
  85. Tty: execConfig.Tty,
  86. }
  87. if err := client.ContainerExecStart(ctx, execID, execStartCheck); err != nil {
  88. return err
  89. }
  90. // For now don't print this - wait for when we support exec wait()
  91. // fmt.Fprintf(dockerCli.Out(), "%s\n", execID)
  92. return nil
  93. }
  94. // Interactive exec requested.
  95. var (
  96. out, stderr io.Writer
  97. in io.ReadCloser
  98. errCh chan error
  99. )
  100. if execConfig.AttachStdin {
  101. in = dockerCli.In()
  102. }
  103. if execConfig.AttachStdout {
  104. out = dockerCli.Out()
  105. }
  106. if execConfig.AttachStderr {
  107. if execConfig.Tty {
  108. stderr = dockerCli.Out()
  109. } else {
  110. stderr = dockerCli.Err()
  111. }
  112. }
  113. resp, err := client.ContainerExecAttach(ctx, execID, *execConfig)
  114. if err != nil {
  115. return err
  116. }
  117. defer resp.Close()
  118. errCh = promise.Go(func() error {
  119. return holdHijackedConnection(ctx, dockerCli, execConfig.Tty, in, out, stderr, resp)
  120. })
  121. if execConfig.Tty && dockerCli.In().IsTerminal() {
  122. if err := MonitorTtySize(ctx, dockerCli, execID, true); err != nil {
  123. fmt.Fprintln(dockerCli.Err(), "Error monitoring TTY size:", err)
  124. }
  125. }
  126. if err := <-errCh; err != nil {
  127. logrus.Debugf("Error hijack: %s", err)
  128. return err
  129. }
  130. var status int
  131. if _, status, err = getExecExitCode(ctx, client, execID); err != nil {
  132. return err
  133. }
  134. if status != 0 {
  135. return cli.StatusError{StatusCode: status}
  136. }
  137. return nil
  138. }
  139. // getExecExitCode perform an inspect on the exec command. It returns
  140. // the running state and the exit code.
  141. func getExecExitCode(ctx context.Context, client apiclient.ContainerAPIClient, execID string) (bool, int, error) {
  142. resp, err := client.ContainerExecInspect(ctx, execID)
  143. if err != nil {
  144. // If we can't connect, then the daemon probably died.
  145. if !apiclient.IsErrConnectionFailed(err) {
  146. return false, -1, err
  147. }
  148. return false, -1, nil
  149. }
  150. return resp.Running, resp.ExitCode, nil
  151. }
  152. // parseExec parses the specified args for the specified command and generates
  153. // an ExecConfig from it.
  154. func parseExec(opts *execOptions, execCmd []string) (*types.ExecConfig, error) {
  155. execConfig := &types.ExecConfig{
  156. User: opts.user,
  157. Privileged: opts.privileged,
  158. Tty: opts.tty,
  159. Cmd: execCmd,
  160. Detach: opts.detach,
  161. }
  162. // If -d is not set, attach to everything by default
  163. if !opts.detach {
  164. execConfig.AttachStdout = true
  165. execConfig.AttachStderr = true
  166. if opts.interactive {
  167. execConfig.AttachStdin = true
  168. }
  169. }
  170. if opts.env != nil {
  171. execConfig.Env = opts.env.GetAll()
  172. }
  173. return execConfig, nil
  174. }