up.go 7.1 KB

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