build.go 16 KB

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