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