build.go 8.0 KB

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