build.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. "path/filepath"
  18. "github.com/compose-spec/compose-go/types"
  19. "github.com/containerd/containerd/platforms"
  20. "github.com/docker/buildx/build"
  21. _ "github.com/docker/buildx/driver/docker" // required to get default driver registered
  22. "github.com/docker/buildx/util/buildflags"
  23. xprogress "github.com/docker/buildx/util/progress"
  24. "github.com/docker/docker/pkg/urlutil"
  25. bclient "github.com/moby/buildkit/client"
  26. "github.com/moby/buildkit/session"
  27. "github.com/moby/buildkit/session/auth/authprovider"
  28. specs "github.com/opencontainers/image-spec/specs-go/v1"
  29. "github.com/docker/compose/v2/pkg/api"
  30. "github.com/docker/compose/v2/pkg/progress"
  31. "github.com/docker/compose/v2/pkg/utils"
  32. )
  33. func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  34. return progress.Run(ctx, func(ctx context.Context) error {
  35. return s.build(ctx, project, options)
  36. })
  37. }
  38. func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  39. opts := map[string]build.Options{}
  40. imagesToBuild := []string{}
  41. args := flatten(options.Args.Resolve(func(s string) (string, bool) {
  42. s, ok := project.Environment[s]
  43. return s, ok
  44. }))
  45. services, err := project.GetServices(options.Services...)
  46. if err != nil {
  47. return err
  48. }
  49. for _, service := range services {
  50. if service.Build != nil {
  51. imageName := getImageName(service, project.Name)
  52. imagesToBuild = append(imagesToBuild, imageName)
  53. buildOptions, err := s.toBuildOptions(project, service, imageName)
  54. if err != nil {
  55. return err
  56. }
  57. buildOptions.Pull = options.Pull
  58. buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
  59. buildOptions.NoCache = options.NoCache
  60. buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
  61. if err != nil {
  62. return err
  63. }
  64. for _, image := range service.Build.CacheFrom {
  65. buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
  66. Type: "registry",
  67. Attrs: map[string]string{"ref": image},
  68. })
  69. }
  70. opts[imageName] = buildOptions
  71. }
  72. }
  73. _, err = s.doBuild(ctx, project, opts, options.Progress)
  74. if err == nil {
  75. if len(imagesToBuild) > 0 && !options.Quiet {
  76. utils.DisplayScanSuggestMsg()
  77. }
  78. }
  79. return err
  80. }
  81. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, quietPull bool) error {
  82. for _, service := range project.Services {
  83. if service.Image == "" && service.Build == nil {
  84. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  85. }
  86. }
  87. images, err := s.getLocalImagesDigests(ctx, project)
  88. if err != nil {
  89. return err
  90. }
  91. err = s.pullRequiredImages(ctx, project, images, quietPull)
  92. if err != nil {
  93. return err
  94. }
  95. mode := xprogress.PrinterModeAuto
  96. if quietPull {
  97. mode = xprogress.PrinterModeQuiet
  98. }
  99. opts, err := s.getBuildOptions(project, images)
  100. if err != nil {
  101. return err
  102. }
  103. builtImages, err := s.doBuild(ctx, project, opts, mode)
  104. if err != nil {
  105. return err
  106. }
  107. if len(builtImages) > 0 {
  108. utils.DisplayScanSuggestMsg()
  109. }
  110. for name, digest := range builtImages {
  111. images[name] = digest
  112. }
  113. // set digest as com.docker.compose.image label so we can detect outdated containers
  114. for i, service := range project.Services {
  115. image := getImageName(service, project.Name)
  116. digest, ok := images[image]
  117. if ok {
  118. if project.Services[i].Labels == nil {
  119. project.Services[i].Labels = types.Labels{}
  120. }
  121. project.Services[i].CustomLabels[api.ImageDigestLabel] = digest
  122. project.Services[i].Image = image
  123. }
  124. }
  125. return nil
  126. }
  127. func (s *composeService) getBuildOptions(project *types.Project, images map[string]string) (map[string]build.Options, error) {
  128. opts := map[string]build.Options{}
  129. for _, service := range project.Services {
  130. if service.Image == "" && service.Build == nil {
  131. return nil, fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  132. }
  133. imageName := getImageName(service, project.Name)
  134. _, localImagePresent := images[imageName]
  135. if service.Build != nil {
  136. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  137. continue
  138. }
  139. opt, err := s.toBuildOptions(project, service, imageName)
  140. if err != nil {
  141. return nil, err
  142. }
  143. opts[imageName] = opt
  144. continue
  145. }
  146. }
  147. return opts, nil
  148. }
  149. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) {
  150. imageNames := []string{}
  151. for _, s := range project.Services {
  152. imgName := getImageName(s, project.Name)
  153. if !utils.StringContains(imageNames, imgName) {
  154. imageNames = append(imageNames, imgName)
  155. }
  156. }
  157. imgs, err := s.getImages(ctx, imageNames)
  158. if err != nil {
  159. return nil, err
  160. }
  161. images := map[string]string{}
  162. for name, info := range imgs {
  163. images[name] = info.ID
  164. }
  165. for _, s := range project.Services {
  166. imgName := getImageName(s, project.Name)
  167. digest, ok := images[imgName]
  168. if ok {
  169. s.CustomLabels[api.ImageDigestLabel] = digest
  170. }
  171. }
  172. return images, nil
  173. }
  174. func (s *composeService) doBuild(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) (map[string]string, error) {
  175. if len(opts) == 0 {
  176. return nil, nil
  177. }
  178. if buildkitEnabled, err := s.dockerCli.BuildKitEnabled(); err != nil || !buildkitEnabled {
  179. return s.doBuildClassic(ctx, opts)
  180. }
  181. return s.doBuildBuildkit(ctx, project, opts, mode)
  182. }
  183. func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, imageTag string) (build.Options, error) {
  184. var tags []string
  185. tags = append(tags, imageTag)
  186. buildArgs := flatten(service.Build.Args.Resolve(func(s string) (string, bool) {
  187. s, ok := project.Environment[s]
  188. return s, ok
  189. }))
  190. var plats []specs.Platform
  191. if platform, ok := project.Environment["DOCKER_DEFAULT_PLATFORM"]; ok {
  192. p, err := platforms.Parse(platform)
  193. if err != nil {
  194. return build.Options{}, err
  195. }
  196. plats = append(plats, p)
  197. }
  198. if service.Platform != "" {
  199. p, err := platforms.Parse(service.Platform)
  200. if err != nil {
  201. return build.Options{}, err
  202. }
  203. plats = append(plats, p)
  204. }
  205. return build.Options{
  206. Inputs: build.Inputs{
  207. ContextPath: service.Build.Context,
  208. DockerfilePath: dockerFilePath(service.Build.Context, service.Build.Dockerfile),
  209. },
  210. BuildArgs: buildArgs,
  211. Tags: tags,
  212. Target: service.Build.Target,
  213. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  214. Platforms: plats,
  215. Labels: service.Build.Labels,
  216. NetworkMode: service.Build.Network,
  217. ExtraHosts: service.Build.ExtraHosts,
  218. Session: []session.Attachable{
  219. authprovider.NewDockerAuthProvider(s.stderr()),
  220. },
  221. }, nil
  222. }
  223. func flatten(in types.MappingWithEquals) types.Mapping {
  224. if len(in) == 0 {
  225. return nil
  226. }
  227. out := types.Mapping{}
  228. for k, v := range in {
  229. if v == nil {
  230. continue
  231. }
  232. out[k] = *v
  233. }
  234. return out
  235. }
  236. func mergeArgs(m ...types.Mapping) types.Mapping {
  237. merged := types.Mapping{}
  238. for _, mapping := range m {
  239. for key, val := range mapping {
  240. merged[key] = val
  241. }
  242. }
  243. return merged
  244. }
  245. func dockerFilePath(context string, dockerfile string) string {
  246. if urlutil.IsGitURL(context) || filepath.IsAbs(dockerfile) {
  247. return dockerfile
  248. }
  249. return filepath.Join(context, dockerfile)
  250. }