run.go 10 KB

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