exec.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "os"
  18. "strings"
  19. "github.com/containerd/console"
  20. "github.com/pkg/errors"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/api/client"
  23. )
  24. type execOpts struct {
  25. Tty bool
  26. }
  27. // ExecCommand runs a command in a running container
  28. func ExecCommand() *cobra.Command {
  29. var opts execOpts
  30. cmd := &cobra.Command{
  31. Use: "exec",
  32. Short: "Run a command in a running container",
  33. Args: cobra.MinimumNArgs(2),
  34. RunE: func(cmd *cobra.Command, args []string) error {
  35. return runExec(cmd.Context(), opts, args[0], strings.Join(args[1:], " "))
  36. },
  37. }
  38. cmd.Flags().BoolVarP(&opts.Tty, "tty", "t", false, "Allocate a pseudo-TTY")
  39. cmd.Flags().BoolP("interactive", "i", false, "Keep STDIN open even if not attached")
  40. return cmd
  41. }
  42. func runExec(ctx context.Context, opts execOpts, name string, command string) error {
  43. c, err := client.New(ctx)
  44. if err != nil {
  45. return errors.Wrap(err, "cannot connect to backend")
  46. }
  47. if opts.Tty {
  48. con := console.Current()
  49. if err := con.SetRaw(); err != nil {
  50. return err
  51. }
  52. defer func() {
  53. if err := con.Reset(); err != nil {
  54. fmt.Println("Unable to close the console")
  55. }
  56. }()
  57. return c.ContainerService().Exec(ctx, name, command, con, con)
  58. }
  59. return c.ContainerService().Exec(ctx, name, command, os.Stdin, os.Stdout)
  60. }