run.go 6.7 KB

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