build.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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. "path/filepath"
  18. "github.com/compose-spec/compose-go/types"
  19. "github.com/containerd/containerd/platforms"
  20. "github.com/docker/buildx/build"
  21. _ "github.com/docker/buildx/driver/docker" // required to get default driver registered
  22. "github.com/docker/buildx/store/storeutil"
  23. "github.com/docker/buildx/util/buildflags"
  24. xprogress "github.com/docker/buildx/util/progress"
  25. "github.com/docker/docker/builder/remotecontext/urlutil"
  26. bclient "github.com/moby/buildkit/client"
  27. "github.com/moby/buildkit/session"
  28. "github.com/moby/buildkit/session/auth/authprovider"
  29. "github.com/moby/buildkit/session/secrets/secretsprovider"
  30. "github.com/moby/buildkit/session/sshforward/sshprovider"
  31. "github.com/moby/buildkit/util/entitlements"
  32. specs "github.com/opencontainers/image-spec/specs-go/v1"
  33. "github.com/docker/compose/v2/pkg/api"
  34. "github.com/docker/compose/v2/pkg/progress"
  35. "github.com/docker/compose/v2/pkg/utils"
  36. )
  37. func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  38. return progress.Run(ctx, func(ctx context.Context) error {
  39. _, err := s.build(ctx, project, options)
  40. return err
  41. }, s.stderr())
  42. }
  43. func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions) (map[string]string, error) {
  44. args := flatten(options.Args.Resolve(envResolver(project.Environment)))
  45. builtIDs := make([]string, len(project.Services))
  46. err := InDependencyOrder(ctx, project, func(ctx context.Context, name string) error {
  47. if len(options.Services) > 0 && !utils.Contains(options.Services, name) {
  48. return nil
  49. }
  50. for i, service := range project.Services {
  51. if service.Name != name {
  52. continue
  53. }
  54. service, err := project.GetService(name)
  55. if err != nil {
  56. return err
  57. }
  58. if service.Build == nil {
  59. return nil
  60. }
  61. imageName := api.GetImageNameOrDefault(service, project.Name)
  62. buildOptions, err := s.toBuildOptions(project, service, imageName, options.SSHs)
  63. if err != nil {
  64. return err
  65. }
  66. buildOptions.Pull = options.Pull
  67. buildOptions.BuildArgs = mergeArgs(buildOptions.BuildArgs, args)
  68. buildOptions.NoCache = options.NoCache
  69. buildOptions.CacheFrom, err = buildflags.ParseCacheEntry(service.Build.CacheFrom)
  70. if err != nil {
  71. return err
  72. }
  73. for _, image := range service.Build.CacheFrom {
  74. buildOptions.CacheFrom = append(buildOptions.CacheFrom, bclient.CacheOptionsEntry{
  75. Type: "registry",
  76. Attrs: map[string]string{"ref": image},
  77. })
  78. }
  79. buildOptions.Exports = []bclient.ExportEntry{{
  80. Type: "docker",
  81. Attrs: map[string]string{
  82. "load": "true",
  83. "push": fmt.Sprint(options.Push),
  84. },
  85. }}
  86. if len(buildOptions.Platforms) > 1 {
  87. buildOptions.Exports = []bclient.ExportEntry{{
  88. Type: "image",
  89. Attrs: map[string]string{
  90. "push": fmt.Sprint(options.Push),
  91. },
  92. }}
  93. }
  94. opts := map[string]build.Options{imageName: buildOptions}
  95. ids, err := s.doBuild(ctx, project, opts, options.Progress)
  96. if err != nil {
  97. return err
  98. }
  99. builtIDs[i] = ids[imageName]
  100. }
  101. return nil
  102. }, func(traversal *graphTraversal) {
  103. traversal.maxConcurrency = s.maxConcurrency
  104. })
  105. imageIDs := map[string]string{}
  106. for i, d := range builtIDs {
  107. if d != "" {
  108. imageIDs[project.Services[i].Image] = d
  109. }
  110. }
  111. return imageIDs, err
  112. }
  113. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, quietPull bool) error {
  114. for _, service := range project.Services {
  115. if service.Image == "" && service.Build == nil {
  116. return fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  117. }
  118. }
  119. images, err := s.getLocalImagesDigests(ctx, project)
  120. if err != nil {
  121. return err
  122. }
  123. err = s.pullRequiredImages(ctx, project, images, quietPull)
  124. if err != nil {
  125. return err
  126. }
  127. mode := xprogress.PrinterModeAuto
  128. if quietPull {
  129. mode = xprogress.PrinterModeQuiet
  130. }
  131. opts, err := s.getBuildOptions(project, images)
  132. if err != nil {
  133. return err
  134. }
  135. builtImages, err := s.doBuild(ctx, project, opts, mode)
  136. if err != nil {
  137. return err
  138. }
  139. for name, digest := range builtImages {
  140. images[name] = digest
  141. }
  142. // set digest as com.docker.compose.image label so we can detect outdated containers
  143. for i, service := range project.Services {
  144. image := api.GetImageNameOrDefault(service, project.Name)
  145. digest, ok := images[image]
  146. if ok {
  147. if project.Services[i].Labels == nil {
  148. project.Services[i].Labels = types.Labels{}
  149. }
  150. project.Services[i].CustomLabels.Add(api.ImageDigestLabel, digest)
  151. }
  152. }
  153. return nil
  154. }
  155. func (s *composeService) getBuildOptions(project *types.Project, images map[string]string) (map[string]build.Options, error) {
  156. opts := map[string]build.Options{}
  157. for _, service := range project.Services {
  158. if service.Image == "" && service.Build == nil {
  159. return nil, fmt.Errorf("invalid service %q. Must specify either image or build", service.Name)
  160. }
  161. imageName := api.GetImageNameOrDefault(service, project.Name)
  162. _, localImagePresent := images[imageName]
  163. if service.Build != nil {
  164. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  165. continue
  166. }
  167. opt, err := s.toBuildOptions(project, service, imageName, []types.SSHKey{})
  168. if err != nil {
  169. return nil, err
  170. }
  171. opt.Exports = []bclient.ExportEntry{{
  172. Type: "docker",
  173. Attrs: map[string]string{
  174. "load": "true",
  175. },
  176. }}
  177. if opt.Platforms, err = useDockerDefaultOrServicePlatform(project, service, true); err != nil {
  178. opt.Platforms = []specs.Platform{}
  179. }
  180. opts[imageName] = opt
  181. continue
  182. }
  183. }
  184. return opts, nil
  185. }
  186. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) {
  187. var imageNames []string
  188. for _, s := range project.Services {
  189. imgName := api.GetImageNameOrDefault(s, project.Name)
  190. if !utils.StringContains(imageNames, imgName) {
  191. imageNames = append(imageNames, imgName)
  192. }
  193. }
  194. imgs, err := s.getImages(ctx, imageNames)
  195. if err != nil {
  196. return nil, err
  197. }
  198. images := map[string]string{}
  199. for name, info := range imgs {
  200. images[name] = info.ID
  201. }
  202. for i := range project.Services {
  203. imgName := api.GetImageNameOrDefault(project.Services[i], project.Name)
  204. digest, ok := images[imgName]
  205. if ok {
  206. project.Services[i].CustomLabels.Add(api.ImageDigestLabel, digest)
  207. }
  208. }
  209. return images, nil
  210. }
  211. func (s *composeService) doBuild(ctx context.Context, project *types.Project, opts map[string]build.Options, mode string) (map[string]string, error) {
  212. if len(opts) == 0 {
  213. return nil, nil
  214. }
  215. if buildkitEnabled, err := s.dockerCli.BuildKitEnabled(); err != nil || !buildkitEnabled {
  216. return s.doBuildClassic(ctx, project, opts)
  217. }
  218. return s.doBuildBuildkit(ctx, opts, mode)
  219. }
  220. func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, imageTag string, sshKeys []types.SSHKey) (build.Options, error) {
  221. var tags []string
  222. tags = append(tags, imageTag)
  223. buildArgs := flatten(service.Build.Args.Resolve(envResolver(project.Environment)))
  224. for k, v := range storeutil.GetProxyConfig(s.dockerCli) {
  225. if _, ok := buildArgs[k]; !ok {
  226. buildArgs[k] = v
  227. }
  228. }
  229. plats, err := addPlatforms(project, service)
  230. if err != nil {
  231. return build.Options{}, err
  232. }
  233. cacheFrom, err := buildflags.ParseCacheEntry(service.Build.CacheFrom)
  234. if err != nil {
  235. return build.Options{}, err
  236. }
  237. cacheTo, err := buildflags.ParseCacheEntry(service.Build.CacheTo)
  238. if err != nil {
  239. return build.Options{}, err
  240. }
  241. sessionConfig := []session.Attachable{
  242. authprovider.NewDockerAuthProvider(s.configFile()),
  243. }
  244. if len(sshKeys) > 0 || len(service.Build.SSH) > 0 {
  245. sshAgentProvider, err := sshAgentProvider(append(service.Build.SSH, sshKeys...))
  246. if err != nil {
  247. return build.Options{}, err
  248. }
  249. sessionConfig = append(sessionConfig, sshAgentProvider)
  250. }
  251. if len(service.Build.Secrets) > 0 {
  252. secretsProvider, err := addSecretsConfig(project, service)
  253. if err != nil {
  254. return build.Options{}, err
  255. }
  256. sessionConfig = append(sessionConfig, secretsProvider)
  257. }
  258. if len(service.Build.Tags) > 0 {
  259. tags = append(tags, service.Build.Tags...)
  260. }
  261. var allow []entitlements.Entitlement
  262. if service.Build.Privileged {
  263. allow = append(allow, entitlements.EntitlementSecurityInsecure)
  264. }
  265. imageLabels := getImageBuildLabels(project, service)
  266. return build.Options{
  267. Inputs: build.Inputs{
  268. ContextPath: service.Build.Context,
  269. DockerfileInline: service.Build.DockerfileInline,
  270. DockerfilePath: dockerFilePath(service.Build.Context, service.Build.Dockerfile),
  271. },
  272. CacheFrom: cacheFrom,
  273. CacheTo: cacheTo,
  274. NoCache: service.Build.NoCache,
  275. Pull: service.Build.Pull,
  276. BuildArgs: buildArgs,
  277. Tags: tags,
  278. Target: service.Build.Target,
  279. Exports: []bclient.ExportEntry{{Type: "image", Attrs: map[string]string{}}},
  280. Platforms: plats,
  281. Labels: imageLabels,
  282. NetworkMode: service.Build.Network,
  283. ExtraHosts: service.Build.ExtraHosts.AsList(),
  284. Session: sessionConfig,
  285. Allow: allow,
  286. }, nil
  287. }
  288. func flatten(in types.MappingWithEquals) types.Mapping {
  289. out := types.Mapping{}
  290. if len(in) == 0 {
  291. return out
  292. }
  293. for k, v := range in {
  294. if v == nil {
  295. continue
  296. }
  297. out[k] = *v
  298. }
  299. return out
  300. }
  301. func mergeArgs(m ...types.Mapping) types.Mapping {
  302. merged := types.Mapping{}
  303. for _, mapping := range m {
  304. for key, val := range mapping {
  305. merged[key] = val
  306. }
  307. }
  308. return merged
  309. }
  310. func dockerFilePath(ctxName string, dockerfile string) string {
  311. if dockerfile == "" {
  312. return ""
  313. }
  314. if urlutil.IsGitURL(ctxName) || filepath.IsAbs(dockerfile) {
  315. return dockerfile
  316. }
  317. return filepath.Join(ctxName, dockerfile)
  318. }
  319. func sshAgentProvider(sshKeys types.SSHConfig) (session.Attachable, error) {
  320. sshConfig := make([]sshprovider.AgentConfig, 0, len(sshKeys))
  321. for _, sshKey := range sshKeys {
  322. sshConfig = append(sshConfig, sshprovider.AgentConfig{
  323. ID: sshKey.ID,
  324. Paths: []string{sshKey.Path},
  325. })
  326. }
  327. return sshprovider.NewSSHAgentProvider(sshConfig)
  328. }
  329. func addSecretsConfig(project *types.Project, service types.ServiceConfig) (session.Attachable, error) {
  330. var sources []secretsprovider.Source
  331. for _, secret := range service.Build.Secrets {
  332. config := project.Secrets[secret.Source]
  333. switch {
  334. case config.File != "":
  335. sources = append(sources, secretsprovider.Source{
  336. ID: secret.Source,
  337. FilePath: config.File,
  338. })
  339. case config.Environment != "":
  340. sources = append(sources, secretsprovider.Source{
  341. ID: secret.Source,
  342. Env: config.Environment,
  343. })
  344. default:
  345. return nil, fmt.Errorf("build.secrets only supports environment or file-based secrets: %q", secret.Source)
  346. }
  347. }
  348. store, err := secretsprovider.NewStore(sources)
  349. if err != nil {
  350. return nil, err
  351. }
  352. return secretsprovider.NewSecretProvider(store), nil
  353. }
  354. func addPlatforms(project *types.Project, service types.ServiceConfig) ([]specs.Platform, error) {
  355. plats, err := useDockerDefaultOrServicePlatform(project, service, false)
  356. if err != nil {
  357. return nil, err
  358. }
  359. for _, buildPlatform := range service.Build.Platforms {
  360. p, err := platforms.Parse(buildPlatform)
  361. if err != nil {
  362. return nil, err
  363. }
  364. if !utils.Contains(plats, p) {
  365. plats = append(plats, p)
  366. }
  367. }
  368. return plats, nil
  369. }
  370. func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels {
  371. ret := make(types.Labels)
  372. if service.Build != nil {
  373. for k, v := range service.Build.Labels {
  374. ret.Add(k, v)
  375. }
  376. }
  377. ret.Add(api.VersionLabel, api.ComposeVersion)
  378. ret.Add(api.ProjectLabel, project.Name)
  379. ret.Add(api.ServiceLabel, service.Name)
  380. return ret
  381. }
  382. func useDockerDefaultPlatform(project *types.Project, platformList types.StringList) ([]specs.Platform, error) {
  383. var plats []specs.Platform
  384. if platform, ok := project.Environment["DOCKER_DEFAULT_PLATFORM"]; ok {
  385. if len(platformList) > 0 && !utils.StringContains(platformList, platform) {
  386. return nil, fmt.Errorf("the DOCKER_DEFAULT_PLATFORM %q value should be part of the service.build.platforms: %q", platform, platformList)
  387. }
  388. p, err := platforms.Parse(platform)
  389. if err != nil {
  390. return nil, err
  391. }
  392. plats = append(plats, p)
  393. }
  394. return plats, nil
  395. }
  396. func useDockerDefaultOrServicePlatform(project *types.Project, service types.ServiceConfig, useOnePlatform bool) ([]specs.Platform, error) {
  397. plats, err := useDockerDefaultPlatform(project, service.Build.Platforms)
  398. if (len(plats) > 0 && useOnePlatform) || err != nil {
  399. return plats, err
  400. }
  401. if service.Platform != "" {
  402. if len(service.Build.Platforms) > 0 && !utils.StringContains(service.Build.Platforms, service.Platform) {
  403. return nil, fmt.Errorf("service.platform %q should be part of the service.build.platforms: %q", service.Platform, service.Build.Platforms)
  404. }
  405. // User defined a service platform and no build platforms, so we should keep the one define on the service level
  406. p, err := platforms.Parse(service.Platform)
  407. if !utils.Contains(plats, p) {
  408. plats = append(plats, p)
  409. }
  410. return plats, err
  411. }
  412. return plats, nil
  413. }