build.go 5.2 KB

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