up.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  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. "strconv"
  18. "strings"
  19. "github.com/docker/compose/v2/cmd/formatter"
  20. "github.com/compose-spec/compose-go/types"
  21. "github.com/spf13/cobra"
  22. "github.com/docker/compose/v2/pkg/api"
  23. "github.com/docker/compose/v2/pkg/utils"
  24. )
  25. // composeOptions hold options common to `up` and `run` to run compose project
  26. type composeOptions struct {
  27. *ProjectOptions
  28. }
  29. type upOptions struct {
  30. *composeOptions
  31. Detach bool
  32. noStart bool
  33. noDeps bool
  34. cascadeStop bool
  35. exitCodeFrom string
  36. scale []string
  37. noColor bool
  38. noPrefix bool
  39. attachDependencies bool
  40. attach []string
  41. noAttach []string
  42. timestamp bool
  43. wait bool
  44. }
  45. func (opts upOptions) apply(project *types.Project, services []string) error {
  46. if opts.noDeps {
  47. err := withSelectedServicesOnly(project, services)
  48. if err != nil {
  49. return err
  50. }
  51. }
  52. if opts.exitCodeFrom != "" {
  53. _, err := project.GetService(opts.exitCodeFrom)
  54. if err != nil {
  55. return err
  56. }
  57. }
  58. for _, scale := range opts.scale {
  59. split := strings.Split(scale, "=")
  60. if len(split) != 2 {
  61. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  62. }
  63. name := split[0]
  64. replicas, err := strconv.Atoi(split[1])
  65. if err != nil {
  66. return err
  67. }
  68. err = setServiceScale(project, name, uint64(replicas))
  69. if err != nil {
  70. return err
  71. }
  72. }
  73. return nil
  74. }
  75. func upCommand(p *ProjectOptions, streams api.Streams, backend api.Service) *cobra.Command {
  76. up := upOptions{}
  77. create := createOptions{}
  78. upCmd := &cobra.Command{
  79. Use: "up [OPTIONS] [SERVICE...]",
  80. Short: "Create and start containers",
  81. PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  82. create.pullChanged = cmd.Flags().Changed("pull")
  83. create.timeChanged = cmd.Flags().Changed("timeout")
  84. return validateFlags(&up, &create)
  85. }),
  86. RunE: p.WithServices(func(ctx context.Context, project *types.Project, services []string) error {
  87. create.ignoreOrphans = utils.StringToBool(project.Environment["COMPOSE_IGNORE_ORPHANS"])
  88. if create.ignoreOrphans && create.removeOrphans {
  89. return fmt.Errorf("COMPOSE_IGNORE_ORPHANS and --remove-orphans cannot be combined")
  90. }
  91. return runUp(ctx, streams, backend, create, up, project, services)
  92. }),
  93. ValidArgsFunction: completeServiceNames(p),
  94. }
  95. flags := upCmd.Flags()
  96. flags.BoolVarP(&up.Detach, "detach", "d", false, "Detached mode: Run containers in the background")
  97. flags.BoolVar(&create.Build, "build", false, "Build images before starting containers.")
  98. flags.BoolVar(&create.noBuild, "no-build", false, "Don't build an image, even if it's missing.")
  99. flags.StringVar(&create.Pull, "pull", "missing", `Pull image before running ("always"|"missing"|"never")`)
  100. flags.BoolVar(&create.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  101. flags.StringArrayVar(&up.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
  102. flags.BoolVar(&up.noColor, "no-color", false, "Produce monochrome output.")
  103. flags.BoolVar(&up.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  104. flags.BoolVar(&create.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed.")
  105. flags.BoolVar(&create.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  106. flags.BoolVar(&up.noStart, "no-start", false, "Don't start the services after creating them.")
  107. flags.BoolVar(&up.cascadeStop, "abort-on-container-exit", false, "Stops all containers if any container was stopped. Incompatible with -d")
  108. flags.StringVar(&up.exitCodeFrom, "exit-code-from", "", "Return the exit code of the selected service container. Implies --abort-on-container-exit")
  109. flags.IntVarP(&create.timeout, "timeout", "t", 10, "Use this timeout in seconds for container shutdown when attached or when containers are already running.")
  110. flags.BoolVar(&up.timestamp, "timestamps", false, "Show timestamps.")
  111. flags.BoolVar(&up.noDeps, "no-deps", false, "Don't start linked services.")
  112. flags.BoolVar(&create.recreateDeps, "always-recreate-deps", false, "Recreate dependent containers. Incompatible with --no-recreate.")
  113. flags.BoolVarP(&create.noInherit, "renew-anon-volumes", "V", false, "Recreate anonymous volumes instead of retrieving data from the previous containers.")
  114. flags.BoolVar(&up.attachDependencies, "attach-dependencies", false, "Attach to dependent containers.")
  115. flags.BoolVar(&create.quietPull, "quiet-pull", false, "Pull without printing progress information.")
  116. flags.StringArrayVar(&up.attach, "attach", []string{}, "Attach to service output.")
  117. flags.StringArrayVar(&up.noAttach, "no-attach", []string{}, "Don't attach to specified service.")
  118. flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.")
  119. return upCmd
  120. }
  121. func validateFlags(up *upOptions, create *createOptions) error {
  122. if up.exitCodeFrom != "" {
  123. up.cascadeStop = true
  124. }
  125. if up.wait {
  126. if up.attachDependencies || up.cascadeStop || len(up.attach) > 0 {
  127. return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
  128. }
  129. up.Detach = true
  130. }
  131. if create.Build && create.noBuild {
  132. return fmt.Errorf("--build and --no-build are incompatible")
  133. }
  134. if up.Detach && (up.attachDependencies || up.cascadeStop || len(up.attach) > 0) {
  135. return fmt.Errorf("--detach cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
  136. }
  137. if create.forceRecreate && create.noRecreate {
  138. return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
  139. }
  140. if create.recreateDeps && create.noRecreate {
  141. return fmt.Errorf("--always-recreate-deps and --no-recreate are incompatible")
  142. }
  143. return nil
  144. }
  145. func runUp(ctx context.Context, streams api.Streams, backend api.Service, createOptions createOptions, upOptions upOptions, project *types.Project, services []string) error {
  146. if len(project.Services) == 0 {
  147. return fmt.Errorf("no service selected")
  148. }
  149. createOptions.Apply(project)
  150. err := upOptions.apply(project, services)
  151. if err != nil {
  152. return err
  153. }
  154. var consumer api.LogConsumer
  155. if !upOptions.Detach {
  156. consumer = formatter.NewLogConsumer(ctx, streams.Out(), streams.Err(), !upOptions.noColor, !upOptions.noPrefix, upOptions.timestamp)
  157. }
  158. attachTo := services
  159. if len(upOptions.attach) > 0 {
  160. attachTo = upOptions.attach
  161. }
  162. if upOptions.attachDependencies {
  163. attachTo = project.ServiceNames()
  164. }
  165. if len(attachTo) == 0 {
  166. attachTo = project.ServiceNames()
  167. }
  168. attachTo = utils.RemoveAll(attachTo, upOptions.noAttach)
  169. create := api.CreateOptions{
  170. Services: services,
  171. RemoveOrphans: createOptions.removeOrphans,
  172. IgnoreOrphans: createOptions.ignoreOrphans,
  173. Recreate: createOptions.recreateStrategy(),
  174. RecreateDependencies: createOptions.dependenciesRecreateStrategy(),
  175. Inherit: !createOptions.noInherit,
  176. Timeout: createOptions.GetTimeout(),
  177. QuietPull: createOptions.quietPull,
  178. }
  179. if upOptions.noStart {
  180. return backend.Create(ctx, project, create)
  181. }
  182. return backend.Up(ctx, project, api.UpOptions{
  183. Create: create,
  184. Start: api.StartOptions{
  185. Project: project,
  186. Attach: consumer,
  187. AttachTo: attachTo,
  188. ExitCodeFrom: upOptions.exitCodeFrom,
  189. CascadeStop: upOptions.cascadeStop,
  190. Wait: upOptions.wait,
  191. Services: services,
  192. },
  193. })
  194. }
  195. func setServiceScale(project *types.Project, name string, replicas uint64) error {
  196. for i, s := range project.Services {
  197. if s.Name != name {
  198. continue
  199. }
  200. service, err := project.GetService(name)
  201. if err != nil {
  202. return err
  203. }
  204. if service.Deploy == nil {
  205. service.Deploy = &types.DeployConfig{}
  206. }
  207. service.Deploy.Replicas = &replicas
  208. project.Services[i] = service
  209. return nil
  210. }
  211. return fmt.Errorf("unknown service %q", name)
  212. }