up.go 8.7 KB

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