up.go 9.5 KB

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