build.go 7.5 KB

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