exec.go 2.1 KB

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