build_classic.go 8.2 KB

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