up.go 10 KB

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