run.go 4.6 KB

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