run.go 8.6 KB

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