build.go 5.8 KB

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