exec.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. Copyright 2020 Docker, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cmd
  14. import (
  15. "context"
  16. "fmt"
  17. "strings"
  18. "github.com/containerd/console"
  19. "github.com/pkg/errors"
  20. "github.com/spf13/cobra"
  21. "github.com/docker/api/client"
  22. )
  23. type execOpts struct {
  24. Tty bool
  25. }
  26. // ExecCommand runs a command in a running container
  27. func ExecCommand() *cobra.Command {
  28. var opts execOpts
  29. cmd := &cobra.Command{
  30. Use: "exec",
  31. Short: "Run a command in a running container",
  32. Args: cobra.MinimumNArgs(2),
  33. RunE: func(cmd *cobra.Command, args []string) error {
  34. return runExec(cmd.Context(), opts, args[0], strings.Join(args[1:], " "))
  35. },
  36. }
  37. cmd.Flags().BoolVarP(&opts.Tty, "tty", "t", false, "Allocate a pseudo-TTY")
  38. return cmd
  39. }
  40. func runExec(ctx context.Context, opts execOpts, name string, command string) error {
  41. c, err := client.New(ctx)
  42. if err != nil {
  43. return errors.Wrap(err, "cannot connect to backend")
  44. }
  45. con := console.Current()
  46. if opts.Tty {
  47. if err := con.SetRaw(); err != nil {
  48. return err
  49. }
  50. defer func() {
  51. if err := con.Reset(); err != nil {
  52. fmt.Println("Unable to close the console")
  53. }
  54. }()
  55. }
  56. return c.ContainerService().Exec(ctx, name, command, con, con)
  57. }