up.go 7.8 KB

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