up.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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/moby/buildkit/util/progress/progressui"
  21. "github.com/compose-spec/compose-go/v2/types"
  22. "github.com/docker/cli/cli/command"
  23. "github.com/docker/compose/v2/cmd/formatter"
  24. "github.com/spf13/cobra"
  25. "github.com/docker/compose/v2/pkg/api"
  26. "github.com/docker/compose/v2/pkg/utils"
  27. )
  28. // composeOptions hold options common to `up` and `run` to run compose project
  29. type composeOptions struct {
  30. *ProjectOptions
  31. }
  32. type upOptions struct {
  33. *composeOptions
  34. Detach bool
  35. noStart bool
  36. noDeps bool
  37. cascadeStop bool
  38. exitCodeFrom string
  39. noColor bool
  40. noPrefix bool
  41. attachDependencies bool
  42. attach []string
  43. noAttach []string
  44. timestamp bool
  45. wait bool
  46. waitTimeout int
  47. }
  48. func (opts upOptions) apply(project *types.Project, services []string) (*types.Project, error) {
  49. if opts.noDeps {
  50. var err error
  51. project, err = project.WithSelectedServices(services, types.IgnoreDependencies)
  52. if err != nil {
  53. return nil, err
  54. }
  55. }
  56. if opts.exitCodeFrom != "" {
  57. _, err := project.GetService(opts.exitCodeFrom)
  58. if err != nil {
  59. return nil, err
  60. }
  61. }
  62. return project, nil
  63. }
  64. func upCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  65. up := upOptions{}
  66. create := createOptions{}
  67. build := buildOptions{ProjectOptions: p}
  68. upCmd := &cobra.Command{
  69. Use: "up [OPTIONS] [SERVICE...]",
  70. Short: "Create and start containers",
  71. PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  72. create.pullChanged = cmd.Flags().Changed("pull")
  73. create.timeChanged = cmd.Flags().Changed("timeout")
  74. return validateFlags(&up, &create)
  75. }),
  76. RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  77. create.ignoreOrphans = utils.StringToBool(project.Environment[ComposeIgnoreOrphans])
  78. if create.ignoreOrphans && create.removeOrphans {
  79. return fmt.Errorf("cannot combine %s and --remove-orphans", ComposeIgnoreOrphans)
  80. }
  81. if len(up.attach) != 0 && up.attachDependencies {
  82. return errors.New("cannot combine --attach and --attach-dependencies")
  83. }
  84. return runUp(ctx, dockerCli, backend, create, up, build, project, services)
  85. }),
  86. ValidArgsFunction: completeServiceNames(dockerCli, p),
  87. }
  88. flags := upCmd.Flags()
  89. flags.BoolVarP(&up.Detach, "detach", "d", false, "Detached mode: Run containers in the background")
  90. flags.BoolVar(&create.Build, "build", false, "Build images before starting containers.")
  91. flags.BoolVar(&create.noBuild, "no-build", false, "Don't build an image, even if it's policy.")
  92. flags.StringVar(&create.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never")`)
  93. flags.BoolVar(&create.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  94. flags.StringArrayVar(&create.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
  95. flags.BoolVar(&up.noColor, "no-color", false, "Produce monochrome output.")
  96. flags.BoolVar(&up.noPrefix, "no-log-prefix", false, "Don't print prefix in logs.")
  97. flags.BoolVar(&create.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed.")
  98. flags.BoolVar(&create.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  99. flags.BoolVar(&up.noStart, "no-start", false, "Don't start the services after creating them.")
  100. flags.BoolVar(&up.cascadeStop, "abort-on-container-exit", false, "Stops all containers if any container was stopped. Incompatible with -d")
  101. flags.StringVar(&up.exitCodeFrom, "exit-code-from", "", "Return the exit code of the selected service container. Implies --abort-on-container-exit")
  102. flags.IntVarP(&create.timeout, "timeout", "t", 0, "Use this timeout in seconds for container shutdown when attached or when containers are already running.")
  103. flags.BoolVar(&up.timestamp, "timestamps", false, "Show timestamps.")
  104. flags.BoolVar(&up.noDeps, "no-deps", false, "Don't start linked services.")
  105. flags.BoolVar(&create.recreateDeps, "always-recreate-deps", false, "Recreate dependent containers. Incompatible with --no-recreate.")
  106. flags.BoolVarP(&create.noInherit, "renew-anon-volumes", "V", false, "Recreate anonymous volumes instead of retrieving data from the previous containers.")
  107. flags.BoolVar(&create.quietPull, "quiet-pull", false, "Pull without printing progress information.")
  108. flags.StringArrayVar(&up.attach, "attach", []string{}, "Restrict attaching to the specified services. Incompatible with --attach-dependencies.")
  109. flags.StringArrayVar(&up.noAttach, "no-attach", []string{}, "Do not attach (stream logs) to the specified services.")
  110. flags.BoolVar(&up.attachDependencies, "attach-dependencies", false, "Automatically attach to log output of dependent services.")
  111. flags.BoolVar(&up.wait, "wait", false, "Wait for services to be running|healthy. Implies detached mode.")
  112. flags.IntVar(&up.waitTimeout, "wait-timeout", 0, "Maximum duration to wait for the project to be running|healthy.")
  113. return upCmd
  114. }
  115. func validateFlags(up *upOptions, create *createOptions) error {
  116. if up.exitCodeFrom != "" {
  117. up.cascadeStop = true
  118. }
  119. if up.wait {
  120. if up.attachDependencies || up.cascadeStop || len(up.attach) > 0 {
  121. return fmt.Errorf("--wait cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
  122. }
  123. up.Detach = true
  124. }
  125. if create.Build && create.noBuild {
  126. return fmt.Errorf("--build and --no-build are incompatible")
  127. }
  128. if up.Detach && (up.attachDependencies || up.cascadeStop || len(up.attach) > 0) {
  129. return fmt.Errorf("--detach cannot be combined with --abort-on-container-exit, --attach or --attach-dependencies")
  130. }
  131. if create.forceRecreate && create.noRecreate {
  132. return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
  133. }
  134. if create.recreateDeps && create.noRecreate {
  135. return fmt.Errorf("--always-recreate-deps and --no-recreate are incompatible")
  136. }
  137. return nil
  138. }
  139. func runUp(
  140. ctx context.Context,
  141. dockerCli command.Cli,
  142. backend api.Service,
  143. createOptions createOptions,
  144. upOptions upOptions,
  145. buildOptions buildOptions,
  146. project *types.Project,
  147. services []string,
  148. ) error {
  149. if len(project.Services) == 0 {
  150. return fmt.Errorf("no service selected")
  151. }
  152. err := createOptions.Apply(project)
  153. if err != nil {
  154. return err
  155. }
  156. project, err = upOptions.apply(project, services)
  157. if err != nil {
  158. return err
  159. }
  160. var build *api.BuildOptions
  161. if !createOptions.noBuild {
  162. if createOptions.quietPull {
  163. buildOptions.Progress = string(xprogress.QuietMode)
  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, dockerCli.Out(), dockerCli.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.ForEachService(services, func(serviceName string, s *types.ServiceConfig) error {
  210. if s.Attach == nil || *s.Attach {
  211. attachSet.Add(serviceName)
  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 int) error {
  238. service, err := project.GetService(name)
  239. if err != nil {
  240. return err
  241. }
  242. service.SetScale(replicas)
  243. project.Services[name] = service
  244. return nil
  245. }