run.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. "strings"
  19. "github.com/compose-spec/compose-go/types"
  20. "github.com/mattn/go-shellwords"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose-cli/api/client"
  23. "github.com/docker/compose-cli/api/compose"
  24. "github.com/docker/compose-cli/api/progress"
  25. "github.com/docker/compose-cli/cli/cmd"
  26. )
  27. type runOptions struct {
  28. *composeOptions
  29. Service string
  30. Command []string
  31. environment []string
  32. Detach bool
  33. Remove bool
  34. noTty bool
  35. user string
  36. workdir string
  37. entrypoint string
  38. labels []string
  39. name string
  40. noDeps bool
  41. }
  42. func runCommand(p *projectOptions) *cobra.Command {
  43. opts := runOptions{
  44. composeOptions: &composeOptions{
  45. projectOptions: p,
  46. },
  47. }
  48. cmd := &cobra.Command{
  49. Use: "run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...]",
  50. Short: "Run a one-off command on a service.",
  51. Args: cobra.MinimumNArgs(1),
  52. RunE: func(cmd *cobra.Command, args []string) error {
  53. if len(args) > 1 {
  54. opts.Command = args[1:]
  55. }
  56. opts.Service = args[0]
  57. return runRun(cmd.Context(), opts)
  58. },
  59. }
  60. flags := cmd.Flags()
  61. flags.BoolVarP(&opts.Detach, "detach", "d", false, "Run container in background and print container ID")
  62. flags.StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables")
  63. flags.StringArrayVarP(&opts.labels, "labels", "l", []string{}, "Add or override a label")
  64. flags.BoolVar(&opts.Remove, "rm", false, "Automatically remove the container when it exits")
  65. flags.BoolVarP(&opts.noTty, "no-TTY", "T", false, "Disable pseudo-tty allocation. By default docker compose run allocates a TTY")
  66. flags.StringVar(&opts.name, "name", "", " Assign a name to the container")
  67. flags.StringVarP(&opts.user, "user", "u", "", "Run as specified username or uid")
  68. flags.StringVarP(&opts.workdir, "workdir", "w", "", "Working directory inside the container")
  69. flags.StringVar(&opts.entrypoint, "entrypoint", "", "Override the entrypoint of the image")
  70. flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't start linked services.")
  71. flags.SetInterspersed(false)
  72. return cmd
  73. }
  74. func runRun(ctx context.Context, opts runOptions) error {
  75. c, project, err := setup(ctx, *opts.composeOptions, []string{opts.Service})
  76. if err != nil {
  77. return err
  78. }
  79. if opts.noDeps {
  80. enabled, err := project.GetService(opts.Service)
  81. if err != nil {
  82. return err
  83. }
  84. for _, s := range project.Services {
  85. if s.Name != opts.Service {
  86. project.DisabledServices = append(project.DisabledServices, s)
  87. }
  88. }
  89. project.Services = types.Services{enabled}
  90. }
  91. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  92. return "", startDependencies(ctx, c, *project, opts.Service)
  93. })
  94. if err != nil {
  95. return err
  96. }
  97. var entrypoint []string
  98. if opts.entrypoint != "" {
  99. entrypoint, err = shellwords.Parse(opts.entrypoint)
  100. if err != nil {
  101. return err
  102. }
  103. }
  104. labels := types.Labels{}
  105. for _, s := range opts.labels {
  106. parts := strings.SplitN(s, "=", 2)
  107. if len(parts) != 2 {
  108. return fmt.Errorf("label must be set as KEY=VALUE")
  109. }
  110. labels[parts[0]] = parts[1]
  111. }
  112. // start container and attach to container streams
  113. runOpts := compose.RunOptions{
  114. Name: opts.name,
  115. Service: opts.Service,
  116. Command: opts.Command,
  117. Detach: opts.Detach,
  118. AutoRemove: opts.Remove,
  119. Writer: os.Stdout,
  120. Reader: os.Stdin,
  121. Tty: !opts.noTty,
  122. WorkingDir: opts.workdir,
  123. User: opts.user,
  124. Environment: opts.environment,
  125. Entrypoint: entrypoint,
  126. Labels: labels,
  127. Index: 0,
  128. }
  129. exitCode, err := c.ComposeService().RunOneOffContainer(ctx, project, runOpts)
  130. if exitCode != 0 {
  131. return cmd.ExitCodeError{ExitCode: exitCode}
  132. }
  133. return err
  134. }
  135. func startDependencies(ctx context.Context, c *client.Client, project types.Project, requestedServiceName string) error {
  136. dependencies := types.Services{}
  137. var requestedService types.ServiceConfig
  138. for _, service := range project.Services {
  139. if service.Name != requestedServiceName {
  140. dependencies = append(dependencies, service)
  141. } else {
  142. requestedService = service
  143. }
  144. }
  145. project.Services = dependencies
  146. project.DisabledServices = append(project.DisabledServices, requestedService)
  147. if err := c.ComposeService().Create(ctx, &project, compose.CreateOptions{}); err != nil {
  148. return err
  149. }
  150. if err := c.ComposeService().Start(ctx, &project, compose.StartOptions{}); err != nil {
  151. return err
  152. }
  153. return nil
  154. }