build.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  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. "os"
  18. "path"
  19. "strings"
  20. "github.com/docker/compose-cli/api/compose"
  21. "github.com/compose-spec/compose-go/types"
  22. "github.com/docker/buildx/build"
  23. "github.com/docker/buildx/driver"
  24. _ "github.com/docker/buildx/driver/docker" // required to get default driver registered
  25. "github.com/docker/buildx/util/progress"
  26. "github.com/docker/docker/errdefs"
  27. bclient "github.com/moby/buildkit/client"
  28. )
  29. func (s *composeService) Build(ctx context.Context, project *types.Project, options compose.BuildOptions) error {
  30. opts := map[string]build.Options{}
  31. imagesToBuild := []string{}
  32. for _, service := range project.Services {
  33. if service.Build != nil {
  34. imageName := getImageName(service, project.Name)
  35. imagesToBuild = append(imagesToBuild, imageName)
  36. buildOptions := s.toBuildOptions(service, project.WorkingDir, imageName)
  37. buildOptions.Pull = options.Pull
  38. buildOptions.BuildArgs = options.Args
  39. opts[imageName] = buildOptions
  40. }
  41. }
  42. err := s.build(ctx, project, opts, options.Progress)
  43. if err == nil {
  44. displayScanSuggestMsg(ctx, imagesToBuild)
  45. }
  46. return err
  47. }
  48. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, quietPull bool) error {
  49. opts := map[string]build.Options{}
  50. imagesToBuild := []string{}
  51. for _, service := range project.Services {
  52. if service.Image == "" && service.Build == nil {
  53. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  54. }
  55. imageName := getImageName(service, project.Name)
  56. localImagePresent, err := s.localImagePresent(ctx, imageName)
  57. if err != nil {
  58. return err
  59. }
  60. if service.Build != nil {
  61. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  62. continue
  63. }
  64. imagesToBuild = append(imagesToBuild, imageName)
  65. opts[imageName] = s.toBuildOptions(service, project.WorkingDir, imageName)
  66. continue
  67. }
  68. if service.Image != "" {
  69. if localImagePresent {
  70. continue
  71. }
  72. }
  73. // Buildx has no command to "just pull", see
  74. // so we bake a temporary dockerfile that will just pull and export pulled image
  75. opts[service.Name] = build.Options{
  76. Inputs: build.Inputs{
  77. ContextPath: ".",
  78. DockerfilePath: "-",
  79. InStream: strings.NewReader("FROM " + service.Image),
  80. },
  81. Tags: []string{service.Image},
  82. Pull: true,
  83. }
  84. }
  85. mode := progress.PrinterModeAuto
  86. if quietPull {
  87. mode = progress.PrinterModeQuiet
  88. }
  89. err := s.build(ctx, project, opts, mode)
  90. if err == nil {
  91. displayScanSuggestMsg(ctx, imagesToBuild)
  92. }
  93. return err
  94. }
  95. func (s *composeService) localImagePresent(ctx context.Context, imageName string) (bool, error) {
  96. _, _, err := s.apiClient.ImageInspectWithRaw(ctx, imageName)
  97. if err != nil {
  98. if errdefs.IsNotFound(err) {
  99. return false, nil
  100. }
  101. return false, err
  102. }
  103. return true, nil
  104. }
  105. func (s *composeService) build(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) error {
  106. if len(opts) == 0 {
  107. return nil
  108. }
  109. const drivername = "default"
  110. d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient, nil, nil, nil, "", nil, nil, project.WorkingDir)
  111. if err != nil {
  112. return err
  113. }
  114. driverInfo := []build.DriverInfo{
  115. {
  116. Name: "default",
  117. Driver: d,
  118. },
  119. }
  120. // Progress needs its own context that lives longer than the
  121. // build one otherwise it won't read all the messages from
  122. // build and will lock
  123. progressCtx, cancel := context.WithCancel(context.Background())
  124. defer cancel()
  125. w := progress.NewPrinter(progressCtx, os.Stdout, mode)
  126. // We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
  127. _, err = build.Build(ctx, driverInfo, opts, nil, nil, w)
  128. errW := w.Wait()
  129. if err == nil {
  130. err = errW
  131. }
  132. return err
  133. }
  134. func (s *composeService) toBuildOptions(service types.ServiceConfig, contextPath string, imageTag string) build.Options {
  135. var tags []string
  136. tags = append(tags, imageTag)
  137. if service.Build.Dockerfile == "" {
  138. service.Build.Dockerfile = "Dockerfile"
  139. }
  140. var buildArgs map[string]string
  141. return build.Options{
  142. Inputs: build.Inputs{
  143. ContextPath: path.Join(contextPath, service.Build.Context),
  144. DockerfilePath: path.Join(contextPath, service.Build.Context, service.Build.Dockerfile),
  145. },
  146. BuildArgs: flatten(mergeArgs(service.Build.Args, buildArgs)),
  147. Tags: tags,
  148. Target: service.Build.Target,
  149. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  150. }
  151. }
  152. func flatten(in types.MappingWithEquals) map[string]string {
  153. if len(in) == 0 {
  154. return nil
  155. }
  156. out := make(map[string]string)
  157. for k, v := range in {
  158. if v == nil {
  159. continue
  160. }
  161. out[k] = *v
  162. }
  163. return out
  164. }
  165. func mergeArgs(src types.MappingWithEquals, values map[string]string) types.MappingWithEquals {
  166. for key := range src {
  167. if val, ok := values[key]; ok {
  168. if val == "" {
  169. src[key] = nil
  170. } else {
  171. src[key] = &val
  172. }
  173. }
  174. }
  175. return src
  176. }