build_classic.go 7.6 KB

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