run.go 12 KB

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