build_classic.go 9.9 KB

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