up.go 8.2 KB

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