build.go 5.1 KB

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