exec.go 4.2 KB

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