exec.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. "github.com/compose-spec/compose-go/v2/types"
  17. "github.com/docker/cli/cli"
  18. "github.com/docker/cli/cli/command"
  19. "github.com/docker/compose/v2/pkg/api"
  20. "github.com/docker/compose/v2/pkg/compose"
  21. "github.com/spf13/cobra"
  22. )
  23. type execOpts struct {
  24. *composeOptions
  25. service string
  26. command []string
  27. environment []string
  28. workingDir string
  29. noTty bool
  30. user string
  31. detach bool
  32. index int
  33. privileged bool
  34. interactive bool
  35. }
  36. func execCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  37. opts := execOpts{
  38. composeOptions: &composeOptions{
  39. ProjectOptions: p,
  40. },
  41. }
  42. runCmd := &cobra.Command{
  43. Use: "exec [OPTIONS] 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, dockerCli, backend, opts)
  53. }),
  54. ValidArgsFunction: completeServiceNames(dockerCli, 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", 0, "Index of the container if service has multiple replicas")
  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", !dockerCli.Out().IsTerminal(), "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().BoolVarP(&opts.interactive, "interactive", "i", true, "Keep STDIN open even if not attached")
  64. runCmd.Flags().MarkHidden("interactive") //nolint:errcheck
  65. runCmd.Flags().BoolP("tty", "t", true, "Allocate a pseudo-TTY")
  66. runCmd.Flags().MarkHidden("tty") //nolint:errcheck
  67. runCmd.Flags().SetInterspersed(false)
  68. return runCmd
  69. }
  70. func runExec(ctx context.Context, dockerCli command.Cli, backend api.Service, opts execOpts) error {
  71. projectName, err := opts.toProjectName(ctx, dockerCli)
  72. if err != nil {
  73. return err
  74. }
  75. projectOptions, err := opts.composeOptions.toProjectOptions()
  76. if err != nil {
  77. return err
  78. }
  79. lookupFn := func(k string) (string, bool) {
  80. v, ok := projectOptions.Environment[k]
  81. return v, ok
  82. }
  83. execOpts := api.RunOptions{
  84. Service: opts.service,
  85. Command: opts.command,
  86. Environment: compose.ToMobyEnv(types.NewMappingWithEquals(opts.environment).Resolve(lookupFn)),
  87. Tty: !opts.noTty,
  88. User: opts.user,
  89. Privileged: opts.privileged,
  90. Index: opts.index,
  91. Detach: opts.detach,
  92. WorkingDir: opts.workingDir,
  93. Interactive: opts.interactive,
  94. }
  95. exitCode, err := backend.Exec(ctx, projectName, execOpts)
  96. if exitCode != 0 {
  97. errMsg := ""
  98. if err != nil {
  99. errMsg = err.Error()
  100. }
  101. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  102. }
  103. return err
  104. }