run.go 8.2 KB

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