build.go 7.7 KB

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