context.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package build
  2. import (
  3. "bufio"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "runtime"
  11. "strings"
  12. "github.com/docker/docker/pkg/archive"
  13. "github.com/docker/docker/pkg/fileutils"
  14. "github.com/docker/docker/pkg/gitutils"
  15. "github.com/docker/docker/pkg/httputils"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/docker/docker/pkg/progress"
  18. "github.com/docker/docker/pkg/streamformatter"
  19. )
  20. const (
  21. // DefaultDockerfileName is the Default filename with Docker commands, read by docker build
  22. DefaultDockerfileName string = "Dockerfile"
  23. )
  24. // ValidateContextDirectory checks if all the contents of the directory
  25. // can be read and returns an error if some files can't be read
  26. // symlinks which point to non-existing files don't trigger an error
  27. func ValidateContextDirectory(srcPath string, excludes []string) error {
  28. contextRoot, err := getContextRoot(srcPath)
  29. if err != nil {
  30. return err
  31. }
  32. return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error {
  33. if err != nil {
  34. if os.IsPermission(err) {
  35. return fmt.Errorf("can't stat '%s'", filePath)
  36. }
  37. if os.IsNotExist(err) {
  38. return nil
  39. }
  40. return err
  41. }
  42. // skip this directory/file if it's not in the path, it won't get added to the context
  43. if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil {
  44. return err
  45. } else if skip, err := fileutils.Matches(relFilePath, excludes); err != nil {
  46. return err
  47. } else if skip {
  48. if f.IsDir() {
  49. return filepath.SkipDir
  50. }
  51. return nil
  52. }
  53. // skip checking if symlinks point to non-existing files, such symlinks can be useful
  54. // also skip named pipes, because they hanging on open
  55. if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 {
  56. return nil
  57. }
  58. if !f.IsDir() {
  59. currentFile, err := os.Open(filePath)
  60. if err != nil && os.IsPermission(err) {
  61. return fmt.Errorf("no permission to read from '%s'", filePath)
  62. }
  63. currentFile.Close()
  64. }
  65. return nil
  66. })
  67. }
  68. // GetContextFromReader will read the contents of the given reader as either a
  69. // Dockerfile or tar archive. Returns a tar archive used as a context and a
  70. // path to the Dockerfile inside the tar.
  71. func GetContextFromReader(r io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) {
  72. buf := bufio.NewReader(r)
  73. magic, err := buf.Peek(archive.HeaderSize)
  74. if err != nil && err != io.EOF {
  75. return nil, "", fmt.Errorf("failed to peek context header from STDIN: %v", err)
  76. }
  77. if archive.IsArchive(magic) {
  78. return ioutils.NewReadCloserWrapper(buf, func() error { return r.Close() }), dockerfileName, nil
  79. }
  80. // Input should be read as a Dockerfile.
  81. tmpDir, err := ioutil.TempDir("", "docker-build-context-")
  82. if err != nil {
  83. return nil, "", fmt.Errorf("unbale to create temporary context directory: %v", err)
  84. }
  85. f, err := os.Create(filepath.Join(tmpDir, DefaultDockerfileName))
  86. if err != nil {
  87. return nil, "", err
  88. }
  89. _, err = io.Copy(f, buf)
  90. if err != nil {
  91. f.Close()
  92. return nil, "", err
  93. }
  94. if err := f.Close(); err != nil {
  95. return nil, "", err
  96. }
  97. if err := r.Close(); err != nil {
  98. return nil, "", err
  99. }
  100. tar, err := archive.Tar(tmpDir, archive.Uncompressed)
  101. if err != nil {
  102. return nil, "", err
  103. }
  104. return ioutils.NewReadCloserWrapper(tar, func() error {
  105. err := tar.Close()
  106. os.RemoveAll(tmpDir)
  107. return err
  108. }), DefaultDockerfileName, nil
  109. }
  110. // GetContextFromGitURL uses a Git URL as context for a `docker build`. The
  111. // git repo is cloned into a temporary directory used as the context directory.
  112. // Returns the absolute path to the temporary context directory, the relative
  113. // path of the dockerfile in that context directory, and a non-nil error on
  114. // success.
  115. func GetContextFromGitURL(gitURL, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  116. if _, err := exec.LookPath("git"); err != nil {
  117. return "", "", fmt.Errorf("unable to find 'git': %v", err)
  118. }
  119. if absContextDir, err = gitutils.Clone(gitURL); err != nil {
  120. return "", "", fmt.Errorf("unable to 'git clone' to temporary context directory: %v", err)
  121. }
  122. return getDockerfileRelPath(absContextDir, dockerfileName)
  123. }
  124. // GetContextFromURL uses a remote URL as context for a `docker build`. The
  125. // remote resource is downloaded as either a Dockerfile or a tar archive.
  126. // Returns the tar archive used for the context and a path of the
  127. // dockerfile inside the tar.
  128. func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) {
  129. response, err := httputils.Download(remoteURL)
  130. if err != nil {
  131. return nil, "", fmt.Errorf("unable to download remote context %s: %v", remoteURL, err)
  132. }
  133. progressOutput := streamformatter.NewStreamFormatter().NewProgressOutput(out, true)
  134. // Pass the response body through a progress reader.
  135. progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL))
  136. return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName)
  137. }
  138. // GetContextFromLocalDir uses the given local directory as context for a
  139. // `docker build`. Returns the absolute path to the local context directory,
  140. // the relative path of the dockerfile in that context directory, and a non-nil
  141. // error on success.
  142. func GetContextFromLocalDir(localDir, dockerfileName string) (absContextDir, relDockerfile string, err error) {
  143. // When using a local context directory, when the Dockerfile is specified
  144. // with the `-f/--file` option then it is considered relative to the
  145. // current directory and not the context directory.
  146. if dockerfileName != "" {
  147. if dockerfileName, err = filepath.Abs(dockerfileName); err != nil {
  148. return "", "", fmt.Errorf("unable to get absolute path to Dockerfile: %v", err)
  149. }
  150. }
  151. return getDockerfileRelPath(localDir, dockerfileName)
  152. }
  153. // getDockerfileRelPath uses the given context directory for a `docker build`
  154. // and returns the absolute path to the context directory, the relative path of
  155. // the dockerfile in that context directory, and a non-nil error on success.
  156. func getDockerfileRelPath(givenContextDir, givenDockerfile string) (absContextDir, relDockerfile string, err error) {
  157. if absContextDir, err = filepath.Abs(givenContextDir); err != nil {
  158. return "", "", fmt.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err)
  159. }
  160. // The context dir might be a symbolic link, so follow it to the actual
  161. // target directory.
  162. //
  163. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  164. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  165. // paths (those starting with \\). This hack means that when using links
  166. // on UNC paths, they will not be followed.
  167. if !isUNC(absContextDir) {
  168. absContextDir, err = filepath.EvalSymlinks(absContextDir)
  169. if err != nil {
  170. return "", "", fmt.Errorf("unable to evaluate symlinks in context path: %v", err)
  171. }
  172. }
  173. stat, err := os.Lstat(absContextDir)
  174. if err != nil {
  175. return "", "", fmt.Errorf("unable to stat context directory %q: %v", absContextDir, err)
  176. }
  177. if !stat.IsDir() {
  178. return "", "", fmt.Errorf("context must be a directory: %s", absContextDir)
  179. }
  180. absDockerfile := givenDockerfile
  181. if absDockerfile == "" {
  182. // No -f/--file was specified so use the default relative to the
  183. // context directory.
  184. absDockerfile = filepath.Join(absContextDir, DefaultDockerfileName)
  185. // Just to be nice ;-) look for 'dockerfile' too but only
  186. // use it if we found it, otherwise ignore this check
  187. if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) {
  188. altPath := filepath.Join(absContextDir, strings.ToLower(DefaultDockerfileName))
  189. if _, err = os.Lstat(altPath); err == nil {
  190. absDockerfile = altPath
  191. }
  192. }
  193. }
  194. // If not already an absolute path, the Dockerfile path should be joined to
  195. // the base directory.
  196. if !filepath.IsAbs(absDockerfile) {
  197. absDockerfile = filepath.Join(absContextDir, absDockerfile)
  198. }
  199. // Evaluate symlinks in the path to the Dockerfile too.
  200. //
  201. // FIXME. We use isUNC (always false on non-Windows platforms) to workaround
  202. // an issue in golang. On Windows, EvalSymLinks does not work on UNC file
  203. // paths (those starting with \\). This hack means that when using links
  204. // on UNC paths, they will not be followed.
  205. if !isUNC(absDockerfile) {
  206. absDockerfile, err = filepath.EvalSymlinks(absDockerfile)
  207. if err != nil {
  208. return "", "", fmt.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err)
  209. }
  210. }
  211. if _, err := os.Lstat(absDockerfile); err != nil {
  212. if os.IsNotExist(err) {
  213. return "", "", fmt.Errorf("Cannot locate Dockerfile: %q", absDockerfile)
  214. }
  215. return "", "", fmt.Errorf("unable to stat Dockerfile: %v", err)
  216. }
  217. if relDockerfile, err = filepath.Rel(absContextDir, absDockerfile); err != nil {
  218. return "", "", fmt.Errorf("unable to get relative Dockerfile path: %v", err)
  219. }
  220. if strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) {
  221. return "", "", fmt.Errorf("The Dockerfile (%s) must be within the build context (%s)", givenDockerfile, givenContextDir)
  222. }
  223. return absContextDir, relDockerfile, nil
  224. }
  225. // isUNC returns true if the path is UNC (one starting \\). It always returns
  226. // false on Linux.
  227. func isUNC(path string) bool {
  228. return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`)
  229. }