run.go 7.9 KB

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