up.go 12 KB

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