run.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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-isatty"
  22. "github.com/mattn/go-shellwords"
  23. "github.com/spf13/cobra"
  24. "github.com/docker/cli/cli"
  25. "github.com/docker/compose-cli/pkg/api"
  26. "github.com/docker/compose-cli/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. 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. 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 api.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. project, err := p.toProject([]string{opts.Service})
  112. if err != nil {
  113. return err
  114. }
  115. return runRun(ctx, backend, project, opts)
  116. }),
  117. }
  118. flags := cmd.Flags()
  119. flags.BoolVarP(&opts.Detach, "detach", "d", false, "Run container in background and print container ID")
  120. flags.StringArrayVarP(&opts.environment, "env", "e", []string{}, "Set environment variables")
  121. flags.StringArrayVarP(&opts.labels, "labels", "l", []string{}, "Add or override a label")
  122. flags.BoolVar(&opts.Remove, "rm", false, "Automatically remove the container when it exits")
  123. flags.BoolVarP(&opts.noTty, "no-TTY", "T", notAtTTY(), "Disable pseudo-noTty allocation. By default docker compose run allocates a TTY")
  124. flags.StringVar(&opts.name, "name", "", " Assign a name to the container")
  125. flags.StringVarP(&opts.user, "user", "u", "", "Run as specified username or uid")
  126. flags.StringVarP(&opts.workdir, "workdir", "w", "", "Working directory inside the container")
  127. flags.StringVar(&opts.entrypoint, "entrypoint", "", "Override the entrypoint of the image")
  128. flags.BoolVar(&opts.noDeps, "no-deps", false, "Don't start linked services.")
  129. flags.StringArrayVarP(&opts.volumes, "volumes", "v", []string{}, "Bind mount a volume.")
  130. flags.StringArrayVarP(&opts.publish, "publish", "p", []string{}, "Publish a container's port(s) to the host.")
  131. flags.BoolVar(&opts.useAliases, "use-aliases", false, "Use the service's network useAliases in the network(s) the container connects to.")
  132. flags.BoolVar(&opts.servicePorts, "service-ports", false, "Run command with the service's ports enabled and mapped to the host.")
  133. flags.SetInterspersed(false)
  134. return cmd
  135. }
  136. func notAtTTY() bool {
  137. return !isatty.IsTerminal(os.Stdout.Fd())
  138. }
  139. func runRun(ctx context.Context, backend api.Service, project *types.Project, opts runOptions) error {
  140. err := opts.apply(project)
  141. if err != nil {
  142. return err
  143. }
  144. err = progress.Run(ctx, func(ctx context.Context) error {
  145. return startDependencies(ctx, backend, *project, opts.Service)
  146. })
  147. if err != nil {
  148. return err
  149. }
  150. var entrypoint []string
  151. if opts.entrypoint != "" {
  152. entrypoint, err = shellwords.Parse(opts.entrypoint)
  153. if err != nil {
  154. return err
  155. }
  156. }
  157. labels := types.Labels{}
  158. for _, s := range opts.labels {
  159. parts := strings.SplitN(s, "=", 2)
  160. if len(parts) != 2 {
  161. return fmt.Errorf("label must be set as KEY=VALUE")
  162. }
  163. labels[parts[0]] = parts[1]
  164. }
  165. // start container and attach to container streams
  166. runOpts := api.RunOptions{
  167. Name: opts.name,
  168. Service: opts.Service,
  169. Command: opts.Command,
  170. Detach: opts.Detach,
  171. AutoRemove: opts.Remove,
  172. Stdin: os.Stdin,
  173. Stdout: os.Stdout,
  174. Stderr: os.Stderr,
  175. Tty: !opts.noTty,
  176. WorkingDir: opts.workdir,
  177. User: opts.user,
  178. Environment: opts.environment,
  179. Entrypoint: entrypoint,
  180. Labels: labels,
  181. UseNetworkAliases: opts.useAliases,
  182. Index: 0,
  183. }
  184. exitCode, err := backend.RunOneOffContainer(ctx, project, runOpts)
  185. if exitCode != 0 {
  186. errMsg := ""
  187. if err != nil {
  188. errMsg = err.Error()
  189. }
  190. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  191. }
  192. return err
  193. }
  194. func startDependencies(ctx context.Context, backend api.Service, project types.Project, requestedServiceName string) error {
  195. dependencies := types.Services{}
  196. var requestedService types.ServiceConfig
  197. for _, service := range project.Services {
  198. if service.Name != requestedServiceName {
  199. dependencies = append(dependencies, service)
  200. } else {
  201. requestedService = service
  202. }
  203. }
  204. project.Services = dependencies
  205. project.DisabledServices = append(project.DisabledServices, requestedService)
  206. if err := backend.Create(ctx, &project, api.CreateOptions{}); err != nil {
  207. return err
  208. }
  209. return backend.Start(ctx, &project, api.StartOptions{})
  210. }