up.go 10 KB

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