create.go 6.7 KB

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