run.go 8.1 KB

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