exec.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "strings"
  6. "github.com/containerd/console"
  7. "github.com/pkg/errors"
  8. "github.com/spf13/cobra"
  9. "github.com/docker/api/client"
  10. )
  11. type execOpts struct {
  12. Tty bool
  13. }
  14. // ExecCommand runs a command in a running container
  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. con := console.Current()
  34. if opts.Tty {
  35. if err := con.SetRaw(); err != nil {
  36. return err
  37. }
  38. defer func() {
  39. if err := con.Reset(); err != nil {
  40. fmt.Println("Unable to close the console")
  41. }
  42. }()
  43. }
  44. return c.ContainerService().Exec(ctx, name, command, con, con)
  45. }