run.go 7.3 KB

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