1
0

create.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. if opts.noInherit {
  108. return api.RecreateForce
  109. }
  110. return api.RecreateDiverged
  111. }
  112. func (opts createOptions) dependenciesRecreateStrategy() string {
  113. if opts.noRecreate {
  114. return api.RecreateNever
  115. }
  116. if opts.recreateDeps {
  117. return api.RecreateForce
  118. }
  119. return api.RecreateDiverged
  120. }
  121. func (opts createOptions) GetTimeout() *time.Duration {
  122. if opts.timeChanged {
  123. t := time.Duration(opts.timeout) * time.Second
  124. return &t
  125. }
  126. return nil
  127. }
  128. func (opts createOptions) Apply(project *types.Project) error {
  129. if opts.pullChanged {
  130. if !opts.isPullPolicyValid() {
  131. return fmt.Errorf("invalid --pull option %q", opts.Pull)
  132. }
  133. for i, service := range project.Services {
  134. service.PullPolicy = opts.Pull
  135. project.Services[i] = service
  136. }
  137. }
  138. // N.B. opts.Build means "force build all", but images can still be built
  139. // when this is false
  140. // e.g. if a service has pull_policy: build or its local image is policy
  141. if opts.Build {
  142. for i, service := range project.Services {
  143. if service.Build == nil {
  144. continue
  145. }
  146. service.PullPolicy = types.PullPolicyBuild
  147. project.Services[i] = service
  148. }
  149. }
  150. if err := applyPlatforms(project, true); err != nil {
  151. return err
  152. }
  153. err := applyScaleOpts(project, opts.scale)
  154. if err != nil {
  155. return err
  156. }
  157. return nil
  158. }
  159. func applyScaleOpts(project *types.Project, opts []string) error {
  160. for _, scale := range opts {
  161. split := strings.Split(scale, "=")
  162. if len(split) != 2 {
  163. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  164. }
  165. name := split[0]
  166. replicas, err := strconv.Atoi(split[1])
  167. if err != nil {
  168. return err
  169. }
  170. err = setServiceScale(project, name, replicas)
  171. if err != nil {
  172. return err
  173. }
  174. }
  175. return nil
  176. }
  177. func (opts createOptions) isPullPolicyValid() bool {
  178. pullPolicies := []string{types.PullPolicyAlways, types.PullPolicyNever, types.PullPolicyBuild,
  179. types.PullPolicyMissing, types.PullPolicyIfNotPresent}
  180. return slices.Contains(pullPolicies, opts.Pull)
  181. }