build.go 6.9 KB

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