run.go 11 KB

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