up.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. "github.com/docker/compose-cli/api/client"
  20. "github.com/docker/compose-cli/api/compose"
  21. "github.com/docker/compose-cli/api/context/store"
  22. "github.com/docker/compose-cli/api/progress"
  23. "github.com/docker/compose-cli/cli/formatter"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/spf13/cobra"
  26. )
  27. // composeOptions hold options common to `up` and `run` to run compose project
  28. type composeOptions struct {
  29. *projectOptions
  30. Build bool
  31. // ACI only
  32. DomainName string
  33. }
  34. type upOptions struct {
  35. *composeOptions
  36. Detach bool
  37. Environment []string
  38. removeOrphans bool
  39. forceRecreate bool
  40. noRecreate bool
  41. noStart bool
  42. }
  43. func (o upOptions) recreateStrategy() string {
  44. if o.noRecreate {
  45. return compose.RecreateNever
  46. }
  47. if o.forceRecreate {
  48. return compose.RecreateForce
  49. }
  50. return compose.RecreateDiverged
  51. }
  52. func upCommand(p *projectOptions, contextType string) *cobra.Command {
  53. opts := upOptions{
  54. composeOptions: &composeOptions{
  55. projectOptions: p,
  56. },
  57. }
  58. upCmd := &cobra.Command{
  59. Use: "up [SERVICE...]",
  60. Short: "Create and start containers",
  61. RunE: func(cmd *cobra.Command, args []string) error {
  62. switch contextType {
  63. case store.LocalContextType, store.DefaultContextType, store.EcsLocalSimulationContextType:
  64. if opts.forceRecreate && opts.noRecreate {
  65. return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
  66. }
  67. return runCreateStart(cmd.Context(), opts, args)
  68. default:
  69. return runUp(cmd.Context(), opts, args)
  70. }
  71. },
  72. }
  73. flags := upCmd.Flags()
  74. flags.StringArrayVarP(&opts.Environment, "environment", "e", []string{}, "Environment variables")
  75. flags.BoolVarP(&opts.Detach, "detach", "d", false, "Detached mode: Run containers in the background")
  76. flags.BoolVar(&opts.Build, "build", false, "Build images before starting containers.")
  77. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  78. switch contextType {
  79. case store.AciContextType:
  80. flags.StringVar(&opts.DomainName, "domainname", "", "Container NIS domain name")
  81. case store.LocalContextType, store.DefaultContextType, store.EcsLocalSimulationContextType:
  82. flags.BoolVar(&opts.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed.")
  83. flags.BoolVar(&opts.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  84. flags.BoolVar(&opts.noStart, "no-start", false, "Don't start the services after creating them.")
  85. }
  86. return upCmd
  87. }
  88. func runUp(ctx context.Context, opts upOptions, services []string) error {
  89. c, project, err := setup(ctx, *opts.composeOptions, services)
  90. if err != nil {
  91. return err
  92. }
  93. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  94. return "", c.ComposeService().Up(ctx, project, compose.UpOptions{
  95. Detach: opts.Detach,
  96. })
  97. })
  98. return err
  99. }
  100. func runCreateStart(ctx context.Context, opts upOptions, services []string) error {
  101. c, project, err := setup(ctx, *opts.composeOptions, services)
  102. if err != nil {
  103. return err
  104. }
  105. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  106. err := c.ComposeService().Create(ctx, project, compose.CreateOptions{
  107. RemoveOrphans: opts.removeOrphans,
  108. Recreate: opts.recreateStrategy(),
  109. })
  110. if err != nil {
  111. return "", err
  112. }
  113. if opts.Detach {
  114. err = c.ComposeService().Start(ctx, project, nil)
  115. }
  116. return "", err
  117. })
  118. if err != nil {
  119. return err
  120. }
  121. if opts.noStart {
  122. return nil
  123. }
  124. if opts.Detach {
  125. return nil
  126. }
  127. err = c.ComposeService().Start(ctx, project, formatter.NewLogConsumer(ctx, os.Stdout))
  128. if errors.Is(ctx.Err(), context.Canceled) {
  129. fmt.Println("Gracefully stopping...")
  130. ctx = context.Background()
  131. _, err = progress.Run(ctx, func(ctx context.Context) (string, error) {
  132. return "", c.ComposeService().Stop(ctx, project)
  133. })
  134. }
  135. return err
  136. }
  137. func setup(ctx context.Context, opts composeOptions, services []string) (*client.Client, *types.Project, error) {
  138. c, err := client.NewWithDefaultLocalBackend(ctx)
  139. if err != nil {
  140. return nil, nil, err
  141. }
  142. project, err := opts.toProject(services)
  143. if err != nil {
  144. return nil, nil, err
  145. }
  146. if opts.DomainName != "" {
  147. // arbitrarily set the domain name on the first service ; ACI backend will expose the entire project
  148. project.Services[0].DomainName = opts.DomainName
  149. }
  150. if opts.Build {
  151. for _, service := range project.Services {
  152. service.PullPolicy = types.PullPolicyBuild
  153. }
  154. }
  155. return c, project, nil
  156. }