create.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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/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.forceRecreate, "force-recreate", false, "Recreate containers even if their configuration and image haven't changed.")
  70. flags.BoolVar(&opts.noRecreate, "no-recreate", false, "If containers already exist, don't recreate them. Incompatible with --force-recreate.")
  71. flags.BoolVar(&opts.removeOrphans, "remove-orphans", false, "Remove containers for services not defined in the Compose file.")
  72. flags.StringArrayVar(&opts.scale, "scale", []string{}, "Scale SERVICE to NUM instances. Overrides the `scale` setting in the Compose file if present.")
  73. return cmd
  74. }
  75. func runCreate(ctx context.Context, _ command.Cli, backend api.Service, createOpts createOptions, buildOpts buildOptions, project *types.Project, services []string) error {
  76. if err := createOpts.Apply(project); err != nil {
  77. return err
  78. }
  79. var build *api.BuildOptions
  80. if !createOpts.noBuild {
  81. bo, err := buildOpts.toAPIBuildOptions(services)
  82. if err != nil {
  83. return err
  84. }
  85. build = &bo
  86. }
  87. return backend.Create(ctx, project, api.CreateOptions{
  88. Build: build,
  89. Services: services,
  90. RemoveOrphans: createOpts.removeOrphans,
  91. IgnoreOrphans: createOpts.ignoreOrphans,
  92. Recreate: createOpts.recreateStrategy(),
  93. RecreateDependencies: createOpts.dependenciesRecreateStrategy(),
  94. Inherit: !createOpts.noInherit,
  95. Timeout: createOpts.GetTimeout(),
  96. QuietPull: false,
  97. })
  98. }
  99. func (opts createOptions) recreateStrategy() string {
  100. if opts.noRecreate {
  101. return api.RecreateNever
  102. }
  103. if opts.forceRecreate {
  104. return api.RecreateForce
  105. }
  106. return api.RecreateDiverged
  107. }
  108. func (opts createOptions) dependenciesRecreateStrategy() string {
  109. if opts.noRecreate {
  110. return api.RecreateNever
  111. }
  112. if opts.recreateDeps {
  113. return api.RecreateForce
  114. }
  115. return api.RecreateDiverged
  116. }
  117. func (opts createOptions) GetTimeout() *time.Duration {
  118. if opts.timeChanged {
  119. t := time.Duration(opts.timeout) * time.Second
  120. return &t
  121. }
  122. return nil
  123. }
  124. func (opts createOptions) Apply(project *types.Project) error {
  125. if opts.pullChanged {
  126. if !opts.isPullPolicyValid() {
  127. return fmt.Errorf("invalid --pull option %q", opts.Pull)
  128. }
  129. for i, service := range project.Services {
  130. service.PullPolicy = opts.Pull
  131. project.Services[i] = service
  132. }
  133. }
  134. // N.B. opts.Build means "force build all", but images can still be built
  135. // when this is false
  136. // e.g. if a service has pull_policy: build or its local image is policy
  137. if opts.Build {
  138. for i, service := range project.Services {
  139. if service.Build == nil {
  140. continue
  141. }
  142. service.PullPolicy = types.PullPolicyBuild
  143. project.Services[i] = service
  144. }
  145. }
  146. // opts.noBuild, however, means do not perform ANY builds
  147. if opts.noBuild {
  148. for i, service := range project.Services {
  149. service.Build = nil
  150. if service.Image == "" {
  151. service.Image = api.GetImageNameOrDefault(service, project.Name)
  152. }
  153. project.Services[i] = service
  154. }
  155. }
  156. if err := applyPlatforms(project, true); err != nil {
  157. return err
  158. }
  159. for _, scale := range opts.scale {
  160. split := strings.Split(scale, "=")
  161. if len(split) != 2 {
  162. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  163. }
  164. name := split[0]
  165. replicas, err := strconv.Atoi(split[1])
  166. if err != nil {
  167. return err
  168. }
  169. err = setServiceScale(project, name, uint64(replicas))
  170. if err != nil {
  171. return err
  172. }
  173. }
  174. return nil
  175. }
  176. func (opts createOptions) isPullPolicyValid() bool {
  177. pullPolicies := []string{types.PullPolicyAlways, types.PullPolicyNever, types.PullPolicyBuild,
  178. types.PullPolicyMissing, types.PullPolicyIfNotPresent}
  179. return slices.Contains(pullPolicies, opts.Pull)
  180. }