run.go 11 KB

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