run.go 8.6 KB

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