run.go 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. cgo "github.com/compose-spec/compose-go/cli"
  20. "github.com/compose-spec/compose-go/loader"
  21. "github.com/compose-spec/compose-go/types"
  22. "github.com/mattn/go-isatty"
  23. "github.com/mattn/go-shellwords"
  24. "github.com/spf13/cobra"
  25. "github.com/docker/cli/cli"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/pkg/progress"
  28. )
  29. type runOptions struct {
  30. *composeOptions
  31. Service string
  32. Command []string
  33. environment []string
  34. Detach bool
  35. Remove bool
  36. noTty bool
  37. user string
  38. workdir string
  39. entrypoint string
  40. labels []string
  41. volumes []string
  42. publish []string
  43. useAliases bool
  44. servicePorts bool
  45. name string
  46. noDeps bool
  47. }
  48. func (opts runOptions) apply(project *types.Project) error {
  49. target, err := project.GetService(opts.Service)
  50. if err != nil {
  51. return err
  52. }
  53. if !opts.servicePorts {
  54. target.Ports = []types.ServicePortConfig{}
  55. }
  56. if len(opts.publish) > 0 {
  57. target.Ports = []types.ServicePortConfig{}
  58. for _, p := range opts.publish {
  59. config, err := types.ParsePortConfig(p)
  60. if err != nil {
  61. return err
  62. }
  63. target.Ports = append(target.Ports, config...)
  64. }
  65. }
  66. if len(opts.volumes) > 0 {
  67. for _, v := range opts.volumes {
  68. volume, err := loader.ParseVolume(v)
  69. if err != nil {
  70. return err
  71. }
  72. target.Volumes = append(target.Volumes, volume)
  73. }
  74. }
  75. if opts.noDeps {
  76. for _, s := range project.Services {
  77. if s.Name != opts.Service {
  78. project.DisabledServices = append(project.DisabledServices, s)
  79. }
  80. }
  81. project.Services = types.Services{target}
  82. }
  83. for i, s := range project.Services {
  84. if s.Name == opts.Service {
  85. project.Services[i] = target
  86. break
  87. }
  88. }
  89. return nil
  90. }
  91. func runCommand(p *projectOptions, backend api.Service) *cobra.Command {
  92. opts := runOptions{
  93. composeOptions: &composeOptions{
  94. projectOptions: p,
  95. },
  96. }
  97. cmd := &cobra.Command{
  98. Use: "run [options] [-v VOLUME...] [-p PORT...] [-e KEY=VAL...] [-l KEY=VALUE...] SERVICE [COMMAND] [ARGS...]",
  99. Short: "Run a one-off command on a service.",
  100. Args: cobra.MinimumNArgs(1),
  101. PreRunE: Adapt(func(ctx context.Context, args []string) error {
  102. opts.Service = args[0]
  103. if len(args) > 1 {
  104. opts.Command = args[1:]
  105. }
  106. if len(opts.publish) > 0 && opts.servicePorts {
  107. return fmt.Errorf("--service-ports and --publish are incompatible")
  108. }
  109. return nil
  110. }),
  111. RunE: Adapt(func(ctx context.Context, args []string) error {
  112. project, err := p.toProject([]string{opts.Service}, cgo.WithResolvedPaths(true))
  113. if err != nil {
  114. return err
  115. }
  116. return runRun(ctx, backend, project, opts)
  117. }),
  118. ValidArgsFunction: serviceCompletion(p),
  119. }
  120. flags := cmd.Flags()
  121. flags.BoolVarP(&opts.Detach, "detach", "d", false, "Run container in background and print container ID")
  122. flags.StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables")
  123. flags.StringArrayVarP(&opts.labels, "labels", "l", []string{}, "Add or override a label")
  124. flags.BoolVar(&opts.Remove, "rm", false, "Automatically remove the container when it exits")
  125. flags.BoolVarP(&opts.noTty, "no-TTY", "T", notAtTTY(), "Disable pseudo-noTty allocation. By default docker compose run allocates a TTY")
  126. flags.StringVar(&opts.name, "name", "", " Assign a name to the container")
  127. flags.StringVarP(&opts.user, "user", "u", "", "Run as specified username or uid")
  128. flags.StringVarP(&opts.workdir, "workdir", "w", "", "Working directory inside the container")
  129. flags.StringVar(&opts.entrypoint, "entrypoint", "", "Override the entrypoint of the image")
  130. flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't start linked services.")
  131. flags.StringArrayVarP(&opts.volumes, "volumes", "v", []string{}, "Bind mount a volume.")
  132. flags.StringArrayVarP(&opts.publish, "publish", "p", []string{}, "Publish a container's port(s) to the host.")
  133. flags.BoolVar(&opts.useAliases, "use-aliases", false, "Use the service's network useAliases in the network(s) the container connects to.")
  134. flags.BoolVar(&opts.servicePorts, "service-ports", false, "Run command with the service's ports enabled and mapped to the host.")
  135. flags.SetInterspersed(false)
  136. return cmd
  137. }
  138. func notAtTTY() bool {
  139. return !isatty.IsTerminal(os.Stdout.Fd())
  140. }
  141. func runRun(ctx context.Context, backend api.Service, project *types.Project, opts runOptions) error {
  142. err := opts.apply(project)
  143. if err != nil {
  144. return err
  145. }
  146. err = progress.Run(ctx, func(ctx context.Context) error {
  147. return startDependencies(ctx, backend, *project, opts.Service)
  148. })
  149. if err != nil {
  150. return err
  151. }
  152. var entrypoint []string
  153. if opts.entrypoint != "" {
  154. entrypoint, err = shellwords.Parse(opts.entrypoint)
  155. if err != nil {
  156. return err
  157. }
  158. }
  159. labels := types.Labels{}
  160. for _, s := range opts.labels {
  161. parts := strings.SplitN(s, "=", 2)
  162. if len(parts) != 2 {
  163. return fmt.Errorf("label must be set as KEY=VALUE")
  164. }
  165. labels[parts[0]] = parts[1]
  166. }
  167. // start container and attach to container streams
  168. runOpts := api.RunOptions{
  169. Name: opts.name,
  170. Service: opts.Service,
  171. Command: opts.Command,
  172. Detach: opts.Detach,
  173. AutoRemove: opts.Remove,
  174. Stdin: os.Stdin,
  175. Stdout: os.Stdout,
  176. Stderr: os.Stderr,
  177. Tty: !opts.noTty,
  178. WorkingDir: opts.workdir,
  179. User: opts.user,
  180. Environment: opts.environment,
  181. Entrypoint: entrypoint,
  182. Labels: labels,
  183. UseNetworkAliases: opts.useAliases,
  184. Index: 0,
  185. }
  186. exitCode, err := backend.RunOneOffContainer(ctx, project, runOpts)
  187. if exitCode != 0 {
  188. errMsg := ""
  189. if err != nil {
  190. errMsg = err.Error()
  191. }
  192. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  193. }
  194. return err
  195. }
  196. func startDependencies(ctx context.Context, backend api.Service, project types.Project, requestedServiceName string) error {
  197. dependencies := types.Services{}
  198. var requestedService types.ServiceConfig
  199. for _, service := range project.Services {
  200. if service.Name != requestedServiceName {
  201. dependencies = append(dependencies, service)
  202. } else {
  203. requestedService = service
  204. }
  205. }
  206. project.Services = dependencies
  207. project.DisabledServices = append(project.DisabledServices, requestedService)
  208. if err := backend.Create(ctx, &project, api.CreateOptions{}); err != nil {
  209. return err
  210. }
  211. return backend.Start(ctx, &project, api.StartOptions{})
  212. }