up.go 13 KB

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