build.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. "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"
  22. _ "github.com/docker/buildx/driver/docker" // required to get default driver registered
  23. "github.com/docker/buildx/util/buildflags"
  24. xprogress "github.com/docker/buildx/util/progress"
  25. moby "github.com/docker/docker/api/types"
  26. bclient "github.com/moby/buildkit/client"
  27. "github.com/moby/buildkit/session"
  28. "github.com/moby/buildkit/session/auth/authprovider"
  29. specs "github.com/opencontainers/image-spec/specs-go/v1"
  30. "github.com/docker/compose-cli/pkg/api"
  31. "github.com/docker/compose-cli/pkg/progress"
  32. "github.com/docker/compose-cli/pkg/utils"
  33. )
  34. func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  35. return progress.Run(ctx, func(ctx context.Context) error {
  36. return s.build(ctx, project, options)
  37. })
  38. }
  39. func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  40. opts := map[string]build.Options{}
  41. imagesToBuild := []string{}
  42. args := flatten(options.Args.Resolve(func(s string) (string, bool) {
  43. s, ok := project.Environment[s]
  44. return s, ok
  45. }))
  46. for _, service := range project.Services {
  47. if service.Build != nil {
  48. imageName := getImageName(service, project.Name)
  49. imagesToBuild = append(imagesToBuild, imageName)
  50. buildOptions, err := s.toBuildOptions(project, service, imageName)
  51. if err != nil {
  52. return err
  53. }
  54. buildOptions.Pull = options.Pull
  55. buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
  56. buildOptions.NoCache = options.NoCache
  57. opts[imageName] = buildOptions
  58. buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
  59. if err != nil {
  60. return err
  61. }
  62. for _, image := range service.Build.CacheFrom {
  63. buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
  64. Type: "registry",
  65. Attrs: map[string]string{"ref": image},
  66. })
  67. }
  68. }
  69. }
  70. _, err := s.doBuild(ctx, project, opts, Containers{}, options.Progress)
  71. if err == nil {
  72. if len(imagesToBuild) > 0 && !options.Quiet {
  73. utils.DisplayScanSuggestMsg()
  74. }
  75. }
  76. return err
  77. }
  78. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, observedState Containers, quietPull bool) error {
  79. for _, service := range project.Services {
  80. if service.Image == "" && service.Build == nil {
  81. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  82. }
  83. }
  84. images, err := s.getLocalImagesDigests(ctx, project)
  85. if err != nil {
  86. return err
  87. }
  88. err = s.pullRequiredImages(ctx, project, images, quietPull)
  89. if err != nil {
  90. return err
  91. }
  92. mode := xprogress.PrinterModeAuto
  93. if quietPull {
  94. mode = xprogress.PrinterModeQuiet
  95. }
  96. opts, imagesToBuild, err := s.getBuildOptions(project, images)
  97. if err != nil {
  98. return err
  99. }
  100. builtImages, err := s.doBuild(ctx, project, opts, observedState, mode)
  101. if err != nil {
  102. return err
  103. }
  104. if len(imagesToBuild) > 0 {
  105. utils.DisplayScanSuggestMsg()
  106. }
  107. for name, digest := range builtImages {
  108. images[name] = digest
  109. }
  110. // set digest as service.Image
  111. for i, service := range project.Services {
  112. digest, ok := images[getImageName(service, project.Name)]
  113. if ok {
  114. project.Services[i].Image = digest
  115. }
  116. }
  117. return nil
  118. }
  119. func (s *composeService) getBuildOptions(project *types.Project, images map[string]string) (map[string]build.Options, []string, error) {
  120. opts := map[string]build.Options{}
  121. imagesToBuild := []string{}
  122. for _, service := range project.Services {
  123. if service.Image == "" && service.Build == nil {
  124. return nil, nil, fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  125. }
  126. imageName := getImageName(service, project.Name)
  127. _, localImagePresent := images[imageName]
  128. if service.Build != nil {
  129. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  130. continue
  131. }
  132. imagesToBuild = append(imagesToBuild, imageName)
  133. opt, err := s.toBuildOptions(project, service, imageName)
  134. if err != nil {
  135. return nil, nil, err
  136. }
  137. opts[imageName] = opt
  138. continue
  139. }
  140. }
  141. return opts, imagesToBuild, nil
  142. }
  143. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) {
  144. imageNames := []string{}
  145. for _, s := range project.Services {
  146. imgName := getImageName(s, project.Name)
  147. if !utils.StringContains(imageNames, imgName) {
  148. imageNames = append(imageNames, imgName)
  149. }
  150. }
  151. imgs, err := s.getImages(ctx, imageNames)
  152. if err != nil {
  153. return nil, err
  154. }
  155. images := map[string]string{}
  156. for name, info := range imgs {
  157. images[name] = info.ID
  158. }
  159. return images, nil
  160. }
  161. func (s *composeService) doBuild(ctx context.Context, project *types.Project, opts map[string]build.Options, observedState Containers, mode string) (map[string]string, error) {
  162. info, err := s.apiClient.Info(ctx)
  163. if err != nil {
  164. return nil, err
  165. }
  166. if info.OSType == "windows" {
  167. // no support yet for Windows container builds in Buildkit
  168. // https://docs.docker.com/develop/develop-images/build_enhancements/#limitations
  169. err := s.windowsBuild(opts, mode)
  170. return nil, WrapCategorisedComposeError(err, BuildFailure)
  171. }
  172. if len(opts) == 0 {
  173. return nil, nil
  174. }
  175. const drivername = "default"
  176. d, err := driver.GetDriver(ctx, drivername, nil, s.apiClient, s.configFile, nil, nil, "", nil, nil, project.WorkingDir)
  177. if err != nil {
  178. return nil, err
  179. }
  180. driverInfo := []build.DriverInfo{
  181. {
  182. Name: "default",
  183. Driver: d,
  184. },
  185. }
  186. // Progress needs its own context that lives longer than the
  187. // build one otherwise it won't read all the messages from
  188. // build and will lock
  189. progressCtx, cancel := context.WithCancel(context.Background())
  190. defer cancel()
  191. w := xprogress.NewPrinter(progressCtx, os.Stdout, mode)
  192. // We rely on buildx "docker" builder integrated in docker engine, so don't need a DockerAPI here
  193. response, err := build.Build(ctx, driverInfo, opts, nil, nil, w)
  194. errW := w.Wait()
  195. if err == nil {
  196. err = errW
  197. }
  198. if err != nil {
  199. return nil, WrapCategorisedComposeError(err, BuildFailure)
  200. }
  201. cw := progress.ContextWriter(ctx)
  202. for _, c := range observedState {
  203. for imageName := range opts {
  204. if c.Image == imageName {
  205. err = s.removeContainers(ctx, cw, []moby.Container{c}, nil, false)
  206. if err != nil {
  207. return nil, err
  208. }
  209. }
  210. }
  211. }
  212. imagesBuilt := map[string]string{}
  213. for name, img := range response {
  214. if img == nil || len(img.ExporterResponse) == 0 {
  215. continue
  216. }
  217. digest, ok := img.ExporterResponse["containerimage.digest"]
  218. if !ok {
  219. continue
  220. }
  221. imagesBuilt[name] = digest
  222. }
  223. return imagesBuilt, err
  224. }
  225. func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, imageTag string) (build.Options, error) {
  226. var tags []string
  227. tags = append(tags, imageTag)
  228. buildArgs := flatten(service.Build.Args.Resolve(func(s string) (string, bool) {
  229. s, ok := project.Environment[s]
  230. return s, ok
  231. }))
  232. var plats []specs.Platform
  233. if service.Platform != "" {
  234. p, err := platforms.Parse(service.Platform)
  235. if err != nil {
  236. return build.Options{}, err
  237. }
  238. plats = append(plats, p)
  239. }
  240. return build.Options{
  241. Inputs: build.Inputs{
  242. ContextPath: service.Build.Context,
  243. DockerfilePath: service.Build.Dockerfile,
  244. },
  245. BuildArgs: buildArgs,
  246. Tags: tags,
  247. Target: service.Build.Target,
  248. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  249. Platforms: plats,
  250. Labels: service.Build.Labels,
  251. Session: []session.Attachable{
  252. authprovider.NewDockerAuthProvider(os.Stderr),
  253. },
  254. }, nil
  255. }
  256. func flatten(in types.MappingWithEquals) types.Mapping {
  257. if len(in) == 0 {
  258. return nil
  259. }
  260. out := types.Mapping{}
  261. for k, v := range in {
  262. if v == nil {
  263. continue
  264. }
  265. out[k] = *v
  266. }
  267. return out
  268. }
  269. func mergeArgs(m ...types.Mapping) types.Mapping {
  270. merged := types.Mapping{}
  271. for _, mapping := range m {
  272. for key, val := range mapping {
  273. merged[key] = val
  274. }
  275. }
  276. return merged
  277. }