build_classic.go 7.5 KB

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