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