build.go 7.9 KB

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