build_classic.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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, authConfig := range creds {
  136. authConfigs[k] = registry.AuthConfig{
  137. Username: authConfig.Username,
  138. Password: authConfig.Password,
  139. ServerAddress: authConfig.ServerAddress,
  140. // TODO(thaJeztah): Are these expected to be included? See https://github.com/docker/cli/pull/6516#discussion_r2387586472
  141. Auth: authConfig.Auth,
  142. IdentityToken: authConfig.IdentityToken,
  143. RegistryToken: authConfig.RegistryToken,
  144. }
  145. }
  146. buildOptions := imageBuildOptions(s.dockerCli, project, service, options)
  147. imageName := api.GetImageNameOrDefault(service, project.Name)
  148. buildOptions.Tags = append(buildOptions.Tags, imageName)
  149. buildOptions.Dockerfile = relDockerfile
  150. buildOptions.AuthConfigs = authConfigs
  151. buildOptions.Memory = options.Memory
  152. ctx, cancel := context.WithCancel(ctx)
  153. defer cancel()
  154. response, err := s.apiClient().ImageBuild(ctx, body, buildOptions)
  155. if err != nil {
  156. return "", err
  157. }
  158. defer response.Body.Close() //nolint:errcheck
  159. imageID := ""
  160. aux := func(msg jsonmessage.JSONMessage) {
  161. var result buildtypes.Result
  162. if err := json.Unmarshal(*msg.Aux, &result); err != nil {
  163. logrus.Errorf("Failed to parse aux message: %s", err)
  164. } else {
  165. imageID = result.ID
  166. }
  167. }
  168. err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux)
  169. if err != nil {
  170. var jerr *jsonmessage.JSONError
  171. if errors.As(err, &jerr) {
  172. // If no error code is set, default to 1
  173. if jerr.Code == 0 {
  174. jerr.Code = 1
  175. }
  176. return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  177. }
  178. return "", err
  179. }
  180. return imageID, nil
  181. }
  182. func isLocalDir(c string) bool {
  183. _, err := os.Stat(c)
  184. return err == nil
  185. }
  186. func imageBuildOptions(dockerCli command.Cli, project *types.Project, service types.ServiceConfig, options api.BuildOptions) buildtypes.ImageBuildOptions {
  187. config := service.Build
  188. return buildtypes.ImageBuildOptions{
  189. Version: buildtypes.BuilderV1,
  190. Tags: config.Tags,
  191. NoCache: config.NoCache,
  192. Remove: true,
  193. PullParent: config.Pull,
  194. BuildArgs: resolveAndMergeBuildArgs(dockerCli, project, service, options),
  195. Labels: config.Labels,
  196. NetworkMode: config.Network,
  197. ExtraHosts: config.ExtraHosts.AsList(":"),
  198. Target: config.Target,
  199. Isolation: container.Isolation(config.Isolation),
  200. }
  201. }