up.go 10 KB

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