exec.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  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", notAtTTY(), "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().SetInterspersed(false)
  65. return runCmd
  66. }
  67. func runExec(ctx context.Context, backend api.Service, opts execOpts) error {
  68. projectName, err := opts.toProjectName()
  69. if err != nil {
  70. return err
  71. }
  72. projectOptions, err := opts.composeOptions.toProjectOptions()
  73. if err != nil {
  74. return err
  75. }
  76. lookupFn := func(k string) (string, bool) {
  77. v, ok := projectOptions.Environment[k]
  78. return v, ok
  79. }
  80. execOpts := api.RunOptions{
  81. Service: opts.service,
  82. Command: opts.command,
  83. Environment: compose.ToMobyEnv(types.NewMappingWithEquals(opts.environment).Resolve(lookupFn)),
  84. Tty: !opts.noTty,
  85. User: opts.user,
  86. Privileged: opts.privileged,
  87. Index: opts.index,
  88. Detach: opts.detach,
  89. WorkingDir: opts.workingDir,
  90. Stdin: os.Stdin,
  91. Stdout: os.Stdout,
  92. Stderr: os.Stderr,
  93. }
  94. if execOpts.Tty {
  95. con := console.Current()
  96. if err := con.SetRaw(); err != nil {
  97. return err
  98. }
  99. defer func() {
  100. if err := con.Reset(); err != nil {
  101. fmt.Println("Unable to close the console")
  102. }
  103. }()
  104. execOpts.Stdin = con
  105. execOpts.Stdout = con
  106. execOpts.Stderr = con
  107. }
  108. exitCode, err := backend.Exec(ctx, projectName, execOpts)
  109. if exitCode != 0 {
  110. errMsg := ""
  111. if err != nil {
  112. errMsg = err.Error()
  113. }
  114. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  115. }
  116. return err
  117. }