build_classic.go 7.7 KB

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