build_classic.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. "encoding/json"
  17. "errors"
  18. "fmt"
  19. "io"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. "github.com/compose-spec/compose-go/v2/types"
  24. "github.com/docker/cli/cli"
  25. "github.com/docker/cli/cli/command/image/build"
  26. "github.com/moby/go-archive"
  27. buildtypes "github.com/moby/moby/api/types/build"
  28. "github.com/moby/moby/api/types/container"
  29. "github.com/moby/moby/api/types/jsonstream"
  30. "github.com/moby/moby/api/types/registry"
  31. "github.com/moby/moby/client"
  32. "github.com/moby/moby/client/pkg/jsonmessage"
  33. "github.com/moby/moby/client/pkg/progress"
  34. "github.com/moby/moby/client/pkg/streamformatter"
  35. "github.com/sirupsen/logrus"
  36. "go.opentelemetry.io/otel/attribute"
  37. "go.opentelemetry.io/otel/trace"
  38. "github.com/docker/compose/v5/pkg/api"
  39. )
  40. func (s *composeService) doBuildClassic(ctx context.Context, project *types.Project, serviceToBuild types.Services, options api.BuildOptions) (map[string]string, error) {
  41. imageIDs := map[string]string{}
  42. // Not using bake, additional_context: service:xx is implemented by building images in dependency order
  43. project, err := project.WithServicesTransform(func(serviceName string, service types.ServiceConfig) (types.ServiceConfig, error) {
  44. if service.Build != nil {
  45. for _, c := range service.Build.AdditionalContexts {
  46. if t, found := strings.CutPrefix(c, types.ServicePrefix); found {
  47. if service.DependsOn == nil {
  48. service.DependsOn = map[string]types.ServiceDependency{}
  49. }
  50. service.DependsOn[t] = types.ServiceDependency{
  51. Condition: "build", // non-canonical, but will force dependency graph ordering
  52. }
  53. }
  54. }
  55. }
  56. return service, nil
  57. })
  58. if err != nil {
  59. return imageIDs, err
  60. }
  61. // we use a pre-allocated []string to collect build digest by service index while running concurrent goroutines
  62. builtDigests := make([]string, len(project.Services))
  63. names := project.ServiceNames()
  64. getServiceIndex := func(name string) int {
  65. for idx, n := range names {
  66. if n == name {
  67. return idx
  68. }
  69. }
  70. return -1
  71. }
  72. err = InDependencyOrder(ctx, project, func(ctx context.Context, name string) error {
  73. trace.SpanFromContext(ctx).SetAttributes(attribute.String("builder", "classic"))
  74. service, ok := serviceToBuild[name]
  75. if !ok {
  76. return nil
  77. }
  78. image := api.GetImageNameOrDefault(service, project.Name)
  79. s.events.On(buildingEvent(image))
  80. id, err := s.doBuildImage(ctx, project, service, options)
  81. if err != nil {
  82. return err
  83. }
  84. s.events.On(builtEvent(image))
  85. builtDigests[getServiceIndex(name)] = id
  86. if options.Push {
  87. return s.push(ctx, project, api.PushOptions{})
  88. }
  89. return nil
  90. }, func(traversal *graphTraversal) {
  91. traversal.maxConcurrency = s.maxConcurrency
  92. })
  93. if err != nil {
  94. return nil, err
  95. }
  96. for i, imageDigest := range builtDigests {
  97. if imageDigest != "" {
  98. service := project.Services[names[i]]
  99. imageRef := api.GetImageNameOrDefault(service, project.Name)
  100. imageIDs[imageRef] = imageDigest
  101. }
  102. }
  103. return imageIDs, err
  104. }
  105. //nolint:gocyclo
  106. func (s *composeService) doBuildImage(ctx context.Context, project *types.Project, service types.ServiceConfig, options api.BuildOptions) (string, error) {
  107. var (
  108. buildCtx io.ReadCloser
  109. dockerfileCtx io.ReadCloser
  110. contextDir string
  111. relDockerfile string
  112. )
  113. if len(service.Build.Platforms) > 1 {
  114. return "", fmt.Errorf("the classic builder doesn't support multi-arch build, set DOCKER_BUILDKIT=1 to use BuildKit")
  115. }
  116. if service.Build.Privileged {
  117. return "", fmt.Errorf("the classic builder doesn't support privileged mode, set DOCKER_BUILDKIT=1 to use BuildKit")
  118. }
  119. if len(service.Build.AdditionalContexts) > 0 {
  120. return "", fmt.Errorf("the classic builder doesn't support additional contexts, set DOCKER_BUILDKIT=1 to use BuildKit")
  121. }
  122. if len(service.Build.SSH) > 0 {
  123. return "", fmt.Errorf("the classic builder doesn't support SSH keys, set DOCKER_BUILDKIT=1 to use BuildKit")
  124. }
  125. if len(service.Build.Secrets) > 0 {
  126. return "", fmt.Errorf("the classic builder doesn't support secrets, set DOCKER_BUILDKIT=1 to use BuildKit")
  127. }
  128. if service.Build.Labels == nil {
  129. service.Build.Labels = make(map[string]string)
  130. }
  131. service.Build.Labels[api.ImageBuilderLabel] = "classic"
  132. dockerfileName := dockerFilePath(service.Build.Context, service.Build.Dockerfile)
  133. specifiedContext := service.Build.Context
  134. progBuff := s.stdout()
  135. buildBuff := s.stdout()
  136. contextType, err := build.DetectContextType(specifiedContext)
  137. if err != nil {
  138. return "", err
  139. }
  140. switch contextType {
  141. case build.ContextTypeStdin:
  142. return "", fmt.Errorf("building from STDIN is not supported")
  143. case build.ContextTypeLocal:
  144. contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, dockerfileName)
  145. if err != nil {
  146. return "", fmt.Errorf("unable to prepare context: %w", err)
  147. }
  148. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  149. // Dockerfile is outside build-context; read the Dockerfile and pass it as dockerfileCtx
  150. dockerfileCtx, err = os.Open(dockerfileName)
  151. if err != nil {
  152. return "", fmt.Errorf("unable to open Dockerfile: %w", err)
  153. }
  154. defer dockerfileCtx.Close() //nolint:errcheck
  155. }
  156. case build.ContextTypeGit:
  157. var tempDir string
  158. tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, dockerfileName)
  159. if err != nil {
  160. return "", fmt.Errorf("unable to prepare context: %w", err)
  161. }
  162. defer func() {
  163. _ = os.RemoveAll(tempDir)
  164. }()
  165. contextDir = tempDir
  166. case build.ContextTypeRemote:
  167. buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, dockerfileName)
  168. if err != nil {
  169. return "", fmt.Errorf("unable to prepare context: %w", err)
  170. }
  171. default:
  172. return "", fmt.Errorf("unable to prepare context: path %q not found", specifiedContext)
  173. }
  174. // read from a directory into tar archive
  175. if buildCtx == nil {
  176. excludes, err := build.ReadDockerignore(contextDir)
  177. if err != nil {
  178. return "", err
  179. }
  180. if err := build.ValidateContextDirectory(contextDir, excludes); err != nil {
  181. return "", fmt.Errorf("checking context: %w", err)
  182. }
  183. // And canonicalize dockerfile name to a platform-independent one
  184. relDockerfile = filepath.ToSlash(relDockerfile)
  185. excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, false)
  186. buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  187. ExcludePatterns: excludes,
  188. ChownOpts: &archive.ChownOpts{UID: 0, GID: 0},
  189. })
  190. if err != nil {
  191. return "", err
  192. }
  193. }
  194. // replace Dockerfile if it was added from stdin or a file outside the build-context, and there is archive context
  195. if dockerfileCtx != nil && buildCtx != nil {
  196. buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx)
  197. if err != nil {
  198. return "", err
  199. }
  200. }
  201. buildCtx, err = build.Compress(buildCtx)
  202. if err != nil {
  203. return "", err
  204. }
  205. // Setup an upload progress bar
  206. progressOutput := streamformatter.NewProgressOutput(progBuff)
  207. body := progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")
  208. configFile := s.configFile()
  209. creds, err := configFile.GetAllCredentials()
  210. if err != nil {
  211. return "", err
  212. }
  213. authConfigs := make(map[string]registry.AuthConfig, len(creds))
  214. for k, authConfig := range creds {
  215. authConfigs[k] = registry.AuthConfig{
  216. Username: authConfig.Username,
  217. Password: authConfig.Password,
  218. ServerAddress: authConfig.ServerAddress,
  219. // TODO(thaJeztah): Are these expected to be included? See https://github.com/docker/cli/pull/6516#discussion_r2387586472
  220. Auth: authConfig.Auth,
  221. IdentityToken: authConfig.IdentityToken,
  222. RegistryToken: authConfig.RegistryToken,
  223. }
  224. }
  225. buildOpts := imageBuildOptions(s.getProxyConfig(), project, service, options)
  226. imageName := api.GetImageNameOrDefault(service, project.Name)
  227. buildOpts.Tags = append(buildOpts.Tags, imageName)
  228. buildOpts.Dockerfile = relDockerfile
  229. buildOpts.AuthConfigs = authConfigs
  230. buildOpts.Memory = options.Memory
  231. ctx, cancel := context.WithCancel(ctx)
  232. defer cancel()
  233. s.events.On(buildingEvent(imageName))
  234. response, err := s.apiClient().ImageBuild(ctx, body, buildOpts)
  235. if err != nil {
  236. return "", err
  237. }
  238. defer response.Body.Close() //nolint:errcheck
  239. imageID := ""
  240. aux := func(msg jsonstream.Message) {
  241. var result buildtypes.Result
  242. if err := json.Unmarshal(*msg.Aux, &result); err != nil {
  243. logrus.Errorf("Failed to parse aux message: %s", err)
  244. } else {
  245. imageID = result.ID
  246. }
  247. }
  248. err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux)
  249. if err != nil {
  250. var jerr *jsonstream.Error
  251. if errors.As(err, &jerr) {
  252. // If no error code is set, default to 1
  253. if jerr.Code == 0 {
  254. jerr.Code = 1
  255. }
  256. return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  257. }
  258. return "", err
  259. }
  260. s.events.On(builtEvent(imageName))
  261. return imageID, nil
  262. }
  263. func imageBuildOptions(proxyConfigs map[string]string, project *types.Project, service types.ServiceConfig, options api.BuildOptions) client.ImageBuildOptions {
  264. config := service.Build
  265. return client.ImageBuildOptions{
  266. Version: buildtypes.BuilderV1,
  267. Tags: config.Tags,
  268. NoCache: config.NoCache,
  269. Remove: true,
  270. PullParent: config.Pull,
  271. BuildArgs: resolveAndMergeBuildArgs(proxyConfigs, project, service, options),
  272. Labels: config.Labels,
  273. NetworkMode: config.Network,
  274. ExtraHosts: config.ExtraHosts.AsList(":"),
  275. Target: config.Target,
  276. Isolation: container.Isolation(config.Isolation),
  277. }
  278. }