build_classic.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. "fmt"
  18. "io"
  19. "os"
  20. "path/filepath"
  21. "runtime"
  22. "strings"
  23. "github.com/docker/docker/api/types/registry"
  24. "github.com/compose-spec/compose-go/types"
  25. "github.com/docker/cli/cli"
  26. "github.com/docker/cli/cli/command/image/build"
  27. dockertypes "github.com/docker/docker/api/types"
  28. "github.com/docker/docker/api/types/container"
  29. "github.com/docker/docker/builder/remotecontext/urlutil"
  30. "github.com/docker/docker/pkg/archive"
  31. "github.com/docker/docker/pkg/idtools"
  32. "github.com/docker/docker/pkg/jsonmessage"
  33. "github.com/docker/docker/pkg/progress"
  34. "github.com/docker/docker/pkg/streamformatter"
  35. "github.com/pkg/errors"
  36. "github.com/docker/compose/v2/pkg/api"
  37. )
  38. //nolint:gocyclo
  39. func (s *composeService) doBuildClassic(ctx context.Context, 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 "", errors.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 "", errors.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 "", errors.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 "", errors.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 "", errors.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 "", errors.Errorf("unable to open Dockerfile: %v", 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 "", errors.Errorf("unable to prepare context: path %q not found", specifiedContext)
  88. }
  89. if err != nil {
  90. return "", errors.Errorf("unable to prepare context: %s", 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 "", errors.Wrap(err, "checking context")
  104. }
  105. // And canonicalize dockerfile name to a platform-independent one
  106. relDockerfile = archive.CanonicalTarNameForPath(relDockerfile)
  107. excludes = build.TrimBuildFilesFromExcludes(excludes, relDockerfile, false)
  108. buildCtx, err = archive.TarWithOptions(contextDir, &archive.TarOptions{
  109. ExcludePatterns: excludes,
  110. ChownOpts: &idtools.Identity{},
  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(service.Build)
  139. buildOptions.Tags = append(buildOptions.Tags, service.Image)
  140. buildOptions.Dockerfile = relDockerfile
  141. buildOptions.AuthConfigs = authConfigs
  142. buildOptions.Memory = options.Memory
  143. ctx, cancel := context.WithCancel(ctx)
  144. defer cancel()
  145. response, err := s.apiClient().ImageBuild(ctx, body, buildOptions)
  146. if err != nil {
  147. return "", err
  148. }
  149. defer response.Body.Close() //nolint:errcheck
  150. imageID := ""
  151. aux := func(msg jsonmessage.JSONMessage) {
  152. var result dockertypes.BuildResult
  153. if err := json.Unmarshal(*msg.Aux, &result); err != nil {
  154. fmt.Fprintf(s.stderr(), "Failed to parse aux message: %s", err)
  155. } else {
  156. imageID = result.ID
  157. }
  158. }
  159. err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux)
  160. if err != nil {
  161. if jerr, ok := err.(*jsonmessage.JSONError); ok {
  162. // If no error code is set, default to 1
  163. if jerr.Code == 0 {
  164. jerr.Code = 1
  165. }
  166. return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  167. }
  168. return "", err
  169. }
  170. // Windows: show error message about modified file permissions if the
  171. // daemon isn't running Windows.
  172. if response.OSType != "windows" && runtime.GOOS == "windows" {
  173. // if response.OSType != "windows" && runtime.GOOS == "windows" && !options.quiet {
  174. fmt.Fprintln(s.stdout(), "SECURITY WARNING: You are building a Docker "+
  175. "image from Windows against a non-Windows Docker host. All files and "+
  176. "directories added to build context will have '-rwxr-xr-x' permissions. "+
  177. "It is recommended to double check and reset permissions for sensitive "+
  178. "files and directories.")
  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(config *types.BuildConfig) dockertypes.ImageBuildOptions {
  187. return dockertypes.ImageBuildOptions{
  188. Version: dockertypes.BuilderV1,
  189. Tags: config.Tags,
  190. NoCache: config.NoCache,
  191. Remove: true,
  192. PullParent: config.Pull,
  193. BuildArgs: config.Args,
  194. Labels: config.Labels,
  195. NetworkMode: config.Network,
  196. ExtraHosts: config.ExtraHosts.AsList(),
  197. Target: config.Target,
  198. Isolation: container.Isolation(config.Isolation),
  199. }
  200. }