build.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. "strings"
  18. "time"
  19. "github.com/compose-spec/compose-go/v2/types"
  20. "github.com/containerd/platforms"
  21. "github.com/docker/compose/v2/internal/tracing"
  22. "github.com/docker/compose/v2/pkg/api"
  23. "github.com/docker/compose/v2/pkg/progress"
  24. "github.com/docker/compose/v2/pkg/utils"
  25. specs "github.com/opencontainers/image-spec/specs-go/v1"
  26. "github.com/sirupsen/logrus"
  27. )
  28. func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  29. err := options.Apply(project)
  30. if err != nil {
  31. return err
  32. }
  33. return progress.Run(ctx, func(ctx context.Context) error {
  34. return tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project),
  35. func(ctx context.Context) error {
  36. _, err := s.build(ctx, project, options, nil)
  37. return err
  38. })(ctx)
  39. }, "build", s.events)
  40. }
  41. func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions, localImages map[string]api.ImageSummary) (map[string]string, error) {
  42. imageIDs := map[string]string{}
  43. serviceToBuild := types.Services{}
  44. var policy types.DependencyOption = types.IgnoreDependencies
  45. if options.Deps {
  46. policy = types.IncludeDependencies
  47. }
  48. if len(options.Services) == 0 {
  49. options.Services = project.ServiceNames()
  50. }
  51. // also include services used as additional_contexts with service: prefix
  52. options.Services = addBuildDependencies(options.Services, project)
  53. // Some build dependencies we just introduced may not be enabled
  54. var err error
  55. project, err = project.WithServicesEnabled(options.Services...)
  56. if err != nil {
  57. return nil, err
  58. }
  59. project, err = project.WithSelectedServices(options.Services)
  60. if err != nil {
  61. return nil, err
  62. }
  63. err = project.ForEachService(options.Services, func(serviceName string, service *types.ServiceConfig) error {
  64. if service.Build == nil {
  65. return nil
  66. }
  67. image := api.GetImageNameOrDefault(*service, project.Name)
  68. _, localImagePresent := localImages[image]
  69. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  70. return nil
  71. }
  72. serviceToBuild[serviceName] = *service
  73. return nil
  74. }, policy)
  75. if err != nil || len(serviceToBuild) == 0 {
  76. return imageIDs, err
  77. }
  78. bake, err := buildWithBake(s.dockerCli)
  79. if err != nil {
  80. return nil, err
  81. }
  82. if bake {
  83. return s.doBuildBake(ctx, project, serviceToBuild, options)
  84. }
  85. return s.doBuildClassic(ctx, project, serviceToBuild, options)
  86. }
  87. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, buildOpts *api.BuildOptions, quietPull bool) error {
  88. for name, service := range project.Services {
  89. if service.Provider == nil && service.Image == "" && service.Build == nil {
  90. return fmt.Errorf("invalid service %q. Must specify either image or build", name)
  91. }
  92. }
  93. images, err := s.getLocalImagesDigests(ctx, project)
  94. if err != nil {
  95. return err
  96. }
  97. err = tracing.SpanWrapFunc("project/pull", tracing.ProjectOptions(ctx, project),
  98. func(ctx context.Context) error {
  99. return s.pullRequiredImages(ctx, project, images, quietPull)
  100. },
  101. )(ctx)
  102. if err != nil {
  103. return err
  104. }
  105. if buildOpts != nil {
  106. err = tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project),
  107. func(ctx context.Context) error {
  108. builtImages, err := s.build(ctx, project, *buildOpts, images)
  109. if err != nil {
  110. return err
  111. }
  112. for name, digest := range builtImages {
  113. images[name] = api.ImageSummary{
  114. Repository: name,
  115. ID: digest,
  116. LastTagTime: time.Now(),
  117. }
  118. }
  119. return nil
  120. },
  121. )(ctx)
  122. if err != nil {
  123. return err
  124. }
  125. }
  126. // set digest as com.docker.compose.image label so we can detect outdated containers
  127. for name, service := range project.Services {
  128. image := api.GetImageNameOrDefault(service, project.Name)
  129. img, ok := images[image]
  130. if ok {
  131. service.CustomLabels.Add(api.ImageDigestLabel, img.ID)
  132. }
  133. project.Services[name] = service
  134. }
  135. return nil
  136. }
  137. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]api.ImageSummary, error) {
  138. imageNames := utils.Set[string]{}
  139. for _, s := range project.Services {
  140. imageNames.Add(api.GetImageNameOrDefault(s, project.Name))
  141. for _, volume := range s.Volumes {
  142. if volume.Type == types.VolumeTypeImage {
  143. imageNames.Add(volume.Source)
  144. }
  145. }
  146. }
  147. imgs, err := s.getImageSummaries(ctx, imageNames.Elements())
  148. if err != nil {
  149. return nil, err
  150. }
  151. for i, service := range project.Services {
  152. imgName := api.GetImageNameOrDefault(service, project.Name)
  153. img, ok := imgs[imgName]
  154. if !ok {
  155. continue
  156. }
  157. if service.Platform != "" {
  158. platform, err := platforms.Parse(service.Platform)
  159. if err != nil {
  160. return nil, err
  161. }
  162. inspect, err := s.apiClient().ImageInspect(ctx, img.ID)
  163. if err != nil {
  164. return nil, err
  165. }
  166. actual := specs.Platform{
  167. Architecture: inspect.Architecture,
  168. OS: inspect.Os,
  169. Variant: inspect.Variant,
  170. }
  171. if !platforms.NewMatcher(platform).Match(actual) {
  172. logrus.Debugf("local image %s doesn't match expected platform %s", service.Image, service.Platform)
  173. // there is a local image, but it's for the wrong platform, so
  174. // pretend it doesn't exist so that we can pull/build an image
  175. // for the correct platform instead
  176. delete(imgs, imgName)
  177. }
  178. }
  179. project.Services[i].CustomLabels.Add(api.ImageDigestLabel, img.ID)
  180. }
  181. return imgs, nil
  182. }
  183. // resolveAndMergeBuildArgs returns the final set of build arguments to use for the service image build.
  184. //
  185. // First, args directly defined via `build.args` in YAML are considered.
  186. // Then, any explicitly passed args in opts (e.g. via `--build-arg` on the CLI) are merged, overwriting any
  187. // keys that already exist.
  188. // Next, any keys without a value are resolved using the project environment.
  189. //
  190. // Finally, standard proxy variables based on the Docker client configuration are added, but will not overwrite
  191. // any values if already present.
  192. func resolveAndMergeBuildArgs(proxyConfig map[string]string, project *types.Project, service types.ServiceConfig, opts api.BuildOptions) types.MappingWithEquals {
  193. result := make(types.MappingWithEquals).
  194. OverrideBy(service.Build.Args).
  195. OverrideBy(opts.Args).
  196. Resolve(envResolver(project.Environment))
  197. // proxy arguments do NOT override and should NOT have env resolution applied,
  198. // so they're handled last
  199. for k, v := range proxyConfig {
  200. if _, ok := result[k]; !ok {
  201. v := v
  202. result[k] = &v
  203. }
  204. }
  205. return result
  206. }
  207. func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels {
  208. ret := make(types.Labels)
  209. if service.Build != nil {
  210. for k, v := range service.Build.Labels {
  211. ret.Add(k, v)
  212. }
  213. }
  214. ret.Add(api.VersionLabel, api.ComposeVersion)
  215. ret.Add(api.ProjectLabel, project.Name)
  216. ret.Add(api.ServiceLabel, service.Name)
  217. return ret
  218. }
  219. func addBuildDependencies(services []string, project *types.Project) []string {
  220. servicesWithDependencies := utils.NewSet(services...)
  221. for _, service := range services {
  222. s, ok := project.Services[service]
  223. if !ok {
  224. s = project.DisabledServices[service]
  225. }
  226. b := s.Build
  227. if b != nil {
  228. for _, target := range b.AdditionalContexts {
  229. if s, found := strings.CutPrefix(target, types.ServicePrefix); found {
  230. servicesWithDependencies.Add(s)
  231. }
  232. }
  233. }
  234. }
  235. if len(servicesWithDependencies) > len(services) {
  236. return addBuildDependencies(servicesWithDependencies.Elements(), project)
  237. }
  238. return servicesWithDependencies.Elements()
  239. }