run.go 11 KB

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