build.go 4.9 KB

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