build_classic.go 7.3 KB

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