build.go 5.1 KB

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