build.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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/containerd/containerd/platforms"
  23. "github.com/docker/buildx/build"
  24. "github.com/docker/buildx/driver"
  25. _ "github.com/docker/buildx/driver/docker" // required to get default driver registered
  26. "github.com/docker/buildx/util/progress"
  27. "github.com/docker/docker/errdefs"
  28. bclient "github.com/moby/buildkit/client"
  29. specs "github.com/opencontainers/image-spec/specs-go/v1"
  30. )
  31. func (s *composeService) Build(ctx context.Context, project *types.Project, options compose.BuildOptions) error {
  32. opts := map[string]build.Options{}
  33. imagesToBuild := []string{}
  34. for _, service := range project.Services {
  35. if service.Build != nil {
  36. imageName := getImageName(service, project.Name)
  37. imagesToBuild = append(imagesToBuild, imageName)
  38. buildOptions, err := s.toBuildOptions(service, project.WorkingDir, imageName)
  39. if err != nil {
  40. return err
  41. }
  42. buildOptions.Pull = options.Pull
  43. buildOptions.BuildArgs = options.Args
  44. opts[imageName] = buildOptions
  45. buildOptions.CacheFrom, err = build.ParseCacheEntry(service.Build.CacheFrom)
  46. if err != nil {
  47. return err
  48. }
  49. for _, image := range service.Build.CacheFrom {
  50. buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
  51. Type: "registry",
  52. Attrs: map[string]string{"ref": image},
  53. })
  54. }
  55. }
  56. }
  57. err := s.build(ctx, project, opts, options.Progress)
  58. if err == nil {
  59. displayScanSuggestMsg(imagesToBuild)
  60. }
  61. return err
  62. }
  63. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, quietPull bool) error {
  64. opts := map[string]build.Options{}
  65. imagesToBuild := []string{}
  66. for _, service := range project.Services {
  67. if service.Image == "" && service.Build == nil {
  68. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  69. }
  70. imageName := getImageName(service, project.Name)
  71. localImagePresent, err := s.localImagePresent(ctx, imageName)
  72. if err != nil {
  73. return err
  74. }
  75. if service.Build != nil {
  76. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  77. continue
  78. }
  79. imagesToBuild = append(imagesToBuild, imageName)
  80. opts[imageName], err = s.toBuildOptions(service, project.WorkingDir, imageName)
  81. if err != nil {
  82. return err
  83. }
  84. continue
  85. }
  86. if service.Image != "" {
  87. if localImagePresent {
  88. continue
  89. }
  90. }
  91. // Buildx has no command to "just pull", see
  92. // so we bake a temporary dockerfile that will just pull and export pulled image
  93. opts[service.Name] = build.Options{
  94. Inputs: build.Inputs{
  95. ContextPath: ".",
  96. DockerfilePath: "-",
  97. InStream: strings.NewReader("FROM " + service.Image),
  98. },
  99. Tags: []string{service.Image},
  100. Pull: true,
  101. }
  102. }
  103. mode := progress.PrinterModeAuto
  104. if quietPull {
  105. mode = progress.PrinterModeQuiet
  106. }
  107. err := s.build(ctx, project, opts, mode)
  108. if err == nil {
  109. displayScanSuggestMsg(imagesToBuild)
  110. }
  111. return err
  112. }
  113. func (s *composeService) localImagePresent(ctx context.Context, imageName string) (bool, error) {
  114. _, _, err := s.apiClient.ImageInspectWithRaw(ctx, imageName)
  115. if err != nil {
  116. if errdefs.IsNotFound(err) {
  117. return false, nil
  118. }
  119. return false, err
  120. }
  121. return true, nil
  122. }
  123. func (s *composeService) build(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) error {
  124. if len(opts) == 0 {
  125. return nil
  126. }
  127. const drivername = "default"
  128. d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient, nil, nil, nil, "", nil, nil, project.WorkingDir)
  129. if err != nil {
  130. return err
  131. }
  132. driverInfo := []build.DriverInfo{
  133. {
  134. Name: "default",
  135. Driver: d,
  136. },
  137. }
  138. // Progress needs its own context that lives longer than the
  139. // build one otherwise it won't read all the messages from
  140. // build and will lock
  141. progressCtx, cancel := context.WithCancel(context.Background())
  142. defer cancel()
  143. w := progress.NewPrinter(progressCtx, os.Stdout, mode)
  144. // We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
  145. _, err = build.Build(ctx, driverInfo, opts, nil, nil, w)
  146. errW := w.Wait()
  147. if err == nil {
  148. err = errW
  149. }
  150. return err
  151. }
  152. func (s *composeService) toBuildOptions(service types.ServiceConfig, contextPath string, imageTag string) (build.Options, error) {
  153. var tags []string
  154. tags = append(tags, imageTag)
  155. if service.Build.Dockerfile == "" {
  156. service.Build.Dockerfile = "Dockerfile"
  157. }
  158. var buildArgs map[string]string
  159. var plats []specs.Platform
  160. if service.Platform != "" {
  161. p, err := platforms.Parse(service.Platform)
  162. if err != nil {
  163. return build.Options{}, err
  164. }
  165. plats = append(plats, p)
  166. }
  167. return build.Options{
  168. Inputs: build.Inputs{
  169. ContextPath: path.Join(contextPath, service.Build.Context),
  170. DockerfilePath: path.Join(contextPath, service.Build.Context, service.Build.Dockerfile),
  171. },
  172. BuildArgs: flatten(mergeArgs(service.Build.Args, buildArgs)),
  173. Tags: tags,
  174. Target: service.Build.Target,
  175. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  176. Platforms: plats,
  177. Labels: service.Build.Labels,
  178. }, nil
  179. }
  180. func flatten(in types.MappingWithEquals) map[string]string {
  181. if len(in) == 0 {
  182. return nil
  183. }
  184. out := make(map[string]string)
  185. for k, v := range in {
  186. if v == nil {
  187. continue
  188. }
  189. out[k] = *v
  190. }
  191. return out
  192. }
  193. func mergeArgs(src types.MappingWithEquals, values map[string]string) types.MappingWithEquals {
  194. for key := range src {
  195. if val, ok := values[key]; ok {
  196. if val == "" {
  197. src[key] = nil
  198. } else {
  199. src[key] = &val
  200. }
  201. }
  202. }
  203. return src
  204. }