1
0

exec.go 1.2 KB

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