build.go 8.9 KB

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