build.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. "errors"
  17. "fmt"
  18. "os"
  19. "github.com/compose-spec/compose-go/v2/types"
  20. "github.com/containerd/platforms"
  21. "github.com/docker/buildx/build"
  22. "github.com/docker/buildx/builder"
  23. "github.com/docker/buildx/controller/pb"
  24. "github.com/docker/buildx/store/storeutil"
  25. "github.com/docker/buildx/util/buildflags"
  26. xprogress "github.com/docker/buildx/util/progress"
  27. "github.com/docker/cli/cli/command"
  28. cliopts "github.com/docker/cli/opts"
  29. "github.com/docker/compose/v2/internal/tracing"
  30. "github.com/docker/compose/v2/pkg/api"
  31. "github.com/docker/compose/v2/pkg/progress"
  32. "github.com/docker/compose/v2/pkg/utils"
  33. "github.com/docker/docker/api/types/container"
  34. bclient "github.com/moby/buildkit/client"
  35. "github.com/moby/buildkit/session"
  36. "github.com/moby/buildkit/session/auth/authprovider"
  37. "github.com/moby/buildkit/session/secrets/secretsprovider"
  38. "github.com/moby/buildkit/session/sshforward/sshprovider"
  39. "github.com/moby/buildkit/util/entitlements"
  40. "github.com/moby/buildkit/util/progress/progressui"
  41. specs "github.com/opencontainers/image-spec/specs-go/v1"
  42. "github.com/sirupsen/logrus"
  43. // required to get default driver registered
  44. _ "github.com/docker/buildx/driver/docker"
  45. )
  46. func (s *composeService) Build(ctx context.Context, project *types.Project, options api.BuildOptions) error {
  47. err := options.Apply(project)
  48. if err != nil {
  49. return err
  50. }
  51. return progress.RunWithTitle(ctx, func(ctx context.Context) error {
  52. _, err := s.build(ctx, project, options, nil)
  53. return err
  54. }, s.stdinfo(), "Building")
  55. }
  56. //nolint:gocyclo
  57. func (s *composeService) build(ctx context.Context, project *types.Project, options api.BuildOptions, localImages map[string]string) (map[string]string, error) {
  58. imageIDs := map[string]string{}
  59. serviceToBuild := types.Services{}
  60. var policy types.DependencyOption = types.IgnoreDependencies
  61. if options.Deps {
  62. policy = types.IncludeDependencies
  63. }
  64. err := project.ForEachService(options.Services, func(serviceName string, service *types.ServiceConfig) error {
  65. if service.Build == nil {
  66. return nil
  67. }
  68. image := api.GetImageNameOrDefault(*service, project.Name)
  69. _, localImagePresent := localImages[image]
  70. if localImagePresent && service.PullPolicy != types.PullPolicyBuild {
  71. return nil
  72. }
  73. serviceToBuild[serviceName] = *service
  74. return nil
  75. }, policy)
  76. if err != nil || len(serviceToBuild) == 0 {
  77. return imageIDs, err
  78. }
  79. bake, err := buildWithBake(s.dockerCli)
  80. if err != nil {
  81. return nil, err
  82. }
  83. if bake {
  84. return s.doBuildBake(ctx, project, serviceToBuild, options)
  85. }
  86. // Initialize buildkit nodes
  87. buildkitEnabled, err := s.dockerCli.BuildKitEnabled()
  88. if err != nil {
  89. return nil, err
  90. }
  91. var (
  92. b *builder.Builder
  93. nodes []builder.Node
  94. w *xprogress.Printer
  95. )
  96. if buildkitEnabled {
  97. builderName := options.Builder
  98. if builderName == "" {
  99. builderName = os.Getenv("BUILDX_BUILDER")
  100. }
  101. b, err = builder.New(s.dockerCli, builder.WithName(builderName))
  102. if err != nil {
  103. return nil, err
  104. }
  105. nodes, err = b.LoadNodes(ctx)
  106. if err != nil {
  107. return nil, err
  108. }
  109. // Progress needs its own context that lives longer than the
  110. // build one otherwise it won't read all the messages from
  111. // build and will lock
  112. progressCtx, cancel := context.WithCancel(context.Background())
  113. defer cancel()
  114. if options.Quiet {
  115. options.Progress = progress.ModeQuiet
  116. }
  117. if options.Progress == "" {
  118. options.Progress = os.Getenv("BUILDKIT_PROGRESS")
  119. }
  120. w, err = xprogress.NewPrinter(progressCtx, os.Stdout, progressui.DisplayMode(options.Progress),
  121. xprogress.WithDesc(
  122. fmt.Sprintf("building with %q instance using %s driver", b.Name, b.Driver),
  123. fmt.Sprintf("%s:%s", b.Driver, b.Name),
  124. ))
  125. if err != nil {
  126. return nil, err
  127. }
  128. }
  129. // we use a pre-allocated []string to collect build digest by service index while running concurrent goroutines
  130. builtDigests := make([]string, len(project.Services))
  131. names := project.ServiceNames()
  132. getServiceIndex := func(name string) int {
  133. for idx, n := range names {
  134. if n == name {
  135. return idx
  136. }
  137. }
  138. return -1
  139. }
  140. cw := progress.ContextWriter(ctx)
  141. err = InDependencyOrder(ctx, project, func(ctx context.Context, name string) error {
  142. service, ok := serviceToBuild[name]
  143. if !ok {
  144. return nil
  145. }
  146. serviceName := fmt.Sprintf("Service %s", name)
  147. if !buildkitEnabled {
  148. cw.Event(progress.BuildingEvent(serviceName))
  149. id, err := s.doBuildClassic(ctx, project, service, options)
  150. if err != nil {
  151. return err
  152. }
  153. cw.Event(progress.BuiltEvent(serviceName))
  154. builtDigests[getServiceIndex(name)] = id
  155. if options.Push {
  156. return s.push(ctx, project, api.PushOptions{})
  157. }
  158. return nil
  159. }
  160. if options.Memory != 0 {
  161. _, _ = fmt.Fprintln(s.stderr(), "WARNING: --memory is not supported by BuildKit and will be ignored")
  162. }
  163. buildOptions, err := s.toBuildOptions(project, service, options)
  164. if err != nil {
  165. return err
  166. }
  167. digest, err := s.doBuildBuildkit(ctx, name, buildOptions, w, nodes)
  168. if err != nil {
  169. return err
  170. }
  171. builtDigests[getServiceIndex(name)] = digest
  172. return nil
  173. }, func(traversal *graphTraversal) {
  174. traversal.maxConcurrency = s.maxConcurrency
  175. })
  176. // enforce all build event get consumed
  177. if buildkitEnabled {
  178. if errw := w.Wait(); errw != nil {
  179. return nil, errw
  180. }
  181. }
  182. if err != nil {
  183. return nil, err
  184. }
  185. for i, imageDigest := range builtDigests {
  186. if imageDigest != "" {
  187. service := project.Services[names[i]]
  188. imageRef := api.GetImageNameOrDefault(service, project.Name)
  189. imageIDs[imageRef] = imageDigest
  190. cw.Event(progress.BuiltEvent(names[i]))
  191. }
  192. }
  193. return imageIDs, err
  194. }
  195. func (s *composeService) ensureImagesExists(ctx context.Context, project *types.Project, buildOpts *api.BuildOptions, quietPull bool) error {
  196. for name, service := range project.Services {
  197. if service.Image == "" && service.Build == nil {
  198. return fmt.Errorf("invalid service %q. Must specify either image or build", name)
  199. }
  200. }
  201. images, err := s.getLocalImagesDigests(ctx, project)
  202. if err != nil {
  203. return err
  204. }
  205. err = tracing.SpanWrapFunc("project/pull", tracing.ProjectOptions(ctx, project),
  206. func(ctx context.Context) error {
  207. return s.pullRequiredImages(ctx, project, images, quietPull)
  208. },
  209. )(ctx)
  210. if err != nil {
  211. return err
  212. }
  213. if buildOpts != nil {
  214. err = tracing.SpanWrapFunc("project/build", tracing.ProjectOptions(ctx, project),
  215. func(ctx context.Context) error {
  216. builtImages, err := s.build(ctx, project, *buildOpts, images)
  217. if err != nil {
  218. return err
  219. }
  220. for name, digest := range builtImages {
  221. images[name] = digest
  222. }
  223. return nil
  224. },
  225. )(ctx)
  226. if err != nil {
  227. return err
  228. }
  229. }
  230. // set digest as com.docker.compose.image label so we can detect outdated containers
  231. for name, service := range project.Services {
  232. image := api.GetImageNameOrDefault(service, project.Name)
  233. digest, ok := images[image]
  234. if ok {
  235. if service.Labels == nil {
  236. service.Labels = types.Labels{}
  237. }
  238. service.CustomLabels.Add(api.ImageDigestLabel, digest)
  239. }
  240. project.Services[name] = service
  241. }
  242. return nil
  243. }
  244. func (s *composeService) getLocalImagesDigests(ctx context.Context, project *types.Project) (map[string]string, error) {
  245. var imageNames []string
  246. for _, s := range project.Services {
  247. imgName := api.GetImageNameOrDefault(s, project.Name)
  248. if !utils.StringContains(imageNames, imgName) {
  249. imageNames = append(imageNames, imgName)
  250. }
  251. }
  252. imgs, err := s.getImageSummaries(ctx, imageNames)
  253. if err != nil {
  254. return nil, err
  255. }
  256. images := map[string]string{}
  257. for name, info := range imgs {
  258. images[name] = info.ID
  259. }
  260. for i, service := range project.Services {
  261. imgName := api.GetImageNameOrDefault(service, project.Name)
  262. digest, ok := images[imgName]
  263. if !ok {
  264. continue
  265. }
  266. if service.Platform != "" {
  267. platform, err := platforms.Parse(service.Platform)
  268. if err != nil {
  269. return nil, err
  270. }
  271. inspect, _, err := s.apiClient().ImageInspectWithRaw(ctx, digest)
  272. if err != nil {
  273. return nil, err
  274. }
  275. actual := specs.Platform{
  276. Architecture: inspect.Architecture,
  277. OS: inspect.Os,
  278. Variant: inspect.Variant,
  279. }
  280. if !platforms.NewMatcher(platform).Match(actual) {
  281. // there is a local image, but it's for the wrong platform, so
  282. // pretend it doesn't exist so that we can pull/build an image
  283. // for the correct platform instead
  284. delete(images, imgName)
  285. }
  286. }
  287. project.Services[i].CustomLabels.Add(api.ImageDigestLabel, digest)
  288. }
  289. return images, nil
  290. }
  291. // resolveAndMergeBuildArgs returns the final set of build arguments to use for the service image build.
  292. //
  293. // First, args directly defined via `build.args` in YAML are considered.
  294. // Then, any explicitly passed args in opts (e.g. via `--build-arg` on the CLI) are merged, overwriting any
  295. // keys that already exist.
  296. // Next, any keys without a value are resolved using the project environment.
  297. //
  298. // Finally, standard proxy variables based on the Docker client configuration are added, but will not overwrite
  299. // any values if already present.
  300. func resolveAndMergeBuildArgs(dockerCli command.Cli, project *types.Project, service types.ServiceConfig, opts api.BuildOptions) types.MappingWithEquals {
  301. result := make(types.MappingWithEquals).
  302. OverrideBy(service.Build.Args).
  303. OverrideBy(opts.Args).
  304. Resolve(envResolver(project.Environment))
  305. // proxy arguments do NOT override and should NOT have env resolution applied,
  306. // so they're handled last
  307. for k, v := range storeutil.GetProxyConfig(dockerCli) {
  308. if _, ok := result[k]; !ok {
  309. v := v
  310. result[k] = &v
  311. }
  312. }
  313. return result
  314. }
  315. func (s *composeService) toBuildOptions(project *types.Project, service types.ServiceConfig, options api.BuildOptions) (build.Options, error) {
  316. plats, err := parsePlatforms(service)
  317. if err != nil {
  318. return build.Options{}, err
  319. }
  320. cacheFrom, err := buildflags.ParseCacheEntry(service.Build.CacheFrom)
  321. if err != nil {
  322. return build.Options{}, err
  323. }
  324. cacheTo, err := buildflags.ParseCacheEntry(service.Build.CacheTo)
  325. if err != nil {
  326. return build.Options{}, err
  327. }
  328. sessionConfig := []session.Attachable{
  329. authprovider.NewDockerAuthProvider(s.configFile(), nil),
  330. }
  331. if len(options.SSHs) > 0 || len(service.Build.SSH) > 0 {
  332. sshAgentProvider, err := sshAgentProvider(append(service.Build.SSH, options.SSHs...))
  333. if err != nil {
  334. return build.Options{}, err
  335. }
  336. sessionConfig = append(sessionConfig, sshAgentProvider)
  337. }
  338. if len(service.Build.Secrets) > 0 {
  339. secretsProvider, err := addSecretsConfig(project, service)
  340. if err != nil {
  341. return build.Options{}, err
  342. }
  343. sessionConfig = append(sessionConfig, secretsProvider)
  344. }
  345. tags := []string{api.GetImageNameOrDefault(service, project.Name)}
  346. if len(service.Build.Tags) > 0 {
  347. tags = append(tags, service.Build.Tags...)
  348. }
  349. allow, err := buildflags.ParseEntitlements(service.Build.Entitlements)
  350. if err != nil {
  351. return build.Options{}, err
  352. }
  353. if service.Build.Privileged {
  354. allow = append(allow, entitlements.EntitlementSecurityInsecure)
  355. }
  356. imageLabels := getImageBuildLabels(project, service)
  357. push := options.Push && service.Image != ""
  358. exports := []bclient.ExportEntry{{
  359. Type: "docker",
  360. Attrs: map[string]string{
  361. "load": "true",
  362. "push": fmt.Sprint(push),
  363. },
  364. }}
  365. if len(service.Build.Platforms) > 1 {
  366. exports = []bclient.ExportEntry{{
  367. Type: "image",
  368. Attrs: map[string]string{
  369. "push": fmt.Sprint(push),
  370. },
  371. }}
  372. }
  373. sp, err := build.ReadSourcePolicy()
  374. if err != nil {
  375. return build.Options{}, err
  376. }
  377. return build.Options{
  378. Inputs: build.Inputs{
  379. ContextPath: service.Build.Context,
  380. DockerfileInline: service.Build.DockerfileInline,
  381. DockerfilePath: dockerFilePath(service.Build.Context, service.Build.Dockerfile),
  382. NamedContexts: toBuildContexts(service.Build.AdditionalContexts),
  383. },
  384. CacheFrom: pb.CreateCaches(cacheFrom.ToPB()),
  385. CacheTo: pb.CreateCaches(cacheTo.ToPB()),
  386. NoCache: service.Build.NoCache,
  387. Pull: service.Build.Pull,
  388. BuildArgs: flatten(resolveAndMergeBuildArgs(s.dockerCli, project, service, options)),
  389. Tags: tags,
  390. Target: service.Build.Target,
  391. Exports: exports,
  392. Platforms: plats,
  393. Labels: imageLabels,
  394. NetworkMode: service.Build.Network,
  395. ExtraHosts: service.Build.ExtraHosts.AsList(":"),
  396. Ulimits: toUlimitOpt(service.Build.Ulimits),
  397. Session: sessionConfig,
  398. Allow: allow,
  399. SourcePolicy: sp,
  400. }, nil
  401. }
  402. func toUlimitOpt(ulimits map[string]*types.UlimitsConfig) *cliopts.UlimitOpt {
  403. ref := map[string]*container.Ulimit{}
  404. for _, limit := range toUlimits(ulimits) {
  405. ref[limit.Name] = &container.Ulimit{
  406. Name: limit.Name,
  407. Hard: limit.Hard,
  408. Soft: limit.Soft,
  409. }
  410. }
  411. return cliopts.NewUlimitOpt(&ref)
  412. }
  413. func flatten(in types.MappingWithEquals) types.Mapping {
  414. out := types.Mapping{}
  415. if len(in) == 0 {
  416. return out
  417. }
  418. for k, v := range in {
  419. if v == nil {
  420. continue
  421. }
  422. out[k] = *v
  423. }
  424. return out
  425. }
  426. func sshAgentProvider(sshKeys types.SSHConfig) (session.Attachable, error) {
  427. sshConfig := make([]sshprovider.AgentConfig, 0, len(sshKeys))
  428. for _, sshKey := range sshKeys {
  429. sshConfig = append(sshConfig, sshprovider.AgentConfig{
  430. ID: sshKey.ID,
  431. Paths: []string{sshKey.Path},
  432. })
  433. }
  434. return sshprovider.NewSSHAgentProvider(sshConfig)
  435. }
  436. func addSecretsConfig(project *types.Project, service types.ServiceConfig) (session.Attachable, error) {
  437. var sources []secretsprovider.Source
  438. for _, secret := range service.Build.Secrets {
  439. config := project.Secrets[secret.Source]
  440. id := secret.Source
  441. if secret.Target != "" {
  442. id = secret.Target
  443. }
  444. switch {
  445. case config.File != "":
  446. sources = append(sources, secretsprovider.Source{
  447. ID: id,
  448. FilePath: config.File,
  449. })
  450. case config.Environment != "":
  451. sources = append(sources, secretsprovider.Source{
  452. ID: id,
  453. Env: config.Environment,
  454. })
  455. default:
  456. return nil, fmt.Errorf("build.secrets only supports environment or file-based secrets: %q", secret.Source)
  457. }
  458. if secret.UID != "" || secret.GID != "" || secret.Mode != nil {
  459. logrus.Warn("secrets `uid`, `gid` and `mode` are not supported by BuildKit, they will be ignored")
  460. }
  461. }
  462. store, err := secretsprovider.NewStore(sources)
  463. if err != nil {
  464. return nil, err
  465. }
  466. return secretsprovider.NewSecretProvider(store), nil
  467. }
  468. func getImageBuildLabels(project *types.Project, service types.ServiceConfig) types.Labels {
  469. ret := make(types.Labels)
  470. if service.Build != nil {
  471. for k, v := range service.Build.Labels {
  472. ret.Add(k, v)
  473. }
  474. }
  475. ret.Add(api.VersionLabel, api.ComposeVersion)
  476. ret.Add(api.ProjectLabel, project.Name)
  477. ret.Add(api.ServiceLabel, service.Name)
  478. return ret
  479. }
  480. func toBuildContexts(additionalContexts types.Mapping) map[string]build.NamedContext {
  481. namedContexts := map[string]build.NamedContext{}
  482. for name, contextPath := range additionalContexts {
  483. namedContexts[name] = build.NamedContext{Path: contextPath}
  484. }
  485. return namedContexts
  486. }
  487. func parsePlatforms(service types.ServiceConfig) ([]specs.Platform, error) {
  488. if service.Build == nil || len(service.Build.Platforms) == 0 {
  489. return nil, nil
  490. }
  491. var errs []error
  492. ret := make([]specs.Platform, len(service.Build.Platforms))
  493. for i := range service.Build.Platforms {
  494. p, err := platforms.Parse(service.Build.Platforms[i])
  495. if err != nil {
  496. errs = append(errs, err)
  497. } else {
  498. ret[i] = p
  499. }
  500. }
  501. if err := errors.Join(errs...); err != nil {
  502. return nil, err
  503. }
  504. return ret, nil
  505. }