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. "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. // if up to this point nothing has set the context then we must have another
  126. // way for sending it(streaming) and set the context to the Dockerfile
  127. if dockerfileCtx != nil && buildCtx == nil {
  128. buildCtx = dockerfileCtx
  129. }
  130. progressOutput := streamformatter.NewProgressOutput(progBuff)
  131. var body io.Reader
  132. if buildCtx != nil {
  133. body = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon")
  134. }
  135. configFile := s.configFile()
  136. creds, err := configFile.GetAllCredentials()
  137. if err != nil {
  138. return "", err
  139. }
  140. authConfigs := make(map[string]dockertypes.AuthConfig, len(creds))
  141. for k, auth := range creds {
  142. authConfigs[k] = dockertypes.AuthConfig(auth)
  143. }
  144. buildOptions := imageBuildOptions(options)
  145. buildOptions.Version = dockertypes.BuilderV1
  146. buildOptions.Dockerfile = relDockerfile
  147. buildOptions.AuthConfigs = authConfigs
  148. ctx, cancel := context.WithCancel(ctx)
  149. defer cancel()
  150. response, err := s.apiClient().ImageBuild(ctx, body, buildOptions)
  151. if err != nil {
  152. return "", err
  153. }
  154. defer response.Body.Close() // nolint:errcheck
  155. imageID := ""
  156. aux := func(msg jsonmessage.JSONMessage) {
  157. var result dockertypes.BuildResult
  158. if err := json.Unmarshal(*msg.Aux, &result); err != nil {
  159. fmt.Fprintf(s.stderr(), "Failed to parse aux message: %s", err)
  160. } else {
  161. imageID = result.ID
  162. }
  163. }
  164. err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, progBuff.FD(), true, aux)
  165. if err != nil {
  166. if jerr, ok := err.(*jsonmessage.JSONError); ok {
  167. // If no error code is set, default to 1
  168. if jerr.Code == 0 {
  169. jerr.Code = 1
  170. }
  171. return "", cli.StatusError{Status: jerr.Message, StatusCode: jerr.Code}
  172. }
  173. return "", err
  174. }
  175. // Windows: show error message about modified file permissions if the
  176. // daemon isn't running Windows.
  177. if response.OSType != "windows" && runtime.GOOS == "windows" {
  178. // if response.OSType != "windows" && runtime.GOOS == "windows" && !options.quiet {
  179. fmt.Fprintln(s.stdout(), "SECURITY WARNING: You are building a Docker "+
  180. "image from Windows against a non-Windows Docker host. All files and "+
  181. "directories added to build context will have '-rwxr-xr-x' permissions. "+
  182. "It is recommended to double check and reset permissions for sensitive "+
  183. "files and directories.")
  184. }
  185. if options.ImageIDFile != "" {
  186. if imageID == "" {
  187. return "", errors.Errorf("Server did not provide an image ID. Cannot write %s", options.ImageIDFile)
  188. }
  189. if err := ioutil.WriteFile(options.ImageIDFile, []byte(imageID), 0666); err != nil {
  190. return "", err
  191. }
  192. }
  193. return imageID, nil
  194. }
  195. func isLocalDir(c string) bool {
  196. _, err := os.Stat(c)
  197. return err == nil
  198. }
  199. func imageBuildOptions(options buildx.Options) dockertypes.ImageBuildOptions {
  200. return dockertypes.ImageBuildOptions{
  201. Tags: options.Tags,
  202. NoCache: options.NoCache,
  203. Remove: true,
  204. PullParent: options.Pull,
  205. BuildArgs: toMapStringStringPtr(options.BuildArgs),
  206. Labels: options.Labels,
  207. NetworkMode: options.NetworkMode,
  208. ExtraHosts: options.ExtraHosts,
  209. Target: options.Target,
  210. }
  211. }
  212. func toMapStringStringPtr(source map[string]string) map[string]*string {
  213. dest := make(map[string]*string)
  214. for k, v := range source {
  215. v := v
  216. dest[k] = &v
  217. }
  218. return dest
  219. }