build_classic.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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"
  26. "github.com/docker/cli/cli/command/image/build"
  27. "github.com/docker/compose/v2/pkg/api"
  28. buildtypes "github.com/docker/docker/api/types/build"
  29. "github.com/docker/docker/api/types/container"
  30. "github.com/docker/docker/api/types/registry"
  31. "github.com/docker/docker/builder/remotecontext/urlutil"
  32. "github.com/docker/docker/pkg/jsonmessage"
  33. "github.com/docker/docker/pkg/progress"
  34. "github.com/docker/docker/pkg/streamformatter"
  35. "github.com/moby/go-archive"
  36. "github.com/sirupsen/logrus"
  37. )
  38. //nolint:gocyclo
  39. func (s *composeService) doBuildClassic(ctx context.Context, project *types.Project, service types.ServiceConfig, options api.BuildOptions) (string, error) {
  40. var (
  41. buildCtx io.ReadCloser
  42. dockerfileCtx io.ReadCloser
  43. contextDir string
  44. tempDir string
  45. relDockerfile string
  46. err error
  47. )
  48. dockerfileName := dockerFilePath(service.Build.Context, service.Build.Dockerfile)
  49. specifiedContext := service.Build.Context
  50. progBuff := s.stdout()
  51. buildBuff := s.stdout()
  52. if len(service.Build.Platforms) > 1 {
  53. return "", fmt.Errorf("the classic builder doesn't support multi-arch build, set DOCKER_BUILDKIT=1 to use BuildKit")
  54. }
  55. if service.Build.Privileged {
  56. return "", fmt.Errorf("the classic builder doesn't support privileged mode, set DOCKER_BUILDKIT=1 to use BuildKit")
  57. }
  58. if len(service.Build.AdditionalContexts) > 0 {
  59. return "", fmt.Errorf("the classic builder doesn't support additional contexts, set DOCKER_BUILDKIT=1 to use BuildKit")
  60. }
  61. if len(service.Build.SSH) > 0 {
  62. return "", fmt.Errorf("the classic builder doesn't support SSH keys, set DOCKER_BUILDKIT=1 to use BuildKit")
  63. }
  64. if len(service.Build.Secrets) > 0 {
  65. return "", fmt.Errorf("the classic builder doesn't support secrets, set DOCKER_BUILDKIT=1 to use BuildKit")
  66. }
  67. if service.Build.Labels == nil {
  68. service.Build.Labels = make(map[string]string)
  69. }
  70. service.Build.Labels[api.ImageBuilderLabel] = "classic"
  71. switch {
  72. case isLocalDir(specifiedContext):
  73. contextDir, relDockerfile, err = build.GetContextFromLocalDir(specifiedContext, dockerfileName)
  74. if err == nil && strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  75. // Dockerfile is outside of build-context; read the Dockerfile and pass it as dockerfileCtx
  76. dockerfileCtx, err = os.Open(dockerfileName)
  77. if err != nil {
  78. return "", fmt.Errorf("unable to open Dockerfile: %w", err)
  79. }
  80. defer dockerfileCtx.Close() //nolint:errcheck
  81. }
  82. case urlutil.IsGitURL(specifiedContext):
  83. tempDir, relDockerfile, err = build.GetContextFromGitURL(specifiedContext, dockerfileName)
  84. case urlutil.IsURL(specifiedContext):
  85. buildCtx, relDockerfile, err = build.GetContextFromURL(progBuff, specifiedContext, dockerfileName)
  86. default:
  87. return "", fmt.Errorf("unable to prepare context: path %q not found", specifiedContext)
  88. }
  89. if err != nil {
  90. return "", fmt.Errorf("unable to prepare context: %w", err)
  91. }
  92. if tempDir != "" {
  93. defer os.RemoveAll(tempDir) //nolint:errcheck
  94. contextDir = tempDir
  95. }
  96. // read from a directory into tar archive
  97. if buildCtx == nil {
  98. excludes, err := build.ReadDockerignore(contextDir)
  99. if err != nil {
  100. return "", err
  101. }
  102. if err := build.ValidateContextDirectory(contextDir, excludes); err != nil {
  103. return "", fmt.Errorf("checking context: %w", err)
  104. }
  105. // And canonicalize dockerfile name to a platform-independent one
  106. relDockerfile = filepath.ToSlash(relDockerfile)
  107. excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, false)
  108. buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  109. ExcludePatterns: excludes,
  110. ChownOpts: &archive.ChownOpts{},
  111. })
  112. if err != nil {
  113. return "", err
  114. }
  115. }
  116. // replace Dockerfile if it was added from stdin or a file outside the build-context, and there is archive context
  117. if dockerfileCtx != nil && buildCtx != nil {
  118. buildCtx, relDockerfile, err = build.AddDockerfileToBuildContext(dockerfileCtx, buildCtx)
  119. if err != nil {
  120. return "", err
  121. }
  122. }
  123. buildCtx, err = build.Compress(buildCtx)
  124. if err != nil {
  125. return "", err
  126. }
  127. progressOutput := streamformatter.NewProgressOutput(progBuff)
  128. body := progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")
  129. configFile := s.configFile()
  130. creds, err := configFile.GetAllCredentials()
  131. if err != nil {
  132. return "", err
  133. }
  134. authConfigs := make(map[string]registry.AuthConfig, len(creds))
  135. for k, auth := range creds {
  136. authConfigs[k] = registry.AuthConfig(auth)
  137. }
  138. buildOptions := imageBuildOptions(s.dockerCli, project, service, options)
  139. imageName := api.GetImageNameOrDefault(service, project.Name)
  140. buildOptions.Tags = append(buildOptions.Tags, imageName)
  141. buildOptions.Dockerfile = relDockerfile
  142. buildOptions.AuthConfigs = authConfigs
  143. buildOptions.Memory = options.Memory
  144. ctx, cancel := context.WithCancel(ctx)
  145. defer cancel()
  146. response, err := s.apiClient().ImageBuild(ctx, body, buildOptions)
  147. if err != nil {
  148. return "", err
  149. }
  150. defer response.Body.Close() //nolint:errcheck
  151. imageID := ""
  152. aux := func(msg jsonmessage.JSONMessage) {
  153. var result buildtypes.Result
  154. if err := json.Unmarshal(*msg.Aux, &result); err != nil {
  155. logrus.Errorf("Failed to parse aux message: %s", err)
  156. } else {
  157. imageID = result.ID
  158. }
  159. }
  160. err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux)
  161. if err != nil {
  162. var jerr *jsonmessage.JSONError
  163. if errors.As(err, &jerr) {
  164. // If no error code is set, default to 1
  165. if jerr.Code == 0 {
  166. jerr.Code = 1
  167. }
  168. return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  169. }
  170. return "", err
  171. }
  172. return imageID, nil
  173. }
  174. func isLocalDir(c string) bool {
  175. _, err := os.Stat(c)
  176. return err == nil
  177. }
  178. func imageBuildOptions(dockerCli command.Cli, project *types.Project, service types.ServiceConfig, options api.BuildOptions) buildtypes.ImageBuildOptions {
  179. config := service.Build
  180. return buildtypes.ImageBuildOptions{
  181. Version: buildtypes.BuilderV1,
  182. Tags: config.Tags,
  183. NoCache: config.NoCache,
  184. Remove: true,
  185. PullParent: config.Pull,
  186. BuildArgs: resolveAndMergeBuildArgs(dockerCli, project, service, options),
  187. Labels: config.Labels,
  188. NetworkMode: config.Network,
  189. ExtraHosts: config.ExtraHosts.AsList(":"),
  190. Target: config.Target,
  191. Isolation: container.Isolation(config.Isolation),
  192. }
  193. }