up.go 12 KB

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