run.go 8.0 KB

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