create.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/sirupsen/logrus"
  24. "github.com/spf13/cobra"
  25. "github.com/spf13/pflag"
  26. "github.com/docker/compose/v5/pkg/api"
  27. "github.com/docker/compose/v5/pkg/compose"
  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. if createOpts.AssumeYes {
  102. backendOptions.Options = append(backendOptions.Options, compose.WithPrompt(compose.AlwaysOkPrompt()))
  103. }
  104. backend, err := compose.NewComposeService(dockerCli, backendOptions.Options...)
  105. if err != nil {
  106. return err
  107. }
  108. return backend.Create(ctx, project, api.CreateOptions{
  109. Build: build,
  110. Services: services,
  111. RemoveOrphans: createOpts.removeOrphans,
  112. IgnoreOrphans: createOpts.ignoreOrphans,
  113. Recreate: createOpts.recreateStrategy(),
  114. RecreateDependencies: createOpts.dependenciesRecreateStrategy(),
  115. Inherit: !createOpts.noInherit,
  116. Timeout: createOpts.GetTimeout(),
  117. QuietPull: createOpts.quietPull,
  118. })
  119. }
  120. func (opts createOptions) recreateStrategy() string {
  121. if opts.noRecreate {
  122. return api.RecreateNever
  123. }
  124. if opts.forceRecreate {
  125. return api.RecreateForce
  126. }
  127. if opts.noInherit {
  128. return api.RecreateForce
  129. }
  130. return api.RecreateDiverged
  131. }
  132. func (opts createOptions) dependenciesRecreateStrategy() string {
  133. if opts.noRecreate {
  134. return api.RecreateNever
  135. }
  136. if opts.recreateDeps {
  137. return api.RecreateForce
  138. }
  139. return api.RecreateDiverged
  140. }
  141. func (opts createOptions) GetTimeout() *time.Duration {
  142. if opts.timeChanged {
  143. t := time.Duration(opts.timeout) * time.Second
  144. return &t
  145. }
  146. return nil
  147. }
  148. func (opts createOptions) Apply(project *types.Project) error {
  149. if opts.pullChanged {
  150. if !opts.isPullPolicyValid() {
  151. return fmt.Errorf("invalid --pull option %q", opts.Pull)
  152. }
  153. for i, service := range project.Services {
  154. service.PullPolicy = opts.Pull
  155. project.Services[i] = service
  156. }
  157. }
  158. // N.B. opts.Build means "force build all", but images can still be built
  159. // when this is false
  160. // e.g. if a service has pull_policy: build or its local image is policy
  161. if opts.Build {
  162. for i, service := range project.Services {
  163. if service.Build == nil {
  164. continue
  165. }
  166. service.PullPolicy = types.PullPolicyBuild
  167. project.Services[i] = service
  168. }
  169. }
  170. if err := applyPlatforms(project, true); err != nil {
  171. return err
  172. }
  173. err := applyScaleOpts(project, opts.scale)
  174. if err != nil {
  175. return err
  176. }
  177. return nil
  178. }
  179. func applyScaleOpts(project *types.Project, opts []string) error {
  180. for _, scale := range opts {
  181. split := strings.Split(scale, "=")
  182. if len(split) != 2 {
  183. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  184. }
  185. name := split[0]
  186. replicas, err := strconv.Atoi(split[1])
  187. if err != nil {
  188. return err
  189. }
  190. err = setServiceScale(project, name, replicas)
  191. if err != nil {
  192. return err
  193. }
  194. }
  195. return nil
  196. }
  197. func (opts createOptions) isPullPolicyValid() bool {
  198. pullPolicies := []string{
  199. types.PullPolicyAlways, types.PullPolicyNever, types.PullPolicyBuild,
  200. types.PullPolicyMissing, types.PullPolicyIfNotPresent,
  201. }
  202. return slices.Contains(pullPolicies, opts.Pull)
  203. }