exec.go 3.9 KB

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