up.go 11 KB

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