up.go 14 KB

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