run.go 10 KB

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