run.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "strings"
  18. cgo "github.com/compose-spec/compose-go/cli"
  19. "github.com/compose-spec/compose-go/loader"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/docker/cli/opts"
  22. "github.com/mattn/go-shellwords"
  23. "github.com/spf13/cobra"
  24. "github.com/spf13/pflag"
  25. "github.com/docker/cli/cli"
  26. "github.com/docker/compose/v2/pkg/api"
  27. "github.com/docker/compose/v2/pkg/progress"
  28. "github.com/docker/compose/v2/pkg/utils"
  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. tty bool
  39. interactive bool
  40. user string
  41. workdir string
  42. entrypoint string
  43. entrypointCmd []string
  44. capAdd opts.ListOpts
  45. capDrop opts.ListOpts
  46. labels []string
  47. volumes []string
  48. publish []string
  49. useAliases bool
  50. servicePorts bool
  51. name string
  52. noDeps bool
  53. ignoreOrphans bool
  54. quietPull bool
  55. }
  56. func (options runOptions) apply(project *types.Project) error {
  57. if options.noDeps {
  58. err := project.ForServices([]string{options.Service}, types.IgnoreDependencies)
  59. if err != nil {
  60. return err
  61. }
  62. }
  63. target, err := project.GetService(options.Service)
  64. if err != nil {
  65. return err
  66. }
  67. target.Tty = !options.noTty
  68. target.StdinOpen = options.interactive
  69. if !options.servicePorts {
  70. target.Ports = []types.ServicePortConfig{}
  71. }
  72. if len(options.publish) > 0 {
  73. target.Ports = []types.ServicePortConfig{}
  74. for _, p := range options.publish {
  75. config, err := types.ParsePortConfig(p)
  76. if err != nil {
  77. return err
  78. }
  79. target.Ports = append(target.Ports, config...)
  80. }
  81. }
  82. if len(options.volumes) > 0 {
  83. for _, v := range options.volumes {
  84. volume, err := loader.ParseVolume(v)
  85. if err != nil {
  86. return err
  87. }
  88. target.Volumes = append(target.Volumes, volume)
  89. }
  90. }
  91. for i, s := range project.Services {
  92. if s.Name == options.Service {
  93. project.Services[i] = target
  94. break
  95. }
  96. }
  97. return nil
  98. }
  99. func runCommand(p *ProjectOptions, streams api.Streams, backend api.Service) *cobra.Command {
  100. options := runOptions{
  101. composeOptions: &composeOptions{
  102. ProjectOptions: p,
  103. },
  104. capAdd: opts.NewListOpts(nil),
  105. capDrop: opts.NewListOpts(nil),
  106. }
  107. createOpts := createOptions{}
  108. cmd := &cobra.Command{
  109. Use: "run [OPTIONS] SERVICE [COMMAND] [ARGS...]",
  110. Short: "Run a one-off command on a service.",
  111. Args: cobra.MinimumNArgs(1),
  112. PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  113. options.Service = args[0]
  114. if len(args) > 1 {
  115. options.Command = args[1:]
  116. }
  117. if len(options.publish) > 0 && options.servicePorts {
  118. return fmt.Errorf("--service-ports and --publish are incompatible")
  119. }
  120. if cmd.Flags().Changed("entrypoint") {
  121. command, err := shellwords.Parse(options.entrypoint)
  122. if err != nil {
  123. return err
  124. }
  125. options.entrypointCmd = command
  126. }
  127. if cmd.Flags().Changed("tty") {
  128. if cmd.Flags().Changed("no-TTY") {
  129. return fmt.Errorf("--tty and --no-TTY can't be used together")
  130. } else {
  131. options.noTty = !options.tty
  132. }
  133. }
  134. return nil
  135. }),
  136. RunE: Adapt(func(ctx context.Context, args []string) error {
  137. project, err := p.ToProject([]string{options.Service}, cgo.WithResolvedPaths(true), cgo.WithDiscardEnvFile)
  138. if err != nil {
  139. return err
  140. }
  141. options.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans])
  142. return runRun(ctx, backend, project, options, createOpts, streams)
  143. }),
  144. ValidArgsFunction: completeServiceNames(p),
  145. }
  146. flags := cmd.Flags()
  147. flags.BoolVarP(&options.Detach, "detach", "d", false, "Run container in background and print container ID")
  148. flags.StringArrayVarP(&options.environment, "env", "e", []string{}, "Set environment variables")
  149. flags.StringArrayVarP(&options.labels, "label", "l", []string{}, "Add or override a label")
  150. flags.BoolVar(&options.Remove, "rm", false, "Automatically remove the container when it exits")
  151. flags.BoolVarP(&options.noTty, "no-TTY", "T", !streams.Out().IsTerminal(), "Disable pseudo-TTY allocation (default: auto-detected).")
  152. flags.StringVar(&options.name, "name", "", "Assign a name to the container")
  153. flags.StringVarP(&options.user, "user", "u", "", "Run as specified username or uid")
  154. flags.StringVarP(&options.workdir, "workdir", "w", "", "Working directory inside the container")
  155. flags.StringVar(&options.entrypoint, "entrypoint", "", "Override the entrypoint of the image")
  156. flags.Var(&options.capAdd, "cap-add", "Add Linux capabilities")
  157. flags.Var(&options.capDrop, "cap-drop", "Drop Linux capabilities")
  158. flags.BoolVar(&options.noDeps, "no-deps", false, "Don't start linked services.")
  159. flags.StringArrayVarP(&options.volumes, "volume", "v", []string{}, "Bind mount a volume.")
  160. flags.StringArrayVarP(&options.publish, "publish", "p", []string{}, "Publish a container's port(s) to the host.")
  161. flags.BoolVar(&options.useAliases, "use-aliases", false, "Use the service's network useAliases in the network(s) the container connects to.")
  162. flags.BoolVar(&options.servicePorts, "service-ports", false, "Run command with the service's ports enabled and mapped to the host.")
  163. flags.BoolVar(&options.quietPull, "quiet-pull", false, "Pull without printing progress information.")
  164. flags.BoolVar(&createOpts.Build, "build", false, "Build image before starting container.")
  165. flags.BoolVar(&createOpts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  166. cmd.Flags().BoolVarP(&options.interactive, "interactive", "i", true, "Keep STDIN open even if not attached.")
  167. cmd.Flags().BoolVarP(&options.tty, "tty", "t", true, "Allocate a pseudo-TTY.")
  168. cmd.Flags().MarkHidden("tty") //nolint:errcheck
  169. flags.SetNormalizeFunc(normalizeRunFlags)
  170. flags.SetInterspersed(false)
  171. return cmd
  172. }
  173. func normalizeRunFlags(f *pflag.FlagSet, name string) pflag.NormalizedName {
  174. switch name {
  175. case "volumes":
  176. name = "volume"
  177. case "labels":
  178. name = "label"
  179. }
  180. return pflag.NormalizedName(name)
  181. }
  182. func runRun(ctx context.Context, backend api.Service, project *types.Project, options runOptions, createOpts createOptions, streams api.Streams) error {
  183. err := options.apply(project)
  184. if err != nil {
  185. return err
  186. }
  187. err = createOpts.Apply(project)
  188. if err != nil {
  189. return err
  190. }
  191. err = progress.Run(ctx, func(ctx context.Context) error {
  192. return startDependencies(ctx, backend, *project, options.Service, options.ignoreOrphans)
  193. }, streams.Err())
  194. if err != nil {
  195. return err
  196. }
  197. labels := types.Labels{}
  198. for _, s := range options.labels {
  199. parts := strings.SplitN(s, "=", 2)
  200. if len(parts) != 2 {
  201. return fmt.Errorf("label must be set as KEY=VALUE")
  202. }
  203. labels[parts[0]] = parts[1]
  204. }
  205. // start container and attach to container streams
  206. runOpts := api.RunOptions{
  207. Name: options.name,
  208. Service: options.Service,
  209. Command: options.Command,
  210. Detach: options.Detach,
  211. AutoRemove: options.Remove,
  212. Tty: !options.noTty,
  213. Interactive: options.interactive,
  214. WorkingDir: options.workdir,
  215. User: options.user,
  216. CapAdd: options.capAdd.GetAll(),
  217. CapDrop: options.capDrop.GetAll(),
  218. Environment: options.environment,
  219. Entrypoint: options.entrypointCmd,
  220. Labels: labels,
  221. UseNetworkAliases: options.useAliases,
  222. NoDeps: options.noDeps,
  223. Index: 0,
  224. QuietPull: options.quietPull,
  225. }
  226. for i, service := range project.Services {
  227. if service.Name == options.Service {
  228. service.StdinOpen = options.interactive
  229. project.Services[i] = service
  230. }
  231. }
  232. exitCode, err := backend.RunOneOffContainer(ctx, project, runOpts)
  233. if exitCode != 0 {
  234. errMsg := ""
  235. if err != nil {
  236. errMsg = err.Error()
  237. }
  238. return cli.StatusError{StatusCode: exitCode, Status: errMsg}
  239. }
  240. return err
  241. }
  242. func startDependencies(ctx context.Context, backend api.Service, project types.Project, requestedServiceName string, ignoreOrphans bool) error {
  243. dependencies := types.Services{}
  244. var requestedService types.ServiceConfig
  245. for _, service := range project.Services {
  246. if service.Name != requestedServiceName {
  247. dependencies = append(dependencies, service)
  248. } else {
  249. requestedService = service
  250. }
  251. }
  252. project.Services = dependencies
  253. project.DisabledServices = append(project.DisabledServices, requestedService)
  254. err := backend.Create(ctx, &project, api.CreateOptions{
  255. IgnoreOrphans: ignoreOrphans,
  256. })
  257. if err != nil {
  258. return err
  259. }
  260. if len(dependencies) > 0 {
  261. return backend.Start(ctx, project.Name, api.StartOptions{
  262. Project: &project,
  263. })
  264. }
  265. return nil
  266. }