run.go 7.3 KB

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