run.go 6.7 KB

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