create.go 6.5 KB

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