build.go 8.0 KB

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