create.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. "fmt"
  17. "slices"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/compose-spec/compose-go/v2/types"
  22. "github.com/docker/cli/cli/command"
  23. "github.com/spf13/cobra"
  24. "github.com/docker/compose/v2/pkg/api"
  25. )
  26. type createOptions struct {
  27. Build bool
  28. noBuild bool
  29. Pull string
  30. pullChanged bool
  31. removeOrphans bool
  32. ignoreOrphans bool
  33. forceRecreate bool
  34. noRecreate bool
  35. recreateDeps bool
  36. noInherit bool
  37. timeChanged bool
  38. timeout int
  39. quietPull bool
  40. scale []string
  41. AssumeYes bool
  42. }
  43. func createCommand(p *ProjectOptions, dockerCli command.Cli, backend api.Service) *cobra.Command {
  44. opts := createOptions{}
  45. buildOpts := buildOptions{
  46. ProjectOptions: p,
  47. }
  48. cmd := &cobra.Command{
  49. Use: "create [OPTIONS] [SERVICE...]",
  50. Short: "Creates containers for a service",
  51. PreRunE: AdaptCmd(func(ctx context.Context, cmd *cobra.Command, args []string) error {
  52. opts.pullChanged = cmd.Flags().Changed("pull")
  53. if opts.Build && opts.noBuild {
  54. return fmt.Errorf("--build and --no-build are incompatible")
  55. }
  56. if opts.forceRecreate && opts.noRecreate {
  57. return fmt.Errorf("--force-recreate and --no-recreate are incompatible")
  58. }
  59. return nil
  60. }),
  61. RunE: p.WithServices(dockerCli, func(ctx context.Context, project *types.Project, services []string) error {
  62. return runCreate(ctx, dockerCli, backend, opts, buildOpts, project, services)
  63. }),
  64. ValidArgsFunction: completeServiceNames(dockerCli, p),
  65. }
  66. flags := cmd.Flags()
  67. flags.BoolVar(&opts.Build, "build", false, "Build images before starting containers")
  68. flags.BoolVar(&opts.noBuild, "no-build", false, "Don't build an image, even if it's policy")
  69. flags.StringVar(&opts.Pull, "pull", "policy", `Pull image before running ("always"|"missing"|"never"|"build")`)
  70. flags.BoolVar(&opts.quietPull, "quiet-pull", false, "Pull without printing progress information")
  71. flags.BoolVar(&opts.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed")
  72. flags.BoolVar(&opts.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  73. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file")
  74. flags.StringArrayVar(&opts.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
  75. flags.BoolVarP(&opts.AssumeYes, "y", "y", false, `Assume "yes" as answer to all prompts and run non-interactively`)
  76. return cmd
  77. }
  78. func runCreate(ctx context.Context, _ command.Cli, backend api.Service, createOpts createOptions, buildOpts buildOptions, project *types.Project, services []string) error {
  79. if err := createOpts.Apply(project); err != nil {
  80. return err
  81. }
  82. var build *api.BuildOptions
  83. if !createOpts.noBuild {
  84. bo, err := buildOpts.toAPIBuildOptions(services)
  85. if err != nil {
  86. return err
  87. }
  88. build = &bo
  89. }
  90. return backend.Create(ctx, project, api.CreateOptions{
  91. Build: build,
  92. Services: services,
  93. RemoveOrphans: createOpts.removeOrphans,
  94. IgnoreOrphans: createOpts.ignoreOrphans,
  95. Recreate: createOpts.recreateStrategy(),
  96. RecreateDependencies: createOpts.dependenciesRecreateStrategy(),
  97. Inherit: !createOpts.noInherit,
  98. Timeout: createOpts.GetTimeout(),
  99. QuietPull: createOpts.quietPull,
  100. AssumeYes: createOpts.AssumeYes,
  101. })
  102. }
  103. func (opts createOptions) recreateStrategy() string {
  104. if opts.noRecreate {
  105. return api.RecreateNever
  106. }
  107. if opts.forceRecreate {
  108. return api.RecreateForce
  109. }
  110. if opts.noInherit {
  111. return api.RecreateForce
  112. }
  113. return api.RecreateDiverged
  114. }
  115. func (opts createOptions) dependenciesRecreateStrategy() string {
  116. if opts.noRecreate {
  117. return api.RecreateNever
  118. }
  119. if opts.recreateDeps {
  120. return api.RecreateForce
  121. }
  122. return api.RecreateDiverged
  123. }
  124. func (opts createOptions) GetTimeout() *time.Duration {
  125. if opts.timeChanged {
  126. t := time.Duration(opts.timeout) * time.Second
  127. return &t
  128. }
  129. return nil
  130. }
  131. func (opts createOptions) Apply(project *types.Project) error {
  132. if opts.pullChanged {
  133. if !opts.isPullPolicyValid() {
  134. return fmt.Errorf("invalid --pull option %q", opts.Pull)
  135. }
  136. for i, service := range project.Services {
  137. service.PullPolicy = opts.Pull
  138. project.Services[i] = service
  139. }
  140. }
  141. // N.B. opts.Build means "force build all", but images can still be built
  142. // when this is false
  143. // e.g. if a service has pull_policy: build or its local image is policy
  144. if opts.Build {
  145. for i, service := range project.Services {
  146. if service.Build == nil {
  147. continue
  148. }
  149. service.PullPolicy = types.PullPolicyBuild
  150. project.Services[i] = service
  151. }
  152. }
  153. if err := applyPlatforms(project, true); err != nil {
  154. return err
  155. }
  156. err := applyScaleOpts(project, opts.scale)
  157. if err != nil {
  158. return err
  159. }
  160. return nil
  161. }
  162. func applyScaleOpts(project *types.Project, opts []string) error {
  163. for _, scale := range opts {
  164. split := strings.Split(scale, "=")
  165. if len(split) != 2 {
  166. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  167. }
  168. name := split[0]
  169. replicas, err := strconv.Atoi(split[1])
  170. if err != nil {
  171. return err
  172. }
  173. err = setServiceScale(project, name, replicas)
  174. if err != nil {
  175. return err
  176. }
  177. }
  178. return nil
  179. }
  180. func (opts createOptions) isPullPolicyValid() bool {
  181. pullPolicies := []string{
  182. types.PullPolicyAlways, types.PullPolicyNever, types.PullPolicyBuild,
  183. types.PullPolicyMissing, types.PullPolicyIfNotPresent,
  184. }
  185. return slices.Contains(pullPolicies, opts.Pull)
  186. }