run.go 11 KB

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