exec.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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. "github.com/compose-spec/compose-go/types"
  19. "github.com/containerd/console"
  20. "github.com/docker/cli/cli"
  21. "github.com/docker/compose/v2/pkg/api"
  22. "github.com/docker/compose/v2/pkg/compose"
  23. "github.com/spf13/cobra"
  24. )
  25. type execOpts struct {
  26. *composeOptions
  27. service string
  28. command []string
  29. environment []string
  30. workingDir string
  31. noTty bool
  32. user string
  33. detach bool
  34. index int
  35. privileged bool
  36. }
  37. func execCommand(p *projectOptions, backend api.Service) *cobra.Command {
  38. opts := execOpts{
  39. composeOptions: &composeOptions{
  40. projectOptions: p,
  41. },
  42. }
  43. runCmd := &cobra.Command{
  44. Use: "exec [options] [-e KEY=VAL...] [--] 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, backend, opts)
  54. }),
  55. ValidArgsFunction: serviceCompletion(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", 1, "index of the container if there are multiple instances of a service [default: 1].")
  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", false, "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().BoolP("interactive", "i", true, "Keep STDIN open even if not attached. DEPRECATED")
  65. runCmd.Flags().MarkHidden("interactive") //nolint:errcheck
  66. runCmd.Flags().BoolP("tty", "t", true, "Allocate a pseudo-TTY. DEPRECATED")
  67. runCmd.Flags().MarkHidden("tty") //nolint:errcheck
  68. runCmd.Flags().SetInterspersed(false)
  69. return runCmd
  70. }
  71. func runExec(ctx context.Context, backend api.Service, opts execOpts) error {
  72. projectName, err := opts.toProjectName()
  73. if err != nil {
  74. return err
  75. }
  76. projectOptions, err := opts.composeOptions.toProjectOptions()
  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. Stdin: os.Stdin,
  95. Stdout: os.Stdout,
  96. Stderr: os.Stderr,
  97. }
  98. if execOpts.Tty {
  99. con := console.Current()
  100. if err := con.SetRaw(); err != nil {
  101. return err
  102. }
  103. defer func() {
  104. if err := con.Reset(); err != nil {
  105. fmt.Println("Unable to close the console")
  106. }
  107. }()
  108. execOpts.Stdin = con
  109. execOpts.Stdout = con
  110. execOpts.Stderr = con
  111. }
  112. exitCode, err := backend.Exec(ctx, projectName, execOpts)
  113. if exitCode != 0 {
  114. errMsg := ""
  115. if err != nil {
  116. errMsg = err.Error()
  117. }
  118. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  119. }
  120. return err
  121. }