build_classic.go 7.9 KB

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