create.go 5.9 KB

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