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