run.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. tty 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() (types.Mapping, error) {
  108. environment := types.NewMappingWithEquals(options.environment).Resolve(os.LookupEnv).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, backend api.Service) *cobra.Command {
  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. cmd := &cobra.Command{
  142. Use: "run [OPTIONS] SERVICE [COMMAND] [ARGS...]",
  143. Short: "Run a one-off command on a service",
  144. Args: cobra.MinimumNArgs(1),
  145. PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  146. options.Service = args[0]
  147. if len(args) > 1 {
  148. options.Command = args[1:]
  149. }
  150. if len(options.publish) > 0 && options.servicePorts {
  151. return fmt.Errorf("--service-ports and --publish are incompatible")
  152. }
  153. if cmd.Flags().Changed("entrypoint") {
  154. command, err := shellwords.Parse(options.entrypoint)
  155. if err != nil {
  156. return err
  157. }
  158. options.entrypointCmd = command
  159. }
  160. if cmd.Flags().Changed("tty") {
  161. if cmd.Flags().Changed("no-TTY") {
  162. return fmt.Errorf("--tty and --no-TTY can't be used together")
  163. } else {
  164. options.noTty = !options.tty
  165. }
  166. }
  167. if options.quiet {
  168. progress.Mode = progress.ModeQuiet
  169. devnull, err := os.Open(os.DevNull)
  170. if err != nil {
  171. return err
  172. }
  173. os.Stdout = devnull
  174. }
  175. createOpts.pullChanged = cmd.Flags().Changed("pull")
  176. return nil
  177. }),
  178. RunE: Adapt(func(ctx context.Context, args []string) error {
  179. project, _, err := p.ToProject(ctx, dockerCli, []string{options.Service}, cgo.WithResolvedPaths(true), cgo.WithoutEnvironmentResolution)
  180. if err != nil {
  181. return err
  182. }
  183. project, err = project.WithServicesEnvironmentResolved(true)
  184. if err != nil {
  185. return err
  186. }
  187. if createOpts.quietPull {
  188. buildOpts.Progress = string(xprogress.QuietMode)
  189. }
  190. options.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans])
  191. return runRun(ctx, backend, project, options, createOpts, buildOpts, dockerCli)
  192. }),
  193. ValidArgsFunction: completeServiceNames(dockerCli, p),
  194. }
  195. flags := cmd.Flags()
  196. flags.BoolVarP(&options.Detach, "detach", "d", false, "Run container in background and print container ID")
  197. flags.StringArrayVarP(&options.environment, "env", "e", []string{}, "Set environment variables")
  198. flags.StringArrayVar(&options.envFiles, "env-from-file", []string{}, "Set environment variables from file")
  199. flags.StringArrayVarP(&options.labels, "label", "l", []string{}, "Add or override a label")
  200. flags.BoolVar(&options.Remove, "rm", false, "Automatically remove the container when it exits")
  201. flags.BoolVarP(&options.noTty, "no-TTY", "T", !dockerCli.Out().IsTerminal(), "Disable pseudo-TTY allocation (default: auto-detected)")
  202. flags.StringVar(&options.name, "name", "", "Assign a name to the container")
  203. flags.StringVarP(&options.user, "user", "u", "", "Run as specified username or uid")
  204. flags.StringVarP(&options.workdir, "workdir", "w", "", "Working directory inside the container")
  205. flags.StringVar(&options.entrypoint, "entrypoint", "", "Override the entrypoint of the image")
  206. flags.Var(&options.capAdd, "cap-add", "Add Linux capabilities")
  207. flags.Var(&options.capDrop, "cap-drop", "Drop Linux capabilities")
  208. flags.BoolVar(&options.noDeps, "no-deps", false, "Don't start linked services")
  209. flags.StringArrayVarP(&options.volumes, "volume", "v", []string{}, "Bind mount a volume")
  210. flags.StringArrayVarP(&options.publish, "publish", "p", []string{}, "Publish a container's port(s) to the host")
  211. flags.BoolVar(&options.useAliases, "use-aliases", false, "Use the service's network useAliases in the network(s) the container connects to")
  212. flags.BoolVarP(&options.servicePorts, "service-ports", "P", false, "Run command with all service's ports enabled and mapped to the host")
  213. flags.StringVar(&createOpts.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never")`)
  214. flags.BoolVarP(&options.quiet, "quiet", "q", false, "Don't print anything to STDOUT")
  215. flags.BoolVar(&buildOpts.quiet, "quiet-build", false, "Suppress progress output from the build process")
  216. flags.BoolVar(&options.quietPull, "quiet-pull", false, "Pull without printing progress information")
  217. flags.BoolVar(&createOpts.Build, "build", false, "Build image before starting container")
  218. flags.BoolVar(&options.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file")
  219. cmd.Flags().BoolVarP(&options.interactive, "interactive", "i", true, "Keep STDIN open even if not attached")
  220. cmd.Flags().BoolVarP(&options.tty, "tty", "t", true, "Allocate a pseudo-TTY")
  221. cmd.Flags().MarkHidden("tty") //nolint:errcheck
  222. flags.SetNormalizeFunc(normalizeRunFlags)
  223. flags.SetInterspersed(false)
  224. return cmd
  225. }
  226. func normalizeRunFlags(f *pflag.FlagSet, name string) pflag.NormalizedName {
  227. switch name {
  228. case "volumes":
  229. name = "volume"
  230. case "labels":
  231. name = "label"
  232. }
  233. return pflag.NormalizedName(name)
  234. }
  235. func runRun(ctx context.Context, backend api.Service, project *types.Project, options runOptions, createOpts createOptions, buildOpts buildOptions, dockerCli command.Cli) error {
  236. project, err := options.apply(project)
  237. if err != nil {
  238. return err
  239. }
  240. err = createOpts.Apply(project)
  241. if err != nil {
  242. return err
  243. }
  244. if err := checksForRemoteStack(ctx, dockerCli, project, buildOpts, createOpts.AssumeYes, []string{}); err != nil {
  245. return err
  246. }
  247. err = progress.Run(ctx, func(ctx context.Context) error {
  248. var buildForDeps *api.BuildOptions
  249. if !createOpts.noBuild {
  250. // allow dependencies needing build to be implicitly selected
  251. bo, err := buildOpts.toAPIBuildOptions(nil)
  252. if err != nil {
  253. return err
  254. }
  255. buildForDeps = &bo
  256. }
  257. return startDependencies(ctx, backend, *project, buildForDeps, options)
  258. }, dockerCli.Err())
  259. if err != nil {
  260. return err
  261. }
  262. labels := types.Labels{}
  263. for _, s := range options.labels {
  264. parts := strings.SplitN(s, "=", 2)
  265. if len(parts) != 2 {
  266. return fmt.Errorf("label must be set as KEY=VALUE")
  267. }
  268. labels[parts[0]] = parts[1]
  269. }
  270. var buildForRun *api.BuildOptions
  271. if !createOpts.noBuild {
  272. // dependencies have already been started above, so only the service
  273. // being run might need to be built at this point
  274. bo, err := buildOpts.toAPIBuildOptions([]string{options.Service})
  275. if err != nil {
  276. return err
  277. }
  278. buildForRun = &bo
  279. }
  280. environment, err := options.getEnvironment()
  281. if err != nil {
  282. return err
  283. }
  284. // start container and attach to container streams
  285. runOpts := api.RunOptions{
  286. Build: buildForRun,
  287. Name: options.name,
  288. Service: options.Service,
  289. Command: options.Command,
  290. Detach: options.Detach,
  291. AutoRemove: options.Remove,
  292. Tty: !options.noTty,
  293. Interactive: options.interactive,
  294. WorkingDir: options.workdir,
  295. User: options.user,
  296. CapAdd: options.capAdd.GetSlice(),
  297. CapDrop: options.capDrop.GetSlice(),
  298. Environment: environment.Values(),
  299. Entrypoint: options.entrypointCmd,
  300. Labels: labels,
  301. UseNetworkAliases: options.useAliases,
  302. NoDeps: options.noDeps,
  303. Index: 0,
  304. QuietPull: options.quietPull,
  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. }
  322. func startDependencies(ctx context.Context, backend api.Service, project types.Project, buildOpts *api.BuildOptions, options runOptions) error {
  323. dependencies := types.Services{}
  324. var requestedService types.ServiceConfig
  325. for name, service := range project.Services {
  326. if name != options.Service {
  327. dependencies[name] = service
  328. } else {
  329. requestedService = service
  330. }
  331. }
  332. project.Services = dependencies
  333. project.DisabledServices[options.Service] = requestedService
  334. err := backend.Create(ctx, &project, api.CreateOptions{
  335. Build: buildOpts,
  336. IgnoreOrphans: options.ignoreOrphans,
  337. RemoveOrphans: options.removeOrphans,
  338. QuietPull: options.quietPull,
  339. })
  340. if err != nil {
  341. return err
  342. }
  343. if len(dependencies) > 0 {
  344. return backend.Start(ctx, project.Name, api.StartOptions{
  345. Project: &project,
  346. })
  347. }
  348. return nil
  349. }