create.go 5.0 KB

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