create.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. if opts.Build {
  114. for i, service := range project.Services {
  115. if service.Build == nil {
  116. continue
  117. }
  118. service.PullPolicy = types.PullPolicyBuild
  119. project.Services[i] = service
  120. }
  121. }
  122. if opts.noBuild {
  123. for i, service := range project.Services {
  124. service.Build = nil
  125. if service.Image == "" {
  126. service.Image = api.GetImageNameOrDefault(service, project.Name)
  127. }
  128. project.Services[i] = service
  129. }
  130. }
  131. for _, scale := range opts.scale {
  132. split := strings.Split(scale, "=")
  133. if len(split) != 2 {
  134. return fmt.Errorf("invalid --scale option %q. Should be SERVICE=NUM", scale)
  135. }
  136. name := split[0]
  137. replicas, err := strconv.Atoi(split[1])
  138. if err != nil {
  139. return err
  140. }
  141. err = setServiceScale(project, name, uint64(replicas))
  142. if err != nil {
  143. return err
  144. }
  145. }
  146. return nil
  147. }