build_classic.go 7.7 KB

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