build.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  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(imagesToBuild)
  45. }
  46. return err
  47. }
  48. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project) 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. err := s.build(ctx, project, opts, "auto")
  86. if err == nil {
  87. displayScanSuggestMsg(imagesToBuild)
  88. }
  89. return err
  90. }
  91. func (s *composeService) localImagePresent(ctx context.Context, imageName string) (bool, error) {
  92. _, _, err := s.apiClient.ImageInspectWithRaw(ctx, imageName)
  93. if err != nil {
  94. if errdefs.IsNotFound(err) {
  95. return false, nil
  96. }
  97. return false, err
  98. }
  99. return true, nil
  100. }
  101. func (s *composeService) build(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) error {
  102. if len(opts) == 0 {
  103. return nil
  104. }
  105. const drivername = "default"
  106. d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient, nil, nil, nil, "", nil, nil, project.WorkingDir)
  107. if err != nil {
  108. return err
  109. }
  110. driverInfo := []build.DriverInfo{
  111. {
  112. Name: "default",
  113. Driver: d,
  114. },
  115. }
  116. // Progress needs its own context that lives longer than the
  117. // build one otherwise it won't read all the messages from
  118. // build and will lock
  119. progressCtx, cancel := context.WithCancel(context.Background())
  120. defer cancel()
  121. w := progress.NewPrinter(progressCtx, os.Stdout, mode)
  122. // We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
  123. _, err = build.Build(ctx, driverInfo, opts, nil, nil, w)
  124. errW := w.Wait()
  125. if err == nil {
  126. err = errW
  127. }
  128. return err
  129. }
  130. func (s *composeService) toBuildOptions(service types.ServiceConfig, contextPath string, imageTag string) build.Options {
  131. var tags []string
  132. tags = append(tags, imageTag)
  133. if service.Build.Dockerfile == "" {
  134. service.Build.Dockerfile = "Dockerfile"
  135. }
  136. var buildArgs map[string]string
  137. return build.Options{
  138. Inputs: build.Inputs{
  139. ContextPath: path.Join(contextPath, service.Build.Context),
  140. DockerfilePath: path.Join(contextPath, service.Build.Context, service.Build.Dockerfile),
  141. },
  142. BuildArgs: flatten(mergeArgs(service.Build.Args, buildArgs)),
  143. Tags: tags,
  144. Target: service.Build.Target,
  145. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  146. }
  147. }
  148. func flatten(in types.MappingWithEquals) map[string]string {
  149. if len(in) == 0 {
  150. return nil
  151. }
  152. out := make(map[string]string)
  153. for k, v := range in {
  154. if v == nil {
  155. continue
  156. }
  157. out[k] = *v
  158. }
  159. return out
  160. }
  161. func mergeArgs(src types.MappingWithEquals, values map[string]string) types.MappingWithEquals {
  162. for key := range src {
  163. if val, ok := values[key]; ok {
  164. if val == "" {
  165. src[key] = nil
  166. } else {
  167. src[key] = &val
  168. }
  169. }
  170. }
  171. return src
  172. }