run.go 10 KB

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