exec.go 5.4 KB

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