create.go 5.6 KB

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