build_buildkit.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. "os"
  17. "path/filepath"
  18. "github.com/compose-spec/compose-go/types"
  19. "github.com/docker/buildx/build"
  20. "github.com/docker/buildx/driver"
  21. xprogress "github.com/docker/buildx/util/progress"
  22. )
  23. func (s *composeService) doBuildBuildkit(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) (map[string]string, error) {
  24. const drivername = "default"
  25. d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient(), s.configFile(), nil, nil, nil, nil, nil, project.WorkingDir)
  26. if err != nil {
  27. return nil, err
  28. }
  29. driverInfo := []build.DriverInfo{
  30. {
  31. Name: drivername,
  32. Driver: d,
  33. },
  34. }
  35. // Progress needs its own context that lives longer than the
  36. // build one otherwise it won't read all the messages from
  37. // build and will lock
  38. progressCtx, cancel := context.WithCancel(context.Background())
  39. defer cancel()
  40. w := xprogress.NewPrinter(progressCtx, s.stdout(), os.Stdout, mode)
  41. // We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
  42. response, err := build.Build(ctx, driverInfo, opts, nil, filepath.Dir(s.configFile().Filename), w)
  43. errW := w.Wait()
  44. if err == nil {
  45. err = errW
  46. }
  47. if err != nil {
  48. return nil, WrapCategorisedComposeError(err, BuildFailure)
  49. }
  50. imagesBuilt := map[string]string{}
  51. for name, img := range response {
  52. if img == nil || len(img.ExporterResponse) == 0 {
  53. continue
  54. }
  55. digest, ok := img.ExporterResponse["containerimage.digest"]
  56. if !ok {
  57. continue
  58. }
  59. imagesBuilt[name] = digest
  60. }
  61. return imagesBuilt, err
  62. }