up.go 12 KB

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