exec.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package cmd
  2. import (
  3. "context"
  4. "io"
  5. "os"
  6. "strings"
  7. "github.com/containerd/console"
  8. "github.com/pkg/errors"
  9. "github.com/spf13/cobra"
  10. "github.com/docker/api/client"
  11. )
  12. type execOpts struct {
  13. Tty bool
  14. }
  15. func ExecCommand() *cobra.Command {
  16. var opts execOpts
  17. cmd := &cobra.Command{
  18. Use: "exec",
  19. Short: "Run a command in a running container",
  20. Args: cobra.MinimumNArgs(2),
  21. RunE: func(cmd *cobra.Command, args []string) error {
  22. return runExec(cmd.Context(), opts, args[0], strings.Join(args[1:], " "))
  23. },
  24. }
  25. cmd.Flags().BoolVarP(&opts.Tty, "tty", "t", false, "Allocate a pseudo-TTY")
  26. return cmd
  27. }
  28. func runExec(ctx context.Context, opts execOpts, name string, command string) error {
  29. c, err := client.New(ctx)
  30. if err != nil {
  31. return errors.Wrap(err, "cannot connect to backend")
  32. }
  33. var (
  34. con console.Console
  35. stdout io.Writer
  36. )
  37. stdout = os.Stdout
  38. if opts.Tty {
  39. con = console.Current()
  40. if err := con.SetRaw(); err != nil {
  41. return err
  42. }
  43. defer func() {
  44. con.Reset()
  45. }()
  46. stdout = con
  47. }
  48. return c.ContainerService().Exec(ctx, name, command, os.Stdin, stdout)
  49. }