exec.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. "errors"
  17. "fmt"
  18. "os"
  19. "github.com/compose-spec/compose-go/v2/types"
  20. "github.com/docker/cli/cli"
  21. "github.com/docker/cli/cli/command"
  22. "github.com/docker/compose/v2/pkg/api"
  23. "github.com/docker/compose/v2/pkg/compose"
  24. "github.com/sirupsen/logrus"
  25. "github.com/spf13/cobra"
  26. "github.com/spf13/pflag"
  27. )
  28. type execOpts struct {
  29. *composeOptions
  30. service string
  31. command []string
  32. environment []string
  33. workingDir string
  34. noTty bool
  35. user string
  36. detach bool
  37. index int
  38. privileged bool
  39. interactive bool
  40. }
  41. func execCommand(p *ProjectOptions, dockerCli command.Cli, backendOptions *BackendOptions) *cobra.Command {
  42. opts := execOpts{
  43. composeOptions: &composeOptions{
  44. ProjectOptions: p,
  45. },
  46. }
  47. runCmd := &cobra.Command{
  48. Use: "exec [OPTIONS] SERVICE COMMAND [ARGS...]",
  49. Short: "Execute a command in a running container",
  50. Args: cobra.MinimumNArgs(2),
  51. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  52. opts.service = args[0]
  53. opts.command = args[1:]
  54. return nil
  55. }),
  56. RunE: Adapt(func(ctx context.Context, args []string) error {
  57. err := runExec(ctx, dockerCli, backendOptions, opts)
  58. if err != nil {
  59. logrus.Debugf("%v", err)
  60. var cliError cli.StatusError
  61. if ok := errors.As(err, &cliError); ok {
  62. os.Exit(err.(cli.StatusError).StatusCode) //nolint: errorlint
  63. }
  64. }
  65. return err
  66. }),
  67. ValidArgsFunction: completeServiceNames(dockerCli, p),
  68. }
  69. runCmd.Flags().BoolVarP(&opts.detach, "detach", "d", false, "Detached mode: Run command in the background")
  70. runCmd.Flags().StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables")
  71. runCmd.Flags().IntVar(&opts.index, "index", 0, "Index of the container if service has multiple replicas")
  72. runCmd.Flags().BoolVarP(&opts.privileged, "privileged", "", false, "Give extended privileges to the process")
  73. runCmd.Flags().StringVarP(&opts.user, "user", "u", "", "Run the command as this user")
  74. runCmd.Flags().BoolVarP(&opts.noTty, "no-tty", "T", !dockerCli.Out().IsTerminal(), "Disable pseudo-TTY allocation. By default 'docker compose exec' allocates a TTY.")
  75. runCmd.Flags().StringVarP(&opts.workingDir, "workdir", "w", "", "Path to workdir directory for this command")
  76. runCmd.Flags().BoolVarP(&opts.interactive, "interactive", "i", true, "Keep STDIN open even if not attached")
  77. runCmd.Flags().MarkHidden("interactive") //nolint:errcheck
  78. runCmd.Flags().BoolP("tty", "t", true, "Allocate a pseudo-TTY")
  79. runCmd.Flags().MarkHidden("tty") //nolint:errcheck
  80. runCmd.Flags().SetInterspersed(false)
  81. runCmd.Flags().SetNormalizeFunc(func(f *pflag.FlagSet, name string) pflag.NormalizedName {
  82. if name == "no-TTY" { // legacy
  83. name = "no-tty"
  84. }
  85. return pflag.NormalizedName(name)
  86. })
  87. return runCmd
  88. }
  89. func runExec(ctx context.Context, dockerCli command.Cli, backendOptions *BackendOptions, opts execOpts) error {
  90. projectName, err := opts.toProjectName(ctx, dockerCli)
  91. if err != nil {
  92. return err
  93. }
  94. projectOptions, err := opts.composeOptions.toProjectOptions() //nolint:staticcheck
  95. if err != nil {
  96. return err
  97. }
  98. lookupFn := func(k string) (string, bool) {
  99. v, ok := projectOptions.Environment[k]
  100. return v, ok
  101. }
  102. execOpts := api.RunOptions{
  103. Service: opts.service,
  104. Command: opts.command,
  105. Environment: compose.ToMobyEnv(types.NewMappingWithEquals(opts.environment).Resolve(lookupFn)),
  106. Tty: !opts.noTty,
  107. User: opts.user,
  108. Privileged: opts.privileged,
  109. Index: opts.index,
  110. Detach: opts.detach,
  111. WorkingDir: opts.workingDir,
  112. Interactive: opts.interactive,
  113. }
  114. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  115. if err != nil {
  116. return err
  117. }
  118. exitCode, err := backend.Exec(ctx, projectName, execOpts)
  119. if exitCode != 0 {
  120. errMsg := fmt.Sprintf("exit status %d", exitCode)
  121. if err != nil && err.Error() != "" {
  122. errMsg = err.Error()
  123. }
  124. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  125. }
  126. return err
  127. }