build.go 4.8 KB

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