exec.go 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. /*
  2. Copyright 2020 Docker Compose CLI authors
  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 compose
  14. import (
  15. "context"
  16. "fmt"
  17. "os"
  18. cgo "github.com/compose-spec/compose-go/cli"
  19. "github.com/containerd/console"
  20. "github.com/docker/cli/cli"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose/v2/pkg/api"
  23. )
  24. type execOpts struct {
  25. *composeOptions
  26. service string
  27. command []string
  28. environment []string
  29. workingDir string
  30. noTty bool
  31. user string
  32. detach bool
  33. index int
  34. privileged bool
  35. }
  36. func execCommand(p *projectOptions, backend api.Service) *cobra.Command {
  37. opts := execOpts{
  38. composeOptions: &composeOptions{
  39. projectOptions: p,
  40. },
  41. }
  42. runCmd := &cobra.Command{
  43. Use: "exec [options] [-e KEY=VAL...] [--] SERVICE COMMAND [ARGS...]",
  44. Short: "Execute a command in a running container.",
  45. Args: cobra.MinimumNArgs(2),
  46. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  47. opts.service = args[0]
  48. opts.command = args[1:]
  49. return nil
  50. }),
  51. RunE: Adapt(func(ctx context.Context, args []string) error {
  52. return runExec(ctx, backend, opts)
  53. }),
  54. ValidArgsFunction: serviceCompletion(p),
  55. }
  56. runCmd.Flags().BoolVarP(&opts.detach, "detach", "d", false, "Detached mode: Run command in the background.")
  57. runCmd.Flags().StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables")
  58. runCmd.Flags().IntVar(&opts.index, "index", 1, "index of the container if there are multiple instances of a service [default: 1].")
  59. runCmd.Flags().BoolVarP(&opts.privileged, "privileged", "", false, "Give extended privileges to the process.")
  60. runCmd.Flags().StringVarP(&opts.user, "user", "u", "", "Run the command as this user.")
  61. runCmd.Flags().BoolVarP(&opts.noTty, "no-TTY", "T", notAtTTY(), "Disable pseudo-TTY allocation. By default `docker compose exec` allocates a TTY.")
  62. runCmd.Flags().StringVarP(&opts.workingDir, "workdir", "w", "", "Path to workdir directory for this command.")
  63. runCmd.Flags().SetInterspersed(false)
  64. return runCmd
  65. }
  66. func runExec(ctx context.Context, backend api.Service, opts execOpts) error {
  67. project, err := opts.toProject(nil, cgo.WithResolvedPaths(true))
  68. if err != nil {
  69. return err
  70. }
  71. execOpts := api.RunOptions{
  72. Service: opts.service,
  73. Command: opts.command,
  74. Environment: opts.environment,
  75. Tty: !opts.noTty,
  76. User: opts.user,
  77. Privileged: opts.privileged,
  78. Index: opts.index,
  79. Detach: opts.detach,
  80. WorkingDir: opts.workingDir,
  81. Stdin: os.Stdin,
  82. Stdout: os.Stdout,
  83. Stderr: os.Stderr,
  84. }
  85. if execOpts.Tty {
  86. con := console.Current()
  87. if err := con.SetRaw(); err != nil {
  88. return err
  89. }
  90. defer func() {
  91. if err := con.Reset(); err != nil {
  92. fmt.Println("Unable to close the console")
  93. }
  94. }()
  95. execOpts.Stdin = con
  96. execOpts.Stdout = con
  97. execOpts.Stderr = con
  98. }
  99. exitCode, err := backend.Exec(ctx, project, execOpts)
  100. if exitCode != 0 {
  101. errMsg := ""
  102. if err != nil {
  103. errMsg = err.Error()
  104. }
  105. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  106. }
  107. return err
  108. }