build.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. resolveImageVolumes(&service, images, project.Name)
  139. project.Services[name] = service
  140. }
  141. return nil
  142. }
  143. func resolveImageVolumes(service *types.ServiceConfig, images map[string]api.ImageSummary, projectName string) {
  144. for i, vol := range service.Volumes {
  145. if vol.Type == types.VolumeTypeImage {
  146. imgName := vol.Source
  147. if _, ok := images[vol.Source]; !ok {
  148. // check if source is another service in the project
  149. imgName = api.GetImageNameOrDefault(types.ServiceConfig{Name: vol.Source}, projectName)
  150. // If we still can't find it, it might be an external image that wasn't pulled yet or doesn't exist
  151. if _, ok := images[imgName]; !ok {
  152. continue
  153. }
  154. }
  155. if img, ok := images[imgName]; ok {
  156. // Use Image ID directly as source.
  157. // Using name@digest format (via reference.WithDigest) fails for local-only images
  158. // that don't have RepoDigests (e.g. built locally in CI).
  159. // Image ID (sha256:...) is always valid and ensures ServiceHash changes on rebuild.
  160. service.Volumes[i].Source = img.ID
  161. }
  162. }
  163. }
  164. }
  165. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]api.ImageSummary, error) {
  166. imageNames := utils.Set[string]{}
  167. for _, s := range project.Services {
  168. imageNames.Add(api.GetImageNameOrDefault(s, project.Name))
  169. for _, volume := range s.Volumes {
  170. if volume.Type == types.VolumeTypeImage {
  171. imageNames.Add(volume.Source)
  172. }
  173. }
  174. }
  175. imgs, err := s.getImageSummaries(ctx, imageNames.Elements())
  176. if err != nil {
  177. return nil, err
  178. }
  179. for i, service := range project.Services {
  180. imgName := api.GetImageNameOrDefault(service, project.Name)
  181. img, ok := imgs[imgName]
  182. if !ok {
  183. continue
  184. }
  185. if service.Platform != "" {
  186. platform, err := platforms.Parse(service.Platform)
  187. if err != nil {
  188. return nil, err
  189. }
  190. inspect, err := s.apiClient().ImageInspect(ctx, img.ID)
  191. if err != nil {
  192. return nil, err
  193. }
  194. actual := specs.Platform{
  195. Architecture: inspect.Architecture,
  196. OS: inspect.Os,
  197. Variant: inspect.Variant,
  198. }
  199. if !platforms.NewMatcher(platform).Match(actual) {
  200. logrus.Debugf("local image %s doesn't match expected platform %s", service.Image, service.Platform)
  201. // there is a local image, but it's for the wrong platform, so
  202. // pretend it doesn't exist so that we can pull/build an image
  203. // for the correct platform instead
  204. delete(imgs, imgName)
  205. }
  206. }
  207. project.Services[i].CustomLabels.Add(api.ImageDigestLabel, img.ID)
  208. }
  209. return imgs, nil
  210. }
  211. // resolveAndMergeBuildArgs returns the final set of build arguments to use for the service image build.
  212. //
  213. // First, args directly defined via `build.args` in YAML are considered.
  214. // Then, any explicitly passed args in opts (e.g. via `--build-arg` on the CLI) are merged, overwriting any
  215. // keys that already exist.
  216. // Next, any keys without a value are resolved using the project environment.
  217. //
  218. // Finally, standard proxy variables based on the Docker client configuration are added, but will not overwrite
  219. // any values if already present.
  220. func resolveAndMergeBuildArgs(proxyConfig map[string]string, project *types.Project, service types.ServiceConfig, opts api.BuildOptions) types.MappingWithEquals {
  221. result := make(types.MappingWithEquals).
  222. OverrideBy(service.Build.Args).
  223. OverrideBy(opts.Args).
  224. Resolve(envResolver(project.Environment))
  225. // proxy arguments do NOT override and should NOT have env resolution applied,
  226. // so they're handled last
  227. for k, v := range proxyConfig {
  228. if _, ok := result[k]; !ok {
  229. v := v
  230. result[k] = &v
  231. }
  232. }
  233. return result
  234. }
  235. func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels {
  236. ret := make(types.Labels)
  237. if service.Build != nil {
  238. for k, v := range service.Build.Labels {
  239. ret.Add(k, v)
  240. }
  241. }
  242. ret.Add(api.VersionLabel, api.ComposeVersion)
  243. ret.Add(api.ProjectLabel, project.Name)
  244. ret.Add(api.ServiceLabel, service.Name)
  245. return ret
  246. }
  247. func addBuildDependencies(services []string, project *types.Project) []string {
  248. servicesWithDependencies := utils.NewSet(services...)
  249. for _, service := range services {
  250. s, ok := project.Services[service]
  251. if !ok {
  252. s = project.DisabledServices[service]
  253. }
  254. b := s.Build
  255. if b != nil {
  256. for _, target := range b.AdditionalContexts {
  257. if s, found := strings.CutPrefix(target, types.ServicePrefix); found {
  258. servicesWithDependencies.Add(s)
  259. }
  260. }
  261. }
  262. }
  263. if len(servicesWithDependencies) > len(services) {
  264. return addBuildDependencies(servicesWithDependencies.Elements(), project)
  265. }
  266. return servicesWithDependencies.Elements()
  267. }