run.go 7.5 KB

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